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