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