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