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 if (!livein_empty() && MRI.tracksLiveness()) { 329 if (Indexes) OS << '\t'; 330 OS.indent(2) << "liveins: "; 331 332 bool First = true; 333 for (const auto &LI : liveins()) { 334 if (!First) 335 OS << ", "; 336 First = false; 337 OS << printReg(LI.PhysReg, TRI); 338 if (!LI.LaneMask.all()) 339 OS << ":0x" << PrintLaneMask(LI.LaneMask); 340 } 341 OS << '\n'; 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()) { 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 OS << '\n'; 372 } 373 } 374 375 // Print the preds of this block according to the CFG. 376 if (!pred_empty()) { 377 if (Indexes) OS << '\t'; 378 // Don't indent(2), align with previous line attributes. 379 OS << "; predecessors: "; 380 for (auto I = pred_begin(), E = pred_end(); I != E; ++I) { 381 if (I != pred_begin()) 382 OS << ", "; 383 OS << printMBBReference(**I); 384 } 385 OS << '\n'; 386 } 387 388 bool IsInBundle = false; 389 for (const MachineInstr &MI : instrs()) { 390 if (Indexes) { 391 if (Indexes->hasIndex(MI)) 392 OS << Indexes->getInstructionIndex(MI); 393 OS << '\t'; 394 } 395 396 if (IsInBundle && !MI.isInsideBundle()) { 397 OS.indent(2) << "}\n"; 398 IsInBundle = false; 399 } 400 401 OS.indent(IsInBundle ? 4 : 2); 402 MI.print(OS, MST, IsStandalone, /*SkipOpers=*/false, /*SkipDebugLoc=*/false, 403 &TII); 404 405 if (!IsInBundle && MI.getFlag(MachineInstr::BundledSucc)) { 406 OS << " {"; 407 IsInBundle = true; 408 } 409 410 OS << '\n'; 411 } 412 413 if (IsInBundle) 414 OS.indent(2) << "}\n"; 415 416 if (IrrLoopHeaderWeight) { 417 if (Indexes) OS << '\t'; 418 OS << " Irreducible loop header weight: " 419 << IrrLoopHeaderWeight.getValue(); 420 OS << '\n'; 421 } 422 } 423 424 void MachineBasicBlock::printAsOperand(raw_ostream &OS, 425 bool /*PrintType*/) const { 426 OS << "%bb." << getNumber(); 427 } 428 429 void MachineBasicBlock::removeLiveIn(MCPhysReg Reg, LaneBitmask LaneMask) { 430 LiveInVector::iterator I = find_if( 431 LiveIns, [Reg](const RegisterMaskPair &LI) { return LI.PhysReg == Reg; }); 432 if (I == LiveIns.end()) 433 return; 434 435 I->LaneMask &= ~LaneMask; 436 if (I->LaneMask.none()) 437 LiveIns.erase(I); 438 } 439 440 MachineBasicBlock::livein_iterator 441 MachineBasicBlock::removeLiveIn(MachineBasicBlock::livein_iterator I) { 442 // Get non-const version of iterator. 443 LiveInVector::iterator LI = LiveIns.begin() + (I - LiveIns.begin()); 444 return LiveIns.erase(LI); 445 } 446 447 bool MachineBasicBlock::isLiveIn(MCPhysReg Reg, LaneBitmask LaneMask) const { 448 livein_iterator I = find_if( 449 LiveIns, [Reg](const RegisterMaskPair &LI) { return LI.PhysReg == Reg; }); 450 return I != livein_end() && (I->LaneMask & LaneMask).any(); 451 } 452 453 void MachineBasicBlock::sortUniqueLiveIns() { 454 std::sort(LiveIns.begin(), LiveIns.end(), 455 [](const RegisterMaskPair &LI0, const RegisterMaskPair &LI1) { 456 return LI0.PhysReg < LI1.PhysReg; 457 }); 458 // Liveins are sorted by physreg now we can merge their lanemasks. 459 LiveInVector::const_iterator I = LiveIns.begin(); 460 LiveInVector::const_iterator J; 461 LiveInVector::iterator Out = LiveIns.begin(); 462 for (; I != LiveIns.end(); ++Out, I = J) { 463 unsigned PhysReg = I->PhysReg; 464 LaneBitmask LaneMask = I->LaneMask; 465 for (J = std::next(I); J != LiveIns.end() && J->PhysReg == PhysReg; ++J) 466 LaneMask |= J->LaneMask; 467 Out->PhysReg = PhysReg; 468 Out->LaneMask = LaneMask; 469 } 470 LiveIns.erase(Out, LiveIns.end()); 471 } 472 473 unsigned 474 MachineBasicBlock::addLiveIn(MCPhysReg PhysReg, const TargetRegisterClass *RC) { 475 assert(getParent() && "MBB must be inserted in function"); 476 assert(TargetRegisterInfo::isPhysicalRegister(PhysReg) && "Expected physreg"); 477 assert(RC && "Register class is required"); 478 assert((isEHPad() || this == &getParent()->front()) && 479 "Only the entry block and landing pads can have physreg live ins"); 480 481 bool LiveIn = isLiveIn(PhysReg); 482 iterator I = SkipPHIsAndLabels(begin()), E = end(); 483 MachineRegisterInfo &MRI = getParent()->getRegInfo(); 484 const TargetInstrInfo &TII = *getParent()->getSubtarget().getInstrInfo(); 485 486 // Look for an existing copy. 487 if (LiveIn) 488 for (;I != E && I->isCopy(); ++I) 489 if (I->getOperand(1).getReg() == PhysReg) { 490 unsigned VirtReg = I->getOperand(0).getReg(); 491 if (!MRI.constrainRegClass(VirtReg, RC)) 492 llvm_unreachable("Incompatible live-in register class."); 493 return VirtReg; 494 } 495 496 // No luck, create a virtual register. 497 unsigned VirtReg = MRI.createVirtualRegister(RC); 498 BuildMI(*this, I, DebugLoc(), TII.get(TargetOpcode::COPY), VirtReg) 499 .addReg(PhysReg, RegState::Kill); 500 if (!LiveIn) 501 addLiveIn(PhysReg); 502 return VirtReg; 503 } 504 505 void MachineBasicBlock::moveBefore(MachineBasicBlock *NewAfter) { 506 getParent()->splice(NewAfter->getIterator(), getIterator()); 507 } 508 509 void MachineBasicBlock::moveAfter(MachineBasicBlock *NewBefore) { 510 getParent()->splice(++NewBefore->getIterator(), getIterator()); 511 } 512 513 void MachineBasicBlock::updateTerminator() { 514 const TargetInstrInfo *TII = getParent()->getSubtarget().getInstrInfo(); 515 // A block with no successors has no concerns with fall-through edges. 516 if (this->succ_empty()) 517 return; 518 519 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; 520 SmallVector<MachineOperand, 4> Cond; 521 DebugLoc DL = findBranchDebugLoc(); 522 bool B = TII->analyzeBranch(*this, TBB, FBB, Cond); 523 (void) B; 524 assert(!B && "UpdateTerminators requires analyzable predecessors!"); 525 if (Cond.empty()) { 526 if (TBB) { 527 // The block has an unconditional branch. If its successor is now its 528 // layout successor, delete the branch. 529 if (isLayoutSuccessor(TBB)) 530 TII->removeBranch(*this); 531 } else { 532 // The block has an unconditional fallthrough. If its successor is not its 533 // layout successor, insert a branch. First we have to locate the only 534 // non-landing-pad successor, as that is the fallthrough block. 535 for (succ_iterator SI = succ_begin(), SE = succ_end(); SI != SE; ++SI) { 536 if ((*SI)->isEHPad()) 537 continue; 538 assert(!TBB && "Found more than one non-landing-pad successor!"); 539 TBB = *SI; 540 } 541 542 // If there is no non-landing-pad successor, the block has no fall-through 543 // edges to be concerned with. 544 if (!TBB) 545 return; 546 547 // Finally update the unconditional successor to be reached via a branch 548 // if it would not be reached by fallthrough. 549 if (!isLayoutSuccessor(TBB)) 550 TII->insertBranch(*this, TBB, nullptr, Cond, DL); 551 } 552 return; 553 } 554 555 if (FBB) { 556 // The block has a non-fallthrough conditional branch. If one of its 557 // successors is its layout successor, rewrite it to a fallthrough 558 // conditional branch. 559 if (isLayoutSuccessor(TBB)) { 560 if (TII->reverseBranchCondition(Cond)) 561 return; 562 TII->removeBranch(*this); 563 TII->insertBranch(*this, FBB, nullptr, Cond, DL); 564 } else if (isLayoutSuccessor(FBB)) { 565 TII->removeBranch(*this); 566 TII->insertBranch(*this, TBB, nullptr, Cond, DL); 567 } 568 return; 569 } 570 571 // Walk through the successors and find the successor which is not a landing 572 // pad and is not the conditional branch destination (in TBB) as the 573 // fallthrough successor. 574 MachineBasicBlock *FallthroughBB = nullptr; 575 for (succ_iterator SI = succ_begin(), SE = succ_end(); SI != SE; ++SI) { 576 if ((*SI)->isEHPad() || *SI == TBB) 577 continue; 578 assert(!FallthroughBB && "Found more than one fallthrough successor."); 579 FallthroughBB = *SI; 580 } 581 582 if (!FallthroughBB) { 583 if (canFallThrough()) { 584 // We fallthrough to the same basic block as the conditional jump targets. 585 // Remove the conditional jump, leaving unconditional fallthrough. 586 // FIXME: This does not seem like a reasonable pattern to support, but it 587 // has been seen in the wild coming out of degenerate ARM test cases. 588 TII->removeBranch(*this); 589 590 // Finally update the unconditional successor to be reached via a branch if 591 // it would not be reached by fallthrough. 592 if (!isLayoutSuccessor(TBB)) 593 TII->insertBranch(*this, TBB, nullptr, Cond, DL); 594 return; 595 } 596 597 // We enter here iff exactly one successor is TBB which cannot fallthrough 598 // and the rest successors if any are EHPads. In this case, we need to 599 // change the conditional branch into unconditional branch. 600 TII->removeBranch(*this); 601 Cond.clear(); 602 TII->insertBranch(*this, TBB, nullptr, Cond, DL); 603 return; 604 } 605 606 // The block has a fallthrough conditional branch. 607 if (isLayoutSuccessor(TBB)) { 608 if (TII->reverseBranchCondition(Cond)) { 609 // We can't reverse the condition, add an unconditional branch. 610 Cond.clear(); 611 TII->insertBranch(*this, FallthroughBB, nullptr, Cond, DL); 612 return; 613 } 614 TII->removeBranch(*this); 615 TII->insertBranch(*this, FallthroughBB, nullptr, Cond, DL); 616 } else if (!isLayoutSuccessor(FallthroughBB)) { 617 TII->removeBranch(*this); 618 TII->insertBranch(*this, TBB, FallthroughBB, Cond, DL); 619 } 620 } 621 622 void MachineBasicBlock::validateSuccProbs() const { 623 #ifndef NDEBUG 624 int64_t Sum = 0; 625 for (auto Prob : Probs) 626 Sum += Prob.getNumerator(); 627 // Due to precision issue, we assume that the sum of probabilities is one if 628 // the difference between the sum of their numerators and the denominator is 629 // no greater than the number of successors. 630 assert((uint64_t)std::abs(Sum - BranchProbability::getDenominator()) <= 631 Probs.size() && 632 "The sum of successors's probabilities exceeds one."); 633 #endif // NDEBUG 634 } 635 636 void MachineBasicBlock::addSuccessor(MachineBasicBlock *Succ, 637 BranchProbability Prob) { 638 // Probability list is either empty (if successor list isn't empty, this means 639 // disabled optimization) or has the same size as successor list. 640 if (!(Probs.empty() && !Successors.empty())) 641 Probs.push_back(Prob); 642 Successors.push_back(Succ); 643 Succ->addPredecessor(this); 644 } 645 646 void MachineBasicBlock::addSuccessorWithoutProb(MachineBasicBlock *Succ) { 647 // We need to make sure probability list is either empty or has the same size 648 // of successor list. When this function is called, we can safely delete all 649 // probability in the list. 650 Probs.clear(); 651 Successors.push_back(Succ); 652 Succ->addPredecessor(this); 653 } 654 655 void MachineBasicBlock::removeSuccessor(MachineBasicBlock *Succ, 656 bool NormalizeSuccProbs) { 657 succ_iterator I = find(Successors, Succ); 658 removeSuccessor(I, NormalizeSuccProbs); 659 } 660 661 MachineBasicBlock::succ_iterator 662 MachineBasicBlock::removeSuccessor(succ_iterator I, bool NormalizeSuccProbs) { 663 assert(I != Successors.end() && "Not a current successor!"); 664 665 // If probability list is empty it means we don't use it (disabled 666 // optimization). 667 if (!Probs.empty()) { 668 probability_iterator WI = getProbabilityIterator(I); 669 Probs.erase(WI); 670 if (NormalizeSuccProbs) 671 normalizeSuccProbs(); 672 } 673 674 (*I)->removePredecessor(this); 675 return Successors.erase(I); 676 } 677 678 void MachineBasicBlock::replaceSuccessor(MachineBasicBlock *Old, 679 MachineBasicBlock *New) { 680 if (Old == New) 681 return; 682 683 succ_iterator E = succ_end(); 684 succ_iterator NewI = E; 685 succ_iterator OldI = E; 686 for (succ_iterator I = succ_begin(); I != E; ++I) { 687 if (*I == Old) { 688 OldI = I; 689 if (NewI != E) 690 break; 691 } 692 if (*I == New) { 693 NewI = I; 694 if (OldI != E) 695 break; 696 } 697 } 698 assert(OldI != E && "Old is not a successor of this block"); 699 700 // If New isn't already a successor, let it take Old's place. 701 if (NewI == E) { 702 Old->removePredecessor(this); 703 New->addPredecessor(this); 704 *OldI = New; 705 return; 706 } 707 708 // New is already a successor. 709 // Update its probability instead of adding a duplicate edge. 710 if (!Probs.empty()) { 711 auto ProbIter = getProbabilityIterator(NewI); 712 if (!ProbIter->isUnknown()) 713 *ProbIter += *getProbabilityIterator(OldI); 714 } 715 removeSuccessor(OldI); 716 } 717 718 void MachineBasicBlock::addPredecessor(MachineBasicBlock *Pred) { 719 Predecessors.push_back(Pred); 720 } 721 722 void MachineBasicBlock::removePredecessor(MachineBasicBlock *Pred) { 723 pred_iterator I = find(Predecessors, Pred); 724 assert(I != Predecessors.end() && "Pred is not a predecessor of this block!"); 725 Predecessors.erase(I); 726 } 727 728 void MachineBasicBlock::transferSuccessors(MachineBasicBlock *FromMBB) { 729 if (this == FromMBB) 730 return; 731 732 while (!FromMBB->succ_empty()) { 733 MachineBasicBlock *Succ = *FromMBB->succ_begin(); 734 735 // If probability list is empty it means we don't use it (disabled optimization). 736 if (!FromMBB->Probs.empty()) { 737 auto Prob = *FromMBB->Probs.begin(); 738 addSuccessor(Succ, Prob); 739 } else 740 addSuccessorWithoutProb(Succ); 741 742 FromMBB->removeSuccessor(Succ); 743 } 744 } 745 746 void 747 MachineBasicBlock::transferSuccessorsAndUpdatePHIs(MachineBasicBlock *FromMBB) { 748 if (this == FromMBB) 749 return; 750 751 while (!FromMBB->succ_empty()) { 752 MachineBasicBlock *Succ = *FromMBB->succ_begin(); 753 if (!FromMBB->Probs.empty()) { 754 auto Prob = *FromMBB->Probs.begin(); 755 addSuccessor(Succ, Prob); 756 } else 757 addSuccessorWithoutProb(Succ); 758 FromMBB->removeSuccessor(Succ); 759 760 // Fix up any PHI nodes in the successor. 761 for (MachineBasicBlock::instr_iterator MI = Succ->instr_begin(), 762 ME = Succ->instr_end(); MI != ME && MI->isPHI(); ++MI) 763 for (unsigned i = 2, e = MI->getNumOperands()+1; i != e; i += 2) { 764 MachineOperand &MO = MI->getOperand(i); 765 if (MO.getMBB() == FromMBB) 766 MO.setMBB(this); 767 } 768 } 769 normalizeSuccProbs(); 770 } 771 772 bool MachineBasicBlock::isPredecessor(const MachineBasicBlock *MBB) const { 773 return is_contained(predecessors(), MBB); 774 } 775 776 bool MachineBasicBlock::isSuccessor(const MachineBasicBlock *MBB) const { 777 return is_contained(successors(), MBB); 778 } 779 780 bool MachineBasicBlock::isLayoutSuccessor(const MachineBasicBlock *MBB) const { 781 MachineFunction::const_iterator I(this); 782 return std::next(I) == MachineFunction::const_iterator(MBB); 783 } 784 785 MachineBasicBlock *MachineBasicBlock::getFallThrough() { 786 MachineFunction::iterator Fallthrough = getIterator(); 787 ++Fallthrough; 788 // If FallthroughBlock is off the end of the function, it can't fall through. 789 if (Fallthrough == getParent()->end()) 790 return nullptr; 791 792 // If FallthroughBlock isn't a successor, no fallthrough is possible. 793 if (!isSuccessor(&*Fallthrough)) 794 return nullptr; 795 796 // Analyze the branches, if any, at the end of the block. 797 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; 798 SmallVector<MachineOperand, 4> Cond; 799 const TargetInstrInfo *TII = getParent()->getSubtarget().getInstrInfo(); 800 if (TII->analyzeBranch(*this, TBB, FBB, Cond)) { 801 // If we couldn't analyze the branch, examine the last instruction. 802 // If the block doesn't end in a known control barrier, assume fallthrough 803 // is possible. The isPredicated check is needed because this code can be 804 // called during IfConversion, where an instruction which is normally a 805 // Barrier is predicated and thus no longer an actual control barrier. 806 return (empty() || !back().isBarrier() || TII->isPredicated(back())) 807 ? &*Fallthrough 808 : nullptr; 809 } 810 811 // If there is no branch, control always falls through. 812 if (!TBB) return &*Fallthrough; 813 814 // If there is some explicit branch to the fallthrough block, it can obviously 815 // reach, even though the branch should get folded to fall through implicitly. 816 if (MachineFunction::iterator(TBB) == Fallthrough || 817 MachineFunction::iterator(FBB) == Fallthrough) 818 return &*Fallthrough; 819 820 // If it's an unconditional branch to some block not the fall through, it 821 // doesn't fall through. 822 if (Cond.empty()) return nullptr; 823 824 // Otherwise, if it is conditional and has no explicit false block, it falls 825 // through. 826 return (FBB == nullptr) ? &*Fallthrough : nullptr; 827 } 828 829 bool MachineBasicBlock::canFallThrough() { 830 return getFallThrough() != nullptr; 831 } 832 833 MachineBasicBlock *MachineBasicBlock::SplitCriticalEdge(MachineBasicBlock *Succ, 834 Pass &P) { 835 if (!canSplitCriticalEdge(Succ)) 836 return nullptr; 837 838 MachineFunction *MF = getParent(); 839 DebugLoc DL; // FIXME: this is nowhere 840 841 MachineBasicBlock *NMBB = MF->CreateMachineBasicBlock(); 842 MF->insert(std::next(MachineFunction::iterator(this)), NMBB); 843 DEBUG(dbgs() << "Splitting critical edge: " << printMBBReference(*this) 844 << " -- " << printMBBReference(*NMBB) << " -- " 845 << printMBBReference(*Succ) << '\n'); 846 847 LiveIntervals *LIS = P.getAnalysisIfAvailable<LiveIntervals>(); 848 SlotIndexes *Indexes = P.getAnalysisIfAvailable<SlotIndexes>(); 849 if (LIS) 850 LIS->insertMBBInMaps(NMBB); 851 else if (Indexes) 852 Indexes->insertMBBInMaps(NMBB); 853 854 // On some targets like Mips, branches may kill virtual registers. Make sure 855 // that LiveVariables is properly updated after updateTerminator replaces the 856 // terminators. 857 LiveVariables *LV = P.getAnalysisIfAvailable<LiveVariables>(); 858 859 // Collect a list of virtual registers killed by the terminators. 860 SmallVector<unsigned, 4> KilledRegs; 861 if (LV) 862 for (instr_iterator I = getFirstInstrTerminator(), E = instr_end(); 863 I != E; ++I) { 864 MachineInstr *MI = &*I; 865 for (MachineInstr::mop_iterator OI = MI->operands_begin(), 866 OE = MI->operands_end(); OI != OE; ++OI) { 867 if (!OI->isReg() || OI->getReg() == 0 || 868 !OI->isUse() || !OI->isKill() || OI->isUndef()) 869 continue; 870 unsigned Reg = OI->getReg(); 871 if (TargetRegisterInfo::isPhysicalRegister(Reg) || 872 LV->getVarInfo(Reg).removeKill(*MI)) { 873 KilledRegs.push_back(Reg); 874 DEBUG(dbgs() << "Removing terminator kill: " << *MI); 875 OI->setIsKill(false); 876 } 877 } 878 } 879 880 SmallVector<unsigned, 4> UsedRegs; 881 if (LIS) { 882 for (instr_iterator I = getFirstInstrTerminator(), E = instr_end(); 883 I != E; ++I) { 884 MachineInstr *MI = &*I; 885 886 for (MachineInstr::mop_iterator OI = MI->operands_begin(), 887 OE = MI->operands_end(); OI != OE; ++OI) { 888 if (!OI->isReg() || OI->getReg() == 0) 889 continue; 890 891 unsigned Reg = OI->getReg(); 892 if (!is_contained(UsedRegs, Reg)) 893 UsedRegs.push_back(Reg); 894 } 895 } 896 } 897 898 ReplaceUsesOfBlockWith(Succ, NMBB); 899 900 // If updateTerminator() removes instructions, we need to remove them from 901 // SlotIndexes. 902 SmallVector<MachineInstr*, 4> Terminators; 903 if (Indexes) { 904 for (instr_iterator I = getFirstInstrTerminator(), E = instr_end(); 905 I != E; ++I) 906 Terminators.push_back(&*I); 907 } 908 909 updateTerminator(); 910 911 if (Indexes) { 912 SmallVector<MachineInstr*, 4> NewTerminators; 913 for (instr_iterator I = getFirstInstrTerminator(), E = instr_end(); 914 I != E; ++I) 915 NewTerminators.push_back(&*I); 916 917 for (SmallVectorImpl<MachineInstr*>::iterator I = Terminators.begin(), 918 E = Terminators.end(); I != E; ++I) { 919 if (!is_contained(NewTerminators, *I)) 920 Indexes->removeMachineInstrFromMaps(**I); 921 } 922 } 923 924 // Insert unconditional "jump Succ" instruction in NMBB if necessary. 925 NMBB->addSuccessor(Succ); 926 if (!NMBB->isLayoutSuccessor(Succ)) { 927 SmallVector<MachineOperand, 4> Cond; 928 const TargetInstrInfo *TII = getParent()->getSubtarget().getInstrInfo(); 929 TII->insertBranch(*NMBB, Succ, nullptr, Cond, DL); 930 931 if (Indexes) { 932 for (MachineInstr &MI : NMBB->instrs()) { 933 // Some instructions may have been moved to NMBB by updateTerminator(), 934 // so we first remove any instruction that already has an index. 935 if (Indexes->hasIndex(MI)) 936 Indexes->removeMachineInstrFromMaps(MI); 937 Indexes->insertMachineInstrInMaps(MI); 938 } 939 } 940 } 941 942 // Fix PHI nodes in Succ so they refer to NMBB instead of this 943 for (MachineBasicBlock::instr_iterator 944 i = Succ->instr_begin(),e = Succ->instr_end(); 945 i != e && i->isPHI(); ++i) 946 for (unsigned ni = 1, ne = i->getNumOperands(); ni != ne; ni += 2) 947 if (i->getOperand(ni+1).getMBB() == this) 948 i->getOperand(ni+1).setMBB(NMBB); 949 950 // Inherit live-ins from the successor 951 for (const auto &LI : Succ->liveins()) 952 NMBB->addLiveIn(LI); 953 954 // Update LiveVariables. 955 const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo(); 956 if (LV) { 957 // Restore kills of virtual registers that were killed by the terminators. 958 while (!KilledRegs.empty()) { 959 unsigned Reg = KilledRegs.pop_back_val(); 960 for (instr_iterator I = instr_end(), E = instr_begin(); I != E;) { 961 if (!(--I)->addRegisterKilled(Reg, TRI, /* addIfNotFound= */ false)) 962 continue; 963 if (TargetRegisterInfo::isVirtualRegister(Reg)) 964 LV->getVarInfo(Reg).Kills.push_back(&*I); 965 DEBUG(dbgs() << "Restored terminator kill: " << *I); 966 break; 967 } 968 } 969 // Update relevant live-through information. 970 LV->addNewBlock(NMBB, this, Succ); 971 } 972 973 if (LIS) { 974 // After splitting the edge and updating SlotIndexes, live intervals may be 975 // in one of two situations, depending on whether this block was the last in 976 // the function. If the original block was the last in the function, all 977 // live intervals will end prior to the beginning of the new split block. If 978 // the original block was not at the end of the function, all live intervals 979 // will extend to the end of the new split block. 980 981 bool isLastMBB = 982 std::next(MachineFunction::iterator(NMBB)) == getParent()->end(); 983 984 SlotIndex StartIndex = Indexes->getMBBEndIdx(this); 985 SlotIndex PrevIndex = StartIndex.getPrevSlot(); 986 SlotIndex EndIndex = Indexes->getMBBEndIdx(NMBB); 987 988 // Find the registers used from NMBB in PHIs in Succ. 989 SmallSet<unsigned, 8> PHISrcRegs; 990 for (MachineBasicBlock::instr_iterator 991 I = Succ->instr_begin(), E = Succ->instr_end(); 992 I != E && I->isPHI(); ++I) { 993 for (unsigned ni = 1, ne = I->getNumOperands(); ni != ne; ni += 2) { 994 if (I->getOperand(ni+1).getMBB() == NMBB) { 995 MachineOperand &MO = I->getOperand(ni); 996 unsigned Reg = MO.getReg(); 997 PHISrcRegs.insert(Reg); 998 if (MO.isUndef()) 999 continue; 1000 1001 LiveInterval &LI = LIS->getInterval(Reg); 1002 VNInfo *VNI = LI.getVNInfoAt(PrevIndex); 1003 assert(VNI && 1004 "PHI sources should be live out of their predecessors."); 1005 LI.addSegment(LiveInterval::Segment(StartIndex, EndIndex, VNI)); 1006 } 1007 } 1008 } 1009 1010 MachineRegisterInfo *MRI = &getParent()->getRegInfo(); 1011 for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) { 1012 unsigned Reg = TargetRegisterInfo::index2VirtReg(i); 1013 if (PHISrcRegs.count(Reg) || !LIS->hasInterval(Reg)) 1014 continue; 1015 1016 LiveInterval &LI = LIS->getInterval(Reg); 1017 if (!LI.liveAt(PrevIndex)) 1018 continue; 1019 1020 bool isLiveOut = LI.liveAt(LIS->getMBBStartIdx(Succ)); 1021 if (isLiveOut && isLastMBB) { 1022 VNInfo *VNI = LI.getVNInfoAt(PrevIndex); 1023 assert(VNI && "LiveInterval should have VNInfo where it is live."); 1024 LI.addSegment(LiveInterval::Segment(StartIndex, EndIndex, VNI)); 1025 } else if (!isLiveOut && !isLastMBB) { 1026 LI.removeSegment(StartIndex, EndIndex); 1027 } 1028 } 1029 1030 // Update all intervals for registers whose uses may have been modified by 1031 // updateTerminator(). 1032 LIS->repairIntervalsInRange(this, getFirstTerminator(), end(), UsedRegs); 1033 } 1034 1035 if (MachineDominatorTree *MDT = 1036 P.getAnalysisIfAvailable<MachineDominatorTree>()) 1037 MDT->recordSplitCriticalEdge(this, Succ, NMBB); 1038 1039 if (MachineLoopInfo *MLI = P.getAnalysisIfAvailable<MachineLoopInfo>()) 1040 if (MachineLoop *TIL = MLI->getLoopFor(this)) { 1041 // If one or the other blocks were not in a loop, the new block is not 1042 // either, and thus LI doesn't need to be updated. 1043 if (MachineLoop *DestLoop = MLI->getLoopFor(Succ)) { 1044 if (TIL == DestLoop) { 1045 // Both in the same loop, the NMBB joins loop. 1046 DestLoop->addBasicBlockToLoop(NMBB, MLI->getBase()); 1047 } else if (TIL->contains(DestLoop)) { 1048 // Edge from an outer loop to an inner loop. Add to the outer loop. 1049 TIL->addBasicBlockToLoop(NMBB, MLI->getBase()); 1050 } else if (DestLoop->contains(TIL)) { 1051 // Edge from an inner loop to an outer loop. Add to the outer loop. 1052 DestLoop->addBasicBlockToLoop(NMBB, MLI->getBase()); 1053 } else { 1054 // Edge from two loops with no containment relation. Because these 1055 // are natural loops, we know that the destination block must be the 1056 // header of its loop (adding a branch into a loop elsewhere would 1057 // create an irreducible loop). 1058 assert(DestLoop->getHeader() == Succ && 1059 "Should not create irreducible loops!"); 1060 if (MachineLoop *P = DestLoop->getParentLoop()) 1061 P->addBasicBlockToLoop(NMBB, MLI->getBase()); 1062 } 1063 } 1064 } 1065 1066 return NMBB; 1067 } 1068 1069 bool MachineBasicBlock::canSplitCriticalEdge( 1070 const MachineBasicBlock *Succ) const { 1071 // Splitting the critical edge to a landing pad block is non-trivial. Don't do 1072 // it in this generic function. 1073 if (Succ->isEHPad()) 1074 return false; 1075 1076 const MachineFunction *MF = getParent(); 1077 1078 // Performance might be harmed on HW that implements branching using exec mask 1079 // where both sides of the branches are always executed. 1080 if (MF->getTarget().requiresStructuredCFG()) 1081 return false; 1082 1083 // We may need to update this's terminator, but we can't do that if 1084 // AnalyzeBranch fails. If this uses a jump table, we won't touch it. 1085 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo(); 1086 MachineBasicBlock *TBB = nullptr, *FBB = nullptr; 1087 SmallVector<MachineOperand, 4> Cond; 1088 // AnalyzeBanch should modify this, since we did not allow modification. 1089 if (TII->analyzeBranch(*const_cast<MachineBasicBlock *>(this), TBB, FBB, Cond, 1090 /*AllowModify*/ false)) 1091 return false; 1092 1093 // Avoid bugpoint weirdness: A block may end with a conditional branch but 1094 // jumps to the same MBB is either case. We have duplicate CFG edges in that 1095 // case that we can't handle. Since this never happens in properly optimized 1096 // code, just skip those edges. 1097 if (TBB && TBB == FBB) { 1098 DEBUG(dbgs() << "Won't split critical edge after degenerate " 1099 << printMBBReference(*this) << '\n'); 1100 return false; 1101 } 1102 return true; 1103 } 1104 1105 /// Prepare MI to be removed from its bundle. This fixes bundle flags on MI's 1106 /// neighboring instructions so the bundle won't be broken by removing MI. 1107 static void unbundleSingleMI(MachineInstr *MI) { 1108 // Removing the first instruction in a bundle. 1109 if (MI->isBundledWithSucc() && !MI->isBundledWithPred()) 1110 MI->unbundleFromSucc(); 1111 // Removing the last instruction in a bundle. 1112 if (MI->isBundledWithPred() && !MI->isBundledWithSucc()) 1113 MI->unbundleFromPred(); 1114 // If MI is not bundled, or if it is internal to a bundle, the neighbor flags 1115 // are already fine. 1116 } 1117 1118 MachineBasicBlock::instr_iterator 1119 MachineBasicBlock::erase(MachineBasicBlock::instr_iterator I) { 1120 unbundleSingleMI(&*I); 1121 return Insts.erase(I); 1122 } 1123 1124 MachineInstr *MachineBasicBlock::remove_instr(MachineInstr *MI) { 1125 unbundleSingleMI(MI); 1126 MI->clearFlag(MachineInstr::BundledPred); 1127 MI->clearFlag(MachineInstr::BundledSucc); 1128 return Insts.remove(MI); 1129 } 1130 1131 MachineBasicBlock::instr_iterator 1132 MachineBasicBlock::insert(instr_iterator I, MachineInstr *MI) { 1133 assert(!MI->isBundledWithPred() && !MI->isBundledWithSucc() && 1134 "Cannot insert instruction with bundle flags"); 1135 // Set the bundle flags when inserting inside a bundle. 1136 if (I != instr_end() && I->isBundledWithPred()) { 1137 MI->setFlag(MachineInstr::BundledPred); 1138 MI->setFlag(MachineInstr::BundledSucc); 1139 } 1140 return Insts.insert(I, MI); 1141 } 1142 1143 /// This method unlinks 'this' from the containing function, and returns it, but 1144 /// does not delete it. 1145 MachineBasicBlock *MachineBasicBlock::removeFromParent() { 1146 assert(getParent() && "Not embedded in a function!"); 1147 getParent()->remove(this); 1148 return this; 1149 } 1150 1151 /// This method unlinks 'this' from the containing function, and deletes it. 1152 void MachineBasicBlock::eraseFromParent() { 1153 assert(getParent() && "Not embedded in a function!"); 1154 getParent()->erase(this); 1155 } 1156 1157 /// Given a machine basic block that branched to 'Old', change the code and CFG 1158 /// so that it branches to 'New' instead. 1159 void MachineBasicBlock::ReplaceUsesOfBlockWith(MachineBasicBlock *Old, 1160 MachineBasicBlock *New) { 1161 assert(Old != New && "Cannot replace self with self!"); 1162 1163 MachineBasicBlock::instr_iterator I = instr_end(); 1164 while (I != instr_begin()) { 1165 --I; 1166 if (!I->isTerminator()) break; 1167 1168 // Scan the operands of this machine instruction, replacing any uses of Old 1169 // with New. 1170 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) 1171 if (I->getOperand(i).isMBB() && 1172 I->getOperand(i).getMBB() == Old) 1173 I->getOperand(i).setMBB(New); 1174 } 1175 1176 // Update the successor information. 1177 replaceSuccessor(Old, New); 1178 } 1179 1180 /// Various pieces of code can cause excess edges in the CFG to be inserted. If 1181 /// we have proven that MBB can only branch to DestA and DestB, remove any other 1182 /// MBB successors from the CFG. DestA and DestB can be null. 1183 /// 1184 /// Besides DestA and DestB, retain other edges leading to LandingPads 1185 /// (currently there can be only one; we don't check or require that here). 1186 /// Note it is possible that DestA and/or DestB are LandingPads. 1187 bool MachineBasicBlock::CorrectExtraCFGEdges(MachineBasicBlock *DestA, 1188 MachineBasicBlock *DestB, 1189 bool IsCond) { 1190 // The values of DestA and DestB frequently come from a call to the 1191 // 'TargetInstrInfo::AnalyzeBranch' method. We take our meaning of the initial 1192 // values from there. 1193 // 1194 // 1. If both DestA and DestB are null, then the block ends with no branches 1195 // (it falls through to its successor). 1196 // 2. If DestA is set, DestB is null, and IsCond is false, then the block ends 1197 // with only an unconditional branch. 1198 // 3. If DestA is set, DestB is null, and IsCond is true, then the block ends 1199 // with a conditional branch that falls through to a successor (DestB). 1200 // 4. If DestA and DestB is set and IsCond is true, then the block ends with a 1201 // conditional branch followed by an unconditional branch. DestA is the 1202 // 'true' destination and DestB is the 'false' destination. 1203 1204 bool Changed = false; 1205 1206 MachineBasicBlock *FallThru = getNextNode(); 1207 1208 if (!DestA && !DestB) { 1209 // Block falls through to successor. 1210 DestA = FallThru; 1211 DestB = FallThru; 1212 } else if (DestA && !DestB) { 1213 if (IsCond) 1214 // Block ends in conditional jump that falls through to successor. 1215 DestB = FallThru; 1216 } else { 1217 assert(DestA && DestB && IsCond && 1218 "CFG in a bad state. Cannot correct CFG edges"); 1219 } 1220 1221 // Remove superfluous edges. I.e., those which aren't destinations of this 1222 // basic block, duplicate edges, or landing pads. 1223 SmallPtrSet<const MachineBasicBlock*, 8> SeenMBBs; 1224 MachineBasicBlock::succ_iterator SI = succ_begin(); 1225 while (SI != succ_end()) { 1226 const MachineBasicBlock *MBB = *SI; 1227 if (!SeenMBBs.insert(MBB).second || 1228 (MBB != DestA && MBB != DestB && !MBB->isEHPad())) { 1229 // This is a superfluous edge, remove it. 1230 SI = removeSuccessor(SI); 1231 Changed = true; 1232 } else { 1233 ++SI; 1234 } 1235 } 1236 1237 if (Changed) 1238 normalizeSuccProbs(); 1239 return Changed; 1240 } 1241 1242 /// Find the next valid DebugLoc starting at MBBI, skipping any DBG_VALUE 1243 /// instructions. Return UnknownLoc if there is none. 1244 DebugLoc 1245 MachineBasicBlock::findDebugLoc(instr_iterator MBBI) { 1246 // Skip debug declarations, we don't want a DebugLoc from them. 1247 MBBI = skipDebugInstructionsForward(MBBI, instr_end()); 1248 if (MBBI != instr_end()) 1249 return MBBI->getDebugLoc(); 1250 return {}; 1251 } 1252 1253 /// Find and return the merged DebugLoc of the branch instructions of the block. 1254 /// Return UnknownLoc if there is none. 1255 DebugLoc 1256 MachineBasicBlock::findBranchDebugLoc() { 1257 DebugLoc DL; 1258 auto TI = getFirstTerminator(); 1259 while (TI != end() && !TI->isBranch()) 1260 ++TI; 1261 1262 if (TI != end()) { 1263 DL = TI->getDebugLoc(); 1264 for (++TI ; TI != end() ; ++TI) 1265 if (TI->isBranch()) 1266 DL = DILocation::getMergedLocation(DL, TI->getDebugLoc()); 1267 } 1268 return DL; 1269 } 1270 1271 /// Return probability of the edge from this block to MBB. 1272 BranchProbability 1273 MachineBasicBlock::getSuccProbability(const_succ_iterator Succ) const { 1274 if (Probs.empty()) 1275 return BranchProbability(1, succ_size()); 1276 1277 const auto &Prob = *getProbabilityIterator(Succ); 1278 if (Prob.isUnknown()) { 1279 // For unknown probabilities, collect the sum of all known ones, and evenly 1280 // ditribute the complemental of the sum to each unknown probability. 1281 unsigned KnownProbNum = 0; 1282 auto Sum = BranchProbability::getZero(); 1283 for (auto &P : Probs) { 1284 if (!P.isUnknown()) { 1285 Sum += P; 1286 KnownProbNum++; 1287 } 1288 } 1289 return Sum.getCompl() / (Probs.size() - KnownProbNum); 1290 } else 1291 return Prob; 1292 } 1293 1294 /// Set successor probability of a given iterator. 1295 void MachineBasicBlock::setSuccProbability(succ_iterator I, 1296 BranchProbability Prob) { 1297 assert(!Prob.isUnknown()); 1298 if (Probs.empty()) 1299 return; 1300 *getProbabilityIterator(I) = Prob; 1301 } 1302 1303 /// Return probability iterator corresonding to the I successor iterator 1304 MachineBasicBlock::const_probability_iterator 1305 MachineBasicBlock::getProbabilityIterator( 1306 MachineBasicBlock::const_succ_iterator I) const { 1307 assert(Probs.size() == Successors.size() && "Async probability list!"); 1308 const size_t index = std::distance(Successors.begin(), I); 1309 assert(index < Probs.size() && "Not a current successor!"); 1310 return Probs.begin() + index; 1311 } 1312 1313 /// Return probability iterator corresonding to the I successor iterator. 1314 MachineBasicBlock::probability_iterator 1315 MachineBasicBlock::getProbabilityIterator(MachineBasicBlock::succ_iterator I) { 1316 assert(Probs.size() == Successors.size() && "Async probability list!"); 1317 const size_t index = std::distance(Successors.begin(), I); 1318 assert(index < Probs.size() && "Not a current successor!"); 1319 return Probs.begin() + index; 1320 } 1321 1322 /// Return whether (physical) register "Reg" has been <def>ined and not <kill>ed 1323 /// as of just before "MI". 1324 /// 1325 /// Search is localised to a neighborhood of 1326 /// Neighborhood instructions before (searching for defs or kills) and N 1327 /// instructions after (searching just for defs) MI. 1328 MachineBasicBlock::LivenessQueryResult 1329 MachineBasicBlock::computeRegisterLiveness(const TargetRegisterInfo *TRI, 1330 unsigned Reg, const_iterator Before, 1331 unsigned Neighborhood) const { 1332 unsigned N = Neighborhood; 1333 1334 // Start by searching backwards from Before, looking for kills, reads or defs. 1335 const_iterator I(Before); 1336 // If this is the first insn in the block, don't search backwards. 1337 if (I != begin()) { 1338 do { 1339 --I; 1340 1341 MachineOperandIteratorBase::PhysRegInfo Info = 1342 ConstMIOperands(*I).analyzePhysReg(Reg, TRI); 1343 1344 // Defs happen after uses so they take precedence if both are present. 1345 1346 // Register is dead after a dead def of the full register. 1347 if (Info.DeadDef) 1348 return LQR_Dead; 1349 // Register is (at least partially) live after a def. 1350 if (Info.Defined) { 1351 if (!Info.PartialDeadDef) 1352 return LQR_Live; 1353 // As soon as we saw a partial definition (dead or not), 1354 // we cannot tell if the value is partial live without 1355 // tracking the lanemasks. We are not going to do this, 1356 // so fall back on the remaining of the analysis. 1357 break; 1358 } 1359 // Register is dead after a full kill or clobber and no def. 1360 if (Info.Killed || Info.Clobbered) 1361 return LQR_Dead; 1362 // Register must be live if we read it. 1363 if (Info.Read) 1364 return LQR_Live; 1365 } while (I != begin() && --N > 0); 1366 } 1367 1368 // Did we get to the start of the block? 1369 if (I == begin()) { 1370 // If so, the register's state is definitely defined by the live-in state. 1371 for (MCRegAliasIterator RAI(Reg, TRI, /*IncludeSelf=*/true); RAI.isValid(); 1372 ++RAI) 1373 if (isLiveIn(*RAI)) 1374 return LQR_Live; 1375 1376 return LQR_Dead; 1377 } 1378 1379 N = Neighborhood; 1380 1381 // Try searching forwards from Before, looking for reads or defs. 1382 I = const_iterator(Before); 1383 // If this is the last insn in the block, don't search forwards. 1384 if (I != end()) { 1385 for (++I; I != end() && N > 0; ++I, --N) { 1386 MachineOperandIteratorBase::PhysRegInfo Info = 1387 ConstMIOperands(*I).analyzePhysReg(Reg, TRI); 1388 1389 // Register is live when we read it here. 1390 if (Info.Read) 1391 return LQR_Live; 1392 // Register is dead if we can fully overwrite or clobber it here. 1393 if (Info.FullyDefined || Info.Clobbered) 1394 return LQR_Dead; 1395 } 1396 } 1397 1398 // At this point we have no idea of the liveness of the register. 1399 return LQR_Unknown; 1400 } 1401 1402 const uint32_t * 1403 MachineBasicBlock::getBeginClobberMask(const TargetRegisterInfo *TRI) const { 1404 // EH funclet entry does not preserve any registers. 1405 return isEHFuncletEntry() ? TRI->getNoPreservedMask() : nullptr; 1406 } 1407 1408 const uint32_t * 1409 MachineBasicBlock::getEndClobberMask(const TargetRegisterInfo *TRI) const { 1410 // If we see a return block with successors, this must be a funclet return, 1411 // which does not preserve any registers. If there are no successors, we don't 1412 // care what kind of return it is, putting a mask after it is a no-op. 1413 return isReturnBlock() && !succ_empty() ? TRI->getNoPreservedMask() : nullptr; 1414 } 1415 1416 void MachineBasicBlock::clearLiveIns() { 1417 LiveIns.clear(); 1418 } 1419 1420 MachineBasicBlock::livein_iterator MachineBasicBlock::livein_begin() const { 1421 assert(getParent()->getProperties().hasProperty( 1422 MachineFunctionProperties::Property::TracksLiveness) && 1423 "Liveness information is accurate"); 1424 return LiveIns.begin(); 1425 } 1426