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