1 //===-- llvm/CodeGen/MachineBasicBlock.cpp ----------------------*- C++ -*-===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // Collect the sequence of machine instructions for a basic block. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "llvm/CodeGen/MachineBasicBlock.h" 14 #include "llvm/ADT/SmallPtrSet.h" 15 #include "llvm/CodeGen/LiveIntervals.h" 16 #include "llvm/CodeGen/LiveVariables.h" 17 #include "llvm/CodeGen/MachineDominators.h" 18 #include "llvm/CodeGen/MachineFunction.h" 19 #include "llvm/CodeGen/MachineInstrBuilder.h" 20 #include "llvm/CodeGen/MachineLoopInfo.h" 21 #include "llvm/CodeGen/MachineRegisterInfo.h" 22 #include "llvm/CodeGen/SlotIndexes.h" 23 #include "llvm/CodeGen/TargetInstrInfo.h" 24 #include "llvm/CodeGen/TargetRegisterInfo.h" 25 #include "llvm/CodeGen/TargetSubtargetInfo.h" 26 #include "llvm/Config/llvm-config.h" 27 #include "llvm/IR/BasicBlock.h" 28 #include "llvm/IR/DataLayout.h" 29 #include "llvm/IR/DebugInfoMetadata.h" 30 #include "llvm/IR/ModuleSlotTracker.h" 31 #include "llvm/MC/MCAsmInfo.h" 32 #include "llvm/MC/MCContext.h" 33 #include "llvm/Support/DataTypes.h" 34 #include "llvm/Support/Debug.h" 35 #include "llvm/Support/raw_ostream.h" 36 #include "llvm/Target/TargetMachine.h" 37 #include <algorithm> 38 using namespace llvm; 39 40 #define DEBUG_TYPE "codegen" 41 42 MachineBasicBlock::MachineBasicBlock(MachineFunction &MF, const BasicBlock *B) 43 : BB(B), Number(-1), xParent(&MF) { 44 Insts.Parent = this; 45 if (B) 46 IrrLoopHeaderWeight = B->getIrrLoopHeaderWeight(); 47 } 48 49 MachineBasicBlock::~MachineBasicBlock() { 50 } 51 52 /// Return the MCSymbol for this basic block. 53 MCSymbol *MachineBasicBlock::getSymbol() const { 54 if (!CachedMCSymbol) { 55 const MachineFunction *MF = getParent(); 56 MCContext &Ctx = MF->getContext(); 57 auto Prefix = Ctx.getAsmInfo()->getPrivateLabelPrefix(); 58 assert(getNumber() >= 0 && "cannot get label for unreachable MBB"); 59 CachedMCSymbol = Ctx.getOrCreateSymbol(Twine(Prefix) + "BB" + 60 Twine(MF->getFunctionNumber()) + 61 "_" + Twine(getNumber())); 62 } 63 64 return CachedMCSymbol; 65 } 66 67 68 raw_ostream &llvm::operator<<(raw_ostream &OS, const MachineBasicBlock &MBB) { 69 MBB.print(OS); 70 return OS; 71 } 72 73 Printable llvm::printMBBReference(const MachineBasicBlock &MBB) { 74 return Printable([&MBB](raw_ostream &OS) { return MBB.printAsOperand(OS); }); 75 } 76 77 /// When an MBB is added to an MF, we need to update the parent pointer of the 78 /// MBB, the MBB numbering, and any instructions in the MBB to be on the right 79 /// operand list for registers. 80 /// 81 /// MBBs start out as #-1. When a MBB is added to a MachineFunction, it 82 /// gets the next available unique MBB number. If it is removed from a 83 /// MachineFunction, it goes back to being #-1. 84 void ilist_callback_traits<MachineBasicBlock>::addNodeToList( 85 MachineBasicBlock *N) { 86 MachineFunction &MF = *N->getParent(); 87 N->Number = MF.addToMBBNumbering(N); 88 89 // Make sure the instructions have their operands in the reginfo lists. 90 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 91 for (MachineBasicBlock::instr_iterator 92 I = N->instr_begin(), E = N->instr_end(); I != E; ++I) 93 I->AddRegOperandsToUseLists(RegInfo); 94 } 95 96 void ilist_callback_traits<MachineBasicBlock>::removeNodeFromList( 97 MachineBasicBlock *N) { 98 N->getParent()->removeFromMBBNumbering(N->Number); 99 N->Number = -1; 100 } 101 102 /// When we add an instruction to a basic block list, we update its parent 103 /// pointer and add its operands from reg use/def lists if appropriate. 104 void ilist_traits<MachineInstr>::addNodeToList(MachineInstr *N) { 105 assert(!N->getParent() && "machine instruction already in a basic block"); 106 N->setParent(Parent); 107 108 // Add the instruction's register operands to their corresponding 109 // use/def lists. 110 MachineFunction *MF = Parent->getParent(); 111 N->AddRegOperandsToUseLists(MF->getRegInfo()); 112 MF->handleInsertion(*N); 113 } 114 115 /// When we remove an instruction from a basic block list, we update its parent 116 /// pointer and remove its operands from reg use/def lists if appropriate. 117 void ilist_traits<MachineInstr>::removeNodeFromList(MachineInstr *N) { 118 assert(N->getParent() && "machine instruction not in a basic block"); 119 120 // Remove from the use/def lists. 121 if (MachineFunction *MF = N->getMF()) { 122 MF->handleRemoval(*N); 123 N->RemoveRegOperandsFromUseLists(MF->getRegInfo()); 124 } 125 126 N->setParent(nullptr); 127 } 128 129 /// When moving a range of instructions from one MBB list to another, we need to 130 /// update the parent pointers and the use/def lists. 131 void ilist_traits<MachineInstr>::transferNodesFromList(ilist_traits &FromList, 132 instr_iterator First, 133 instr_iterator Last) { 134 assert(Parent->getParent() == FromList.Parent->getParent() && 135 "MachineInstr parent mismatch!"); 136 assert(this != &FromList && "Called without a real transfer..."); 137 assert(Parent != FromList.Parent && "Two lists have the same parent?"); 138 139 // If splicing between two blocks within the same function, just update the 140 // parent pointers. 141 for (; First != Last; ++First) 142 First->setParent(Parent); 143 } 144 145 void ilist_traits<MachineInstr>::deleteNode(MachineInstr *MI) { 146 assert(!MI->getParent() && "MI is still in a block!"); 147 Parent->getParent()->DeleteMachineInstr(MI); 148 } 149 150 MachineBasicBlock::iterator MachineBasicBlock::getFirstNonPHI() { 151 instr_iterator I = instr_begin(), E = instr_end(); 152 while (I != E && I->isPHI()) 153 ++I; 154 assert((I == E || !I->isInsideBundle()) && 155 "First non-phi MI cannot be inside a bundle!"); 156 return I; 157 } 158 159 MachineBasicBlock::iterator 160 MachineBasicBlock::SkipPHIsAndLabels(MachineBasicBlock::iterator I) { 161 const TargetInstrInfo *TII = getParent()->getSubtarget().getInstrInfo(); 162 163 iterator E = end(); 164 while (I != E && (I->isPHI() || I->isPosition() || 165 TII->isBasicBlockPrologue(*I))) 166 ++I; 167 // FIXME: This needs to change if we wish to bundle labels 168 // inside the bundle. 169 assert((I == E || !I->isInsideBundle()) && 170 "First non-phi / non-label instruction is inside a bundle!"); 171 return I; 172 } 173 174 MachineBasicBlock::iterator 175 MachineBasicBlock::SkipPHIsLabelsAndDebug(MachineBasicBlock::iterator I) { 176 const TargetInstrInfo *TII = getParent()->getSubtarget().getInstrInfo(); 177 178 iterator E = end(); 179 while (I != E && (I->isPHI() || I->isPosition() || I->isDebugInstr() || 180 TII->isBasicBlockPrologue(*I))) 181 ++I; 182 // FIXME: This needs to change if we wish to bundle labels / dbg_values 183 // inside the bundle. 184 assert((I == E || !I->isInsideBundle()) && 185 "First non-phi / non-label / non-debug " 186 "instruction is inside a bundle!"); 187 return I; 188 } 189 190 MachineBasicBlock::iterator MachineBasicBlock::getFirstTerminator() { 191 iterator B = begin(), E = end(), I = E; 192 while (I != B && ((--I)->isTerminator() || I->isDebugInstr())) 193 ; /*noop */ 194 while (I != E && !I->isTerminator()) 195 ++I; 196 return I; 197 } 198 199 MachineBasicBlock::instr_iterator MachineBasicBlock::getFirstInstrTerminator() { 200 instr_iterator B = instr_begin(), E = instr_end(), I = E; 201 while (I != B && ((--I)->isTerminator() || I->isDebugInstr())) 202 ; /*noop */ 203 while (I != E && !I->isTerminator()) 204 ++I; 205 return I; 206 } 207 208 MachineBasicBlock::iterator MachineBasicBlock::getFirstNonDebugInstr() { 209 // Skip over begin-of-block dbg_value instructions. 210 return skipDebugInstructionsForward(begin(), end()); 211 } 212 213 MachineBasicBlock::iterator MachineBasicBlock::getLastNonDebugInstr() { 214 // Skip over end-of-block dbg_value instructions. 215 instr_iterator B = instr_begin(), I = instr_end(); 216 while (I != B) { 217 --I; 218 // Return instruction that starts a bundle. 219 if (I->isDebugInstr() || I->isInsideBundle()) 220 continue; 221 return I; 222 } 223 // The block is all debug values. 224 return end(); 225 } 226 227 bool MachineBasicBlock::hasEHPadSuccessor() const { 228 for (const_succ_iterator I = succ_begin(), E = succ_end(); I != E; ++I) 229 if ((*I)->isEHPad()) 230 return true; 231 return false; 232 } 233 234 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 235 LLVM_DUMP_METHOD void MachineBasicBlock::dump() const { 236 print(dbgs()); 237 } 238 #endif 239 240 bool MachineBasicBlock::isLegalToHoistInto() const { 241 if (isReturnBlock() || hasEHPadSuccessor()) 242 return false; 243 return true; 244 } 245 246 StringRef MachineBasicBlock::getName() const { 247 if (const BasicBlock *LBB = getBasicBlock()) 248 return LBB->getName(); 249 else 250 return StringRef("", 0); 251 } 252 253 /// Return a hopefully unique identifier for this block. 254 std::string MachineBasicBlock::getFullName() const { 255 std::string Name; 256 if (getParent()) 257 Name = (getParent()->getName() + ":").str(); 258 if (getBasicBlock()) 259 Name += getBasicBlock()->getName(); 260 else 261 Name += ("BB" + Twine(getNumber())).str(); 262 return Name; 263 } 264 265 void MachineBasicBlock::print(raw_ostream &OS, const SlotIndexes *Indexes, 266 bool IsStandalone) const { 267 const MachineFunction *MF = getParent(); 268 if (!MF) { 269 OS << "Can't print out MachineBasicBlock because parent MachineFunction" 270 << " is null\n"; 271 return; 272 } 273 const Function &F = MF->getFunction(); 274 const Module *M = F.getParent(); 275 ModuleSlotTracker MST(M); 276 MST.incorporateFunction(F); 277 print(OS, MST, Indexes, IsStandalone); 278 } 279 280 void MachineBasicBlock::print(raw_ostream &OS, ModuleSlotTracker &MST, 281 const SlotIndexes *Indexes, 282 bool IsStandalone) const { 283 const MachineFunction *MF = getParent(); 284 if (!MF) { 285 OS << "Can't print out MachineBasicBlock because parent MachineFunction" 286 << " is null\n"; 287 return; 288 } 289 290 if (Indexes) 291 OS << Indexes->getMBBStartIdx(this) << '\t'; 292 293 OS << "bb." << getNumber(); 294 bool HasAttributes = false; 295 if (const auto *BB = getBasicBlock()) { 296 if (BB->hasName()) { 297 OS << "." << BB->getName(); 298 } else { 299 HasAttributes = true; 300 OS << " ("; 301 int Slot = MST.getLocalSlot(BB); 302 if (Slot == -1) 303 OS << "<ir-block badref>"; 304 else 305 OS << (Twine("%ir-block.") + Twine(Slot)).str(); 306 } 307 } 308 309 if (hasAddressTaken()) { 310 OS << (HasAttributes ? ", " : " ("); 311 OS << "address-taken"; 312 HasAttributes = true; 313 } 314 if (isEHPad()) { 315 OS << (HasAttributes ? ", " : " ("); 316 OS << "landing-pad"; 317 HasAttributes = true; 318 } 319 if (getAlignment()) { 320 OS << (HasAttributes ? ", " : " ("); 321 OS << "align " << getAlignment(); 322 HasAttributes = true; 323 } 324 if (HasAttributes) 325 OS << ")"; 326 OS << ":\n"; 327 328 const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo(); 329 const MachineRegisterInfo &MRI = MF->getRegInfo(); 330 const TargetInstrInfo &TII = *getParent()->getSubtarget().getInstrInfo(); 331 bool HasLineAttributes = false; 332 333 // Print the preds of this block according to the CFG. 334 if (!pred_empty() && IsStandalone) { 335 if (Indexes) OS << '\t'; 336 // Don't indent(2), align with previous line attributes. 337 OS << "; predecessors: "; 338 for (auto I = pred_begin(), E = pred_end(); I != E; ++I) { 339 if (I != pred_begin()) 340 OS << ", "; 341 OS << printMBBReference(**I); 342 } 343 OS << '\n'; 344 HasLineAttributes = true; 345 } 346 347 if (!succ_empty()) { 348 if (Indexes) OS << '\t'; 349 // Print the successors 350 OS.indent(2) << "successors: "; 351 for (auto I = succ_begin(), E = succ_end(); I != E; ++I) { 352 if (I != succ_begin()) 353 OS << ", "; 354 OS << printMBBReference(**I); 355 if (!Probs.empty()) 356 OS << '(' 357 << format("0x%08" PRIx32, getSuccProbability(I).getNumerator()) 358 << ')'; 359 } 360 if (!Probs.empty() && IsStandalone) { 361 // Print human readable probabilities as comments. 362 OS << "; "; 363 for (auto I = succ_begin(), E = succ_end(); I != E; ++I) { 364 const BranchProbability &BP = getSuccProbability(I); 365 if (I != succ_begin()) 366 OS << ", "; 367 OS << printMBBReference(**I) << '(' 368 << format("%.2f%%", 369 rint(((double)BP.getNumerator() / BP.getDenominator()) * 370 100.0 * 100.0) / 371 100.0) 372 << ')'; 373 } 374 } 375 376 OS << '\n'; 377 HasLineAttributes = true; 378 } 379 380 if (!livein_empty() && MRI.tracksLiveness()) { 381 if (Indexes) OS << '\t'; 382 OS.indent(2) << "liveins: "; 383 384 bool First = true; 385 for (const auto &LI : liveins()) { 386 if (!First) 387 OS << ", "; 388 First = false; 389 OS << printReg(LI.PhysReg, TRI); 390 if (!LI.LaneMask.all()) 391 OS << ":0x" << PrintLaneMask(LI.LaneMask); 392 } 393 HasLineAttributes = true; 394 } 395 396 if (HasLineAttributes) 397 OS << '\n'; 398 399 bool IsInBundle = false; 400 for (const MachineInstr &MI : instrs()) { 401 if (Indexes) { 402 if (Indexes->hasIndex(MI)) 403 OS << Indexes->getInstructionIndex(MI); 404 OS << '\t'; 405 } 406 407 if (IsInBundle && !MI.isInsideBundle()) { 408 OS.indent(2) << "}\n"; 409 IsInBundle = false; 410 } 411 412 OS.indent(IsInBundle ? 4 : 2); 413 MI.print(OS, MST, IsStandalone, /*SkipOpers=*/false, /*SkipDebugLoc=*/false, 414 /*AddNewLine=*/false, &TII); 415 416 if (!IsInBundle && MI.getFlag(MachineInstr::BundledSucc)) { 417 OS << " {"; 418 IsInBundle = true; 419 } 420 OS << '\n'; 421 } 422 423 if (IsInBundle) 424 OS.indent(2) << "}\n"; 425 426 if (IrrLoopHeaderWeight && IsStandalone) { 427 if (Indexes) OS << '\t'; 428 OS.indent(2) << "; Irreducible loop header weight: " 429 << IrrLoopHeaderWeight.getValue() << '\n'; 430 } 431 } 432 433 void MachineBasicBlock::printAsOperand(raw_ostream &OS, 434 bool /*PrintType*/) const { 435 OS << "%bb." << getNumber(); 436 } 437 438 void MachineBasicBlock::removeLiveIn(MCPhysReg Reg, LaneBitmask LaneMask) { 439 LiveInVector::iterator I = find_if( 440 LiveIns, [Reg](const RegisterMaskPair &LI) { return LI.PhysReg == Reg; }); 441 if (I == LiveIns.end()) 442 return; 443 444 I->LaneMask &= ~LaneMask; 445 if (I->LaneMask.none()) 446 LiveIns.erase(I); 447 } 448 449 MachineBasicBlock::livein_iterator 450 MachineBasicBlock::removeLiveIn(MachineBasicBlock::livein_iterator I) { 451 // Get non-const version of iterator. 452 LiveInVector::iterator LI = LiveIns.begin() + (I - LiveIns.begin()); 453 return LiveIns.erase(LI); 454 } 455 456 bool MachineBasicBlock::isLiveIn(MCPhysReg Reg, LaneBitmask LaneMask) const { 457 livein_iterator I = find_if( 458 LiveIns, [Reg](const RegisterMaskPair &LI) { return LI.PhysReg == Reg; }); 459 return I != livein_end() && (I->LaneMask & LaneMask).any(); 460 } 461 462 void MachineBasicBlock::sortUniqueLiveIns() { 463 llvm::sort(LiveIns, 464 [](const RegisterMaskPair &LI0, const RegisterMaskPair &LI1) { 465 return LI0.PhysReg < LI1.PhysReg; 466 }); 467 // Liveins are sorted by physreg now we can merge their lanemasks. 468 LiveInVector::const_iterator I = LiveIns.begin(); 469 LiveInVector::const_iterator J; 470 LiveInVector::iterator Out = LiveIns.begin(); 471 for (; I != LiveIns.end(); ++Out, I = J) { 472 unsigned PhysReg = I->PhysReg; 473 LaneBitmask LaneMask = I->LaneMask; 474 for (J = std::next(I); J != LiveIns.end() && J->PhysReg == PhysReg; ++J) 475 LaneMask |= J->LaneMask; 476 Out->PhysReg = PhysReg; 477 Out->LaneMask = LaneMask; 478 } 479 LiveIns.erase(Out, LiveIns.end()); 480 } 481 482 unsigned 483 MachineBasicBlock::addLiveIn(MCPhysReg PhysReg, const TargetRegisterClass *RC) { 484 assert(getParent() && "MBB must be inserted in function"); 485 assert(TargetRegisterInfo::isPhysicalRegister(PhysReg) && "Expected physreg"); 486 assert(RC && "Register class is required"); 487 assert((isEHPad() || this == &getParent()->front()) && 488 "Only the entry block and landing pads can have physreg live ins"); 489 490 bool LiveIn = isLiveIn(PhysReg); 491 iterator I = SkipPHIsAndLabels(begin()), E = end(); 492 MachineRegisterInfo &MRI = getParent()->getRegInfo(); 493 const TargetInstrInfo &TII = *getParent()->getSubtarget().getInstrInfo(); 494 495 // Look for an existing copy. 496 if (LiveIn) 497 for (;I != E && I->isCopy(); ++I) 498 if (I->getOperand(1).getReg() == PhysReg) { 499 unsigned VirtReg = I->getOperand(0).getReg(); 500 if (!MRI.constrainRegClass(VirtReg, RC)) 501 llvm_unreachable("Incompatible live-in register class."); 502 return VirtReg; 503 } 504 505 // No luck, create a virtual register. 506 unsigned VirtReg = MRI.createVirtualRegister(RC); 507 BuildMI(*this, I, DebugLoc(), TII.get(TargetOpcode::COPY), VirtReg) 508 .addReg(PhysReg, RegState::Kill); 509 if (!LiveIn) 510 addLiveIn(PhysReg); 511 return VirtReg; 512 } 513 514 void MachineBasicBlock::moveBefore(MachineBasicBlock *NewAfter) { 515 getParent()->splice(NewAfter->getIterator(), getIterator()); 516 } 517 518 void MachineBasicBlock::moveAfter(MachineBasicBlock *NewBefore) { 519 getParent()->splice(++NewBefore->getIterator(), getIterator()); 520 } 521 522 void MachineBasicBlock::updateTerminator() { 523 const TargetInstrInfo *TII = getParent()->getSubtarget().getInstrInfo(); 524 // A block with no successors has no concerns with fall-through edges. 525 if (this->succ_empty()) 526 return; 527 528 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; 529 SmallVector<MachineOperand, 4> Cond; 530 DebugLoc DL = findBranchDebugLoc(); 531 bool B = TII->analyzeBranch(*this, TBB, FBB, Cond); 532 (void) B; 533 assert(!B && "UpdateTerminators requires analyzable predecessors!"); 534 if (Cond.empty()) { 535 if (TBB) { 536 // The block has an unconditional branch. If its successor is now its 537 // layout successor, delete the branch. 538 if (isLayoutSuccessor(TBB)) 539 TII->removeBranch(*this); 540 } else { 541 // The block has an unconditional fallthrough. If its successor is not its 542 // layout successor, insert a branch. First we have to locate the only 543 // non-landing-pad successor, as that is the fallthrough block. 544 for (succ_iterator SI = succ_begin(), SE = succ_end(); SI != SE; ++SI) { 545 if ((*SI)->isEHPad()) 546 continue; 547 assert(!TBB && "Found more than one non-landing-pad successor!"); 548 TBB = *SI; 549 } 550 551 // If there is no non-landing-pad successor, the block has no fall-through 552 // edges to be concerned with. 553 if (!TBB) 554 return; 555 556 // Finally update the unconditional successor to be reached via a branch 557 // if it would not be reached by fallthrough. 558 if (!isLayoutSuccessor(TBB)) 559 TII->insertBranch(*this, TBB, nullptr, Cond, DL); 560 } 561 return; 562 } 563 564 if (FBB) { 565 // The block has a non-fallthrough conditional branch. If one of its 566 // successors is its layout successor, rewrite it to a fallthrough 567 // conditional branch. 568 if (isLayoutSuccessor(TBB)) { 569 if (TII->reverseBranchCondition(Cond)) 570 return; 571 TII->removeBranch(*this); 572 TII->insertBranch(*this, FBB, nullptr, Cond, DL); 573 } else if (isLayoutSuccessor(FBB)) { 574 TII->removeBranch(*this); 575 TII->insertBranch(*this, TBB, nullptr, Cond, DL); 576 } 577 return; 578 } 579 580 // Walk through the successors and find the successor which is not a landing 581 // pad and is not the conditional branch destination (in TBB) as the 582 // fallthrough successor. 583 MachineBasicBlock *FallthroughBB = nullptr; 584 for (succ_iterator SI = succ_begin(), SE = succ_end(); SI != SE; ++SI) { 585 if ((*SI)->isEHPad() || *SI == TBB) 586 continue; 587 assert(!FallthroughBB && "Found more than one fallthrough successor."); 588 FallthroughBB = *SI; 589 } 590 591 if (!FallthroughBB) { 592 if (canFallThrough()) { 593 // We fallthrough to the same basic block as the conditional jump targets. 594 // Remove the conditional jump, leaving unconditional fallthrough. 595 // FIXME: This does not seem like a reasonable pattern to support, but it 596 // has been seen in the wild coming out of degenerate ARM test cases. 597 TII->removeBranch(*this); 598 599 // Finally update the unconditional successor to be reached via a branch if 600 // it would not be reached by fallthrough. 601 if (!isLayoutSuccessor(TBB)) 602 TII->insertBranch(*this, TBB, nullptr, Cond, DL); 603 return; 604 } 605 606 // We enter here iff exactly one successor is TBB which cannot fallthrough 607 // and the rest successors if any are EHPads. In this case, we need to 608 // change the conditional branch into unconditional branch. 609 TII->removeBranch(*this); 610 Cond.clear(); 611 TII->insertBranch(*this, TBB, nullptr, Cond, DL); 612 return; 613 } 614 615 // The block has a fallthrough conditional branch. 616 if (isLayoutSuccessor(TBB)) { 617 if (TII->reverseBranchCondition(Cond)) { 618 // We can't reverse the condition, add an unconditional branch. 619 Cond.clear(); 620 TII->insertBranch(*this, FallthroughBB, nullptr, Cond, DL); 621 return; 622 } 623 TII->removeBranch(*this); 624 TII->insertBranch(*this, FallthroughBB, nullptr, Cond, DL); 625 } else if (!isLayoutSuccessor(FallthroughBB)) { 626 TII->removeBranch(*this); 627 TII->insertBranch(*this, TBB, FallthroughBB, Cond, DL); 628 } 629 } 630 631 void MachineBasicBlock::validateSuccProbs() const { 632 #ifndef NDEBUG 633 int64_t Sum = 0; 634 for (auto Prob : Probs) 635 Sum += Prob.getNumerator(); 636 // Due to precision issue, we assume that the sum of probabilities is one if 637 // the difference between the sum of their numerators and the denominator is 638 // no greater than the number of successors. 639 assert((uint64_t)std::abs(Sum - BranchProbability::getDenominator()) <= 640 Probs.size() && 641 "The sum of successors's probabilities exceeds one."); 642 #endif // NDEBUG 643 } 644 645 void MachineBasicBlock::addSuccessor(MachineBasicBlock *Succ, 646 BranchProbability Prob) { 647 // Probability list is either empty (if successor list isn't empty, this means 648 // disabled optimization) or has the same size as successor list. 649 if (!(Probs.empty() && !Successors.empty())) 650 Probs.push_back(Prob); 651 Successors.push_back(Succ); 652 Succ->addPredecessor(this); 653 } 654 655 void MachineBasicBlock::addSuccessorWithoutProb(MachineBasicBlock *Succ) { 656 // We need to make sure probability list is either empty or has the same size 657 // of successor list. When this function is called, we can safely delete all 658 // probability in the list. 659 Probs.clear(); 660 Successors.push_back(Succ); 661 Succ->addPredecessor(this); 662 } 663 664 void MachineBasicBlock::splitSuccessor(MachineBasicBlock *Old, 665 MachineBasicBlock *New, 666 bool NormalizeSuccProbs) { 667 succ_iterator OldI = llvm::find(successors(), Old); 668 assert(OldI != succ_end() && "Old is not a successor of this block!"); 669 assert(llvm::find(successors(), New) == succ_end() && 670 "New is already a successor of this block!"); 671 672 // Add a new successor with equal probability as the original one. Note 673 // that we directly copy the probability using the iterator rather than 674 // getting a potentially synthetic probability computed when unknown. This 675 // preserves the probabilities as-is and then we can renormalize them and 676 // query them effectively afterward. 677 addSuccessor(New, Probs.empty() ? BranchProbability::getUnknown() 678 : *getProbabilityIterator(OldI)); 679 if (NormalizeSuccProbs) 680 normalizeSuccProbs(); 681 } 682 683 void MachineBasicBlock::removeSuccessor(MachineBasicBlock *Succ, 684 bool NormalizeSuccProbs) { 685 succ_iterator I = find(Successors, Succ); 686 removeSuccessor(I, NormalizeSuccProbs); 687 } 688 689 MachineBasicBlock::succ_iterator 690 MachineBasicBlock::removeSuccessor(succ_iterator I, bool NormalizeSuccProbs) { 691 assert(I != Successors.end() && "Not a current successor!"); 692 693 // If probability list is empty it means we don't use it (disabled 694 // optimization). 695 if (!Probs.empty()) { 696 probability_iterator WI = getProbabilityIterator(I); 697 Probs.erase(WI); 698 if (NormalizeSuccProbs) 699 normalizeSuccProbs(); 700 } 701 702 (*I)->removePredecessor(this); 703 return Successors.erase(I); 704 } 705 706 void MachineBasicBlock::replaceSuccessor(MachineBasicBlock *Old, 707 MachineBasicBlock *New) { 708 if (Old == New) 709 return; 710 711 succ_iterator E = succ_end(); 712 succ_iterator NewI = E; 713 succ_iterator OldI = E; 714 for (succ_iterator I = succ_begin(); I != E; ++I) { 715 if (*I == Old) { 716 OldI = I; 717 if (NewI != E) 718 break; 719 } 720 if (*I == New) { 721 NewI = I; 722 if (OldI != E) 723 break; 724 } 725 } 726 assert(OldI != E && "Old is not a successor of this block"); 727 728 // If New isn't already a successor, let it take Old's place. 729 if (NewI == E) { 730 Old->removePredecessor(this); 731 New->addPredecessor(this); 732 *OldI = New; 733 return; 734 } 735 736 // New is already a successor. 737 // Update its probability instead of adding a duplicate edge. 738 if (!Probs.empty()) { 739 auto ProbIter = getProbabilityIterator(NewI); 740 if (!ProbIter->isUnknown()) 741 *ProbIter += *getProbabilityIterator(OldI); 742 } 743 removeSuccessor(OldI); 744 } 745 746 void MachineBasicBlock::copySuccessor(MachineBasicBlock *Orig, 747 succ_iterator I) { 748 if (Orig->Probs.empty()) 749 addSuccessor(*I, Orig->getSuccProbability(I)); 750 else 751 addSuccessorWithoutProb(*I); 752 } 753 754 void MachineBasicBlock::addPredecessor(MachineBasicBlock *Pred) { 755 Predecessors.push_back(Pred); 756 } 757 758 void MachineBasicBlock::removePredecessor(MachineBasicBlock *Pred) { 759 pred_iterator I = find(Predecessors, Pred); 760 assert(I != Predecessors.end() && "Pred is not a predecessor of this block!"); 761 Predecessors.erase(I); 762 } 763 764 void MachineBasicBlock::transferSuccessors(MachineBasicBlock *FromMBB) { 765 if (this == FromMBB) 766 return; 767 768 while (!FromMBB->succ_empty()) { 769 MachineBasicBlock *Succ = *FromMBB->succ_begin(); 770 771 // If probability list is empty it means we don't use it (disabled optimization). 772 if (!FromMBB->Probs.empty()) { 773 auto Prob = *FromMBB->Probs.begin(); 774 addSuccessor(Succ, Prob); 775 } else 776 addSuccessorWithoutProb(Succ); 777 778 FromMBB->removeSuccessor(Succ); 779 } 780 } 781 782 void 783 MachineBasicBlock::transferSuccessorsAndUpdatePHIs(MachineBasicBlock *FromMBB) { 784 if (this == FromMBB) 785 return; 786 787 while (!FromMBB->succ_empty()) { 788 MachineBasicBlock *Succ = *FromMBB->succ_begin(); 789 if (!FromMBB->Probs.empty()) { 790 auto Prob = *FromMBB->Probs.begin(); 791 addSuccessor(Succ, Prob); 792 } else 793 addSuccessorWithoutProb(Succ); 794 FromMBB->removeSuccessor(Succ); 795 796 // Fix up any PHI nodes in the successor. 797 for (MachineBasicBlock::instr_iterator MI = Succ->instr_begin(), 798 ME = Succ->instr_end(); MI != ME && MI->isPHI(); ++MI) 799 for (unsigned i = 2, e = MI->getNumOperands()+1; i != e; i += 2) { 800 MachineOperand &MO = MI->getOperand(i); 801 if (MO.getMBB() == FromMBB) 802 MO.setMBB(this); 803 } 804 } 805 normalizeSuccProbs(); 806 } 807 808 bool MachineBasicBlock::isPredecessor(const MachineBasicBlock *MBB) const { 809 return is_contained(predecessors(), MBB); 810 } 811 812 bool MachineBasicBlock::isSuccessor(const MachineBasicBlock *MBB) const { 813 return is_contained(successors(), MBB); 814 } 815 816 bool MachineBasicBlock::isLayoutSuccessor(const MachineBasicBlock *MBB) const { 817 MachineFunction::const_iterator I(this); 818 return std::next(I) == MachineFunction::const_iterator(MBB); 819 } 820 821 MachineBasicBlock *MachineBasicBlock::getFallThrough() { 822 MachineFunction::iterator Fallthrough = getIterator(); 823 ++Fallthrough; 824 // If FallthroughBlock is off the end of the function, it can't fall through. 825 if (Fallthrough == getParent()->end()) 826 return nullptr; 827 828 // If FallthroughBlock isn't a successor, no fallthrough is possible. 829 if (!isSuccessor(&*Fallthrough)) 830 return nullptr; 831 832 // Analyze the branches, if any, at the end of the block. 833 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; 834 SmallVector<MachineOperand, 4> Cond; 835 const TargetInstrInfo *TII = getParent()->getSubtarget().getInstrInfo(); 836 if (TII->analyzeBranch(*this, TBB, FBB, Cond)) { 837 // If we couldn't analyze the branch, examine the last instruction. 838 // If the block doesn't end in a known control barrier, assume fallthrough 839 // is possible. The isPredicated check is needed because this code can be 840 // called during IfConversion, where an instruction which is normally a 841 // Barrier is predicated and thus no longer an actual control barrier. 842 return (empty() || !back().isBarrier() || TII->isPredicated(back())) 843 ? &*Fallthrough 844 : nullptr; 845 } 846 847 // If there is no branch, control always falls through. 848 if (!TBB) return &*Fallthrough; 849 850 // If there is some explicit branch to the fallthrough block, it can obviously 851 // reach, even though the branch should get folded to fall through implicitly. 852 if (MachineFunction::iterator(TBB) == Fallthrough || 853 MachineFunction::iterator(FBB) == Fallthrough) 854 return &*Fallthrough; 855 856 // If it's an unconditional branch to some block not the fall through, it 857 // doesn't fall through. 858 if (Cond.empty()) return nullptr; 859 860 // Otherwise, if it is conditional and has no explicit false block, it falls 861 // through. 862 return (FBB == nullptr) ? &*Fallthrough : nullptr; 863 } 864 865 bool MachineBasicBlock::canFallThrough() { 866 return getFallThrough() != nullptr; 867 } 868 869 MachineBasicBlock *MachineBasicBlock::SplitCriticalEdge(MachineBasicBlock *Succ, 870 Pass &P) { 871 if (!canSplitCriticalEdge(Succ)) 872 return nullptr; 873 874 MachineFunction *MF = getParent(); 875 DebugLoc DL; // FIXME: this is nowhere 876 877 MachineBasicBlock *NMBB = MF->CreateMachineBasicBlock(); 878 MF->insert(std::next(MachineFunction::iterator(this)), NMBB); 879 LLVM_DEBUG(dbgs() << "Splitting critical edge: " << printMBBReference(*this) 880 << " -- " << printMBBReference(*NMBB) << " -- " 881 << printMBBReference(*Succ) << '\n'); 882 883 LiveIntervals *LIS = P.getAnalysisIfAvailable<LiveIntervals>(); 884 SlotIndexes *Indexes = P.getAnalysisIfAvailable<SlotIndexes>(); 885 if (LIS) 886 LIS->insertMBBInMaps(NMBB); 887 else if (Indexes) 888 Indexes->insertMBBInMaps(NMBB); 889 890 // On some targets like Mips, branches may kill virtual registers. Make sure 891 // that LiveVariables is properly updated after updateTerminator replaces the 892 // terminators. 893 LiveVariables *LV = P.getAnalysisIfAvailable<LiveVariables>(); 894 895 // Collect a list of virtual registers killed by the terminators. 896 SmallVector<unsigned, 4> KilledRegs; 897 if (LV) 898 for (instr_iterator I = getFirstInstrTerminator(), E = instr_end(); 899 I != E; ++I) { 900 MachineInstr *MI = &*I; 901 for (MachineInstr::mop_iterator OI = MI->operands_begin(), 902 OE = MI->operands_end(); OI != OE; ++OI) { 903 if (!OI->isReg() || OI->getReg() == 0 || 904 !OI->isUse() || !OI->isKill() || OI->isUndef()) 905 continue; 906 unsigned Reg = OI->getReg(); 907 if (TargetRegisterInfo::isPhysicalRegister(Reg) || 908 LV->getVarInfo(Reg).removeKill(*MI)) { 909 KilledRegs.push_back(Reg); 910 LLVM_DEBUG(dbgs() << "Removing terminator kill: " << *MI); 911 OI->setIsKill(false); 912 } 913 } 914 } 915 916 SmallVector<unsigned, 4> UsedRegs; 917 if (LIS) { 918 for (instr_iterator I = getFirstInstrTerminator(), E = instr_end(); 919 I != E; ++I) { 920 MachineInstr *MI = &*I; 921 922 for (MachineInstr::mop_iterator OI = MI->operands_begin(), 923 OE = MI->operands_end(); OI != OE; ++OI) { 924 if (!OI->isReg() || OI->getReg() == 0) 925 continue; 926 927 unsigned Reg = OI->getReg(); 928 if (!is_contained(UsedRegs, Reg)) 929 UsedRegs.push_back(Reg); 930 } 931 } 932 } 933 934 ReplaceUsesOfBlockWith(Succ, NMBB); 935 936 // If updateTerminator() removes instructions, we need to remove them from 937 // SlotIndexes. 938 SmallVector<MachineInstr*, 4> Terminators; 939 if (Indexes) { 940 for (instr_iterator I = getFirstInstrTerminator(), E = instr_end(); 941 I != E; ++I) 942 Terminators.push_back(&*I); 943 } 944 945 updateTerminator(); 946 947 if (Indexes) { 948 SmallVector<MachineInstr*, 4> NewTerminators; 949 for (instr_iterator I = getFirstInstrTerminator(), E = instr_end(); 950 I != E; ++I) 951 NewTerminators.push_back(&*I); 952 953 for (SmallVectorImpl<MachineInstr*>::iterator I = Terminators.begin(), 954 E = Terminators.end(); I != E; ++I) { 955 if (!is_contained(NewTerminators, *I)) 956 Indexes->removeMachineInstrFromMaps(**I); 957 } 958 } 959 960 // Insert unconditional "jump Succ" instruction in NMBB if necessary. 961 NMBB->addSuccessor(Succ); 962 if (!NMBB->isLayoutSuccessor(Succ)) { 963 SmallVector<MachineOperand, 4> Cond; 964 const TargetInstrInfo *TII = getParent()->getSubtarget().getInstrInfo(); 965 TII->insertBranch(*NMBB, Succ, nullptr, Cond, DL); 966 967 if (Indexes) { 968 for (MachineInstr &MI : NMBB->instrs()) { 969 // Some instructions may have been moved to NMBB by updateTerminator(), 970 // so we first remove any instruction that already has an index. 971 if (Indexes->hasIndex(MI)) 972 Indexes->removeMachineInstrFromMaps(MI); 973 Indexes->insertMachineInstrInMaps(MI); 974 } 975 } 976 } 977 978 // Fix PHI nodes in Succ so they refer to NMBB instead of this 979 for (MachineBasicBlock::instr_iterator 980 i = Succ->instr_begin(),e = Succ->instr_end(); 981 i != e && i->isPHI(); ++i) 982 for (unsigned ni = 1, ne = i->getNumOperands(); ni != ne; ni += 2) 983 if (i->getOperand(ni+1).getMBB() == this) 984 i->getOperand(ni+1).setMBB(NMBB); 985 986 // Inherit live-ins from the successor 987 for (const auto &LI : Succ->liveins()) 988 NMBB->addLiveIn(LI); 989 990 // Update LiveVariables. 991 const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo(); 992 if (LV) { 993 // Restore kills of virtual registers that were killed by the terminators. 994 while (!KilledRegs.empty()) { 995 unsigned Reg = KilledRegs.pop_back_val(); 996 for (instr_iterator I = instr_end(), E = instr_begin(); I != E;) { 997 if (!(--I)->addRegisterKilled(Reg, TRI, /* addIfNotFound= */ false)) 998 continue; 999 if (TargetRegisterInfo::isVirtualRegister(Reg)) 1000 LV->getVarInfo(Reg).Kills.push_back(&*I); 1001 LLVM_DEBUG(dbgs() << "Restored terminator kill: " << *I); 1002 break; 1003 } 1004 } 1005 // Update relevant live-through information. 1006 LV->addNewBlock(NMBB, this, Succ); 1007 } 1008 1009 if (LIS) { 1010 // After splitting the edge and updating SlotIndexes, live intervals may be 1011 // in one of two situations, depending on whether this block was the last in 1012 // the function. If the original block was the last in the function, all 1013 // live intervals will end prior to the beginning of the new split block. If 1014 // the original block was not at the end of the function, all live intervals 1015 // will extend to the end of the new split block. 1016 1017 bool isLastMBB = 1018 std::next(MachineFunction::iterator(NMBB)) == getParent()->end(); 1019 1020 SlotIndex StartIndex = Indexes->getMBBEndIdx(this); 1021 SlotIndex PrevIndex = StartIndex.getPrevSlot(); 1022 SlotIndex EndIndex = Indexes->getMBBEndIdx(NMBB); 1023 1024 // Find the registers used from NMBB in PHIs in Succ. 1025 SmallSet<unsigned, 8> PHISrcRegs; 1026 for (MachineBasicBlock::instr_iterator 1027 I = Succ->instr_begin(), E = Succ->instr_end(); 1028 I != E && I->isPHI(); ++I) { 1029 for (unsigned ni = 1, ne = I->getNumOperands(); ni != ne; ni += 2) { 1030 if (I->getOperand(ni+1).getMBB() == NMBB) { 1031 MachineOperand &MO = I->getOperand(ni); 1032 unsigned Reg = MO.getReg(); 1033 PHISrcRegs.insert(Reg); 1034 if (MO.isUndef()) 1035 continue; 1036 1037 LiveInterval &LI = LIS->getInterval(Reg); 1038 VNInfo *VNI = LI.getVNInfoAt(PrevIndex); 1039 assert(VNI && 1040 "PHI sources should be live out of their predecessors."); 1041 LI.addSegment(LiveInterval::Segment(StartIndex, EndIndex, VNI)); 1042 } 1043 } 1044 } 1045 1046 MachineRegisterInfo *MRI = &getParent()->getRegInfo(); 1047 for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) { 1048 unsigned Reg = TargetRegisterInfo::index2VirtReg(i); 1049 if (PHISrcRegs.count(Reg) || !LIS->hasInterval(Reg)) 1050 continue; 1051 1052 LiveInterval &LI = LIS->getInterval(Reg); 1053 if (!LI.liveAt(PrevIndex)) 1054 continue; 1055 1056 bool isLiveOut = LI.liveAt(LIS->getMBBStartIdx(Succ)); 1057 if (isLiveOut && isLastMBB) { 1058 VNInfo *VNI = LI.getVNInfoAt(PrevIndex); 1059 assert(VNI && "LiveInterval should have VNInfo where it is live."); 1060 LI.addSegment(LiveInterval::Segment(StartIndex, EndIndex, VNI)); 1061 } else if (!isLiveOut && !isLastMBB) { 1062 LI.removeSegment(StartIndex, EndIndex); 1063 } 1064 } 1065 1066 // Update all intervals for registers whose uses may have been modified by 1067 // updateTerminator(). 1068 LIS->repairIntervalsInRange(this, getFirstTerminator(), end(), UsedRegs); 1069 } 1070 1071 if (MachineDominatorTree *MDT = 1072 P.getAnalysisIfAvailable<MachineDominatorTree>()) 1073 MDT->recordSplitCriticalEdge(this, Succ, NMBB); 1074 1075 if (MachineLoopInfo *MLI = P.getAnalysisIfAvailable<MachineLoopInfo>()) 1076 if (MachineLoop *TIL = MLI->getLoopFor(this)) { 1077 // If one or the other blocks were not in a loop, the new block is not 1078 // either, and thus LI doesn't need to be updated. 1079 if (MachineLoop *DestLoop = MLI->getLoopFor(Succ)) { 1080 if (TIL == DestLoop) { 1081 // Both in the same loop, the NMBB joins loop. 1082 DestLoop->addBasicBlockToLoop(NMBB, MLI->getBase()); 1083 } else if (TIL->contains(DestLoop)) { 1084 // Edge from an outer loop to an inner loop. Add to the outer loop. 1085 TIL->addBasicBlockToLoop(NMBB, MLI->getBase()); 1086 } else if (DestLoop->contains(TIL)) { 1087 // Edge from an inner loop to an outer loop. Add to the outer loop. 1088 DestLoop->addBasicBlockToLoop(NMBB, MLI->getBase()); 1089 } else { 1090 // Edge from two loops with no containment relation. Because these 1091 // are natural loops, we know that the destination block must be the 1092 // header of its loop (adding a branch into a loop elsewhere would 1093 // create an irreducible loop). 1094 assert(DestLoop->getHeader() == Succ && 1095 "Should not create irreducible loops!"); 1096 if (MachineLoop *P = DestLoop->getParentLoop()) 1097 P->addBasicBlockToLoop(NMBB, MLI->getBase()); 1098 } 1099 } 1100 } 1101 1102 return NMBB; 1103 } 1104 1105 bool MachineBasicBlock::canSplitCriticalEdge( 1106 const MachineBasicBlock *Succ) const { 1107 // Splitting the critical edge to a landing pad block is non-trivial. Don't do 1108 // it in this generic function. 1109 if (Succ->isEHPad()) 1110 return false; 1111 1112 const MachineFunction *MF = getParent(); 1113 1114 // Performance might be harmed on HW that implements branching using exec mask 1115 // where both sides of the branches are always executed. 1116 if (MF->getTarget().requiresStructuredCFG()) 1117 return false; 1118 1119 // We may need to update this's terminator, but we can't do that if 1120 // AnalyzeBranch fails. If this uses a jump table, we won't touch it. 1121 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo(); 1122 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; 1123 SmallVector<MachineOperand, 4> Cond; 1124 // AnalyzeBanch should modify this, since we did not allow modification. 1125 if (TII->analyzeBranch(*const_cast<MachineBasicBlock *>(this), TBB, FBB, Cond, 1126 /*AllowModify*/ false)) 1127 return false; 1128 1129 // Avoid bugpoint weirdness: A block may end with a conditional branch but 1130 // jumps to the same MBB is either case. We have duplicate CFG edges in that 1131 // case that we can't handle. Since this never happens in properly optimized 1132 // code, just skip those edges. 1133 if (TBB && TBB == FBB) { 1134 LLVM_DEBUG(dbgs() << "Won't split critical edge after degenerate " 1135 << printMBBReference(*this) << '\n'); 1136 return false; 1137 } 1138 return true; 1139 } 1140 1141 /// Prepare MI to be removed from its bundle. This fixes bundle flags on MI's 1142 /// neighboring instructions so the bundle won't be broken by removing MI. 1143 static void unbundleSingleMI(MachineInstr *MI) { 1144 // Removing the first instruction in a bundle. 1145 if (MI->isBundledWithSucc() && !MI->isBundledWithPred()) 1146 MI->unbundleFromSucc(); 1147 // Removing the last instruction in a bundle. 1148 if (MI->isBundledWithPred() && !MI->isBundledWithSucc()) 1149 MI->unbundleFromPred(); 1150 // If MI is not bundled, or if it is internal to a bundle, the neighbor flags 1151 // are already fine. 1152 } 1153 1154 MachineBasicBlock::instr_iterator 1155 MachineBasicBlock::erase(MachineBasicBlock::instr_iterator I) { 1156 unbundleSingleMI(&*I); 1157 return Insts.erase(I); 1158 } 1159 1160 MachineInstr *MachineBasicBlock::remove_instr(MachineInstr *MI) { 1161 unbundleSingleMI(MI); 1162 MI->clearFlag(MachineInstr::BundledPred); 1163 MI->clearFlag(MachineInstr::BundledSucc); 1164 return Insts.remove(MI); 1165 } 1166 1167 MachineBasicBlock::instr_iterator 1168 MachineBasicBlock::insert(instr_iterator I, MachineInstr *MI) { 1169 assert(!MI->isBundledWithPred() && !MI->isBundledWithSucc() && 1170 "Cannot insert instruction with bundle flags"); 1171 // Set the bundle flags when inserting inside a bundle. 1172 if (I != instr_end() && I->isBundledWithPred()) { 1173 MI->setFlag(MachineInstr::BundledPred); 1174 MI->setFlag(MachineInstr::BundledSucc); 1175 } 1176 return Insts.insert(I, MI); 1177 } 1178 1179 /// This method unlinks 'this' from the containing function, and returns it, but 1180 /// does not delete it. 1181 MachineBasicBlock *MachineBasicBlock::removeFromParent() { 1182 assert(getParent() && "Not embedded in a function!"); 1183 getParent()->remove(this); 1184 return this; 1185 } 1186 1187 /// This method unlinks 'this' from the containing function, and deletes it. 1188 void MachineBasicBlock::eraseFromParent() { 1189 assert(getParent() && "Not embedded in a function!"); 1190 getParent()->erase(this); 1191 } 1192 1193 /// Given a machine basic block that branched to 'Old', change the code and CFG 1194 /// so that it branches to 'New' instead. 1195 void MachineBasicBlock::ReplaceUsesOfBlockWith(MachineBasicBlock *Old, 1196 MachineBasicBlock *New) { 1197 assert(Old != New && "Cannot replace self with self!"); 1198 1199 MachineBasicBlock::instr_iterator I = instr_end(); 1200 while (I != instr_begin()) { 1201 --I; 1202 if (!I->isTerminator()) break; 1203 1204 // Scan the operands of this machine instruction, replacing any uses of Old 1205 // with New. 1206 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) 1207 if (I->getOperand(i).isMBB() && 1208 I->getOperand(i).getMBB() == Old) 1209 I->getOperand(i).setMBB(New); 1210 } 1211 1212 // Update the successor information. 1213 replaceSuccessor(Old, New); 1214 } 1215 1216 /// Various pieces of code can cause excess edges in the CFG to be inserted. If 1217 /// we have proven that MBB can only branch to DestA and DestB, remove any other 1218 /// MBB successors from the CFG. DestA and DestB can be null. 1219 /// 1220 /// Besides DestA and DestB, retain other edges leading to LandingPads 1221 /// (currently there can be only one; we don't check or require that here). 1222 /// Note it is possible that DestA and/or DestB are LandingPads. 1223 bool MachineBasicBlock::CorrectExtraCFGEdges(MachineBasicBlock *DestA, 1224 MachineBasicBlock *DestB, 1225 bool IsCond) { 1226 // The values of DestA and DestB frequently come from a call to the 1227 // 'TargetInstrInfo::AnalyzeBranch' method. We take our meaning of the initial 1228 // values from there. 1229 // 1230 // 1. If both DestA and DestB are null, then the block ends with no branches 1231 // (it falls through to its successor). 1232 // 2. If DestA is set, DestB is null, and IsCond is false, then the block ends 1233 // with only an unconditional branch. 1234 // 3. If DestA is set, DestB is null, and IsCond is true, then the block ends 1235 // with a conditional branch that falls through to a successor (DestB). 1236 // 4. If DestA and DestB is set and IsCond is true, then the block ends with a 1237 // conditional branch followed by an unconditional branch. DestA is the 1238 // 'true' destination and DestB is the 'false' destination. 1239 1240 bool Changed = false; 1241 1242 MachineBasicBlock *FallThru = getNextNode(); 1243 1244 if (!DestA && !DestB) { 1245 // Block falls through to successor. 1246 DestA = FallThru; 1247 DestB = FallThru; 1248 } else if (DestA && !DestB) { 1249 if (IsCond) 1250 // Block ends in conditional jump that falls through to successor. 1251 DestB = FallThru; 1252 } else { 1253 assert(DestA && DestB && IsCond && 1254 "CFG in a bad state. Cannot correct CFG edges"); 1255 } 1256 1257 // Remove superfluous edges. I.e., those which aren't destinations of this 1258 // basic block, duplicate edges, or landing pads. 1259 SmallPtrSet<const MachineBasicBlock*, 8> SeenMBBs; 1260 MachineBasicBlock::succ_iterator SI = succ_begin(); 1261 while (SI != succ_end()) { 1262 const MachineBasicBlock *MBB = *SI; 1263 if (!SeenMBBs.insert(MBB).second || 1264 (MBB != DestA && MBB != DestB && !MBB->isEHPad())) { 1265 // This is a superfluous edge, remove it. 1266 SI = removeSuccessor(SI); 1267 Changed = true; 1268 } else { 1269 ++SI; 1270 } 1271 } 1272 1273 if (Changed) 1274 normalizeSuccProbs(); 1275 return Changed; 1276 } 1277 1278 /// Find the next valid DebugLoc starting at MBBI, skipping any DBG_VALUE 1279 /// instructions. Return UnknownLoc if there is none. 1280 DebugLoc 1281 MachineBasicBlock::findDebugLoc(instr_iterator MBBI) { 1282 // Skip debug declarations, we don't want a DebugLoc from them. 1283 MBBI = skipDebugInstructionsForward(MBBI, instr_end()); 1284 if (MBBI != instr_end()) 1285 return MBBI->getDebugLoc(); 1286 return {}; 1287 } 1288 1289 /// Find the previous valid DebugLoc preceding MBBI, skipping and DBG_VALUE 1290 /// instructions. Return UnknownLoc if there is none. 1291 DebugLoc MachineBasicBlock::findPrevDebugLoc(instr_iterator MBBI) { 1292 if (MBBI == instr_begin()) return {}; 1293 // Skip debug declarations, we don't want a DebugLoc from them. 1294 MBBI = skipDebugInstructionsBackward(std::prev(MBBI), instr_begin()); 1295 if (!MBBI->isDebugInstr()) return MBBI->getDebugLoc(); 1296 return {}; 1297 } 1298 1299 /// Find and return the merged DebugLoc of the branch instructions of the block. 1300 /// Return UnknownLoc if there is none. 1301 DebugLoc 1302 MachineBasicBlock::findBranchDebugLoc() { 1303 DebugLoc DL; 1304 auto TI = getFirstTerminator(); 1305 while (TI != end() && !TI->isBranch()) 1306 ++TI; 1307 1308 if (TI != end()) { 1309 DL = TI->getDebugLoc(); 1310 for (++TI ; TI != end() ; ++TI) 1311 if (TI->isBranch()) 1312 DL = DILocation::getMergedLocation(DL, TI->getDebugLoc()); 1313 } 1314 return DL; 1315 } 1316 1317 /// Return probability of the edge from this block to MBB. 1318 BranchProbability 1319 MachineBasicBlock::getSuccProbability(const_succ_iterator Succ) const { 1320 if (Probs.empty()) 1321 return BranchProbability(1, succ_size()); 1322 1323 const auto &Prob = *getProbabilityIterator(Succ); 1324 if (Prob.isUnknown()) { 1325 // For unknown probabilities, collect the sum of all known ones, and evenly 1326 // ditribute the complemental of the sum to each unknown probability. 1327 unsigned KnownProbNum = 0; 1328 auto Sum = BranchProbability::getZero(); 1329 for (auto &P : Probs) { 1330 if (!P.isUnknown()) { 1331 Sum += P; 1332 KnownProbNum++; 1333 } 1334 } 1335 return Sum.getCompl() / (Probs.size() - KnownProbNum); 1336 } else 1337 return Prob; 1338 } 1339 1340 /// Set successor probability of a given iterator. 1341 void MachineBasicBlock::setSuccProbability(succ_iterator I, 1342 BranchProbability Prob) { 1343 assert(!Prob.isUnknown()); 1344 if (Probs.empty()) 1345 return; 1346 *getProbabilityIterator(I) = Prob; 1347 } 1348 1349 /// Return probability iterator corresonding to the I successor iterator 1350 MachineBasicBlock::const_probability_iterator 1351 MachineBasicBlock::getProbabilityIterator( 1352 MachineBasicBlock::const_succ_iterator I) const { 1353 assert(Probs.size() == Successors.size() && "Async probability list!"); 1354 const size_t index = std::distance(Successors.begin(), I); 1355 assert(index < Probs.size() && "Not a current successor!"); 1356 return Probs.begin() + index; 1357 } 1358 1359 /// Return probability iterator corresonding to the I successor iterator. 1360 MachineBasicBlock::probability_iterator 1361 MachineBasicBlock::getProbabilityIterator(MachineBasicBlock::succ_iterator I) { 1362 assert(Probs.size() == Successors.size() && "Async probability list!"); 1363 const size_t index = std::distance(Successors.begin(), I); 1364 assert(index < Probs.size() && "Not a current successor!"); 1365 return Probs.begin() + index; 1366 } 1367 1368 /// Return whether (physical) register "Reg" has been <def>ined and not <kill>ed 1369 /// as of just before "MI". 1370 /// 1371 /// Search is localised to a neighborhood of 1372 /// Neighborhood instructions before (searching for defs or kills) and N 1373 /// instructions after (searching just for defs) MI. 1374 MachineBasicBlock::LivenessQueryResult 1375 MachineBasicBlock::computeRegisterLiveness(const TargetRegisterInfo *TRI, 1376 unsigned Reg, const_iterator Before, 1377 unsigned Neighborhood) const { 1378 unsigned N = Neighborhood; 1379 1380 // Try searching forwards from Before, looking for reads or defs. 1381 const_iterator I(Before); 1382 for (; I != end() && N > 0; ++I) { 1383 if (I->isDebugInstr()) 1384 continue; 1385 1386 --N; 1387 1388 MachineOperandIteratorBase::PhysRegInfo Info = 1389 ConstMIOperands(*I).analyzePhysReg(Reg, TRI); 1390 1391 // Register is live when we read it here. 1392 if (Info.Read) 1393 return LQR_Live; 1394 // Register is dead if we can fully overwrite or clobber it here. 1395 if (Info.FullyDefined || Info.Clobbered) 1396 return LQR_Dead; 1397 } 1398 1399 // If we reached the end, it is safe to clobber Reg at the end of a block of 1400 // no successor has it live in. 1401 if (I == end()) { 1402 for (MachineBasicBlock *S : successors()) { 1403 for (const MachineBasicBlock::RegisterMaskPair &LI : S->liveins()) { 1404 if (TRI->regsOverlap(LI.PhysReg, Reg)) 1405 return LQR_Live; 1406 } 1407 } 1408 1409 return LQR_Dead; 1410 } 1411 1412 1413 N = Neighborhood; 1414 1415 // Start by searching backwards from Before, looking for kills, reads or defs. 1416 I = const_iterator(Before); 1417 // If this is the first insn in the block, don't search backwards. 1418 if (I != begin()) { 1419 do { 1420 --I; 1421 1422 if (I->isDebugInstr()) 1423 continue; 1424 1425 --N; 1426 1427 MachineOperandIteratorBase::PhysRegInfo Info = 1428 ConstMIOperands(*I).analyzePhysReg(Reg, TRI); 1429 1430 // Defs happen after uses so they take precedence if both are present. 1431 1432 // Register is dead after a dead def of the full register. 1433 if (Info.DeadDef) 1434 return LQR_Dead; 1435 // Register is (at least partially) live after a def. 1436 if (Info.Defined) { 1437 if (!Info.PartialDeadDef) 1438 return LQR_Live; 1439 // As soon as we saw a partial definition (dead or not), 1440 // we cannot tell if the value is partial live without 1441 // tracking the lanemasks. We are not going to do this, 1442 // so fall back on the remaining of the analysis. 1443 break; 1444 } 1445 // Register is dead after a full kill or clobber and no def. 1446 if (Info.Killed || Info.Clobbered) 1447 return LQR_Dead; 1448 // Register must be live if we read it. 1449 if (Info.Read) 1450 return LQR_Live; 1451 1452 } while (I != begin() && N > 0); 1453 } 1454 1455 // Did we get to the start of the block? 1456 if (I == begin()) { 1457 // If so, the register's state is definitely defined by the live-in state. 1458 for (const MachineBasicBlock::RegisterMaskPair &LI : liveins()) 1459 if (TRI->regsOverlap(LI.PhysReg, Reg)) 1460 return LQR_Live; 1461 1462 return LQR_Dead; 1463 } 1464 1465 // At this point we have no idea of the liveness of the register. 1466 return LQR_Unknown; 1467 } 1468 1469 const uint32_t * 1470 MachineBasicBlock::getBeginClobberMask(const TargetRegisterInfo *TRI) const { 1471 // EH funclet entry does not preserve any registers. 1472 return isEHFuncletEntry() ? TRI->getNoPreservedMask() : nullptr; 1473 } 1474 1475 const uint32_t * 1476 MachineBasicBlock::getEndClobberMask(const TargetRegisterInfo *TRI) const { 1477 // If we see a return block with successors, this must be a funclet return, 1478 // which does not preserve any registers. If there are no successors, we don't 1479 // care what kind of return it is, putting a mask after it is a no-op. 1480 return isReturnBlock() && !succ_empty() ? TRI->getNoPreservedMask() : nullptr; 1481 } 1482 1483 void MachineBasicBlock::clearLiveIns() { 1484 LiveIns.clear(); 1485 } 1486 1487 MachineBasicBlock::livein_iterator MachineBasicBlock::livein_begin() const { 1488 assert(getParent()->getProperties().hasProperty( 1489 MachineFunctionProperties::Property::TracksLiveness) && 1490 "Liveness information is accurate"); 1491 return LiveIns.begin(); 1492 } 1493