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/LeakDetector.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 *bb)
42 : BB(bb), Number(-1), xParent(&mf), Alignment(0), IsLandingPad(false),
43 AddressTaken(false), CachedMCSymbol(nullptr) {
47 MachineBasicBlock::~MachineBasicBlock() {
48 LeakDetector::removeGarbageObject(this);
51 /// getSymbol - 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 const char *Prefix = Ctx.getAsmInfo()->getPrivateLabelPrefix();
58 CachedMCSymbol = Ctx.GetOrCreateSymbol(Twine(Prefix) + "BB" +
59 Twine(MF->getFunctionNumber()) +
60 "_" + Twine(getNumber()));
63 return CachedMCSymbol;
67 raw_ostream &llvm::operator<<(raw_ostream &OS, const MachineBasicBlock &MBB) {
72 /// addNodeToList (MBB) - When an MBB is added to an MF, we need to update the
73 /// parent pointer of the MBB, the MBB numbering, and any instructions in the
74 /// MBB to be on the right operand list for registers.
76 /// MBBs start out as #-1. When a MBB is added to a MachineFunction, it
77 /// gets the next available unique MBB number. If it is removed from a
78 /// MachineFunction, it goes back to being #-1.
79 void ilist_traits<MachineBasicBlock>::addNodeToList(MachineBasicBlock *N) {
80 MachineFunction &MF = *N->getParent();
81 N->Number = MF.addToMBBNumbering(N);
83 // Make sure the instructions have their operands in the reginfo lists.
84 MachineRegisterInfo &RegInfo = MF.getRegInfo();
85 for (MachineBasicBlock::instr_iterator
86 I = N->instr_begin(), E = N->instr_end(); I != E; ++I)
87 I->AddRegOperandsToUseLists(RegInfo);
89 LeakDetector::removeGarbageObject(N);
92 void ilist_traits<MachineBasicBlock>::removeNodeFromList(MachineBasicBlock *N) {
93 N->getParent()->removeFromMBBNumbering(N->Number);
95 LeakDetector::addGarbageObject(N);
99 /// addNodeToList (MI) - When we add an instruction to a basic block
100 /// list, we update its parent pointer and add its operands from reg use/def
101 /// lists if appropriate.
102 void ilist_traits<MachineInstr>::addNodeToList(MachineInstr *N) {
103 assert(!N->getParent() && "machine instruction already in a basic block");
104 N->setParent(Parent);
106 // Add the instruction's register operands to their corresponding
108 MachineFunction *MF = Parent->getParent();
109 N->AddRegOperandsToUseLists(MF->getRegInfo());
112 /// removeNodeFromList (MI) - When we remove an instruction from a basic block
113 /// list, we update its parent pointer and remove its operands from reg use/def
114 /// lists if appropriate.
115 void ilist_traits<MachineInstr>::removeNodeFromList(MachineInstr *N) {
116 assert(N->getParent() && "machine instruction not in a basic block");
118 // Remove from the use/def lists.
119 if (MachineFunction *MF = N->getParent()->getParent())
120 N->RemoveRegOperandsFromUseLists(MF->getRegInfo());
122 N->setParent(nullptr);
125 /// transferNodesFromList (MI) - When moving a range of instructions from one
126 /// MBB list to another, we need to update the parent pointers and the use/def
128 void ilist_traits<MachineInstr>::
129 transferNodesFromList(ilist_traits<MachineInstr> &fromList,
130 ilist_iterator<MachineInstr> first,
131 ilist_iterator<MachineInstr> last) {
132 assert(Parent->getParent() == fromList.Parent->getParent() &&
133 "MachineInstr parent mismatch!");
135 // Splice within the same MBB -> no change.
136 if (Parent == fromList.Parent) return;
138 // If splicing between two blocks within the same function, just update the
140 for (; first != last; ++first)
141 first->setParent(Parent);
144 void ilist_traits<MachineInstr>::deleteNode(MachineInstr* MI) {
145 assert(!MI->getParent() && "MI is still in a block!");
146 Parent->getParent()->DeleteMachineInstr(MI);
149 MachineBasicBlock::iterator MachineBasicBlock::getFirstNonPHI() {
150 instr_iterator I = instr_begin(), E = instr_end();
151 while (I != E && I->isPHI())
153 assert((I == E || !I->isInsideBundle()) &&
154 "First non-phi MI cannot be inside a bundle!");
158 MachineBasicBlock::iterator
159 MachineBasicBlock::SkipPHIsAndLabels(MachineBasicBlock::iterator I) {
161 while (I != E && (I->isPHI() || I->isPosition() || I->isDebugValue()))
163 // FIXME: This needs to change if we wish to bundle labels / dbg_values
164 // inside the bundle.
165 assert((I == E || !I->isInsideBundle()) &&
166 "First non-phi / non-label instruction is inside a bundle!");
170 MachineBasicBlock::iterator MachineBasicBlock::getFirstTerminator() {
171 iterator B = begin(), E = end(), I = E;
172 while (I != B && ((--I)->isTerminator() || I->isDebugValue()))
174 while (I != E && !I->isTerminator())
179 MachineBasicBlock::const_iterator
180 MachineBasicBlock::getFirstTerminator() const {
181 const_iterator B = begin(), E = end(), I = E;
182 while (I != B && ((--I)->isTerminator() || I->isDebugValue()))
184 while (I != E && !I->isTerminator())
189 MachineBasicBlock::instr_iterator MachineBasicBlock::getFirstInstrTerminator() {
190 instr_iterator B = instr_begin(), E = instr_end(), I = E;
191 while (I != B && ((--I)->isTerminator() || I->isDebugValue()))
193 while (I != E && !I->isTerminator())
198 MachineBasicBlock::iterator MachineBasicBlock::getLastNonDebugInstr() {
199 // Skip over end-of-block dbg_value instructions.
200 instr_iterator B = instr_begin(), I = instr_end();
203 // Return instruction that starts a bundle.
204 if (I->isDebugValue() || I->isInsideBundle())
208 // The block is all debug values.
212 MachineBasicBlock::const_iterator
213 MachineBasicBlock::getLastNonDebugInstr() const {
214 // Skip over end-of-block dbg_value instructions.
215 const_instr_iterator B = instr_begin(), I = instr_end();
218 // Return instruction that starts a bundle.
219 if (I->isDebugValue() || I->isInsideBundle())
223 // The block is all debug values.
227 const MachineBasicBlock *MachineBasicBlock::getLandingPadSuccessor() const {
228 // A block with a landing pad successor only has one other successor.
231 for (const_succ_iterator I = succ_begin(), E = succ_end(); I != E; ++I)
232 if ((*I)->isLandingPad())
237 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
238 void MachineBasicBlock::dump() const {
243 StringRef MachineBasicBlock::getName() const {
244 if (const BasicBlock *LBB = getBasicBlock())
245 return LBB->getName();
250 /// Return a hopefully unique identifier for this block.
251 std::string MachineBasicBlock::getFullName() const {
254 Name = (getParent()->getName() + ":").str();
256 Name += getBasicBlock()->getName();
258 Name += (Twine("BB") + Twine(getNumber())).str();
262 void MachineBasicBlock::print(raw_ostream &OS, SlotIndexes *Indexes) const {
263 const MachineFunction *MF = getParent();
265 OS << "Can't print out MachineBasicBlock because parent MachineFunction"
271 OS << Indexes->getMBBStartIdx(this) << '\t';
273 OS << "BB#" << getNumber() << ": ";
275 const char *Comma = "";
276 if (const BasicBlock *LBB = getBasicBlock()) {
277 OS << Comma << "derived from LLVM BB ";
278 LBB->printAsOperand(OS, /*PrintType=*/false);
281 if (isLandingPad()) { OS << Comma << "EH LANDING PAD"; Comma = ", "; }
282 if (hasAddressTaken()) { OS << Comma << "ADDRESS TAKEN"; Comma = ", "; }
284 OS << Comma << "Align " << Alignment << " (" << (1u << Alignment)
289 const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
290 if (!livein_empty()) {
291 if (Indexes) OS << '\t';
293 for (livein_iterator I = livein_begin(),E = livein_end(); I != E; ++I)
294 OS << ' ' << PrintReg(*I, TRI);
297 // Print the preds of this block according to the CFG.
299 if (Indexes) OS << '\t';
300 OS << " Predecessors according to CFG:";
301 for (const_pred_iterator PI = pred_begin(), E = pred_end(); PI != E; ++PI)
302 OS << " BB#" << (*PI)->getNumber();
306 for (const_instr_iterator I = instr_begin(); I != instr_end(); ++I) {
308 if (Indexes->hasIndex(I))
309 OS << Indexes->getInstructionIndex(I);
313 if (I->isInsideBundle())
315 I->print(OS, &getParent()->getTarget());
318 // Print the successors of this block according to the CFG.
320 if (Indexes) OS << '\t';
321 OS << " Successors according to CFG:";
322 for (const_succ_iterator SI = succ_begin(), E = succ_end(); SI != E; ++SI) {
323 OS << " BB#" << (*SI)->getNumber();
324 if (!Weights.empty())
325 OS << '(' << *getWeightIterator(SI) << ')';
331 void MachineBasicBlock::printAsOperand(raw_ostream &OS, bool /*PrintType*/) const {
332 OS << "BB#" << getNumber();
335 void MachineBasicBlock::removeLiveIn(unsigned Reg) {
336 std::vector<unsigned>::iterator I =
337 std::find(LiveIns.begin(), LiveIns.end(), Reg);
338 if (I != LiveIns.end())
342 bool MachineBasicBlock::isLiveIn(unsigned Reg) const {
343 livein_iterator I = std::find(livein_begin(), livein_end(), Reg);
344 return I != livein_end();
348 MachineBasicBlock::addLiveIn(unsigned PhysReg, const TargetRegisterClass *RC) {
349 assert(getParent() && "MBB must be inserted in function");
350 assert(TargetRegisterInfo::isPhysicalRegister(PhysReg) && "Expected physreg");
351 assert(RC && "Register class is required");
352 assert((isLandingPad() || this == &getParent()->front()) &&
353 "Only the entry block and landing pads can have physreg live ins");
355 bool LiveIn = isLiveIn(PhysReg);
356 iterator I = SkipPHIsAndLabels(begin()), E = end();
357 MachineRegisterInfo &MRI = getParent()->getRegInfo();
358 const TargetInstrInfo &TII = *getParent()->getSubtarget().getInstrInfo();
360 // Look for an existing copy.
362 for (;I != E && I->isCopy(); ++I)
363 if (I->getOperand(1).getReg() == PhysReg) {
364 unsigned VirtReg = I->getOperand(0).getReg();
365 if (!MRI.constrainRegClass(VirtReg, RC))
366 llvm_unreachable("Incompatible live-in register class.");
370 // No luck, create a virtual register.
371 unsigned VirtReg = MRI.createVirtualRegister(RC);
372 BuildMI(*this, I, DebugLoc(), TII.get(TargetOpcode::COPY), VirtReg)
373 .addReg(PhysReg, RegState::Kill);
379 void MachineBasicBlock::moveBefore(MachineBasicBlock *NewAfter) {
380 getParent()->splice(NewAfter, this);
383 void MachineBasicBlock::moveAfter(MachineBasicBlock *NewBefore) {
384 MachineFunction::iterator BBI = NewBefore;
385 getParent()->splice(++BBI, this);
388 void MachineBasicBlock::updateTerminator() {
389 const TargetInstrInfo *TII = getParent()->getSubtarget().getInstrInfo();
390 // A block with no successors has no concerns with fall-through edges.
391 if (this->succ_empty()) return;
393 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
394 SmallVector<MachineOperand, 4> Cond;
395 DebugLoc dl; // FIXME: this is nowhere
396 bool B = TII->AnalyzeBranch(*this, TBB, FBB, Cond);
398 assert(!B && "UpdateTerminators requires analyzable predecessors!");
401 // The block has an unconditional branch. If its successor is now
402 // its layout successor, delete the branch.
403 if (isLayoutSuccessor(TBB))
404 TII->RemoveBranch(*this);
406 // The block has an unconditional fallthrough. If its successor is not
407 // its layout successor, insert a branch. First we have to locate the
408 // only non-landing-pad successor, as that is the fallthrough block.
409 for (succ_iterator SI = succ_begin(), SE = succ_end(); SI != SE; ++SI) {
410 if ((*SI)->isLandingPad())
412 assert(!TBB && "Found more than one non-landing-pad successor!");
416 // If there is no non-landing-pad successor, the block has no
417 // fall-through edges to be concerned with.
421 // Finally update the unconditional successor to be reached via a branch
422 // if it would not be reached by fallthrough.
423 if (!isLayoutSuccessor(TBB))
424 TII->InsertBranch(*this, TBB, nullptr, Cond, dl);
428 // The block has a non-fallthrough conditional branch. If one of its
429 // successors is its layout successor, rewrite it to a fallthrough
430 // conditional branch.
431 if (isLayoutSuccessor(TBB)) {
432 if (TII->ReverseBranchCondition(Cond))
434 TII->RemoveBranch(*this);
435 TII->InsertBranch(*this, FBB, nullptr, Cond, dl);
436 } else if (isLayoutSuccessor(FBB)) {
437 TII->RemoveBranch(*this);
438 TII->InsertBranch(*this, TBB, nullptr, Cond, dl);
441 // Walk through the successors and find the successor which is not
442 // a landing pad and is not the conditional branch destination (in TBB)
443 // as the fallthrough successor.
444 MachineBasicBlock *FallthroughBB = nullptr;
445 for (succ_iterator SI = succ_begin(), SE = succ_end(); SI != SE; ++SI) {
446 if ((*SI)->isLandingPad() || *SI == TBB)
448 assert(!FallthroughBB && "Found more than one fallthrough successor.");
451 if (!FallthroughBB && canFallThrough()) {
452 // We fallthrough to the same basic block as the conditional jump
453 // targets. Remove the conditional jump, leaving unconditional
455 // FIXME: This does not seem like a reasonable pattern to support, but it
456 // has been seen in the wild coming out of degenerate ARM test cases.
457 TII->RemoveBranch(*this);
459 // Finally update the unconditional successor to be reached via a branch
460 // if it would not be reached by fallthrough.
461 if (!isLayoutSuccessor(TBB))
462 TII->InsertBranch(*this, TBB, nullptr, Cond, dl);
466 // The block has a fallthrough conditional branch.
467 if (isLayoutSuccessor(TBB)) {
468 if (TII->ReverseBranchCondition(Cond)) {
469 // We can't reverse the condition, add an unconditional branch.
471 TII->InsertBranch(*this, FallthroughBB, nullptr, Cond, dl);
474 TII->RemoveBranch(*this);
475 TII->InsertBranch(*this, FallthroughBB, nullptr, Cond, dl);
476 } else if (!isLayoutSuccessor(FallthroughBB)) {
477 TII->RemoveBranch(*this);
478 TII->InsertBranch(*this, TBB, FallthroughBB, Cond, dl);
484 void MachineBasicBlock::addSuccessor(MachineBasicBlock *succ, uint32_t weight) {
486 // If we see non-zero value for the first time it means we actually use Weight
487 // list, so we fill all Weights with 0's.
488 if (weight != 0 && Weights.empty())
489 Weights.resize(Successors.size());
491 if (weight != 0 || !Weights.empty())
492 Weights.push_back(weight);
494 Successors.push_back(succ);
495 succ->addPredecessor(this);
498 void MachineBasicBlock::removeSuccessor(MachineBasicBlock *succ) {
499 succ->removePredecessor(this);
500 succ_iterator I = std::find(Successors.begin(), Successors.end(), succ);
501 assert(I != Successors.end() && "Not a current successor!");
503 // If Weight list is empty it means we don't use it (disabled optimization).
504 if (!Weights.empty()) {
505 weight_iterator WI = getWeightIterator(I);
512 MachineBasicBlock::succ_iterator
513 MachineBasicBlock::removeSuccessor(succ_iterator I) {
514 assert(I != Successors.end() && "Not a current successor!");
516 // If Weight list is empty it means we don't use it (disabled optimization).
517 if (!Weights.empty()) {
518 weight_iterator WI = getWeightIterator(I);
522 (*I)->removePredecessor(this);
523 return Successors.erase(I);
526 void MachineBasicBlock::replaceSuccessor(MachineBasicBlock *Old,
527 MachineBasicBlock *New) {
531 succ_iterator E = succ_end();
532 succ_iterator NewI = E;
533 succ_iterator OldI = E;
534 for (succ_iterator I = succ_begin(); I != E; ++I) {
546 assert(OldI != E && "Old is not a successor of this block");
547 Old->removePredecessor(this);
549 // If New isn't already a successor, let it take Old's place.
551 New->addPredecessor(this);
556 // New is already a successor.
557 // Update its weight instead of adding a duplicate edge.
558 if (!Weights.empty()) {
559 weight_iterator OldWI = getWeightIterator(OldI);
560 *getWeightIterator(NewI) += *OldWI;
561 Weights.erase(OldWI);
563 Successors.erase(OldI);
566 void MachineBasicBlock::addPredecessor(MachineBasicBlock *pred) {
567 Predecessors.push_back(pred);
570 void MachineBasicBlock::removePredecessor(MachineBasicBlock *pred) {
571 pred_iterator I = std::find(Predecessors.begin(), Predecessors.end(), pred);
572 assert(I != Predecessors.end() && "Pred is not a predecessor of this block!");
573 Predecessors.erase(I);
576 void MachineBasicBlock::transferSuccessors(MachineBasicBlock *fromMBB) {
580 while (!fromMBB->succ_empty()) {
581 MachineBasicBlock *Succ = *fromMBB->succ_begin();
584 // If Weight list is empty it means we don't use it (disabled optimization).
585 if (!fromMBB->Weights.empty())
586 Weight = *fromMBB->Weights.begin();
588 addSuccessor(Succ, Weight);
589 fromMBB->removeSuccessor(Succ);
594 MachineBasicBlock::transferSuccessorsAndUpdatePHIs(MachineBasicBlock *fromMBB) {
598 while (!fromMBB->succ_empty()) {
599 MachineBasicBlock *Succ = *fromMBB->succ_begin();
601 if (!fromMBB->Weights.empty())
602 Weight = *fromMBB->Weights.begin();
603 addSuccessor(Succ, Weight);
604 fromMBB->removeSuccessor(Succ);
606 // Fix up any PHI nodes in the successor.
607 for (MachineBasicBlock::instr_iterator MI = Succ->instr_begin(),
608 ME = Succ->instr_end(); MI != ME && MI->isPHI(); ++MI)
609 for (unsigned i = 2, e = MI->getNumOperands()+1; i != e; i += 2) {
610 MachineOperand &MO = MI->getOperand(i);
611 if (MO.getMBB() == fromMBB)
617 bool MachineBasicBlock::isPredecessor(const MachineBasicBlock *MBB) const {
618 return std::find(pred_begin(), pred_end(), MBB) != pred_end();
621 bool MachineBasicBlock::isSuccessor(const MachineBasicBlock *MBB) const {
622 return std::find(succ_begin(), succ_end(), MBB) != succ_end();
625 bool MachineBasicBlock::isLayoutSuccessor(const MachineBasicBlock *MBB) const {
626 MachineFunction::const_iterator I(this);
627 return std::next(I) == MachineFunction::const_iterator(MBB);
630 bool MachineBasicBlock::canFallThrough() {
631 MachineFunction::iterator Fallthrough = this;
633 // If FallthroughBlock is off the end of the function, it can't fall through.
634 if (Fallthrough == getParent()->end())
637 // If FallthroughBlock isn't a successor, no fallthrough is possible.
638 if (!isSuccessor(Fallthrough))
641 // Analyze the branches, if any, at the end of the block.
642 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
643 SmallVector<MachineOperand, 4> Cond;
644 const TargetInstrInfo *TII = getParent()->getSubtarget().getInstrInfo();
645 if (TII->AnalyzeBranch(*this, TBB, FBB, Cond)) {
646 // If we couldn't analyze the branch, examine the last instruction.
647 // If the block doesn't end in a known control barrier, assume fallthrough
648 // is possible. The isPredicated check is needed because this code can be
649 // called during IfConversion, where an instruction which is normally a
650 // Barrier is predicated and thus no longer an actual control barrier.
651 return empty() || !back().isBarrier() || TII->isPredicated(&back());
654 // If there is no branch, control always falls through.
655 if (!TBB) return true;
657 // If there is some explicit branch to the fallthrough block, it can obviously
658 // reach, even though the branch should get folded to fall through implicitly.
659 if (MachineFunction::iterator(TBB) == Fallthrough ||
660 MachineFunction::iterator(FBB) == Fallthrough)
663 // If it's an unconditional branch to some block not the fall through, it
664 // doesn't fall through.
665 if (Cond.empty()) return false;
667 // Otherwise, if it is conditional and has no explicit false block, it falls
669 return FBB == nullptr;
673 MachineBasicBlock::SplitCriticalEdge(MachineBasicBlock *Succ, Pass *P) {
674 // Splitting the critical edge to a landing pad block is non-trivial. Don't do
675 // it in this generic function.
676 if (Succ->isLandingPad())
679 MachineFunction *MF = getParent();
680 DebugLoc dl; // FIXME: this is nowhere
682 // Performance might be harmed on HW that implements branching using exec mask
683 // where both sides of the branches are always executed.
684 if (MF->getTarget().requiresStructuredCFG())
687 // We may need to update this's terminator, but we can't do that if
688 // AnalyzeBranch fails. If this uses a jump table, we won't touch it.
689 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
690 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
691 SmallVector<MachineOperand, 4> Cond;
692 if (TII->AnalyzeBranch(*this, TBB, FBB, Cond))
695 // Avoid bugpoint weirdness: A block may end with a conditional branch but
696 // jumps to the same MBB is either case. We have duplicate CFG edges in that
697 // case that we can't handle. Since this never happens in properly optimized
698 // code, just skip those edges.
699 if (TBB && TBB == FBB) {
700 DEBUG(dbgs() << "Won't split critical edge after degenerate BB#"
701 << getNumber() << '\n');
705 MachineBasicBlock *NMBB = MF->CreateMachineBasicBlock();
706 MF->insert(std::next(MachineFunction::iterator(this)), NMBB);
707 DEBUG(dbgs() << "Splitting critical edge:"
708 " BB#" << getNumber()
709 << " -- BB#" << NMBB->getNumber()
710 << " -- BB#" << Succ->getNumber() << '\n');
712 LiveIntervals *LIS = P->getAnalysisIfAvailable<LiveIntervals>();
713 SlotIndexes *Indexes = P->getAnalysisIfAvailable<SlotIndexes>();
715 LIS->insertMBBInMaps(NMBB);
717 Indexes->insertMBBInMaps(NMBB);
719 // On some targets like Mips, branches may kill virtual registers. Make sure
720 // that LiveVariables is properly updated after updateTerminator replaces the
722 LiveVariables *LV = P->getAnalysisIfAvailable<LiveVariables>();
724 // Collect a list of virtual registers killed by the terminators.
725 SmallVector<unsigned, 4> KilledRegs;
727 for (instr_iterator I = getFirstInstrTerminator(), E = instr_end();
729 MachineInstr *MI = I;
730 for (MachineInstr::mop_iterator OI = MI->operands_begin(),
731 OE = MI->operands_end(); OI != OE; ++OI) {
732 if (!OI->isReg() || OI->getReg() == 0 ||
733 !OI->isUse() || !OI->isKill() || OI->isUndef())
735 unsigned Reg = OI->getReg();
736 if (TargetRegisterInfo::isPhysicalRegister(Reg) ||
737 LV->getVarInfo(Reg).removeKill(MI)) {
738 KilledRegs.push_back(Reg);
739 DEBUG(dbgs() << "Removing terminator kill: " << *MI);
740 OI->setIsKill(false);
745 SmallVector<unsigned, 4> UsedRegs;
747 for (instr_iterator I = getFirstInstrTerminator(), E = instr_end();
749 MachineInstr *MI = I;
751 for (MachineInstr::mop_iterator OI = MI->operands_begin(),
752 OE = MI->operands_end(); OI != OE; ++OI) {
753 if (!OI->isReg() || OI->getReg() == 0)
756 unsigned Reg = OI->getReg();
757 if (std::find(UsedRegs.begin(), UsedRegs.end(), Reg) == UsedRegs.end())
758 UsedRegs.push_back(Reg);
763 ReplaceUsesOfBlockWith(Succ, NMBB);
765 // If updateTerminator() removes instructions, we need to remove them from
767 SmallVector<MachineInstr*, 4> Terminators;
769 for (instr_iterator I = getFirstInstrTerminator(), E = instr_end();
771 Terminators.push_back(I);
777 SmallVector<MachineInstr*, 4> NewTerminators;
778 for (instr_iterator I = getFirstInstrTerminator(), E = instr_end();
780 NewTerminators.push_back(I);
782 for (SmallVectorImpl<MachineInstr*>::iterator I = Terminators.begin(),
783 E = Terminators.end(); I != E; ++I) {
784 if (std::find(NewTerminators.begin(), NewTerminators.end(), *I) ==
785 NewTerminators.end())
786 Indexes->removeMachineInstrFromMaps(*I);
790 // Insert unconditional "jump Succ" instruction in NMBB if necessary.
791 NMBB->addSuccessor(Succ);
792 if (!NMBB->isLayoutSuccessor(Succ)) {
794 MF->getSubtarget().getInstrInfo()->InsertBranch(*NMBB, Succ, nullptr, Cond,
798 for (instr_iterator I = NMBB->instr_begin(), E = NMBB->instr_end();
800 // Some instructions may have been moved to NMBB by updateTerminator(),
801 // so we first remove any instruction that already has an index.
802 if (Indexes->hasIndex(I))
803 Indexes->removeMachineInstrFromMaps(I);
804 Indexes->insertMachineInstrInMaps(I);
809 // Fix PHI nodes in Succ so they refer to NMBB instead of this
810 for (MachineBasicBlock::instr_iterator
811 i = Succ->instr_begin(),e = Succ->instr_end();
812 i != e && i->isPHI(); ++i)
813 for (unsigned ni = 1, ne = i->getNumOperands(); ni != ne; ni += 2)
814 if (i->getOperand(ni+1).getMBB() == this)
815 i->getOperand(ni+1).setMBB(NMBB);
817 // Inherit live-ins from the successor
818 for (MachineBasicBlock::livein_iterator I = Succ->livein_begin(),
819 E = Succ->livein_end(); I != E; ++I)
822 // Update LiveVariables.
823 const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
825 // Restore kills of virtual registers that were killed by the terminators.
826 while (!KilledRegs.empty()) {
827 unsigned Reg = KilledRegs.pop_back_val();
828 for (instr_iterator I = instr_end(), E = instr_begin(); I != E;) {
829 if (!(--I)->addRegisterKilled(Reg, TRI, /* addIfNotFound= */ false))
831 if (TargetRegisterInfo::isVirtualRegister(Reg))
832 LV->getVarInfo(Reg).Kills.push_back(I);
833 DEBUG(dbgs() << "Restored terminator kill: " << *I);
837 // Update relevant live-through information.
838 LV->addNewBlock(NMBB, this, Succ);
842 // After splitting the edge and updating SlotIndexes, live intervals may be
843 // in one of two situations, depending on whether this block was the last in
844 // the function. If the original block was the last in the function, all live
845 // intervals will end prior to the beginning of the new split block. If the
846 // original block was not at the end of the function, all live intervals will
847 // extend to the end of the new split block.
850 std::next(MachineFunction::iterator(NMBB)) == getParent()->end();
852 SlotIndex StartIndex = Indexes->getMBBEndIdx(this);
853 SlotIndex PrevIndex = StartIndex.getPrevSlot();
854 SlotIndex EndIndex = Indexes->getMBBEndIdx(NMBB);
856 // Find the registers used from NMBB in PHIs in Succ.
857 SmallSet<unsigned, 8> PHISrcRegs;
858 for (MachineBasicBlock::instr_iterator
859 I = Succ->instr_begin(), E = Succ->instr_end();
860 I != E && I->isPHI(); ++I) {
861 for (unsigned ni = 1, ne = I->getNumOperands(); ni != ne; ni += 2) {
862 if (I->getOperand(ni+1).getMBB() == NMBB) {
863 MachineOperand &MO = I->getOperand(ni);
864 unsigned Reg = MO.getReg();
865 PHISrcRegs.insert(Reg);
869 LiveInterval &LI = LIS->getInterval(Reg);
870 VNInfo *VNI = LI.getVNInfoAt(PrevIndex);
871 assert(VNI && "PHI sources should be live out of their predecessors.");
872 LI.addSegment(LiveInterval::Segment(StartIndex, EndIndex, VNI));
877 MachineRegisterInfo *MRI = &getParent()->getRegInfo();
878 for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
879 unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
880 if (PHISrcRegs.count(Reg) || !LIS->hasInterval(Reg))
883 LiveInterval &LI = LIS->getInterval(Reg);
884 if (!LI.liveAt(PrevIndex))
887 bool isLiveOut = LI.liveAt(LIS->getMBBStartIdx(Succ));
888 if (isLiveOut && isLastMBB) {
889 VNInfo *VNI = LI.getVNInfoAt(PrevIndex);
890 assert(VNI && "LiveInterval should have VNInfo where it is live.");
891 LI.addSegment(LiveInterval::Segment(StartIndex, EndIndex, VNI));
892 } else if (!isLiveOut && !isLastMBB) {
893 LI.removeSegment(StartIndex, EndIndex);
897 // Update all intervals for registers whose uses may have been modified by
898 // updateTerminator().
899 LIS->repairIntervalsInRange(this, getFirstTerminator(), end(), UsedRegs);
902 if (MachineDominatorTree *MDT =
903 P->getAnalysisIfAvailable<MachineDominatorTree>())
904 MDT->recordSplitCriticalEdge(this, Succ, NMBB);
906 if (MachineLoopInfo *MLI = P->getAnalysisIfAvailable<MachineLoopInfo>())
907 if (MachineLoop *TIL = MLI->getLoopFor(this)) {
908 // If one or the other blocks were not in a loop, the new block is not
909 // either, and thus LI doesn't need to be updated.
910 if (MachineLoop *DestLoop = MLI->getLoopFor(Succ)) {
911 if (TIL == DestLoop) {
912 // Both in the same loop, the NMBB joins loop.
913 DestLoop->addBasicBlockToLoop(NMBB, MLI->getBase());
914 } else if (TIL->contains(DestLoop)) {
915 // Edge from an outer loop to an inner loop. Add to the outer loop.
916 TIL->addBasicBlockToLoop(NMBB, MLI->getBase());
917 } else if (DestLoop->contains(TIL)) {
918 // Edge from an inner loop to an outer loop. Add to the outer loop.
919 DestLoop->addBasicBlockToLoop(NMBB, MLI->getBase());
921 // Edge from two loops with no containment relation. Because these
922 // are natural loops, we know that the destination block must be the
923 // header of its loop (adding a branch into a loop elsewhere would
924 // create an irreducible loop).
925 assert(DestLoop->getHeader() == Succ &&
926 "Should not create irreducible loops!");
927 if (MachineLoop *P = DestLoop->getParentLoop())
928 P->addBasicBlockToLoop(NMBB, MLI->getBase());
936 /// Prepare MI to be removed from its bundle. This fixes bundle flags on MI's
937 /// neighboring instructions so the bundle won't be broken by removing MI.
938 static void unbundleSingleMI(MachineInstr *MI) {
939 // Removing the first instruction in a bundle.
940 if (MI->isBundledWithSucc() && !MI->isBundledWithPred())
941 MI->unbundleFromSucc();
942 // Removing the last instruction in a bundle.
943 if (MI->isBundledWithPred() && !MI->isBundledWithSucc())
944 MI->unbundleFromPred();
945 // If MI is not bundled, or if it is internal to a bundle, the neighbor flags
949 MachineBasicBlock::instr_iterator
950 MachineBasicBlock::erase(MachineBasicBlock::instr_iterator I) {
952 return Insts.erase(I);
955 MachineInstr *MachineBasicBlock::remove_instr(MachineInstr *MI) {
956 unbundleSingleMI(MI);
957 MI->clearFlag(MachineInstr::BundledPred);
958 MI->clearFlag(MachineInstr::BundledSucc);
959 return Insts.remove(MI);
962 MachineBasicBlock::instr_iterator
963 MachineBasicBlock::insert(instr_iterator I, MachineInstr *MI) {
964 assert(!MI->isBundledWithPred() && !MI->isBundledWithSucc() &&
965 "Cannot insert instruction with bundle flags");
966 // Set the bundle flags when inserting inside a bundle.
967 if (I != instr_end() && I->isBundledWithPred()) {
968 MI->setFlag(MachineInstr::BundledPred);
969 MI->setFlag(MachineInstr::BundledSucc);
971 return Insts.insert(I, MI);
974 /// removeFromParent - This method unlinks 'this' from the containing function,
975 /// and returns it, but does not delete it.
976 MachineBasicBlock *MachineBasicBlock::removeFromParent() {
977 assert(getParent() && "Not embedded in a function!");
978 getParent()->remove(this);
983 /// eraseFromParent - This method unlinks 'this' from the containing function,
985 void MachineBasicBlock::eraseFromParent() {
986 assert(getParent() && "Not embedded in a function!");
987 getParent()->erase(this);
991 /// ReplaceUsesOfBlockWith - Given a machine basic block that branched to
992 /// 'Old', change the code and CFG so that it branches to 'New' instead.
993 void MachineBasicBlock::ReplaceUsesOfBlockWith(MachineBasicBlock *Old,
994 MachineBasicBlock *New) {
995 assert(Old != New && "Cannot replace self with self!");
997 MachineBasicBlock::instr_iterator I = instr_end();
998 while (I != instr_begin()) {
1000 if (!I->isTerminator()) break;
1002 // Scan the operands of this machine instruction, replacing any uses of Old
1004 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1005 if (I->getOperand(i).isMBB() &&
1006 I->getOperand(i).getMBB() == Old)
1007 I->getOperand(i).setMBB(New);
1010 // Update the successor information.
1011 replaceSuccessor(Old, New);
1014 /// CorrectExtraCFGEdges - Various pieces of code can cause excess edges in the
1015 /// CFG to be inserted. If we have proven that MBB can only branch to DestA and
1016 /// DestB, remove any other MBB successors from the CFG. DestA and DestB can be
1019 /// Besides DestA and DestB, retain other edges leading to LandingPads
1020 /// (currently there can be only one; we don't check or require that here).
1021 /// Note it is possible that DestA and/or DestB are LandingPads.
1022 bool MachineBasicBlock::CorrectExtraCFGEdges(MachineBasicBlock *DestA,
1023 MachineBasicBlock *DestB,
1025 // The values of DestA and DestB frequently come from a call to the
1026 // 'TargetInstrInfo::AnalyzeBranch' method. We take our meaning of the initial
1027 // values from there.
1029 // 1. If both DestA and DestB are null, then the block ends with no branches
1030 // (it falls through to its successor).
1031 // 2. If DestA is set, DestB is null, and isCond is false, then the block ends
1032 // with only an unconditional branch.
1033 // 3. If DestA is set, DestB is null, and isCond is true, then the block ends
1034 // with a conditional branch that falls through to a successor (DestB).
1035 // 4. If DestA and DestB is set and isCond is true, then the block ends with a
1036 // conditional branch followed by an unconditional branch. DestA is the
1037 // 'true' destination and DestB is the 'false' destination.
1039 bool Changed = false;
1041 MachineFunction::iterator FallThru =
1042 std::next(MachineFunction::iterator(this));
1044 if (!DestA && !DestB) {
1045 // Block falls through to successor.
1048 } else if (DestA && !DestB) {
1050 // Block ends in conditional jump that falls through to successor.
1053 assert(DestA && DestB && isCond &&
1054 "CFG in a bad state. Cannot correct CFG edges");
1057 // Remove superfluous edges. I.e., those which aren't destinations of this
1058 // basic block, duplicate edges, or landing pads.
1059 SmallPtrSet<const MachineBasicBlock*, 8> SeenMBBs;
1060 MachineBasicBlock::succ_iterator SI = succ_begin();
1061 while (SI != succ_end()) {
1062 const MachineBasicBlock *MBB = *SI;
1063 if (!SeenMBBs.insert(MBB).second ||
1064 (MBB != DestA && MBB != DestB && !MBB->isLandingPad())) {
1065 // This is a superfluous edge, remove it.
1066 SI = removeSuccessor(SI);
1076 /// findDebugLoc - find the next valid DebugLoc starting at MBBI, skipping
1077 /// any DBG_VALUE instructions. Return UnknownLoc if there is none.
1079 MachineBasicBlock::findDebugLoc(instr_iterator MBBI) {
1081 instr_iterator E = instr_end();
1085 // Skip debug declarations, we don't want a DebugLoc from them.
1086 while (MBBI != E && MBBI->isDebugValue())
1089 DL = MBBI->getDebugLoc();
1093 /// getSuccWeight - Return weight of the edge from this block to MBB.
1095 uint32_t MachineBasicBlock::getSuccWeight(const_succ_iterator Succ) const {
1096 if (Weights.empty())
1099 return *getWeightIterator(Succ);
1102 /// Set successor weight of a given iterator.
1103 void MachineBasicBlock::setSuccWeight(succ_iterator I, uint32_t weight) {
1104 if (Weights.empty())
1106 *getWeightIterator(I) = weight;
1109 /// getWeightIterator - Return wight iterator corresonding to the I successor
1111 MachineBasicBlock::weight_iterator MachineBasicBlock::
1112 getWeightIterator(MachineBasicBlock::succ_iterator I) {
1113 assert(Weights.size() == Successors.size() && "Async weight list!");
1114 size_t index = std::distance(Successors.begin(), I);
1115 assert(index < Weights.size() && "Not a current successor!");
1116 return Weights.begin() + index;
1119 /// getWeightIterator - Return wight iterator corresonding to the I successor
1121 MachineBasicBlock::const_weight_iterator MachineBasicBlock::
1122 getWeightIterator(MachineBasicBlock::const_succ_iterator I) const {
1123 assert(Weights.size() == Successors.size() && "Async weight list!");
1124 const size_t index = std::distance(Successors.begin(), I);
1125 assert(index < Weights.size() && "Not a current successor!");
1126 return Weights.begin() + index;
1129 /// Return whether (physical) register "Reg" has been <def>ined and not <kill>ed
1130 /// as of just before "MI".
1132 /// Search is localised to a neighborhood of
1133 /// Neighborhood instructions before (searching for defs or kills) and N
1134 /// instructions after (searching just for defs) MI.
1135 MachineBasicBlock::LivenessQueryResult
1136 MachineBasicBlock::computeRegisterLiveness(const TargetRegisterInfo *TRI,
1137 unsigned Reg, MachineInstr *MI,
1138 unsigned Neighborhood) {
1139 unsigned N = Neighborhood;
1140 MachineBasicBlock *MBB = MI->getParent();
1142 // Start by searching backwards from MI, looking for kills, reads or defs.
1144 MachineBasicBlock::iterator I(MI);
1145 // If this is the first insn in the block, don't search backwards.
1146 if (I != MBB->begin()) {
1150 MachineOperandIteratorBase::PhysRegInfo Analysis =
1151 MIOperands(I).analyzePhysReg(Reg, TRI);
1153 if (Analysis.Defines)
1154 // Outputs happen after inputs so they take precedence if both are
1156 return Analysis.DefinesDead ? LQR_Dead : LQR_Live;
1158 if (Analysis.Kills || Analysis.Clobbers)
1159 // Register killed, so isn't live.
1162 else if (Analysis.ReadsOverlap)
1163 // Defined or read without a previous kill - live.
1164 return Analysis.Reads ? LQR_Live : LQR_OverlappingLive;
1166 } while (I != MBB->begin() && --N > 0);
1169 // Did we get to the start of the block?
1170 if (I == MBB->begin()) {
1171 // If so, the register's state is definitely defined by the live-in state.
1172 for (MCRegAliasIterator RAI(Reg, TRI, /*IncludeSelf=*/true);
1173 RAI.isValid(); ++RAI) {
1174 if (MBB->isLiveIn(*RAI))
1175 return (*RAI == Reg) ? LQR_Live : LQR_OverlappingLive;
1183 // Try searching forwards from MI, looking for reads or defs.
1184 I = MachineBasicBlock::iterator(MI);
1185 // If this is the last insn in the block, don't search forwards.
1186 if (I != MBB->end()) {
1187 for (++I; I != MBB->end() && N > 0; ++I, --N) {
1188 MachineOperandIteratorBase::PhysRegInfo Analysis =
1189 MIOperands(I).analyzePhysReg(Reg, TRI);
1191 if (Analysis.ReadsOverlap)
1192 // Used, therefore must have been live.
1193 return (Analysis.Reads) ?
1194 LQR_Live : LQR_OverlappingLive;
1196 else if (Analysis.Clobbers || Analysis.Defines)
1197 // Defined (but not read) therefore cannot have been live.
1202 // At this point we have no idea of the liveness of the register.