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