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