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/Assembly/Writer.h"
18 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
19 #include "llvm/CodeGen/LiveVariables.h"
20 #include "llvm/CodeGen/MachineDominators.h"
21 #include "llvm/CodeGen/MachineFunction.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 char *Prefix = Ctx.getAsmInfo().getPrivateGlobalPrefix();
55 CachedMCSymbol = Ctx.GetOrCreateSymbol(Twine(Prefix) + "BB" +
56 Twine(MF->getFunctionNumber()) +
57 "_" + Twine(getNumber()));
60 return CachedMCSymbol;
64 raw_ostream &llvm::operator<<(raw_ostream &OS, const MachineBasicBlock &MBB) {
69 /// addNodeToList (MBB) - When an MBB is added to an MF, we need to update the
70 /// parent pointer of the MBB, the MBB numbering, and any instructions in the
71 /// MBB to be on the right operand list for registers.
73 /// MBBs start out as #-1. When a MBB is added to a MachineFunction, it
74 /// gets the next available unique MBB number. If it is removed from a
75 /// MachineFunction, it goes back to being #-1.
76 void ilist_traits<MachineBasicBlock>::addNodeToList(MachineBasicBlock *N) {
77 MachineFunction &MF = *N->getParent();
78 N->Number = MF.addToMBBNumbering(N);
80 // Make sure the instructions have their operands in the reginfo lists.
81 MachineRegisterInfo &RegInfo = MF.getRegInfo();
82 for (MachineBasicBlock::instr_iterator
83 I = N->instr_begin(), E = N->instr_end(); I != E; ++I)
84 I->AddRegOperandsToUseLists(RegInfo);
86 LeakDetector::removeGarbageObject(N);
89 void ilist_traits<MachineBasicBlock>::removeNodeFromList(MachineBasicBlock *N) {
90 N->getParent()->removeFromMBBNumbering(N->Number);
92 LeakDetector::addGarbageObject(N);
96 /// addNodeToList (MI) - When we add an instruction to a basic block
97 /// list, we update its parent pointer and add its operands from reg use/def
98 /// lists if appropriate.
99 void ilist_traits<MachineInstr>::addNodeToList(MachineInstr *N) {
100 assert(N->getParent() == 0 && "machine instruction already in a basic block");
101 N->setParent(Parent);
103 // Add the instruction's register operands to their corresponding
105 MachineFunction *MF = Parent->getParent();
106 N->AddRegOperandsToUseLists(MF->getRegInfo());
108 LeakDetector::removeGarbageObject(N);
111 /// removeNodeFromList (MI) - When we remove an instruction from a basic block
112 /// list, we update its parent pointer and remove its operands from reg use/def
113 /// lists if appropriate.
114 void ilist_traits<MachineInstr>::removeNodeFromList(MachineInstr *N) {
115 assert(N->getParent() != 0 && "machine instruction not in a basic block");
117 // Remove from the use/def lists.
118 if (MachineFunction *MF = N->getParent()->getParent())
119 N->RemoveRegOperandsFromUseLists(MF->getRegInfo());
123 LeakDetector::addGarbageObject(N);
126 /// transferNodesFromList (MI) - When moving a range of instructions from one
127 /// MBB list to another, we need to update the parent pointers and the use/def
129 void ilist_traits<MachineInstr>::
130 transferNodesFromList(ilist_traits<MachineInstr> &fromList,
131 ilist_iterator<MachineInstr> first,
132 ilist_iterator<MachineInstr> last) {
133 assert(Parent->getParent() == fromList.Parent->getParent() &&
134 "MachineInstr parent mismatch!");
136 // Splice within the same MBB -> no change.
137 if (Parent == fromList.Parent) return;
139 // If splicing between two blocks within the same function, just update the
141 for (; first != last; ++first)
142 first->setParent(Parent);
145 void ilist_traits<MachineInstr>::deleteNode(MachineInstr* MI) {
146 assert(!MI->getParent() && "MI is still in a block!");
147 Parent->getParent()->DeleteMachineInstr(MI);
150 MachineBasicBlock::iterator MachineBasicBlock::getFirstNonPHI() {
151 instr_iterator I = instr_begin(), E = instr_end();
152 while (I != E && I->isPHI())
154 assert((I == E || !I->isInsideBundle()) &&
155 "First non-phi MI cannot be inside a bundle!");
159 MachineBasicBlock::iterator
160 MachineBasicBlock::SkipPHIsAndLabels(MachineBasicBlock::iterator I) {
162 while (I != E && (I->isPHI() || I->isLabel() || I->isDebugValue()))
164 // FIXME: This needs to change if we wish to bundle labels / dbg_values
165 // inside the bundle.
166 assert((I == E || !I->isInsideBundle()) &&
167 "First non-phi / non-label instruction is inside a bundle!");
171 MachineBasicBlock::iterator MachineBasicBlock::getFirstTerminator() {
172 iterator B = begin(), E = end(), I = E;
173 while (I != B && ((--I)->isTerminator() || I->isDebugValue()))
175 while (I != E && !I->isTerminator())
180 MachineBasicBlock::const_iterator
181 MachineBasicBlock::getFirstTerminator() const {
182 const_iterator B = begin(), E = end(), I = E;
183 while (I != B && ((--I)->isTerminator() || I->isDebugValue()))
185 while (I != E && !I->isTerminator())
190 MachineBasicBlock::instr_iterator MachineBasicBlock::getFirstInstrTerminator() {
191 instr_iterator B = instr_begin(), E = instr_end(), I = E;
192 while (I != B && ((--I)->isTerminator() || I->isDebugValue()))
194 while (I != E && !I->isTerminator())
199 MachineBasicBlock::iterator MachineBasicBlock::getLastNonDebugInstr() {
200 // Skip over end-of-block dbg_value instructions.
201 instr_iterator B = instr_begin(), I = instr_end();
204 // Return instruction that starts a bundle.
205 if (I->isDebugValue() || I->isInsideBundle())
209 // The block is all debug values.
213 MachineBasicBlock::const_iterator
214 MachineBasicBlock::getLastNonDebugInstr() const {
215 // Skip over end-of-block dbg_value instructions.
216 const_instr_iterator B = instr_begin(), I = instr_end();
219 // Return instruction that starts a bundle.
220 if (I->isDebugValue() || I->isInsideBundle())
224 // The block is all debug values.
228 const MachineBasicBlock *MachineBasicBlock::getLandingPadSuccessor() const {
229 // A block with a landing pad successor only has one other successor.
232 for (const_succ_iterator I = succ_begin(), E = succ_end(); I != E; ++I)
233 if ((*I)->isLandingPad())
238 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
239 void MachineBasicBlock::dump() const {
244 StringRef MachineBasicBlock::getName() const {
245 if (const BasicBlock *LBB = getBasicBlock())
246 return LBB->getName();
251 /// Return a hopefully unique identifier for this block.
252 std::string MachineBasicBlock::getFullName() const {
255 Name = (getParent()->getName() + ":").str();
257 Name += getBasicBlock()->getName();
259 Name += (Twine("BB") + Twine(getNumber())).str();
263 void MachineBasicBlock::print(raw_ostream &OS, SlotIndexes *Indexes) const {
264 const MachineFunction *MF = getParent();
266 OS << "Can't print out MachineBasicBlock because parent MachineFunction"
272 OS << Indexes->getMBBStartIdx(this) << '\t';
274 OS << "BB#" << getNumber() << ": ";
276 const char *Comma = "";
277 if (const BasicBlock *LBB = getBasicBlock()) {
278 OS << Comma << "derived from LLVM BB ";
279 WriteAsOperand(OS, LBB, /*PrintType=*/false);
282 if (isLandingPad()) { OS << Comma << "EH LANDING PAD"; Comma = ", "; }
283 if (hasAddressTaken()) { OS << Comma << "ADDRESS TAKEN"; Comma = ", "; }
285 OS << Comma << "Align " << Alignment << " (" << (1u << Alignment)
290 const TargetRegisterInfo *TRI = MF->getTarget().getRegisterInfo();
291 if (!livein_empty()) {
292 if (Indexes) OS << '\t';
294 for (livein_iterator I = livein_begin(),E = livein_end(); I != E; ++I)
295 OS << ' ' << PrintReg(*I, TRI);
298 // Print the preds of this block according to the CFG.
300 if (Indexes) OS << '\t';
301 OS << " Predecessors according to CFG:";
302 for (const_pred_iterator PI = pred_begin(), E = pred_end(); PI != E; ++PI)
303 OS << " BB#" << (*PI)->getNumber();
307 for (const_instr_iterator I = instr_begin(); I != instr_end(); ++I) {
309 if (Indexes->hasIndex(I))
310 OS << Indexes->getInstructionIndex(I);
314 if (I->isInsideBundle())
316 I->print(OS, &getParent()->getTarget());
319 // Print the successors of this block according to the CFG.
321 if (Indexes) OS << '\t';
322 OS << " Successors according to CFG:";
323 for (const_succ_iterator SI = succ_begin(), E = succ_end(); SI != E; ++SI) {
324 OS << " BB#" << (*SI)->getNumber();
325 if (!Weights.empty())
326 OS << '(' << *getWeightIterator(SI) << ')';
332 void MachineBasicBlock::removeLiveIn(unsigned Reg) {
333 std::vector<unsigned>::iterator I =
334 std::find(LiveIns.begin(), LiveIns.end(), Reg);
335 if (I != LiveIns.end())
339 bool MachineBasicBlock::isLiveIn(unsigned Reg) const {
340 livein_iterator I = std::find(livein_begin(), livein_end(), Reg);
341 return I != livein_end();
344 void MachineBasicBlock::moveBefore(MachineBasicBlock *NewAfter) {
345 getParent()->splice(NewAfter, this);
348 void MachineBasicBlock::moveAfter(MachineBasicBlock *NewBefore) {
349 MachineFunction::iterator BBI = NewBefore;
350 getParent()->splice(++BBI, this);
353 void MachineBasicBlock::updateTerminator() {
354 const TargetInstrInfo *TII = getParent()->getTarget().getInstrInfo();
355 // A block with no successors has no concerns with fall-through edges.
356 if (this->succ_empty()) return;
358 MachineBasicBlock *TBB = 0, *FBB = 0;
359 SmallVector<MachineOperand, 4> Cond;
360 DebugLoc dl; // FIXME: this is nowhere
361 bool B = TII->AnalyzeBranch(*this, TBB, FBB, Cond);
363 assert(!B && "UpdateTerminators requires analyzable predecessors!");
366 // The block has an unconditional branch. If its successor is now
367 // its layout successor, delete the branch.
368 if (isLayoutSuccessor(TBB))
369 TII->RemoveBranch(*this);
371 // The block has an unconditional fallthrough. If its successor is not
372 // its layout successor, insert a branch. First we have to locate the
373 // only non-landing-pad successor, as that is the fallthrough block.
374 for (succ_iterator SI = succ_begin(), SE = succ_end(); SI != SE; ++SI) {
375 if ((*SI)->isLandingPad())
377 assert(!TBB && "Found more than one non-landing-pad successor!");
381 // If there is no non-landing-pad successor, the block has no
382 // fall-through edges to be concerned with.
386 // Finally update the unconditional successor to be reached via a branch
387 // if it would not be reached by fallthrough.
388 if (!isLayoutSuccessor(TBB))
389 TII->InsertBranch(*this, TBB, 0, Cond, dl);
393 // The block has a non-fallthrough conditional branch. If one of its
394 // successors is its layout successor, rewrite it to a fallthrough
395 // conditional branch.
396 if (isLayoutSuccessor(TBB)) {
397 if (TII->ReverseBranchCondition(Cond))
399 TII->RemoveBranch(*this);
400 TII->InsertBranch(*this, FBB, 0, Cond, dl);
401 } else if (isLayoutSuccessor(FBB)) {
402 TII->RemoveBranch(*this);
403 TII->InsertBranch(*this, TBB, 0, Cond, dl);
406 // Walk through the successors and find the successor which is not
407 // a landing pad and is not the conditional branch destination (in TBB)
408 // as the fallthrough successor.
409 MachineBasicBlock *FallthroughBB = 0;
410 for (succ_iterator SI = succ_begin(), SE = succ_end(); SI != SE; ++SI) {
411 if ((*SI)->isLandingPad() || *SI == TBB)
413 assert(!FallthroughBB && "Found more than one fallthrough successor.");
416 if (!FallthroughBB && canFallThrough()) {
417 // We fallthrough to the same basic block as the conditional jump
418 // targets. Remove the conditional jump, leaving unconditional
420 // FIXME: This does not seem like a reasonable pattern to support, but it
421 // has been seen in the wild coming out of degenerate ARM test cases.
422 TII->RemoveBranch(*this);
424 // Finally update the unconditional successor to be reached via a branch
425 // if it would not be reached by fallthrough.
426 if (!isLayoutSuccessor(TBB))
427 TII->InsertBranch(*this, TBB, 0, Cond, dl);
431 // The block has a fallthrough conditional branch.
432 if (isLayoutSuccessor(TBB)) {
433 if (TII->ReverseBranchCondition(Cond)) {
434 // We can't reverse the condition, add an unconditional branch.
436 TII->InsertBranch(*this, FallthroughBB, 0, Cond, dl);
439 TII->RemoveBranch(*this);
440 TII->InsertBranch(*this, FallthroughBB, 0, Cond, dl);
441 } else if (!isLayoutSuccessor(FallthroughBB)) {
442 TII->RemoveBranch(*this);
443 TII->InsertBranch(*this, TBB, FallthroughBB, Cond, dl);
449 void MachineBasicBlock::addSuccessor(MachineBasicBlock *succ, uint32_t weight) {
451 // If we see non-zero value for the first time it means we actually use Weight
452 // list, so we fill all Weights with 0's.
453 if (weight != 0 && Weights.empty())
454 Weights.resize(Successors.size());
456 if (weight != 0 || !Weights.empty())
457 Weights.push_back(weight);
459 Successors.push_back(succ);
460 succ->addPredecessor(this);
463 void MachineBasicBlock::removeSuccessor(MachineBasicBlock *succ) {
464 succ->removePredecessor(this);
465 succ_iterator I = std::find(Successors.begin(), Successors.end(), succ);
466 assert(I != Successors.end() && "Not a current successor!");
468 // If Weight list is empty it means we don't use it (disabled optimization).
469 if (!Weights.empty()) {
470 weight_iterator WI = getWeightIterator(I);
477 MachineBasicBlock::succ_iterator
478 MachineBasicBlock::removeSuccessor(succ_iterator I) {
479 assert(I != Successors.end() && "Not a current successor!");
481 // If Weight list is empty it means we don't use it (disabled optimization).
482 if (!Weights.empty()) {
483 weight_iterator WI = getWeightIterator(I);
487 (*I)->removePredecessor(this);
488 return Successors.erase(I);
491 void MachineBasicBlock::replaceSuccessor(MachineBasicBlock *Old,
492 MachineBasicBlock *New) {
496 succ_iterator E = succ_end();
497 succ_iterator NewI = E;
498 succ_iterator OldI = E;
499 for (succ_iterator I = succ_begin(); I != E; ++I) {
511 assert(OldI != E && "Old is not a successor of this block");
512 Old->removePredecessor(this);
514 // If New isn't already a successor, let it take Old's place.
516 New->addPredecessor(this);
521 // New is already a successor.
522 // Update its weight instead of adding a duplicate edge.
523 if (!Weights.empty()) {
524 weight_iterator OldWI = getWeightIterator(OldI);
525 *getWeightIterator(NewI) += *OldWI;
526 Weights.erase(OldWI);
528 Successors.erase(OldI);
531 void MachineBasicBlock::addPredecessor(MachineBasicBlock *pred) {
532 Predecessors.push_back(pred);
535 void MachineBasicBlock::removePredecessor(MachineBasicBlock *pred) {
536 pred_iterator I = std::find(Predecessors.begin(), Predecessors.end(), pred);
537 assert(I != Predecessors.end() && "Pred is not a predecessor of this block!");
538 Predecessors.erase(I);
541 void MachineBasicBlock::transferSuccessors(MachineBasicBlock *fromMBB) {
545 while (!fromMBB->succ_empty()) {
546 MachineBasicBlock *Succ = *fromMBB->succ_begin();
549 // If Weight list is empty it means we don't use it (disabled optimization).
550 if (!fromMBB->Weights.empty())
551 Weight = *fromMBB->Weights.begin();
553 addSuccessor(Succ, Weight);
554 fromMBB->removeSuccessor(Succ);
559 MachineBasicBlock::transferSuccessorsAndUpdatePHIs(MachineBasicBlock *fromMBB) {
563 while (!fromMBB->succ_empty()) {
564 MachineBasicBlock *Succ = *fromMBB->succ_begin();
566 if (!fromMBB->Weights.empty())
567 Weight = *fromMBB->Weights.begin();
568 addSuccessor(Succ, Weight);
569 fromMBB->removeSuccessor(Succ);
571 // Fix up any PHI nodes in the successor.
572 for (MachineBasicBlock::instr_iterator MI = Succ->instr_begin(),
573 ME = Succ->instr_end(); MI != ME && MI->isPHI(); ++MI)
574 for (unsigned i = 2, e = MI->getNumOperands()+1; i != e; i += 2) {
575 MachineOperand &MO = MI->getOperand(i);
576 if (MO.getMBB() == fromMBB)
582 bool MachineBasicBlock::isPredecessor(const MachineBasicBlock *MBB) const {
583 return std::find(pred_begin(), pred_end(), MBB) != pred_end();
586 bool MachineBasicBlock::isSuccessor(const MachineBasicBlock *MBB) const {
587 return std::find(succ_begin(), succ_end(), MBB) != succ_end();
590 bool MachineBasicBlock::isLayoutSuccessor(const MachineBasicBlock *MBB) const {
591 MachineFunction::const_iterator I(this);
592 return llvm::next(I) == MachineFunction::const_iterator(MBB);
595 bool MachineBasicBlock::canFallThrough() {
596 MachineFunction::iterator Fallthrough = this;
598 // If FallthroughBlock is off the end of the function, it can't fall through.
599 if (Fallthrough == getParent()->end())
602 // If FallthroughBlock isn't a successor, no fallthrough is possible.
603 if (!isSuccessor(Fallthrough))
606 // Analyze the branches, if any, at the end of the block.
607 MachineBasicBlock *TBB = 0, *FBB = 0;
608 SmallVector<MachineOperand, 4> Cond;
609 const TargetInstrInfo *TII = getParent()->getTarget().getInstrInfo();
610 if (TII->AnalyzeBranch(*this, TBB, FBB, Cond)) {
611 // If we couldn't analyze the branch, examine the last instruction.
612 // If the block doesn't end in a known control barrier, assume fallthrough
613 // is possible. The isPredicated check is needed because this code can be
614 // called during IfConversion, where an instruction which is normally a
615 // Barrier is predicated and thus no longer an actual control barrier.
616 return empty() || !back().isBarrier() || TII->isPredicated(&back());
619 // If there is no branch, control always falls through.
620 if (TBB == 0) return true;
622 // If there is some explicit branch to the fallthrough block, it can obviously
623 // reach, even though the branch should get folded to fall through implicitly.
624 if (MachineFunction::iterator(TBB) == Fallthrough ||
625 MachineFunction::iterator(FBB) == Fallthrough)
628 // If it's an unconditional branch to some block not the fall through, it
629 // doesn't fall through.
630 if (Cond.empty()) return false;
632 // Otherwise, if it is conditional and has no explicit false block, it falls
638 MachineBasicBlock::SplitCriticalEdge(MachineBasicBlock *Succ, Pass *P) {
639 // Splitting the critical edge to a landing pad block is non-trivial. Don't do
640 // it in this generic function.
641 if (Succ->isLandingPad())
644 MachineFunction *MF = getParent();
645 DebugLoc dl; // FIXME: this is nowhere
647 // We may need to update this's terminator, but we can't do that if
648 // AnalyzeBranch fails. If this uses a jump table, we won't touch it.
649 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
650 MachineBasicBlock *TBB = 0, *FBB = 0;
651 SmallVector<MachineOperand, 4> Cond;
652 if (TII->AnalyzeBranch(*this, TBB, FBB, Cond))
655 // Avoid bugpoint weirdness: A block may end with a conditional branch but
656 // jumps to the same MBB is either case. We have duplicate CFG edges in that
657 // case that we can't handle. Since this never happens in properly optimized
658 // code, just skip those edges.
659 if (TBB && TBB == FBB) {
660 DEBUG(dbgs() << "Won't split critical edge after degenerate BB#"
661 << getNumber() << '\n');
665 MachineBasicBlock *NMBB = MF->CreateMachineBasicBlock();
666 MF->insert(llvm::next(MachineFunction::iterator(this)), NMBB);
667 DEBUG(dbgs() << "Splitting critical edge:"
668 " BB#" << getNumber()
669 << " -- BB#" << NMBB->getNumber()
670 << " -- BB#" << Succ->getNumber() << '\n');
672 LiveIntervals *LIS = P->getAnalysisIfAvailable<LiveIntervals>();
673 SlotIndexes *Indexes = P->getAnalysisIfAvailable<SlotIndexes>();
675 LIS->insertMBBInMaps(NMBB);
677 Indexes->insertMBBInMaps(NMBB);
679 // On some targets like Mips, branches may kill virtual registers. Make sure
680 // that LiveVariables is properly updated after updateTerminator replaces the
682 LiveVariables *LV = P->getAnalysisIfAvailable<LiveVariables>();
684 // Collect a list of virtual registers killed by the terminators.
685 SmallVector<unsigned, 4> KilledRegs;
687 for (instr_iterator I = getFirstInstrTerminator(), E = instr_end();
689 MachineInstr *MI = I;
690 for (MachineInstr::mop_iterator OI = MI->operands_begin(),
691 OE = MI->operands_end(); OI != OE; ++OI) {
692 if (!OI->isReg() || OI->getReg() == 0 ||
693 !OI->isUse() || !OI->isKill() || OI->isUndef())
695 unsigned Reg = OI->getReg();
696 if (TargetRegisterInfo::isPhysicalRegister(Reg) ||
697 LV->getVarInfo(Reg).removeKill(MI)) {
698 KilledRegs.push_back(Reg);
699 DEBUG(dbgs() << "Removing terminator kill: " << *MI);
700 OI->setIsKill(false);
705 SmallVector<unsigned, 4> UsedRegs;
707 for (instr_iterator I = getFirstInstrTerminator(), E = instr_end();
709 MachineInstr *MI = I;
711 for (MachineInstr::mop_iterator OI = MI->operands_begin(),
712 OE = MI->operands_end(); OI != OE; ++OI) {
713 if (!OI->isReg() || OI->getReg() == 0)
716 unsigned Reg = OI->getReg();
717 if (std::find(UsedRegs.begin(), UsedRegs.end(), Reg) == UsedRegs.end())
718 UsedRegs.push_back(Reg);
723 ReplaceUsesOfBlockWith(Succ, NMBB);
725 // If updateTerminator() removes instructions, we need to remove them from
727 SmallVector<MachineInstr*, 4> Terminators;
729 for (instr_iterator I = getFirstInstrTerminator(), E = instr_end();
731 Terminators.push_back(I);
737 SmallVector<MachineInstr*, 4> NewTerminators;
738 for (instr_iterator I = getFirstInstrTerminator(), E = instr_end();
740 NewTerminators.push_back(I);
742 for (SmallVectorImpl<MachineInstr*>::iterator I = Terminators.begin(),
743 E = Terminators.end(); I != E; ++I) {
744 if (std::find(NewTerminators.begin(), NewTerminators.end(), *I) ==
745 NewTerminators.end())
746 Indexes->removeMachineInstrFromMaps(*I);
750 // Insert unconditional "jump Succ" instruction in NMBB if necessary.
751 NMBB->addSuccessor(Succ);
752 if (!NMBB->isLayoutSuccessor(Succ)) {
754 MF->getTarget().getInstrInfo()->InsertBranch(*NMBB, Succ, NULL, Cond, dl);
757 for (instr_iterator I = NMBB->instr_begin(), E = NMBB->instr_end();
759 // Some instructions may have been moved to NMBB by updateTerminator(),
760 // so we first remove any instruction that already has an index.
761 if (Indexes->hasIndex(I))
762 Indexes->removeMachineInstrFromMaps(I);
763 Indexes->insertMachineInstrInMaps(I);
768 // Fix PHI nodes in Succ so they refer to NMBB instead of this
769 for (MachineBasicBlock::instr_iterator
770 i = Succ->instr_begin(),e = Succ->instr_end();
771 i != e && i->isPHI(); ++i)
772 for (unsigned ni = 1, ne = i->getNumOperands(); ni != ne; ni += 2)
773 if (i->getOperand(ni+1).getMBB() == this)
774 i->getOperand(ni+1).setMBB(NMBB);
776 // Inherit live-ins from the successor
777 for (MachineBasicBlock::livein_iterator I = Succ->livein_begin(),
778 E = Succ->livein_end(); I != E; ++I)
781 // Update LiveVariables.
782 const TargetRegisterInfo *TRI = MF->getTarget().getRegisterInfo();
784 // Restore kills of virtual registers that were killed by the terminators.
785 while (!KilledRegs.empty()) {
786 unsigned Reg = KilledRegs.pop_back_val();
787 for (instr_iterator I = instr_end(), E = instr_begin(); I != E;) {
788 if (!(--I)->addRegisterKilled(Reg, TRI, /* addIfNotFound= */ false))
790 if (TargetRegisterInfo::isVirtualRegister(Reg))
791 LV->getVarInfo(Reg).Kills.push_back(I);
792 DEBUG(dbgs() << "Restored terminator kill: " << *I);
796 // Update relevant live-through information.
797 LV->addNewBlock(NMBB, this, Succ);
801 // After splitting the edge and updating SlotIndexes, live intervals may be
802 // in one of two situations, depending on whether this block was the last in
803 // the function. If the original block was the last in the function, all live
804 // intervals will end prior to the beginning of the new split block. If the
805 // original block was not at the end of the function, all live intervals will
806 // extend to the end of the new split block.
809 llvm::next(MachineFunction::iterator(NMBB)) == getParent()->end();
811 SlotIndex StartIndex = Indexes->getMBBEndIdx(this);
812 SlotIndex PrevIndex = StartIndex.getPrevSlot();
813 SlotIndex EndIndex = Indexes->getMBBEndIdx(NMBB);
815 // Find the registers used from NMBB in PHIs in Succ.
816 SmallSet<unsigned, 8> PHISrcRegs;
817 for (MachineBasicBlock::instr_iterator
818 I = Succ->instr_begin(), E = Succ->instr_end();
819 I != E && I->isPHI(); ++I) {
820 for (unsigned ni = 1, ne = I->getNumOperands(); ni != ne; ni += 2) {
821 if (I->getOperand(ni+1).getMBB() == NMBB) {
822 MachineOperand &MO = I->getOperand(ni);
823 unsigned Reg = MO.getReg();
824 PHISrcRegs.insert(Reg);
828 LiveInterval &LI = LIS->getInterval(Reg);
829 VNInfo *VNI = LI.getVNInfoAt(PrevIndex);
830 assert(VNI && "PHI sources should be live out of their predecessors.");
831 LI.addRange(LiveRange(StartIndex, EndIndex, VNI));
836 MachineRegisterInfo *MRI = &getParent()->getRegInfo();
837 for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
838 unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
839 if (PHISrcRegs.count(Reg) || !LIS->hasInterval(Reg))
842 LiveInterval &LI = LIS->getInterval(Reg);
843 if (!LI.liveAt(PrevIndex))
846 bool isLiveOut = LI.liveAt(LIS->getMBBStartIdx(Succ));
847 if (isLiveOut && isLastMBB) {
848 VNInfo *VNI = LI.getVNInfoAt(PrevIndex);
849 assert(VNI && "LiveInterval should have VNInfo where it is live.");
850 LI.addRange(LiveRange(StartIndex, EndIndex, VNI));
851 } else if (!isLiveOut && !isLastMBB) {
852 LI.removeRange(StartIndex, EndIndex);
856 // Update all intervals for registers whose uses may have been modified by
857 // updateTerminator().
858 LIS->repairIntervalsInRange(this, getFirstTerminator(), end(), UsedRegs);
861 if (MachineDominatorTree *MDT =
862 P->getAnalysisIfAvailable<MachineDominatorTree>()) {
863 // Update dominator information.
864 MachineDomTreeNode *SucccDTNode = MDT->getNode(Succ);
866 bool IsNewIDom = true;
867 for (const_pred_iterator PI = Succ->pred_begin(), E = Succ->pred_end();
869 MachineBasicBlock *PredBB = *PI;
872 if (!MDT->dominates(SucccDTNode, MDT->getNode(PredBB))) {
878 // We know "this" dominates the newly created basic block.
879 MachineDomTreeNode *NewDTNode = MDT->addNewBlock(NMBB, this);
881 // If all the other predecessors of "Succ" are dominated by "Succ" itself
882 // then the new block is the new immediate dominator of "Succ". Otherwise,
883 // the new block doesn't dominate anything.
885 MDT->changeImmediateDominator(SucccDTNode, NewDTNode);
888 if (MachineLoopInfo *MLI = P->getAnalysisIfAvailable<MachineLoopInfo>())
889 if (MachineLoop *TIL = MLI->getLoopFor(this)) {
890 // If one or the other blocks were not in a loop, the new block is not
891 // either, and thus LI doesn't need to be updated.
892 if (MachineLoop *DestLoop = MLI->getLoopFor(Succ)) {
893 if (TIL == DestLoop) {
894 // Both in the same loop, the NMBB joins loop.
895 DestLoop->addBasicBlockToLoop(NMBB, MLI->getBase());
896 } else if (TIL->contains(DestLoop)) {
897 // Edge from an outer loop to an inner loop. Add to the outer loop.
898 TIL->addBasicBlockToLoop(NMBB, MLI->getBase());
899 } else if (DestLoop->contains(TIL)) {
900 // Edge from an inner loop to an outer loop. Add to the outer loop.
901 DestLoop->addBasicBlockToLoop(NMBB, MLI->getBase());
903 // Edge from two loops with no containment relation. Because these
904 // are natural loops, we know that the destination block must be the
905 // header of its loop (adding a branch into a loop elsewhere would
906 // create an irreducible loop).
907 assert(DestLoop->getHeader() == Succ &&
908 "Should not create irreducible loops!");
909 if (MachineLoop *P = DestLoop->getParentLoop())
910 P->addBasicBlockToLoop(NMBB, MLI->getBase());
918 /// Prepare MI to be removed from its bundle. This fixes bundle flags on MI's
919 /// neighboring instructions so the bundle won't be broken by removing MI.
920 static void unbundleSingleMI(MachineInstr *MI) {
921 // Removing the first instruction in a bundle.
922 if (MI->isBundledWithSucc() && !MI->isBundledWithPred())
923 MI->unbundleFromSucc();
924 // Removing the last instruction in a bundle.
925 if (MI->isBundledWithPred() && !MI->isBundledWithSucc())
926 MI->unbundleFromPred();
927 // If MI is not bundled, or if it is internal to a bundle, the neighbor flags
931 MachineBasicBlock::instr_iterator
932 MachineBasicBlock::erase(MachineBasicBlock::instr_iterator I) {
934 return Insts.erase(I);
937 MachineInstr *MachineBasicBlock::remove_instr(MachineInstr *MI) {
938 unbundleSingleMI(MI);
939 MI->clearFlag(MachineInstr::BundledPred);
940 MI->clearFlag(MachineInstr::BundledSucc);
941 return Insts.remove(MI);
944 MachineBasicBlock::instr_iterator
945 MachineBasicBlock::insert(instr_iterator I, MachineInstr *MI) {
946 assert(!MI->isBundledWithPred() && !MI->isBundledWithSucc() &&
947 "Cannot insert instruction with bundle flags");
948 // Set the bundle flags when inserting inside a bundle.
949 if (I != instr_end() && I->isBundledWithPred()) {
950 MI->setFlag(MachineInstr::BundledPred);
951 MI->setFlag(MachineInstr::BundledSucc);
953 return Insts.insert(I, MI);
956 /// removeFromParent - This method unlinks 'this' from the containing function,
957 /// and returns it, but does not delete it.
958 MachineBasicBlock *MachineBasicBlock::removeFromParent() {
959 assert(getParent() && "Not embedded in a function!");
960 getParent()->remove(this);
965 /// eraseFromParent - This method unlinks 'this' from the containing function,
967 void MachineBasicBlock::eraseFromParent() {
968 assert(getParent() && "Not embedded in a function!");
969 getParent()->erase(this);
973 /// ReplaceUsesOfBlockWith - Given a machine basic block that branched to
974 /// 'Old', change the code and CFG so that it branches to 'New' instead.
975 void MachineBasicBlock::ReplaceUsesOfBlockWith(MachineBasicBlock *Old,
976 MachineBasicBlock *New) {
977 assert(Old != New && "Cannot replace self with self!");
979 MachineBasicBlock::instr_iterator I = instr_end();
980 while (I != instr_begin()) {
982 if (!I->isTerminator()) break;
984 // Scan the operands of this machine instruction, replacing any uses of Old
986 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
987 if (I->getOperand(i).isMBB() &&
988 I->getOperand(i).getMBB() == Old)
989 I->getOperand(i).setMBB(New);
992 // Update the successor information.
993 replaceSuccessor(Old, New);
996 /// CorrectExtraCFGEdges - Various pieces of code can cause excess edges in the
997 /// CFG to be inserted. If we have proven that MBB can only branch to DestA and
998 /// DestB, remove any other MBB successors from the CFG. DestA and DestB can be
1001 /// Besides DestA and DestB, retain other edges leading to LandingPads
1002 /// (currently there can be only one; we don't check or require that here).
1003 /// Note it is possible that DestA and/or DestB are LandingPads.
1004 bool MachineBasicBlock::CorrectExtraCFGEdges(MachineBasicBlock *DestA,
1005 MachineBasicBlock *DestB,
1007 // The values of DestA and DestB frequently come from a call to the
1008 // 'TargetInstrInfo::AnalyzeBranch' method. We take our meaning of the initial
1009 // values from there.
1011 // 1. If both DestA and DestB are null, then the block ends with no branches
1012 // (it falls through to its successor).
1013 // 2. If DestA is set, DestB is null, and isCond is false, then the block ends
1014 // with only an unconditional branch.
1015 // 3. If DestA is set, DestB is null, and isCond is true, then the block ends
1016 // with a conditional branch that falls through to a successor (DestB).
1017 // 4. If DestA and DestB is set and isCond is true, then the block ends with a
1018 // conditional branch followed by an unconditional branch. DestA is the
1019 // 'true' destination and DestB is the 'false' destination.
1021 bool Changed = false;
1023 MachineFunction::iterator FallThru =
1024 llvm::next(MachineFunction::iterator(this));
1026 if (DestA == 0 && DestB == 0) {
1027 // Block falls through to successor.
1030 } else if (DestA != 0 && DestB == 0) {
1032 // Block ends in conditional jump that falls through to successor.
1035 assert(DestA && DestB && isCond &&
1036 "CFG in a bad state. Cannot correct CFG edges");
1039 // Remove superfluous edges. I.e., those which aren't destinations of this
1040 // basic block, duplicate edges, or landing pads.
1041 SmallPtrSet<const MachineBasicBlock*, 8> SeenMBBs;
1042 MachineBasicBlock::succ_iterator SI = succ_begin();
1043 while (SI != succ_end()) {
1044 const MachineBasicBlock *MBB = *SI;
1045 if (!SeenMBBs.insert(MBB) ||
1046 (MBB != DestA && MBB != DestB && !MBB->isLandingPad())) {
1047 // This is a superfluous edge, remove it.
1048 SI = removeSuccessor(SI);
1058 /// findDebugLoc - find the next valid DebugLoc starting at MBBI, skipping
1059 /// any DBG_VALUE instructions. Return UnknownLoc if there is none.
1061 MachineBasicBlock::findDebugLoc(instr_iterator MBBI) {
1063 instr_iterator E = instr_end();
1067 // Skip debug declarations, we don't want a DebugLoc from them.
1068 while (MBBI != E && MBBI->isDebugValue())
1071 DL = MBBI->getDebugLoc();
1075 /// getSuccWeight - Return weight of the edge from this block to MBB.
1077 uint32_t MachineBasicBlock::getSuccWeight(const_succ_iterator Succ) const {
1078 if (Weights.empty())
1081 return *getWeightIterator(Succ);
1084 /// getWeightIterator - Return wight iterator corresonding to the I successor
1086 MachineBasicBlock::weight_iterator MachineBasicBlock::
1087 getWeightIterator(MachineBasicBlock::succ_iterator I) {
1088 assert(Weights.size() == Successors.size() && "Async weight list!");
1089 size_t index = std::distance(Successors.begin(), I);
1090 assert(index < Weights.size() && "Not a current successor!");
1091 return Weights.begin() + index;
1094 /// getWeightIterator - Return wight iterator corresonding to the I successor
1096 MachineBasicBlock::const_weight_iterator MachineBasicBlock::
1097 getWeightIterator(MachineBasicBlock::const_succ_iterator I) const {
1098 assert(Weights.size() == Successors.size() && "Async weight list!");
1099 const size_t index = std::distance(Successors.begin(), I);
1100 assert(index < Weights.size() && "Not a current successor!");
1101 return Weights.begin() + index;
1104 /// Return whether (physical) register "Reg" has been <def>ined and not <kill>ed
1105 /// as of just before "MI".
1107 /// Search is localised to a neighborhood of
1108 /// Neighborhood instructions before (searching for defs or kills) and N
1109 /// instructions after (searching just for defs) MI.
1110 MachineBasicBlock::LivenessQueryResult
1111 MachineBasicBlock::computeRegisterLiveness(const TargetRegisterInfo *TRI,
1112 unsigned Reg, MachineInstr *MI,
1113 unsigned Neighborhood) {
1114 unsigned N = Neighborhood;
1115 MachineBasicBlock *MBB = MI->getParent();
1117 // Start by searching backwards from MI, looking for kills, reads or defs.
1119 MachineBasicBlock::iterator I(MI);
1120 // If this is the first insn in the block, don't search backwards.
1121 if (I != MBB->begin()) {
1125 MachineOperandIteratorBase::PhysRegInfo Analysis =
1126 MIOperands(I).analyzePhysReg(Reg, TRI);
1128 if (Analysis.Defines)
1129 // Outputs happen after inputs so they take precedence if both are
1131 return Analysis.DefinesDead ? LQR_Dead : LQR_Live;
1133 if (Analysis.Kills || Analysis.Clobbers)
1134 // Register killed, so isn't live.
1137 else if (Analysis.ReadsOverlap)
1138 // Defined or read without a previous kill - live.
1139 return Analysis.Reads ? LQR_Live : LQR_OverlappingLive;
1141 } while (I != MBB->begin() && --N > 0);
1144 // Did we get to the start of the block?
1145 if (I == MBB->begin()) {
1146 // If so, the register's state is definitely defined by the live-in state.
1147 for (MCRegAliasIterator RAI(Reg, TRI, /*IncludeSelf=*/true);
1148 RAI.isValid(); ++RAI) {
1149 if (MBB->isLiveIn(*RAI))
1150 return (*RAI == Reg) ? LQR_Live : LQR_OverlappingLive;
1158 // Try searching forwards from MI, looking for reads or defs.
1159 I = MachineBasicBlock::iterator(MI);
1160 // If this is the last insn in the block, don't search forwards.
1161 if (I != MBB->end()) {
1162 for (++I; I != MBB->end() && N > 0; ++I, --N) {
1163 MachineOperandIteratorBase::PhysRegInfo Analysis =
1164 MIOperands(I).analyzePhysReg(Reg, TRI);
1166 if (Analysis.ReadsOverlap)
1167 // Used, therefore must have been live.
1168 return (Analysis.Reads) ?
1169 LQR_Live : LQR_OverlappingLive;
1171 else if (Analysis.Clobbers || Analysis.Defines)
1172 // Defined (but not read) therefore cannot have been live.
1177 // At this point we have no idea of the liveness of the register.
1181 void llvm::WriteAsOperand(raw_ostream &OS, const MachineBasicBlock *MBB,
1183 OS << "BB#" << MBB->getNumber();