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