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