1 //===-- llvm/CodeGen/MachineBasicBlock.cpp ----------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Collect the sequence of machine instructions for a basic block.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/CodeGen/MachineBasicBlock.h"
15 #include "llvm/ADT/SmallPtrSet.h"
16 #include "llvm/ADT/SmallString.h"
17 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
18 #include "llvm/CodeGen/LiveVariables.h"
19 #include "llvm/CodeGen/MachineDominators.h"
20 #include "llvm/CodeGen/MachineFunction.h"
21 #include "llvm/CodeGen/MachineInstrBuilder.h"
22 #include "llvm/CodeGen/MachineLoopInfo.h"
23 #include "llvm/CodeGen/MachineRegisterInfo.h"
24 #include "llvm/CodeGen/SlotIndexes.h"
25 #include "llvm/IR/BasicBlock.h"
26 #include "llvm/IR/DataLayout.h"
27 #include "llvm/IR/ModuleSlotTracker.h"
28 #include "llvm/MC/MCAsmInfo.h"
29 #include "llvm/MC/MCContext.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/raw_ostream.h"
32 #include "llvm/Target/TargetInstrInfo.h"
33 #include "llvm/Target/TargetMachine.h"
34 #include "llvm/Target/TargetRegisterInfo.h"
35 #include "llvm/Target/TargetSubtargetInfo.h"
39 #define DEBUG_TYPE "codegen"
41 MachineBasicBlock::MachineBasicBlock(MachineFunction &MF, const BasicBlock *B)
42 : BB(B), Number(-1), xParent(&MF) {
46 MachineBasicBlock::~MachineBasicBlock() {
49 /// Return the MCSymbol for this basic block.
50 MCSymbol *MachineBasicBlock::getSymbol() const {
51 if (!CachedMCSymbol) {
52 const MachineFunction *MF = getParent();
53 MCContext &Ctx = MF->getContext();
54 const char *Prefix = Ctx.getAsmInfo()->getPrivateLabelPrefix();
55 assert(getNumber() >= 0 && "cannot get label for unreachable MBB");
56 CachedMCSymbol = Ctx.getOrCreateSymbol(Twine(Prefix) + "BB" +
57 Twine(MF->getFunctionNumber()) +
58 "_" + Twine(getNumber()));
61 return CachedMCSymbol;
65 raw_ostream &llvm::operator<<(raw_ostream &OS, const MachineBasicBlock &MBB) {
70 /// When an MBB is added to an MF, we need to update the parent pointer of the
71 /// MBB, the MBB numbering, and any instructions in the MBB to be on the right
72 /// operand list for registers.
74 /// MBBs start out as #-1. When a MBB is added to a MachineFunction, it
75 /// gets the next available unique MBB number. If it is removed from a
76 /// MachineFunction, it goes back to being #-1.
77 void ilist_traits<MachineBasicBlock>::addNodeToList(MachineBasicBlock *N) {
78 MachineFunction &MF = *N->getParent();
79 N->Number = MF.addToMBBNumbering(N);
81 // Make sure the instructions have their operands in the reginfo lists.
82 MachineRegisterInfo &RegInfo = MF.getRegInfo();
83 for (MachineBasicBlock::instr_iterator
84 I = N->instr_begin(), E = N->instr_end(); I != E; ++I)
85 I->AddRegOperandsToUseLists(RegInfo);
88 void ilist_traits<MachineBasicBlock>::removeNodeFromList(MachineBasicBlock *N) {
89 N->getParent()->removeFromMBBNumbering(N->Number);
93 /// When we add an instruction to a basic block list, we update its parent
94 /// pointer and add its operands from reg use/def lists if appropriate.
95 void ilist_traits<MachineInstr>::addNodeToList(MachineInstr *N) {
96 assert(!N->getParent() && "machine instruction already in a basic block");
99 // Add the instruction's register operands to their corresponding
101 MachineFunction *MF = Parent->getParent();
102 N->AddRegOperandsToUseLists(MF->getRegInfo());
105 /// When we remove an instruction from a basic block list, we update its parent
106 /// pointer and remove its operands from reg use/def lists if appropriate.
107 void ilist_traits<MachineInstr>::removeNodeFromList(MachineInstr *N) {
108 assert(N->getParent() && "machine instruction not in a basic block");
110 // Remove from the use/def lists.
111 if (MachineFunction *MF = N->getParent()->getParent())
112 N->RemoveRegOperandsFromUseLists(MF->getRegInfo());
114 N->setParent(nullptr);
117 /// When moving a range of instructions from one MBB list to another, we need to
118 /// update the parent pointers and the use/def lists.
119 void ilist_traits<MachineInstr>::
120 transferNodesFromList(ilist_traits<MachineInstr> &FromList,
121 ilist_iterator<MachineInstr> First,
122 ilist_iterator<MachineInstr> Last) {
123 assert(Parent->getParent() == FromList.Parent->getParent() &&
124 "MachineInstr parent mismatch!");
126 // Splice within the same MBB -> no change.
127 if (Parent == FromList.Parent) return;
129 // If splicing between two blocks within the same function, just update the
131 for (; First != Last; ++First)
132 First->setParent(Parent);
135 void ilist_traits<MachineInstr>::deleteNode(MachineInstr* MI) {
136 assert(!MI->getParent() && "MI is still in a block!");
137 Parent->getParent()->DeleteMachineInstr(MI);
140 MachineBasicBlock::iterator MachineBasicBlock::getFirstNonPHI() {
141 instr_iterator I = instr_begin(), E = instr_end();
142 while (I != E && I->isPHI())
144 assert((I == E || !I->isInsideBundle()) &&
145 "First non-phi MI cannot be inside a bundle!");
149 MachineBasicBlock::iterator
150 MachineBasicBlock::SkipPHIsAndLabels(MachineBasicBlock::iterator I) {
152 while (I != E && (I->isPHI() || I->isPosition() || I->isDebugValue()))
154 // FIXME: This needs to change if we wish to bundle labels / dbg_values
155 // inside the bundle.
156 assert((I == E || !I->isInsideBundle()) &&
157 "First non-phi / non-label instruction is inside a bundle!");
161 MachineBasicBlock::iterator MachineBasicBlock::getFirstTerminator() {
162 iterator B = begin(), E = end(), I = E;
163 while (I != B && ((--I)->isTerminator() || I->isDebugValue()))
165 while (I != E && !I->isTerminator())
170 MachineBasicBlock::instr_iterator MachineBasicBlock::getFirstInstrTerminator() {
171 instr_iterator B = instr_begin(), E = instr_end(), I = E;
172 while (I != B && ((--I)->isTerminator() || I->isDebugValue()))
174 while (I != E && !I->isTerminator())
179 MachineBasicBlock::iterator MachineBasicBlock::getFirstNonDebugInstr() {
180 // Skip over begin-of-block dbg_value instructions.
181 iterator I = begin(), E = end();
182 while (I != E && I->isDebugValue())
187 MachineBasicBlock::iterator MachineBasicBlock::getLastNonDebugInstr() {
188 // Skip over end-of-block dbg_value instructions.
189 instr_iterator B = instr_begin(), I = instr_end();
192 // Return instruction that starts a bundle.
193 if (I->isDebugValue() || I->isInsideBundle())
197 // The block is all debug values.
201 const MachineBasicBlock *MachineBasicBlock::getLandingPadSuccessor() const {
202 // A block with a landing pad successor only has one other successor.
205 for (const_succ_iterator I = succ_begin(), E = succ_end(); I != E; ++I)
211 bool MachineBasicBlock::hasEHPadSuccessor() const {
212 for (const_succ_iterator I = succ_begin(), E = succ_end(); I != E; ++I)
218 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
219 void MachineBasicBlock::dump() const {
224 StringRef MachineBasicBlock::getName() const {
225 if (const BasicBlock *LBB = getBasicBlock())
226 return LBB->getName();
231 /// Return a hopefully unique identifier for this block.
232 std::string MachineBasicBlock::getFullName() const {
235 Name = (getParent()->getName() + ":").str();
237 Name += getBasicBlock()->getName();
239 Name += ("BB" + Twine(getNumber())).str();
243 void MachineBasicBlock::print(raw_ostream &OS, SlotIndexes *Indexes) const {
244 const MachineFunction *MF = getParent();
246 OS << "Can't print out MachineBasicBlock because parent MachineFunction"
250 const Function *F = MF->getFunction();
251 const Module *M = F ? F->getParent() : nullptr;
252 ModuleSlotTracker MST(M);
253 print(OS, MST, Indexes);
256 void MachineBasicBlock::print(raw_ostream &OS, ModuleSlotTracker &MST,
257 SlotIndexes *Indexes) const {
258 const MachineFunction *MF = getParent();
260 OS << "Can't print out MachineBasicBlock because parent MachineFunction"
266 OS << Indexes->getMBBStartIdx(this) << '\t';
268 OS << "BB#" << getNumber() << ": ";
270 const char *Comma = "";
271 if (const BasicBlock *LBB = getBasicBlock()) {
272 OS << Comma << "derived from LLVM BB ";
273 LBB->printAsOperand(OS, /*PrintType=*/false, MST);
276 if (isEHPad()) { OS << Comma << "EH LANDING PAD"; Comma = ", "; }
277 if (hasAddressTaken()) { OS << Comma << "ADDRESS TAKEN"; Comma = ", "; }
279 OS << Comma << "Align " << Alignment << " (" << (1u << Alignment)
284 const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
285 if (!livein_empty()) {
286 if (Indexes) OS << '\t';
288 for (const auto &LI : make_range(livein_begin(), livein_end())) {
289 OS << ' ' << PrintReg(LI.PhysReg, TRI);
290 if (LI.LaneMask != ~0u)
291 OS << ':' << PrintLaneMask(LI.LaneMask);
295 // Print the preds of this block according to the CFG.
297 if (Indexes) OS << '\t';
298 OS << " Predecessors according to CFG:";
299 for (const_pred_iterator PI = pred_begin(), E = pred_end(); PI != E; ++PI)
300 OS << " BB#" << (*PI)->getNumber();
304 for (const_instr_iterator I = instr_begin(); I != instr_end(); ++I) {
306 if (Indexes->hasIndex(&*I))
307 OS << Indexes->getInstructionIndex(&*I);
311 if (I->isInsideBundle())
316 // Print the successors of this block according to the CFG.
318 if (Indexes) OS << '\t';
319 OS << " Successors according to CFG:";
320 for (const_succ_iterator SI = succ_begin(), E = succ_end(); SI != E; ++SI) {
321 OS << " BB#" << (*SI)->getNumber();
323 OS << '(' << *getProbabilityIterator(SI) << ')';
329 void MachineBasicBlock::printAsOperand(raw_ostream &OS,
330 bool /*PrintType*/) const {
331 OS << "BB#" << getNumber();
334 void MachineBasicBlock::removeLiveIn(MCPhysReg Reg, LaneBitmask LaneMask) {
335 LiveInVector::iterator I = std::find_if(
336 LiveIns.begin(), LiveIns.end(),
337 [Reg] (const RegisterMaskPair &LI) { return LI.PhysReg == Reg; });
338 if (I == LiveIns.end())
341 I->LaneMask &= ~LaneMask;
342 if (I->LaneMask == 0)
346 bool MachineBasicBlock::isLiveIn(MCPhysReg Reg, LaneBitmask LaneMask) const {
347 livein_iterator I = std::find_if(
348 LiveIns.begin(), LiveIns.end(),
349 [Reg] (const RegisterMaskPair &LI) { return LI.PhysReg == Reg; });
350 return I != livein_end() && (I->LaneMask & LaneMask) != 0;
353 void MachineBasicBlock::sortUniqueLiveIns() {
354 std::sort(LiveIns.begin(), LiveIns.end(),
355 [](const RegisterMaskPair &LI0, const RegisterMaskPair &LI1) {
356 return LI0.PhysReg < LI1.PhysReg;
358 // Liveins are sorted by physreg now we can merge their lanemasks.
359 LiveInVector::const_iterator I = LiveIns.begin();
360 LiveInVector::const_iterator J;
361 LiveInVector::iterator Out = LiveIns.begin();
362 for (; I != LiveIns.end(); ++Out, I = J) {
363 unsigned PhysReg = I->PhysReg;
364 LaneBitmask LaneMask = I->LaneMask;
365 for (J = std::next(I); J != LiveIns.end() && J->PhysReg == PhysReg; ++J)
366 LaneMask |= J->LaneMask;
367 Out->PhysReg = PhysReg;
368 Out->LaneMask = LaneMask;
370 LiveIns.erase(Out, LiveIns.end());
374 MachineBasicBlock::addLiveIn(MCPhysReg PhysReg, const TargetRegisterClass *RC) {
375 assert(getParent() && "MBB must be inserted in function");
376 assert(TargetRegisterInfo::isPhysicalRegister(PhysReg) && "Expected physreg");
377 assert(RC && "Register class is required");
378 assert((isEHPad() || this == &getParent()->front()) &&
379 "Only the entry block and landing pads can have physreg live ins");
381 bool LiveIn = isLiveIn(PhysReg);
382 iterator I = SkipPHIsAndLabels(begin()), E = end();
383 MachineRegisterInfo &MRI = getParent()->getRegInfo();
384 const TargetInstrInfo &TII = *getParent()->getSubtarget().getInstrInfo();
386 // Look for an existing copy.
388 for (;I != E && I->isCopy(); ++I)
389 if (I->getOperand(1).getReg() == PhysReg) {
390 unsigned VirtReg = I->getOperand(0).getReg();
391 if (!MRI.constrainRegClass(VirtReg, RC))
392 llvm_unreachable("Incompatible live-in register class.");
396 // No luck, create a virtual register.
397 unsigned VirtReg = MRI.createVirtualRegister(RC);
398 BuildMI(*this, I, DebugLoc(), TII.get(TargetOpcode::COPY), VirtReg)
399 .addReg(PhysReg, RegState::Kill);
405 void MachineBasicBlock::moveBefore(MachineBasicBlock *NewAfter) {
406 getParent()->splice(NewAfter->getIterator(), getIterator());
409 void MachineBasicBlock::moveAfter(MachineBasicBlock *NewBefore) {
410 getParent()->splice(++NewBefore->getIterator(), getIterator());
413 void MachineBasicBlock::updateTerminator() {
414 const TargetInstrInfo *TII = getParent()->getSubtarget().getInstrInfo();
415 // A block with no successors has no concerns with fall-through edges.
416 if (this->succ_empty()) return;
418 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
419 SmallVector<MachineOperand, 4> Cond;
420 DebugLoc DL; // FIXME: this is nowhere
421 bool B = TII->AnalyzeBranch(*this, TBB, FBB, Cond);
423 assert(!B && "UpdateTerminators requires analyzable predecessors!");
426 // The block has an unconditional branch. If its successor is now
427 // its layout successor, delete the branch.
428 if (isLayoutSuccessor(TBB))
429 TII->RemoveBranch(*this);
431 // The block has an unconditional fallthrough. If its successor is not
432 // its layout successor, insert a branch. First we have to locate the
433 // only non-landing-pad successor, as that is the fallthrough block.
434 for (succ_iterator SI = succ_begin(), SE = succ_end(); SI != SE; ++SI) {
435 if ((*SI)->isEHPad())
437 assert(!TBB && "Found more than one non-landing-pad successor!");
441 // If there is no non-landing-pad successor, the block has no
442 // fall-through edges to be concerned with.
446 // Finally update the unconditional successor to be reached via a branch
447 // if it would not be reached by fallthrough.
448 if (!isLayoutSuccessor(TBB))
449 TII->InsertBranch(*this, TBB, nullptr, Cond, DL);
453 // The block has a non-fallthrough conditional branch. If one of its
454 // successors is its layout successor, rewrite it to a fallthrough
455 // conditional branch.
456 if (isLayoutSuccessor(TBB)) {
457 if (TII->ReverseBranchCondition(Cond))
459 TII->RemoveBranch(*this);
460 TII->InsertBranch(*this, FBB, nullptr, Cond, DL);
461 } else if (isLayoutSuccessor(FBB)) {
462 TII->RemoveBranch(*this);
463 TII->InsertBranch(*this, TBB, nullptr, Cond, DL);
466 // Walk through the successors and find the successor which is not
467 // a landing pad and is not the conditional branch destination (in TBB)
468 // as the fallthrough successor.
469 MachineBasicBlock *FallthroughBB = nullptr;
470 for (succ_iterator SI = succ_begin(), SE = succ_end(); SI != SE; ++SI) {
471 if ((*SI)->isEHPad() || *SI == TBB)
473 assert(!FallthroughBB && "Found more than one fallthrough successor.");
476 if (!FallthroughBB && canFallThrough()) {
477 // We fallthrough to the same basic block as the conditional jump
478 // targets. Remove the conditional jump, leaving unconditional
480 // FIXME: This does not seem like a reasonable pattern to support, but
481 // it has been seen in the wild coming out of degenerate ARM test cases.
482 TII->RemoveBranch(*this);
484 // Finally update the unconditional successor to be reached via a branch
485 // if it would not be reached by fallthrough.
486 if (!isLayoutSuccessor(TBB))
487 TII->InsertBranch(*this, TBB, nullptr, Cond, DL);
491 // The block has a fallthrough conditional branch.
492 if (isLayoutSuccessor(TBB)) {
493 if (TII->ReverseBranchCondition(Cond)) {
494 // We can't reverse the condition, add an unconditional branch.
496 TII->InsertBranch(*this, FallthroughBB, nullptr, Cond, DL);
499 TII->RemoveBranch(*this);
500 TII->InsertBranch(*this, FallthroughBB, nullptr, Cond, DL);
501 } else if (!isLayoutSuccessor(FallthroughBB)) {
502 TII->RemoveBranch(*this);
503 TII->InsertBranch(*this, TBB, FallthroughBB, Cond, DL);
509 void MachineBasicBlock::addSuccessor(MachineBasicBlock *Succ,
510 BranchProbability Prob) {
511 // Probability list is either empty (if successor list isn't empty, this means
512 // disabled optimization) or has the same size as successor list.
513 if (!(Probs.empty() && !Successors.empty()))
514 Probs.push_back(Prob);
515 Successors.push_back(Succ);
516 Succ->addPredecessor(this);
519 void MachineBasicBlock::addSuccessorWithoutProb(MachineBasicBlock *Succ) {
520 // We need to make sure probability list is either empty or has the same size
521 // of successor list. When this function is called, we can safely delete all
522 // probability in the list.
524 Successors.push_back(Succ);
525 Succ->addPredecessor(this);
528 void MachineBasicBlock::removeSuccessor(MachineBasicBlock *Succ) {
529 succ_iterator I = std::find(Successors.begin(), Successors.end(), Succ);
533 MachineBasicBlock::succ_iterator
534 MachineBasicBlock::removeSuccessor(succ_iterator I) {
535 assert(I != Successors.end() && "Not a current successor!");
537 // If probability list is empty it means we don't use it (disabled
539 if (!Probs.empty()) {
540 probability_iterator WI = getProbabilityIterator(I);
544 (*I)->removePredecessor(this);
545 return Successors.erase(I);
548 void MachineBasicBlock::replaceSuccessor(MachineBasicBlock *Old,
549 MachineBasicBlock *New) {
553 succ_iterator E = succ_end();
554 succ_iterator NewI = E;
555 succ_iterator OldI = E;
556 for (succ_iterator I = succ_begin(); I != E; ++I) {
568 assert(OldI != E && "Old is not a successor of this block");
570 // If New isn't already a successor, let it take Old's place.
572 Old->removePredecessor(this);
573 New->addPredecessor(this);
578 // New is already a successor.
579 // Update its probability instead of adding a duplicate edge.
580 if (!Probs.empty()) {
581 auto ProbIter = getProbabilityIterator(NewI);
582 if (!ProbIter->isUnknown())
583 *ProbIter += *getProbabilityIterator(OldI);
585 removeSuccessor(OldI);
588 void MachineBasicBlock::addPredecessor(MachineBasicBlock *Pred) {
589 Predecessors.push_back(Pred);
592 void MachineBasicBlock::removePredecessor(MachineBasicBlock *Pred) {
593 pred_iterator I = std::find(Predecessors.begin(), Predecessors.end(), Pred);
594 assert(I != Predecessors.end() && "Pred is not a predecessor of this block!");
595 Predecessors.erase(I);
598 void MachineBasicBlock::transferSuccessors(MachineBasicBlock *FromMBB) {
602 while (!FromMBB->succ_empty()) {
603 MachineBasicBlock *Succ = *FromMBB->succ_begin();
605 // If probability list is empty it means we don't use it (disabled optimization).
606 if (!FromMBB->Probs.empty()) {
607 auto Prob = *FromMBB->Probs.begin();
608 addSuccessor(Succ, Prob);
610 addSuccessorWithoutProb(Succ);
612 FromMBB->removeSuccessor(Succ);
617 MachineBasicBlock::transferSuccessorsAndUpdatePHIs(MachineBasicBlock *FromMBB) {
621 while (!FromMBB->succ_empty()) {
622 MachineBasicBlock *Succ = *FromMBB->succ_begin();
623 if (!FromMBB->Probs.empty()) {
624 auto Prob = *FromMBB->Probs.begin();
625 addSuccessor(Succ, Prob);
627 addSuccessorWithoutProb(Succ);
628 FromMBB->removeSuccessor(Succ);
630 // Fix up any PHI nodes in the successor.
631 for (MachineBasicBlock::instr_iterator MI = Succ->instr_begin(),
632 ME = Succ->instr_end(); MI != ME && MI->isPHI(); ++MI)
633 for (unsigned i = 2, e = MI->getNumOperands()+1; i != e; i += 2) {
634 MachineOperand &MO = MI->getOperand(i);
635 if (MO.getMBB() == FromMBB)
641 bool MachineBasicBlock::isPredecessor(const MachineBasicBlock *MBB) const {
642 return std::find(pred_begin(), pred_end(), MBB) != pred_end();
645 bool MachineBasicBlock::isSuccessor(const MachineBasicBlock *MBB) const {
646 return std::find(succ_begin(), succ_end(), MBB) != succ_end();
649 bool MachineBasicBlock::isLayoutSuccessor(const MachineBasicBlock *MBB) const {
650 MachineFunction::const_iterator I(this);
651 return std::next(I) == MachineFunction::const_iterator(MBB);
654 bool MachineBasicBlock::canFallThrough() {
655 MachineFunction::iterator Fallthrough = getIterator();
657 // If FallthroughBlock is off the end of the function, it can't fall through.
658 if (Fallthrough == getParent()->end())
661 // If FallthroughBlock isn't a successor, no fallthrough is possible.
662 if (!isSuccessor(&*Fallthrough))
665 // Analyze the branches, if any, at the end of the block.
666 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
667 SmallVector<MachineOperand, 4> Cond;
668 const TargetInstrInfo *TII = getParent()->getSubtarget().getInstrInfo();
669 if (TII->AnalyzeBranch(*this, TBB, FBB, Cond)) {
670 // If we couldn't analyze the branch, examine the last instruction.
671 // If the block doesn't end in a known control barrier, assume fallthrough
672 // is possible. The isPredicated check is needed because this code can be
673 // called during IfConversion, where an instruction which is normally a
674 // Barrier is predicated and thus no longer an actual control barrier.
675 return empty() || !back().isBarrier() || TII->isPredicated(&back());
678 // If there is no branch, control always falls through.
679 if (!TBB) return true;
681 // If there is some explicit branch to the fallthrough block, it can obviously
682 // reach, even though the branch should get folded to fall through implicitly.
683 if (MachineFunction::iterator(TBB) == Fallthrough ||
684 MachineFunction::iterator(FBB) == Fallthrough)
687 // If it's an unconditional branch to some block not the fall through, it
688 // doesn't fall through.
689 if (Cond.empty()) return false;
691 // Otherwise, if it is conditional and has no explicit false block, it falls
693 return FBB == nullptr;
697 MachineBasicBlock::SplitCriticalEdge(MachineBasicBlock *Succ, Pass *P) {
698 // Splitting the critical edge to a landing pad block is non-trivial. Don't do
699 // it in this generic function.
703 MachineFunction *MF = getParent();
704 DebugLoc DL; // FIXME: this is nowhere
706 // Performance might be harmed on HW that implements branching using exec mask
707 // where both sides of the branches are always executed.
708 if (MF->getTarget().requiresStructuredCFG())
711 // We may need to update this's terminator, but we can't do that if
712 // AnalyzeBranch fails. If this uses a jump table, we won't touch it.
713 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
714 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
715 SmallVector<MachineOperand, 4> Cond;
716 if (TII->AnalyzeBranch(*this, TBB, FBB, Cond))
719 // Avoid bugpoint weirdness: A block may end with a conditional branch but
720 // jumps to the same MBB is either case. We have duplicate CFG edges in that
721 // case that we can't handle. Since this never happens in properly optimized
722 // code, just skip those edges.
723 if (TBB && TBB == FBB) {
724 DEBUG(dbgs() << "Won't split critical edge after degenerate BB#"
725 << getNumber() << '\n');
729 MachineBasicBlock *NMBB = MF->CreateMachineBasicBlock();
730 MF->insert(std::next(MachineFunction::iterator(this)), NMBB);
731 DEBUG(dbgs() << "Splitting critical edge:"
732 " BB#" << getNumber()
733 << " -- BB#" << NMBB->getNumber()
734 << " -- BB#" << Succ->getNumber() << '\n');
736 LiveIntervals *LIS = P->getAnalysisIfAvailable<LiveIntervals>();
737 SlotIndexes *Indexes = P->getAnalysisIfAvailable<SlotIndexes>();
739 LIS->insertMBBInMaps(NMBB);
741 Indexes->insertMBBInMaps(NMBB);
743 // On some targets like Mips, branches may kill virtual registers. Make sure
744 // that LiveVariables is properly updated after updateTerminator replaces the
746 LiveVariables *LV = P->getAnalysisIfAvailable<LiveVariables>();
748 // Collect a list of virtual registers killed by the terminators.
749 SmallVector<unsigned, 4> KilledRegs;
751 for (instr_iterator I = getFirstInstrTerminator(), E = instr_end();
753 MachineInstr *MI = &*I;
754 for (MachineInstr::mop_iterator OI = MI->operands_begin(),
755 OE = MI->operands_end(); OI != OE; ++OI) {
756 if (!OI->isReg() || OI->getReg() == 0 ||
757 !OI->isUse() || !OI->isKill() || OI->isUndef())
759 unsigned Reg = OI->getReg();
760 if (TargetRegisterInfo::isPhysicalRegister(Reg) ||
761 LV->getVarInfo(Reg).removeKill(MI)) {
762 KilledRegs.push_back(Reg);
763 DEBUG(dbgs() << "Removing terminator kill: " << *MI);
764 OI->setIsKill(false);
769 SmallVector<unsigned, 4> UsedRegs;
771 for (instr_iterator I = getFirstInstrTerminator(), E = instr_end();
773 MachineInstr *MI = &*I;
775 for (MachineInstr::mop_iterator OI = MI->operands_begin(),
776 OE = MI->operands_end(); OI != OE; ++OI) {
777 if (!OI->isReg() || OI->getReg() == 0)
780 unsigned Reg = OI->getReg();
781 if (std::find(UsedRegs.begin(), UsedRegs.end(), Reg) == UsedRegs.end())
782 UsedRegs.push_back(Reg);
787 ReplaceUsesOfBlockWith(Succ, NMBB);
789 // If updateTerminator() removes instructions, we need to remove them from
791 SmallVector<MachineInstr*, 4> Terminators;
793 for (instr_iterator I = getFirstInstrTerminator(), E = instr_end();
795 Terminators.push_back(&*I);
801 SmallVector<MachineInstr*, 4> NewTerminators;
802 for (instr_iterator I = getFirstInstrTerminator(), E = instr_end();
804 NewTerminators.push_back(&*I);
806 for (SmallVectorImpl<MachineInstr*>::iterator I = Terminators.begin(),
807 E = Terminators.end(); I != E; ++I) {
808 if (std::find(NewTerminators.begin(), NewTerminators.end(), *I) ==
809 NewTerminators.end())
810 Indexes->removeMachineInstrFromMaps(*I);
814 // Insert unconditional "jump Succ" instruction in NMBB if necessary.
815 NMBB->addSuccessor(Succ);
816 if (!NMBB->isLayoutSuccessor(Succ)) {
818 TII->InsertBranch(*NMBB, Succ, nullptr, Cond, DL);
821 for (instr_iterator I = NMBB->instr_begin(), E = NMBB->instr_end();
823 // Some instructions may have been moved to NMBB by updateTerminator(),
824 // so we first remove any instruction that already has an index.
825 if (Indexes->hasIndex(&*I))
826 Indexes->removeMachineInstrFromMaps(&*I);
827 Indexes->insertMachineInstrInMaps(&*I);
832 // Fix PHI nodes in Succ so they refer to NMBB instead of this
833 for (MachineBasicBlock::instr_iterator
834 i = Succ->instr_begin(),e = Succ->instr_end();
835 i != e && i->isPHI(); ++i)
836 for (unsigned ni = 1, ne = i->getNumOperands(); ni != ne; ni += 2)
837 if (i->getOperand(ni+1).getMBB() == this)
838 i->getOperand(ni+1).setMBB(NMBB);
840 // Inherit live-ins from the successor
841 for (const auto &LI : Succ->liveins())
844 // Update LiveVariables.
845 const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
847 // Restore kills of virtual registers that were killed by the terminators.
848 while (!KilledRegs.empty()) {
849 unsigned Reg = KilledRegs.pop_back_val();
850 for (instr_iterator I = instr_end(), E = instr_begin(); I != E;) {
851 if (!(--I)->addRegisterKilled(Reg, TRI, /* addIfNotFound= */ false))
853 if (TargetRegisterInfo::isVirtualRegister(Reg))
854 LV->getVarInfo(Reg).Kills.push_back(&*I);
855 DEBUG(dbgs() << "Restored terminator kill: " << *I);
859 // Update relevant live-through information.
860 LV->addNewBlock(NMBB, this, Succ);
864 // After splitting the edge and updating SlotIndexes, live intervals may be
865 // in one of two situations, depending on whether this block was the last in
866 // the function. If the original block was the last in the function, all
867 // live intervals will end prior to the beginning of the new split block. If
868 // the original block was not at the end of the function, all live intervals
869 // will extend to the end of the new split block.
872 std::next(MachineFunction::iterator(NMBB)) == getParent()->end();
874 SlotIndex StartIndex = Indexes->getMBBEndIdx(this);
875 SlotIndex PrevIndex = StartIndex.getPrevSlot();
876 SlotIndex EndIndex = Indexes->getMBBEndIdx(NMBB);
878 // Find the registers used from NMBB in PHIs in Succ.
879 SmallSet<unsigned, 8> PHISrcRegs;
880 for (MachineBasicBlock::instr_iterator
881 I = Succ->instr_begin(), E = Succ->instr_end();
882 I != E && I->isPHI(); ++I) {
883 for (unsigned ni = 1, ne = I->getNumOperands(); ni != ne; ni += 2) {
884 if (I->getOperand(ni+1).getMBB() == NMBB) {
885 MachineOperand &MO = I->getOperand(ni);
886 unsigned Reg = MO.getReg();
887 PHISrcRegs.insert(Reg);
891 LiveInterval &LI = LIS->getInterval(Reg);
892 VNInfo *VNI = LI.getVNInfoAt(PrevIndex);
894 "PHI sources should be live out of their predecessors.");
895 LI.addSegment(LiveInterval::Segment(StartIndex, EndIndex, VNI));
900 MachineRegisterInfo *MRI = &getParent()->getRegInfo();
901 for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
902 unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
903 if (PHISrcRegs.count(Reg) || !LIS->hasInterval(Reg))
906 LiveInterval &LI = LIS->getInterval(Reg);
907 if (!LI.liveAt(PrevIndex))
910 bool isLiveOut = LI.liveAt(LIS->getMBBStartIdx(Succ));
911 if (isLiveOut && isLastMBB) {
912 VNInfo *VNI = LI.getVNInfoAt(PrevIndex);
913 assert(VNI && "LiveInterval should have VNInfo where it is live.");
914 LI.addSegment(LiveInterval::Segment(StartIndex, EndIndex, VNI));
915 } else if (!isLiveOut && !isLastMBB) {
916 LI.removeSegment(StartIndex, EndIndex);
920 // Update all intervals for registers whose uses may have been modified by
921 // updateTerminator().
922 LIS->repairIntervalsInRange(this, getFirstTerminator(), end(), UsedRegs);
925 if (MachineDominatorTree *MDT =
926 P->getAnalysisIfAvailable<MachineDominatorTree>())
927 MDT->recordSplitCriticalEdge(this, Succ, NMBB);
929 if (MachineLoopInfo *MLI = P->getAnalysisIfAvailable<MachineLoopInfo>())
930 if (MachineLoop *TIL = MLI->getLoopFor(this)) {
931 // If one or the other blocks were not in a loop, the new block is not
932 // either, and thus LI doesn't need to be updated.
933 if (MachineLoop *DestLoop = MLI->getLoopFor(Succ)) {
934 if (TIL == DestLoop) {
935 // Both in the same loop, the NMBB joins loop.
936 DestLoop->addBasicBlockToLoop(NMBB, MLI->getBase());
937 } else if (TIL->contains(DestLoop)) {
938 // Edge from an outer loop to an inner loop. Add to the outer loop.
939 TIL->addBasicBlockToLoop(NMBB, MLI->getBase());
940 } else if (DestLoop->contains(TIL)) {
941 // Edge from an inner loop to an outer loop. Add to the outer loop.
942 DestLoop->addBasicBlockToLoop(NMBB, MLI->getBase());
944 // Edge from two loops with no containment relation. Because these
945 // are natural loops, we know that the destination block must be the
946 // header of its loop (adding a branch into a loop elsewhere would
947 // create an irreducible loop).
948 assert(DestLoop->getHeader() == Succ &&
949 "Should not create irreducible loops!");
950 if (MachineLoop *P = DestLoop->getParentLoop())
951 P->addBasicBlockToLoop(NMBB, MLI->getBase());
959 /// Prepare MI to be removed from its bundle. This fixes bundle flags on MI's
960 /// neighboring instructions so the bundle won't be broken by removing MI.
961 static void unbundleSingleMI(MachineInstr *MI) {
962 // Removing the first instruction in a bundle.
963 if (MI->isBundledWithSucc() && !MI->isBundledWithPred())
964 MI->unbundleFromSucc();
965 // Removing the last instruction in a bundle.
966 if (MI->isBundledWithPred() && !MI->isBundledWithSucc())
967 MI->unbundleFromPred();
968 // If MI is not bundled, or if it is internal to a bundle, the neighbor flags
972 MachineBasicBlock::instr_iterator
973 MachineBasicBlock::erase(MachineBasicBlock::instr_iterator I) {
974 unbundleSingleMI(&*I);
975 return Insts.erase(I);
978 MachineInstr *MachineBasicBlock::remove_instr(MachineInstr *MI) {
979 unbundleSingleMI(MI);
980 MI->clearFlag(MachineInstr::BundledPred);
981 MI->clearFlag(MachineInstr::BundledSucc);
982 return Insts.remove(MI);
985 MachineBasicBlock::instr_iterator
986 MachineBasicBlock::insert(instr_iterator I, MachineInstr *MI) {
987 assert(!MI->isBundledWithPred() && !MI->isBundledWithSucc() &&
988 "Cannot insert instruction with bundle flags");
989 // Set the bundle flags when inserting inside a bundle.
990 if (I != instr_end() && I->isBundledWithPred()) {
991 MI->setFlag(MachineInstr::BundledPred);
992 MI->setFlag(MachineInstr::BundledSucc);
994 return Insts.insert(I, MI);
997 /// This method unlinks 'this' from the containing function, and returns it, but
998 /// does not delete it.
999 MachineBasicBlock *MachineBasicBlock::removeFromParent() {
1000 assert(getParent() && "Not embedded in a function!");
1001 getParent()->remove(this);
1005 /// This method unlinks 'this' from the containing function, and deletes it.
1006 void MachineBasicBlock::eraseFromParent() {
1007 assert(getParent() && "Not embedded in a function!");
1008 getParent()->erase(this);
1011 /// Given a machine basic block that branched to 'Old', change the code and CFG
1012 /// so that it branches to 'New' instead.
1013 void MachineBasicBlock::ReplaceUsesOfBlockWith(MachineBasicBlock *Old,
1014 MachineBasicBlock *New) {
1015 assert(Old != New && "Cannot replace self with self!");
1017 MachineBasicBlock::instr_iterator I = instr_end();
1018 while (I != instr_begin()) {
1020 if (!I->isTerminator()) break;
1022 // Scan the operands of this machine instruction, replacing any uses of Old
1024 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1025 if (I->getOperand(i).isMBB() &&
1026 I->getOperand(i).getMBB() == Old)
1027 I->getOperand(i).setMBB(New);
1030 // Update the successor information.
1031 replaceSuccessor(Old, New);
1034 /// Various pieces of code can cause excess edges in the CFG to be inserted. If
1035 /// we have proven that MBB can only branch to DestA and DestB, remove any other
1036 /// MBB successors from the CFG. DestA and DestB can be null.
1038 /// Besides DestA and DestB, retain other edges leading to LandingPads
1039 /// (currently there can be only one; we don't check or require that here).
1040 /// Note it is possible that DestA and/or DestB are LandingPads.
1041 bool MachineBasicBlock::CorrectExtraCFGEdges(MachineBasicBlock *DestA,
1042 MachineBasicBlock *DestB,
1044 // The values of DestA and DestB frequently come from a call to the
1045 // 'TargetInstrInfo::AnalyzeBranch' method. We take our meaning of the initial
1046 // values from there.
1048 // 1. If both DestA and DestB are null, then the block ends with no branches
1049 // (it falls through to its successor).
1050 // 2. If DestA is set, DestB is null, and IsCond is false, then the block ends
1051 // with only an unconditional branch.
1052 // 3. If DestA is set, DestB is null, and IsCond is true, then the block ends
1053 // with a conditional branch that falls through to a successor (DestB).
1054 // 4. If DestA and DestB is set and IsCond is true, then the block ends with a
1055 // conditional branch followed by an unconditional branch. DestA is the
1056 // 'true' destination and DestB is the 'false' destination.
1058 bool Changed = false;
1060 MachineFunction::iterator FallThru = std::next(getIterator());
1062 if (!DestA && !DestB) {
1063 // Block falls through to successor.
1066 } else if (DestA && !DestB) {
1068 // Block ends in conditional jump that falls through to successor.
1071 assert(DestA && DestB && IsCond &&
1072 "CFG in a bad state. Cannot correct CFG edges");
1075 // Remove superfluous edges. I.e., those which aren't destinations of this
1076 // basic block, duplicate edges, or landing pads.
1077 SmallPtrSet<const MachineBasicBlock*, 8> SeenMBBs;
1078 MachineBasicBlock::succ_iterator SI = succ_begin();
1079 while (SI != succ_end()) {
1080 const MachineBasicBlock *MBB = *SI;
1081 if (!SeenMBBs.insert(MBB).second ||
1082 (MBB != DestA && MBB != DestB && !MBB->isEHPad())) {
1083 // This is a superfluous edge, remove it.
1084 SI = removeSuccessor(SI);
1094 /// Find the next valid DebugLoc starting at MBBI, skipping any DBG_VALUE
1095 /// instructions. Return UnknownLoc if there is none.
1097 MachineBasicBlock::findDebugLoc(instr_iterator MBBI) {
1099 instr_iterator E = instr_end();
1103 // Skip debug declarations, we don't want a DebugLoc from them.
1104 while (MBBI != E && MBBI->isDebugValue())
1107 DL = MBBI->getDebugLoc();
1111 /// Return probability of the edge from this block to MBB.
1113 MachineBasicBlock::getSuccProbability(const_succ_iterator Succ) const {
1115 return BranchProbability(1, succ_size());
1117 const auto &Prob = *getProbabilityIterator(Succ);
1118 if (Prob.isUnknown()) {
1119 // For unknown probabilities, collect the sum of all known ones, and evenly
1120 // ditribute the complemental of the sum to each unknown probability.
1121 unsigned KnownProbNum = 0;
1122 auto Sum = BranchProbability::getZero();
1123 for (auto &P : Probs) {
1124 if (!P.isUnknown()) {
1129 return Sum.getCompl() / (Probs.size() - KnownProbNum);
1134 /// Set successor probability of a given iterator.
1135 void MachineBasicBlock::setSuccProbability(succ_iterator I,
1136 BranchProbability Prob) {
1137 assert(!Prob.isUnknown());
1140 *getProbabilityIterator(I) = Prob;
1143 /// Return probability iterator corresonding to the I successor iterator
1144 MachineBasicBlock::const_probability_iterator
1145 MachineBasicBlock::getProbabilityIterator(
1146 MachineBasicBlock::const_succ_iterator I) const {
1147 assert(Probs.size() == Successors.size() && "Async probability list!");
1148 const size_t index = std::distance(Successors.begin(), I);
1149 assert(index < Probs.size() && "Not a current successor!");
1150 return Probs.begin() + index;
1153 /// Return probability iterator corresonding to the I successor iterator.
1154 MachineBasicBlock::probability_iterator
1155 MachineBasicBlock::getProbabilityIterator(MachineBasicBlock::succ_iterator I) {
1156 assert(Probs.size() == Successors.size() && "Async probability list!");
1157 const size_t index = std::distance(Successors.begin(), I);
1158 assert(index < Probs.size() && "Not a current successor!");
1159 return Probs.begin() + index;
1162 /// Return whether (physical) register "Reg" has been <def>ined and not <kill>ed
1163 /// as of just before "MI".
1165 /// Search is localised to a neighborhood of
1166 /// Neighborhood instructions before (searching for defs or kills) and N
1167 /// instructions after (searching just for defs) MI.
1168 MachineBasicBlock::LivenessQueryResult
1169 MachineBasicBlock::computeRegisterLiveness(const TargetRegisterInfo *TRI,
1170 unsigned Reg, const_iterator Before,
1171 unsigned Neighborhood) const {
1172 unsigned N = Neighborhood;
1174 // Start by searching backwards from Before, looking for kills, reads or defs.
1175 const_iterator I(Before);
1176 // If this is the first insn in the block, don't search backwards.
1181 MachineOperandIteratorBase::PhysRegInfo Analysis =
1182 ConstMIOperands(I).analyzePhysReg(Reg, TRI);
1184 if (Analysis.Defines)
1185 // Outputs happen after inputs so they take precedence if both are
1187 return Analysis.DefinesDead ? LQR_Dead : LQR_Live;
1189 if (Analysis.Kills || Analysis.Clobbers)
1190 // Register killed, so isn't live.
1193 else if (Analysis.ReadsOverlap)
1194 // Defined or read without a previous kill - live.
1195 return Analysis.Reads ? LQR_Live : LQR_OverlappingLive;
1197 } while (I != begin() && --N > 0);
1200 // Did we get to the start of the block?
1202 // If so, the register's state is definitely defined by the live-in state.
1203 for (MCRegAliasIterator RAI(Reg, TRI, /*IncludeSelf=*/true);
1204 RAI.isValid(); ++RAI) {
1206 return (*RAI == Reg) ? LQR_Live : LQR_OverlappingLive;
1214 // Try searching forwards from Before, looking for reads or defs.
1215 I = const_iterator(Before);
1216 // If this is the last insn in the block, don't search forwards.
1218 for (++I; I != end() && N > 0; ++I, --N) {
1219 MachineOperandIteratorBase::PhysRegInfo Analysis =
1220 ConstMIOperands(I).analyzePhysReg(Reg, TRI);
1222 if (Analysis.ReadsOverlap)
1223 // Used, therefore must have been live.
1224 return (Analysis.Reads) ?
1225 LQR_Live : LQR_OverlappingLive;
1227 else if (Analysis.Clobbers || Analysis.Defines)
1228 // Defined (but not read) therefore cannot have been live.
1233 // At this point we have no idea of the liveness of the register.
1238 MachineBasicBlock::getBeginClobberMask(const TargetRegisterInfo *TRI) const {
1239 // EH funclet entry does not preserve any registers.
1240 return isEHFuncletEntry() ? TRI->getNoPreservedMask() : nullptr;
1244 MachineBasicBlock::getEndClobberMask(const TargetRegisterInfo *TRI) const {
1245 // If we see a return block with successors, this must be a funclet return,
1246 // which does not preserve any registers. If there are no successors, we don't
1247 // care what kind of return it is, putting a mask after it is a no-op.
1248 return isReturnBlock() && !succ_empty() ? TRI->getNoPreservedMask() : nullptr;