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