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/MC/MCAsmInfo.h"
28 #include "llvm/MC/MCContext.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Support/LeakDetector.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"
38 MachineBasicBlock::MachineBasicBlock(MachineFunction &mf, const BasicBlock *bb)
39 : BB(bb), Number(-1), xParent(&mf), Alignment(0), IsLandingPad(false),
40 AddressTaken(false), CachedMCSymbol(NULL) {
44 MachineBasicBlock::~MachineBasicBlock() {
45 LeakDetector::removeGarbageObject(this);
48 /// getSymbol - 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 TargetMachine &TM = MF->getTarget();
55 const char *Prefix = TM.getDataLayout()->getPrivateGlobalPrefix();
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 /// addNodeToList (MBB) - When an MBB is added to an MF, we need to update the
71 /// parent pointer of the MBB, the MBB numbering, and any instructions in the
72 /// MBB to be on the right 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);
87 LeakDetector::removeGarbageObject(N);
90 void ilist_traits<MachineBasicBlock>::removeNodeFromList(MachineBasicBlock *N) {
91 N->getParent()->removeFromMBBNumbering(N->Number);
93 LeakDetector::addGarbageObject(N);
97 /// addNodeToList (MI) - When we add an instruction to a basic block
98 /// list, we update its parent pointer and add its operands from reg use/def
99 /// lists if appropriate.
100 void ilist_traits<MachineInstr>::addNodeToList(MachineInstr *N) {
101 assert(N->getParent() == 0 && "machine instruction already in a basic block");
102 N->setParent(Parent);
104 // Add the instruction's register operands to their corresponding
106 MachineFunction *MF = Parent->getParent();
107 N->AddRegOperandsToUseLists(MF->getRegInfo());
109 LeakDetector::removeGarbageObject(N);
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() != 0 && "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());
124 LeakDetector::addGarbageObject(N);
127 /// transferNodesFromList (MI) - When moving a range of instructions from one
128 /// MBB list to another, we need to update the parent pointers and the use/def
130 void ilist_traits<MachineInstr>::
131 transferNodesFromList(ilist_traits<MachineInstr> &fromList,
132 ilist_iterator<MachineInstr> first,
133 ilist_iterator<MachineInstr> last) {
134 assert(Parent->getParent() == fromList.Parent->getParent() &&
135 "MachineInstr parent mismatch!");
137 // Splice within the same MBB -> no change.
138 if (Parent == fromList.Parent) return;
140 // If splicing between two blocks within the same function, just update the
142 for (; first != last; ++first)
143 first->setParent(Parent);
146 void ilist_traits<MachineInstr>::deleteNode(MachineInstr* MI) {
147 assert(!MI->getParent() && "MI is still in a block!");
148 Parent->getParent()->DeleteMachineInstr(MI);
151 MachineBasicBlock::iterator MachineBasicBlock::getFirstNonPHI() {
152 instr_iterator I = instr_begin(), E = instr_end();
153 while (I != E && I->isPHI())
155 assert((I == E || !I->isInsideBundle()) &&
156 "First non-phi MI cannot be inside a bundle!");
160 MachineBasicBlock::iterator
161 MachineBasicBlock::SkipPHIsAndLabels(MachineBasicBlock::iterator I) {
163 while (I != E && (I->isPHI() || I->isLabel() || I->isDebugValue()))
165 // FIXME: This needs to change if we wish to bundle labels / dbg_values
166 // inside the bundle.
167 assert((I == E || !I->isInsideBundle()) &&
168 "First non-phi / non-label instruction is inside a bundle!");
172 MachineBasicBlock::iterator MachineBasicBlock::getFirstTerminator() {
173 iterator B = begin(), E = end(), I = E;
174 while (I != B && ((--I)->isTerminator() || I->isDebugValue()))
176 while (I != E && !I->isTerminator())
181 MachineBasicBlock::const_iterator
182 MachineBasicBlock::getFirstTerminator() const {
183 const_iterator B = begin(), E = end(), I = E;
184 while (I != B && ((--I)->isTerminator() || I->isDebugValue()))
186 while (I != E && !I->isTerminator())
191 MachineBasicBlock::instr_iterator MachineBasicBlock::getFirstInstrTerminator() {
192 instr_iterator B = instr_begin(), E = instr_end(), I = E;
193 while (I != B && ((--I)->isTerminator() || I->isDebugValue()))
195 while (I != E && !I->isTerminator())
200 MachineBasicBlock::iterator MachineBasicBlock::getLastNonDebugInstr() {
201 // Skip over end-of-block dbg_value instructions.
202 instr_iterator B = instr_begin(), I = instr_end();
205 // Return instruction that starts a bundle.
206 if (I->isDebugValue() || I->isInsideBundle())
210 // The block is all debug values.
214 MachineBasicBlock::const_iterator
215 MachineBasicBlock::getLastNonDebugInstr() const {
216 // Skip over end-of-block dbg_value instructions.
217 const_instr_iterator B = instr_begin(), I = instr_end();
220 // Return instruction that starts a bundle.
221 if (I->isDebugValue() || I->isInsideBundle())
225 // The block is all debug values.
229 const MachineBasicBlock *MachineBasicBlock::getLandingPadSuccessor() const {
230 // A block with a landing pad successor only has one other successor.
233 for (const_succ_iterator I = succ_begin(), E = succ_end(); I != E; ++I)
234 if ((*I)->isLandingPad())
239 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
240 void MachineBasicBlock::dump() const {
245 StringRef MachineBasicBlock::getName() const {
246 if (const BasicBlock *LBB = getBasicBlock())
247 return LBB->getName();
252 /// Return a hopefully unique identifier for this block.
253 std::string MachineBasicBlock::getFullName() const {
256 Name = (getParent()->getName() + ":").str();
258 Name += getBasicBlock()->getName();
260 Name += (Twine("BB") + Twine(getNumber())).str();
264 void MachineBasicBlock::print(raw_ostream &OS, SlotIndexes *Indexes) const {
265 const MachineFunction *MF = getParent();
267 OS << "Can't print out MachineBasicBlock because parent MachineFunction"
273 OS << Indexes->getMBBStartIdx(this) << '\t';
275 OS << "BB#" << getNumber() << ": ";
277 const char *Comma = "";
278 if (const BasicBlock *LBB = getBasicBlock()) {
279 OS << Comma << "derived from LLVM BB ";
280 LBB->printAsOperand(OS, /*PrintType=*/false);
283 if (isLandingPad()) { OS << Comma << "EH LANDING PAD"; Comma = ", "; }
284 if (hasAddressTaken()) { OS << Comma << "ADDRESS TAKEN"; Comma = ", "; }
286 OS << Comma << "Align " << Alignment << " (" << (1u << Alignment)
291 const TargetRegisterInfo *TRI = MF->getTarget().getRegisterInfo();
292 if (!livein_empty()) {
293 if (Indexes) OS << '\t';
295 for (livein_iterator I = livein_begin(),E = livein_end(); I != E; ++I)
296 OS << ' ' << PrintReg(*I, TRI);
299 // Print the preds of this block according to the CFG.
301 if (Indexes) OS << '\t';
302 OS << " Predecessors according to CFG:";
303 for (const_pred_iterator PI = pred_begin(), E = pred_end(); PI != E; ++PI)
304 OS << " BB#" << (*PI)->getNumber();
308 for (const_instr_iterator I = instr_begin(); I != instr_end(); ++I) {
310 if (Indexes->hasIndex(I))
311 OS << Indexes->getInstructionIndex(I);
315 if (I->isInsideBundle())
317 I->print(OS, &getParent()->getTarget());
320 // Print the successors of this block according to the CFG.
322 if (Indexes) OS << '\t';
323 OS << " Successors according to CFG:";
324 for (const_succ_iterator SI = succ_begin(), E = succ_end(); SI != E; ++SI) {
325 OS << " BB#" << (*SI)->getNumber();
326 if (!Weights.empty())
327 OS << '(' << *getWeightIterator(SI) << ')';
333 void MachineBasicBlock::printAsOperand(raw_ostream &OS, bool /*PrintType*/) {
334 OS << "BB#" << getNumber();
337 void MachineBasicBlock::removeLiveIn(unsigned Reg) {
338 std::vector<unsigned>::iterator I =
339 std::find(LiveIns.begin(), LiveIns.end(), Reg);
340 if (I != LiveIns.end())
344 bool MachineBasicBlock::isLiveIn(unsigned Reg) const {
345 livein_iterator I = std::find(livein_begin(), livein_end(), Reg);
346 return I != livein_end();
350 MachineBasicBlock::addLiveIn(unsigned PhysReg, const TargetRegisterClass *RC) {
351 assert(getParent() && "MBB must be inserted in function");
352 assert(TargetRegisterInfo::isPhysicalRegister(PhysReg) && "Expected physreg");
353 assert(RC && "Register class is required");
354 assert((isLandingPad() || this == &getParent()->front()) &&
355 "Only the entry block and landing pads can have physreg live ins");
357 bool LiveIn = isLiveIn(PhysReg);
358 iterator I = SkipPHIsAndLabels(begin()), E = end();
359 MachineRegisterInfo &MRI = getParent()->getRegInfo();
360 const TargetInstrInfo &TII = *getParent()->getTarget().getInstrInfo();
362 // Look for an existing copy.
364 for (;I != E && I->isCopy(); ++I)
365 if (I->getOperand(1).getReg() == PhysReg) {
366 unsigned VirtReg = I->getOperand(0).getReg();
367 if (!MRI.constrainRegClass(VirtReg, RC))
368 llvm_unreachable("Incompatible live-in register class.");
372 // No luck, create a virtual register.
373 unsigned VirtReg = MRI.createVirtualRegister(RC);
374 BuildMI(*this, I, DebugLoc(), TII.get(TargetOpcode::COPY), VirtReg)
375 .addReg(PhysReg, RegState::Kill);
381 void MachineBasicBlock::moveBefore(MachineBasicBlock *NewAfter) {
382 getParent()->splice(NewAfter, this);
385 void MachineBasicBlock::moveAfter(MachineBasicBlock *NewBefore) {
386 MachineFunction::iterator BBI = NewBefore;
387 getParent()->splice(++BBI, this);
390 void MachineBasicBlock::updateTerminator() {
391 const TargetInstrInfo *TII = getParent()->getTarget().getInstrInfo();
392 // A block with no successors has no concerns with fall-through edges.
393 if (this->succ_empty()) return;
395 MachineBasicBlock *TBB = 0, *FBB = 0;
396 SmallVector<MachineOperand, 4> Cond;
397 DebugLoc dl; // FIXME: this is nowhere
398 bool B = TII->AnalyzeBranch(*this, TBB, FBB, Cond);
400 assert(!B && "UpdateTerminators requires analyzable predecessors!");
403 // The block has an unconditional branch. If its successor is now
404 // its layout successor, delete the branch.
405 if (isLayoutSuccessor(TBB))
406 TII->RemoveBranch(*this);
408 // The block has an unconditional fallthrough. If its successor is not
409 // its layout successor, insert a branch. First we have to locate the
410 // only non-landing-pad successor, as that is the fallthrough block.
411 for (succ_iterator SI = succ_begin(), SE = succ_end(); SI != SE; ++SI) {
412 if ((*SI)->isLandingPad())
414 assert(!TBB && "Found more than one non-landing-pad successor!");
418 // If there is no non-landing-pad successor, the block has no
419 // fall-through edges to be concerned with.
423 // Finally update the unconditional successor to be reached via a branch
424 // if it would not be reached by fallthrough.
425 if (!isLayoutSuccessor(TBB))
426 TII->InsertBranch(*this, TBB, 0, Cond, dl);
430 // The block has a non-fallthrough conditional branch. If one of its
431 // successors is its layout successor, rewrite it to a fallthrough
432 // conditional branch.
433 if (isLayoutSuccessor(TBB)) {
434 if (TII->ReverseBranchCondition(Cond))
436 TII->RemoveBranch(*this);
437 TII->InsertBranch(*this, FBB, 0, Cond, dl);
438 } else if (isLayoutSuccessor(FBB)) {
439 TII->RemoveBranch(*this);
440 TII->InsertBranch(*this, TBB, 0, Cond, dl);
443 // Walk through the successors and find the successor which is not
444 // a landing pad and is not the conditional branch destination (in TBB)
445 // as the fallthrough successor.
446 MachineBasicBlock *FallthroughBB = 0;
447 for (succ_iterator SI = succ_begin(), SE = succ_end(); SI != SE; ++SI) {
448 if ((*SI)->isLandingPad() || *SI == TBB)
450 assert(!FallthroughBB && "Found more than one fallthrough successor.");
453 if (!FallthroughBB && canFallThrough()) {
454 // We fallthrough to the same basic block as the conditional jump
455 // targets. Remove the conditional jump, leaving unconditional
457 // FIXME: This does not seem like a reasonable pattern to support, but it
458 // has been seen in the wild coming out of degenerate ARM test cases.
459 TII->RemoveBranch(*this);
461 // Finally update the unconditional successor to be reached via a branch
462 // if it would not be reached by fallthrough.
463 if (!isLayoutSuccessor(TBB))
464 TII->InsertBranch(*this, TBB, 0, Cond, dl);
468 // The block has a fallthrough conditional branch.
469 if (isLayoutSuccessor(TBB)) {
470 if (TII->ReverseBranchCondition(Cond)) {
471 // We can't reverse the condition, add an unconditional branch.
473 TII->InsertBranch(*this, FallthroughBB, 0, Cond, dl);
476 TII->RemoveBranch(*this);
477 TII->InsertBranch(*this, FallthroughBB, 0, Cond, dl);
478 } else if (!isLayoutSuccessor(FallthroughBB)) {
479 TII->RemoveBranch(*this);
480 TII->InsertBranch(*this, TBB, FallthroughBB, Cond, dl);
486 void MachineBasicBlock::addSuccessor(MachineBasicBlock *succ, uint32_t weight) {
488 // If we see non-zero value for the first time it means we actually use Weight
489 // list, so we fill all Weights with 0's.
490 if (weight != 0 && Weights.empty())
491 Weights.resize(Successors.size());
493 if (weight != 0 || !Weights.empty())
494 Weights.push_back(weight);
496 Successors.push_back(succ);
497 succ->addPredecessor(this);
500 void MachineBasicBlock::removeSuccessor(MachineBasicBlock *succ) {
501 succ->removePredecessor(this);
502 succ_iterator I = std::find(Successors.begin(), Successors.end(), succ);
503 assert(I != Successors.end() && "Not a current successor!");
505 // If Weight list is empty it means we don't use it (disabled optimization).
506 if (!Weights.empty()) {
507 weight_iterator WI = getWeightIterator(I);
514 MachineBasicBlock::succ_iterator
515 MachineBasicBlock::removeSuccessor(succ_iterator I) {
516 assert(I != Successors.end() && "Not a current successor!");
518 // If Weight list is empty it means we don't use it (disabled optimization).
519 if (!Weights.empty()) {
520 weight_iterator WI = getWeightIterator(I);
524 (*I)->removePredecessor(this);
525 return Successors.erase(I);
528 void MachineBasicBlock::replaceSuccessor(MachineBasicBlock *Old,
529 MachineBasicBlock *New) {
533 succ_iterator E = succ_end();
534 succ_iterator NewI = E;
535 succ_iterator OldI = E;
536 for (succ_iterator I = succ_begin(); I != E; ++I) {
548 assert(OldI != E && "Old is not a successor of this block");
549 Old->removePredecessor(this);
551 // If New isn't already a successor, let it take Old's place.
553 New->addPredecessor(this);
558 // New is already a successor.
559 // Update its weight instead of adding a duplicate edge.
560 if (!Weights.empty()) {
561 weight_iterator OldWI = getWeightIterator(OldI);
562 *getWeightIterator(NewI) += *OldWI;
563 Weights.erase(OldWI);
565 Successors.erase(OldI);
568 void MachineBasicBlock::addPredecessor(MachineBasicBlock *pred) {
569 Predecessors.push_back(pred);
572 void MachineBasicBlock::removePredecessor(MachineBasicBlock *pred) {
573 pred_iterator I = std::find(Predecessors.begin(), Predecessors.end(), pred);
574 assert(I != Predecessors.end() && "Pred is not a predecessor of this block!");
575 Predecessors.erase(I);
578 void MachineBasicBlock::transferSuccessors(MachineBasicBlock *fromMBB) {
582 while (!fromMBB->succ_empty()) {
583 MachineBasicBlock *Succ = *fromMBB->succ_begin();
586 // If Weight list is empty it means we don't use it (disabled optimization).
587 if (!fromMBB->Weights.empty())
588 Weight = *fromMBB->Weights.begin();
590 addSuccessor(Succ, Weight);
591 fromMBB->removeSuccessor(Succ);
596 MachineBasicBlock::transferSuccessorsAndUpdatePHIs(MachineBasicBlock *fromMBB) {
600 while (!fromMBB->succ_empty()) {
601 MachineBasicBlock *Succ = *fromMBB->succ_begin();
603 if (!fromMBB->Weights.empty())
604 Weight = *fromMBB->Weights.begin();
605 addSuccessor(Succ, Weight);
606 fromMBB->removeSuccessor(Succ);
608 // Fix up any PHI nodes in the successor.
609 for (MachineBasicBlock::instr_iterator MI = Succ->instr_begin(),
610 ME = Succ->instr_end(); MI != ME && MI->isPHI(); ++MI)
611 for (unsigned i = 2, e = MI->getNumOperands()+1; i != e; i += 2) {
612 MachineOperand &MO = MI->getOperand(i);
613 if (MO.getMBB() == fromMBB)
619 bool MachineBasicBlock::isPredecessor(const MachineBasicBlock *MBB) const {
620 return std::find(pred_begin(), pred_end(), MBB) != pred_end();
623 bool MachineBasicBlock::isSuccessor(const MachineBasicBlock *MBB) const {
624 return std::find(succ_begin(), succ_end(), MBB) != succ_end();
627 bool MachineBasicBlock::isLayoutSuccessor(const MachineBasicBlock *MBB) const {
628 MachineFunction::const_iterator I(this);
629 return llvm::next(I) == MachineFunction::const_iterator(MBB);
632 bool MachineBasicBlock::canFallThrough() {
633 MachineFunction::iterator Fallthrough = this;
635 // If FallthroughBlock is off the end of the function, it can't fall through.
636 if (Fallthrough == getParent()->end())
639 // If FallthroughBlock isn't a successor, no fallthrough is possible.
640 if (!isSuccessor(Fallthrough))
643 // Analyze the branches, if any, at the end of the block.
644 MachineBasicBlock *TBB = 0, *FBB = 0;
645 SmallVector<MachineOperand, 4> Cond;
646 const TargetInstrInfo *TII = getParent()->getTarget().getInstrInfo();
647 if (TII->AnalyzeBranch(*this, TBB, FBB, Cond)) {
648 // If we couldn't analyze the branch, examine the last instruction.
649 // If the block doesn't end in a known control barrier, assume fallthrough
650 // is possible. The isPredicated check is needed because this code can be
651 // called during IfConversion, where an instruction which is normally a
652 // Barrier is predicated and thus no longer an actual control barrier.
653 return empty() || !back().isBarrier() || TII->isPredicated(&back());
656 // If there is no branch, control always falls through.
657 if (TBB == 0) return true;
659 // If there is some explicit branch to the fallthrough block, it can obviously
660 // reach, even though the branch should get folded to fall through implicitly.
661 if (MachineFunction::iterator(TBB) == Fallthrough ||
662 MachineFunction::iterator(FBB) == Fallthrough)
665 // If it's an unconditional branch to some block not the fall through, it
666 // doesn't fall through.
667 if (Cond.empty()) return false;
669 // Otherwise, if it is conditional and has no explicit false block, it falls
675 MachineBasicBlock::SplitCriticalEdge(MachineBasicBlock *Succ, Pass *P) {
676 // Splitting the critical edge to a landing pad block is non-trivial. Don't do
677 // it in this generic function.
678 if (Succ->isLandingPad())
681 MachineFunction *MF = getParent();
682 DebugLoc dl; // FIXME: this is nowhere
684 // Performance might be harmed on HW that implements branching using exec mask
685 // where both sides of the branches are always executed.
686 if (MF->getTarget().requiresStructuredCFG())
689 // We may need to update this's terminator, but we can't do that if
690 // AnalyzeBranch fails. If this uses a jump table, we won't touch it.
691 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
692 MachineBasicBlock *TBB = 0, *FBB = 0;
693 SmallVector<MachineOperand, 4> Cond;
694 if (TII->AnalyzeBranch(*this, TBB, FBB, Cond))
697 // Avoid bugpoint weirdness: A block may end with a conditional branch but
698 // jumps to the same MBB is either case. We have duplicate CFG edges in that
699 // case that we can't handle. Since this never happens in properly optimized
700 // code, just skip those edges.
701 if (TBB && TBB == FBB) {
702 DEBUG(dbgs() << "Won't split critical edge after degenerate BB#"
703 << getNumber() << '\n');
707 MachineBasicBlock *NMBB = MF->CreateMachineBasicBlock();
708 MF->insert(llvm::next(MachineFunction::iterator(this)), NMBB);
709 DEBUG(dbgs() << "Splitting critical edge:"
710 " BB#" << getNumber()
711 << " -- BB#" << NMBB->getNumber()
712 << " -- BB#" << Succ->getNumber() << '\n');
714 LiveIntervals *LIS = P->getAnalysisIfAvailable<LiveIntervals>();
715 SlotIndexes *Indexes = P->getAnalysisIfAvailable<SlotIndexes>();
717 LIS->insertMBBInMaps(NMBB);
719 Indexes->insertMBBInMaps(NMBB);
721 // On some targets like Mips, branches may kill virtual registers. Make sure
722 // that LiveVariables is properly updated after updateTerminator replaces the
724 LiveVariables *LV = P->getAnalysisIfAvailable<LiveVariables>();
726 // Collect a list of virtual registers killed by the terminators.
727 SmallVector<unsigned, 4> KilledRegs;
729 for (instr_iterator I = getFirstInstrTerminator(), E = instr_end();
731 MachineInstr *MI = I;
732 for (MachineInstr::mop_iterator OI = MI->operands_begin(),
733 OE = MI->operands_end(); OI != OE; ++OI) {
734 if (!OI->isReg() || OI->getReg() == 0 ||
735 !OI->isUse() || !OI->isKill() || OI->isUndef())
737 unsigned Reg = OI->getReg();
738 if (TargetRegisterInfo::isPhysicalRegister(Reg) ||
739 LV->getVarInfo(Reg).removeKill(MI)) {
740 KilledRegs.push_back(Reg);
741 DEBUG(dbgs() << "Removing terminator kill: " << *MI);
742 OI->setIsKill(false);
747 SmallVector<unsigned, 4> UsedRegs;
749 for (instr_iterator I = getFirstInstrTerminator(), E = instr_end();
751 MachineInstr *MI = I;
753 for (MachineInstr::mop_iterator OI = MI->operands_begin(),
754 OE = MI->operands_end(); OI != OE; ++OI) {
755 if (!OI->isReg() || OI->getReg() == 0)
758 unsigned Reg = OI->getReg();
759 if (std::find(UsedRegs.begin(), UsedRegs.end(), Reg) == UsedRegs.end())
760 UsedRegs.push_back(Reg);
765 ReplaceUsesOfBlockWith(Succ, NMBB);
767 // If updateTerminator() removes instructions, we need to remove them from
769 SmallVector<MachineInstr*, 4> Terminators;
771 for (instr_iterator I = getFirstInstrTerminator(), E = instr_end();
773 Terminators.push_back(I);
779 SmallVector<MachineInstr*, 4> NewTerminators;
780 for (instr_iterator I = getFirstInstrTerminator(), E = instr_end();
782 NewTerminators.push_back(I);
784 for (SmallVectorImpl<MachineInstr*>::iterator I = Terminators.begin(),
785 E = Terminators.end(); I != E; ++I) {
786 if (std::find(NewTerminators.begin(), NewTerminators.end(), *I) ==
787 NewTerminators.end())
788 Indexes->removeMachineInstrFromMaps(*I);
792 // Insert unconditional "jump Succ" instruction in NMBB if necessary.
793 NMBB->addSuccessor(Succ);
794 if (!NMBB->isLayoutSuccessor(Succ)) {
796 MF->getTarget().getInstrInfo()->InsertBranch(*NMBB, Succ, NULL, Cond, dl);
799 for (instr_iterator I = NMBB->instr_begin(), E = NMBB->instr_end();
801 // Some instructions may have been moved to NMBB by updateTerminator(),
802 // so we first remove any instruction that already has an index.
803 if (Indexes->hasIndex(I))
804 Indexes->removeMachineInstrFromMaps(I);
805 Indexes->insertMachineInstrInMaps(I);
810 // Fix PHI nodes in Succ so they refer to NMBB instead of this
811 for (MachineBasicBlock::instr_iterator
812 i = Succ->instr_begin(),e = Succ->instr_end();
813 i != e && i->isPHI(); ++i)
814 for (unsigned ni = 1, ne = i->getNumOperands(); ni != ne; ni += 2)
815 if (i->getOperand(ni+1).getMBB() == this)
816 i->getOperand(ni+1).setMBB(NMBB);
818 // Inherit live-ins from the successor
819 for (MachineBasicBlock::livein_iterator I = Succ->livein_begin(),
820 E = Succ->livein_end(); I != E; ++I)
823 // Update LiveVariables.
824 const TargetRegisterInfo *TRI = MF->getTarget().getRegisterInfo();
826 // Restore kills of virtual registers that were killed by the terminators.
827 while (!KilledRegs.empty()) {
828 unsigned Reg = KilledRegs.pop_back_val();
829 for (instr_iterator I = instr_end(), E = instr_begin(); I != E;) {
830 if (!(--I)->addRegisterKilled(Reg, TRI, /* addIfNotFound= */ false))
832 if (TargetRegisterInfo::isVirtualRegister(Reg))
833 LV->getVarInfo(Reg).Kills.push_back(I);
834 DEBUG(dbgs() << "Restored terminator kill: " << *I);
838 // Update relevant live-through information.
839 LV->addNewBlock(NMBB, this, Succ);
843 // After splitting the edge and updating SlotIndexes, live intervals may be
844 // in one of two situations, depending on whether this block was the last in
845 // the function. If the original block was the last in the function, all live
846 // intervals will end prior to the beginning of the new split block. If the
847 // original block was not at the end of the function, all live intervals will
848 // extend to the end of the new split block.
851 llvm::next(MachineFunction::iterator(NMBB)) == getParent()->end();
853 SlotIndex StartIndex = Indexes->getMBBEndIdx(this);
854 SlotIndex PrevIndex = StartIndex.getPrevSlot();
855 SlotIndex EndIndex = Indexes->getMBBEndIdx(NMBB);
857 // Find the registers used from NMBB in PHIs in Succ.
858 SmallSet<unsigned, 8> PHISrcRegs;
859 for (MachineBasicBlock::instr_iterator
860 I = Succ->instr_begin(), E = Succ->instr_end();
861 I != E && I->isPHI(); ++I) {
862 for (unsigned ni = 1, ne = I->getNumOperands(); ni != ne; ni += 2) {
863 if (I->getOperand(ni+1).getMBB() == NMBB) {
864 MachineOperand &MO = I->getOperand(ni);
865 unsigned Reg = MO.getReg();
866 PHISrcRegs.insert(Reg);
870 LiveInterval &LI = LIS->getInterval(Reg);
871 VNInfo *VNI = LI.getVNInfoAt(PrevIndex);
872 assert(VNI && "PHI sources should be live out of their predecessors.");
873 LI.addSegment(LiveInterval::Segment(StartIndex, EndIndex, VNI));
878 MachineRegisterInfo *MRI = &getParent()->getRegInfo();
879 for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
880 unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
881 if (PHISrcRegs.count(Reg) || !LIS->hasInterval(Reg))
884 LiveInterval &LI = LIS->getInterval(Reg);
885 if (!LI.liveAt(PrevIndex))
888 bool isLiveOut = LI.liveAt(LIS->getMBBStartIdx(Succ));
889 if (isLiveOut && isLastMBB) {
890 VNInfo *VNI = LI.getVNInfoAt(PrevIndex);
891 assert(VNI && "LiveInterval should have VNInfo where it is live.");
892 LI.addSegment(LiveInterval::Segment(StartIndex, EndIndex, VNI));
893 } else if (!isLiveOut && !isLastMBB) {
894 LI.removeSegment(StartIndex, EndIndex);
898 // Update all intervals for registers whose uses may have been modified by
899 // updateTerminator().
900 LIS->repairIntervalsInRange(this, getFirstTerminator(), end(), UsedRegs);
903 if (MachineDominatorTree *MDT =
904 P->getAnalysisIfAvailable<MachineDominatorTree>()) {
905 // Update dominator information.
906 MachineDomTreeNode *SucccDTNode = MDT->getNode(Succ);
908 bool IsNewIDom = true;
909 for (const_pred_iterator PI = Succ->pred_begin(), E = Succ->pred_end();
911 MachineBasicBlock *PredBB = *PI;
914 if (!MDT->dominates(SucccDTNode, MDT->getNode(PredBB))) {
920 // We know "this" dominates the newly created basic block.
921 MachineDomTreeNode *NewDTNode = MDT->addNewBlock(NMBB, this);
923 // If all the other predecessors of "Succ" are dominated by "Succ" itself
924 // then the new block is the new immediate dominator of "Succ". Otherwise,
925 // the new block doesn't dominate anything.
927 MDT->changeImmediateDominator(SucccDTNode, NewDTNode);
930 if (MachineLoopInfo *MLI = P->getAnalysisIfAvailable<MachineLoopInfo>())
931 if (MachineLoop *TIL = MLI->getLoopFor(this)) {
932 // If one or the other blocks were not in a loop, the new block is not
933 // either, and thus LI doesn't need to be updated.
934 if (MachineLoop *DestLoop = MLI->getLoopFor(Succ)) {
935 if (TIL == DestLoop) {
936 // Both in the same loop, the NMBB joins loop.
937 DestLoop->addBasicBlockToLoop(NMBB, MLI->getBase());
938 } else if (TIL->contains(DestLoop)) {
939 // Edge from an outer loop to an inner loop. Add to the outer loop.
940 TIL->addBasicBlockToLoop(NMBB, MLI->getBase());
941 } else if (DestLoop->contains(TIL)) {
942 // Edge from an inner loop to an outer loop. Add to the outer loop.
943 DestLoop->addBasicBlockToLoop(NMBB, MLI->getBase());
945 // Edge from two loops with no containment relation. Because these
946 // are natural loops, we know that the destination block must be the
947 // header of its loop (adding a branch into a loop elsewhere would
948 // create an irreducible loop).
949 assert(DestLoop->getHeader() == Succ &&
950 "Should not create irreducible loops!");
951 if (MachineLoop *P = DestLoop->getParentLoop())
952 P->addBasicBlockToLoop(NMBB, MLI->getBase());
960 /// Prepare MI to be removed from its bundle. This fixes bundle flags on MI's
961 /// neighboring instructions so the bundle won't be broken by removing MI.
962 static void unbundleSingleMI(MachineInstr *MI) {
963 // Removing the first instruction in a bundle.
964 if (MI->isBundledWithSucc() && !MI->isBundledWithPred())
965 MI->unbundleFromSucc();
966 // Removing the last instruction in a bundle.
967 if (MI->isBundledWithPred() && !MI->isBundledWithSucc())
968 MI->unbundleFromPred();
969 // If MI is not bundled, or if it is internal to a bundle, the neighbor flags
973 MachineBasicBlock::instr_iterator
974 MachineBasicBlock::erase(MachineBasicBlock::instr_iterator I) {
976 return Insts.erase(I);
979 MachineInstr *MachineBasicBlock::remove_instr(MachineInstr *MI) {
980 unbundleSingleMI(MI);
981 MI->clearFlag(MachineInstr::BundledPred);
982 MI->clearFlag(MachineInstr::BundledSucc);
983 return Insts.remove(MI);
986 MachineBasicBlock::instr_iterator
987 MachineBasicBlock::insert(instr_iterator I, MachineInstr *MI) {
988 assert(!MI->isBundledWithPred() && !MI->isBundledWithSucc() &&
989 "Cannot insert instruction with bundle flags");
990 // Set the bundle flags when inserting inside a bundle.
991 if (I != instr_end() && I->isBundledWithPred()) {
992 MI->setFlag(MachineInstr::BundledPred);
993 MI->setFlag(MachineInstr::BundledSucc);
995 return Insts.insert(I, MI);
998 /// removeFromParent - This method unlinks 'this' from the containing function,
999 /// and returns it, but does not delete it.
1000 MachineBasicBlock *MachineBasicBlock::removeFromParent() {
1001 assert(getParent() && "Not embedded in a function!");
1002 getParent()->remove(this);
1007 /// eraseFromParent - This method unlinks 'this' from the containing function,
1009 void MachineBasicBlock::eraseFromParent() {
1010 assert(getParent() && "Not embedded in a function!");
1011 getParent()->erase(this);
1015 /// ReplaceUsesOfBlockWith - Given a machine basic block that branched to
1016 /// 'Old', change the code and CFG so that it branches to 'New' instead.
1017 void MachineBasicBlock::ReplaceUsesOfBlockWith(MachineBasicBlock *Old,
1018 MachineBasicBlock *New) {
1019 assert(Old != New && "Cannot replace self with self!");
1021 MachineBasicBlock::instr_iterator I = instr_end();
1022 while (I != instr_begin()) {
1024 if (!I->isTerminator()) break;
1026 // Scan the operands of this machine instruction, replacing any uses of Old
1028 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1029 if (I->getOperand(i).isMBB() &&
1030 I->getOperand(i).getMBB() == Old)
1031 I->getOperand(i).setMBB(New);
1034 // Update the successor information.
1035 replaceSuccessor(Old, New);
1038 /// CorrectExtraCFGEdges - Various pieces of code can cause excess edges in the
1039 /// CFG to be inserted. If we have proven that MBB can only branch to DestA and
1040 /// DestB, remove any other MBB successors from the CFG. DestA and DestB can be
1043 /// Besides DestA and DestB, retain other edges leading to LandingPads
1044 /// (currently there can be only one; we don't check or require that here).
1045 /// Note it is possible that DestA and/or DestB are LandingPads.
1046 bool MachineBasicBlock::CorrectExtraCFGEdges(MachineBasicBlock *DestA,
1047 MachineBasicBlock *DestB,
1049 // The values of DestA and DestB frequently come from a call to the
1050 // 'TargetInstrInfo::AnalyzeBranch' method. We take our meaning of the initial
1051 // values from there.
1053 // 1. If both DestA and DestB are null, then the block ends with no branches
1054 // (it falls through to its successor).
1055 // 2. If DestA is set, DestB is null, and isCond is false, then the block ends
1056 // with only an unconditional branch.
1057 // 3. If DestA is set, DestB is null, and isCond is true, then the block ends
1058 // with a conditional branch that falls through to a successor (DestB).
1059 // 4. If DestA and DestB is set and isCond is true, then the block ends with a
1060 // conditional branch followed by an unconditional branch. DestA is the
1061 // 'true' destination and DestB is the 'false' destination.
1063 bool Changed = false;
1065 MachineFunction::iterator FallThru =
1066 llvm::next(MachineFunction::iterator(this));
1068 if (DestA == 0 && DestB == 0) {
1069 // Block falls through to successor.
1072 } else if (DestA != 0 && DestB == 0) {
1074 // Block ends in conditional jump that falls through to successor.
1077 assert(DestA && DestB && isCond &&
1078 "CFG in a bad state. Cannot correct CFG edges");
1081 // Remove superfluous edges. I.e., those which aren't destinations of this
1082 // basic block, duplicate edges, or landing pads.
1083 SmallPtrSet<const MachineBasicBlock*, 8> SeenMBBs;
1084 MachineBasicBlock::succ_iterator SI = succ_begin();
1085 while (SI != succ_end()) {
1086 const MachineBasicBlock *MBB = *SI;
1087 if (!SeenMBBs.insert(MBB) ||
1088 (MBB != DestA && MBB != DestB && !MBB->isLandingPad())) {
1089 // This is a superfluous edge, remove it.
1090 SI = removeSuccessor(SI);
1100 /// findDebugLoc - find the next valid DebugLoc starting at MBBI, skipping
1101 /// any DBG_VALUE instructions. Return UnknownLoc if there is none.
1103 MachineBasicBlock::findDebugLoc(instr_iterator MBBI) {
1105 instr_iterator E = instr_end();
1109 // Skip debug declarations, we don't want a DebugLoc from them.
1110 while (MBBI != E && MBBI->isDebugValue())
1113 DL = MBBI->getDebugLoc();
1117 /// getSuccWeight - Return weight of the edge from this block to MBB.
1119 uint32_t MachineBasicBlock::getSuccWeight(const_succ_iterator Succ) const {
1120 if (Weights.empty())
1123 return *getWeightIterator(Succ);
1126 /// getWeightIterator - Return wight iterator corresonding to the I successor
1128 MachineBasicBlock::weight_iterator MachineBasicBlock::
1129 getWeightIterator(MachineBasicBlock::succ_iterator I) {
1130 assert(Weights.size() == Successors.size() && "Async weight list!");
1131 size_t index = std::distance(Successors.begin(), I);
1132 assert(index < Weights.size() && "Not a current successor!");
1133 return Weights.begin() + index;
1136 /// getWeightIterator - Return wight iterator corresonding to the I successor
1138 MachineBasicBlock::const_weight_iterator MachineBasicBlock::
1139 getWeightIterator(MachineBasicBlock::const_succ_iterator I) const {
1140 assert(Weights.size() == Successors.size() && "Async weight list!");
1141 const size_t index = std::distance(Successors.begin(), I);
1142 assert(index < Weights.size() && "Not a current successor!");
1143 return Weights.begin() + index;
1146 /// Return whether (physical) register "Reg" has been <def>ined and not <kill>ed
1147 /// as of just before "MI".
1149 /// Search is localised to a neighborhood of
1150 /// Neighborhood instructions before (searching for defs or kills) and N
1151 /// instructions after (searching just for defs) MI.
1152 MachineBasicBlock::LivenessQueryResult
1153 MachineBasicBlock::computeRegisterLiveness(const TargetRegisterInfo *TRI,
1154 unsigned Reg, MachineInstr *MI,
1155 unsigned Neighborhood) {
1156 unsigned N = Neighborhood;
1157 MachineBasicBlock *MBB = MI->getParent();
1159 // Start by searching backwards from MI, looking for kills, reads or defs.
1161 MachineBasicBlock::iterator I(MI);
1162 // If this is the first insn in the block, don't search backwards.
1163 if (I != MBB->begin()) {
1167 MachineOperandIteratorBase::PhysRegInfo Analysis =
1168 MIOperands(I).analyzePhysReg(Reg, TRI);
1170 if (Analysis.Defines)
1171 // Outputs happen after inputs so they take precedence if both are
1173 return Analysis.DefinesDead ? LQR_Dead : LQR_Live;
1175 if (Analysis.Kills || Analysis.Clobbers)
1176 // Register killed, so isn't live.
1179 else if (Analysis.ReadsOverlap)
1180 // Defined or read without a previous kill - live.
1181 return Analysis.Reads ? LQR_Live : LQR_OverlappingLive;
1183 } while (I != MBB->begin() && --N > 0);
1186 // Did we get to the start of the block?
1187 if (I == MBB->begin()) {
1188 // If so, the register's state is definitely defined by the live-in state.
1189 for (MCRegAliasIterator RAI(Reg, TRI, /*IncludeSelf=*/true);
1190 RAI.isValid(); ++RAI) {
1191 if (MBB->isLiveIn(*RAI))
1192 return (*RAI == Reg) ? LQR_Live : LQR_OverlappingLive;
1200 // Try searching forwards from MI, looking for reads or defs.
1201 I = MachineBasicBlock::iterator(MI);
1202 // If this is the last insn in the block, don't search forwards.
1203 if (I != MBB->end()) {
1204 for (++I; I != MBB->end() && N > 0; ++I, --N) {
1205 MachineOperandIteratorBase::PhysRegInfo Analysis =
1206 MIOperands(I).analyzePhysReg(Reg, TRI);
1208 if (Analysis.ReadsOverlap)
1209 // Used, therefore must have been live.
1210 return (Analysis.Reads) ?
1211 LQR_Live : LQR_OverlappingLive;
1213 else if (Analysis.Clobbers || Analysis.Defines)
1214 // Defined (but not read) therefore cannot have been live.
1219 // At this point we have no idea of the liveness of the register.