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/LiveVariables.h"
19 #include "llvm/CodeGen/MachineDominators.h"
20 #include "llvm/CodeGen/MachineFunction.h"
21 #include "llvm/CodeGen/MachineLoopInfo.h"
22 #include "llvm/CodeGen/SlotIndexes.h"
23 #include "llvm/IR/BasicBlock.h"
24 #include "llvm/IR/DataLayout.h"
25 #include "llvm/MC/MCAsmInfo.h"
26 #include "llvm/MC/MCContext.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/LeakDetector.h"
29 #include "llvm/Support/raw_ostream.h"
30 #include "llvm/Target/TargetInstrInfo.h"
31 #include "llvm/Target/TargetMachine.h"
32 #include "llvm/Target/TargetRegisterInfo.h"
36 MachineBasicBlock::MachineBasicBlock(MachineFunction &mf, const BasicBlock *bb)
37 : BB(bb), Number(-1), xParent(&mf), Alignment(0), IsLandingPad(false),
42 MachineBasicBlock::~MachineBasicBlock() {
43 LeakDetector::removeGarbageObject(this);
46 /// getSymbol - Return the MCSymbol for this basic block.
48 MCSymbol *MachineBasicBlock::getSymbol() const {
49 const MachineFunction *MF = getParent();
50 MCContext &Ctx = MF->getContext();
51 const char *Prefix = Ctx.getAsmInfo().getPrivateGlobalPrefix();
52 return Ctx.GetOrCreateSymbol(Twine(Prefix) + "BB" +
53 Twine(MF->getFunctionNumber()) + "_" +
58 raw_ostream &llvm::operator<<(raw_ostream &OS, const MachineBasicBlock &MBB) {
63 /// addNodeToList (MBB) - When an MBB is added to an MF, we need to update the
64 /// parent pointer of the MBB, the MBB numbering, and any instructions in the
65 /// MBB to be on the right operand list for registers.
67 /// MBBs start out as #-1. When a MBB is added to a MachineFunction, it
68 /// gets the next available unique MBB number. If it is removed from a
69 /// MachineFunction, it goes back to being #-1.
70 void ilist_traits<MachineBasicBlock>::addNodeToList(MachineBasicBlock *N) {
71 MachineFunction &MF = *N->getParent();
72 N->Number = MF.addToMBBNumbering(N);
74 // Make sure the instructions have their operands in the reginfo lists.
75 MachineRegisterInfo &RegInfo = MF.getRegInfo();
76 for (MachineBasicBlock::instr_iterator
77 I = N->instr_begin(), E = N->instr_end(); I != E; ++I)
78 I->AddRegOperandsToUseLists(RegInfo);
80 LeakDetector::removeGarbageObject(N);
83 void ilist_traits<MachineBasicBlock>::removeNodeFromList(MachineBasicBlock *N) {
84 N->getParent()->removeFromMBBNumbering(N->Number);
86 LeakDetector::addGarbageObject(N);
90 /// addNodeToList (MI) - When we add an instruction to a basic block
91 /// list, we update its parent pointer and add its operands from reg use/def
92 /// lists if appropriate.
93 void ilist_traits<MachineInstr>::addNodeToList(MachineInstr *N) {
94 assert(N->getParent() == 0 && "machine instruction already in a basic block");
97 // Add the instruction's register operands to their corresponding
99 MachineFunction *MF = Parent->getParent();
100 N->AddRegOperandsToUseLists(MF->getRegInfo());
102 LeakDetector::removeGarbageObject(N);
105 /// removeNodeFromList (MI) - When we remove an instruction from a basic block
106 /// list, we update its parent pointer and remove its operands from reg use/def
107 /// lists if appropriate.
108 void ilist_traits<MachineInstr>::removeNodeFromList(MachineInstr *N) {
109 assert(N->getParent() != 0 && "machine instruction not in a basic block");
111 // Remove from the use/def lists.
112 if (MachineFunction *MF = N->getParent()->getParent())
113 N->RemoveRegOperandsFromUseLists(MF->getRegInfo());
117 LeakDetector::addGarbageObject(N);
120 /// transferNodesFromList (MI) - When moving a range of instructions from one
121 /// MBB list to another, we need to update the parent pointers and the use/def
123 void ilist_traits<MachineInstr>::
124 transferNodesFromList(ilist_traits<MachineInstr> &fromList,
125 ilist_iterator<MachineInstr> first,
126 ilist_iterator<MachineInstr> last) {
127 assert(Parent->getParent() == fromList.Parent->getParent() &&
128 "MachineInstr parent mismatch!");
130 // Splice within the same MBB -> no change.
131 if (Parent == fromList.Parent) return;
133 // If splicing between two blocks within the same function, just update the
135 for (; first != last; ++first)
136 first->setParent(Parent);
139 void ilist_traits<MachineInstr>::deleteNode(MachineInstr* MI) {
140 assert(!MI->getParent() && "MI is still in a block!");
141 Parent->getParent()->DeleteMachineInstr(MI);
144 MachineBasicBlock::iterator MachineBasicBlock::getFirstNonPHI() {
145 instr_iterator I = instr_begin(), E = instr_end();
146 while (I != E && I->isPHI())
148 assert((I == E || !I->isInsideBundle()) &&
149 "First non-phi MI cannot be inside a bundle!");
153 MachineBasicBlock::iterator
154 MachineBasicBlock::SkipPHIsAndLabels(MachineBasicBlock::iterator I) {
156 while (I != E && (I->isPHI() || I->isLabel() || I->isDebugValue()))
158 // FIXME: This needs to change if we wish to bundle labels / dbg_values
159 // inside the bundle.
160 assert((I == E || !I->isInsideBundle()) &&
161 "First non-phi / non-label instruction is inside a bundle!");
165 MachineBasicBlock::iterator MachineBasicBlock::getFirstTerminator() {
166 iterator B = begin(), E = end(), I = E;
167 while (I != B && ((--I)->isTerminator() || I->isDebugValue()))
169 while (I != E && !I->isTerminator())
174 MachineBasicBlock::const_iterator
175 MachineBasicBlock::getFirstTerminator() const {
176 const_iterator B = begin(), E = end(), I = E;
177 while (I != B && ((--I)->isTerminator() || I->isDebugValue()))
179 while (I != E && !I->isTerminator())
184 MachineBasicBlock::instr_iterator MachineBasicBlock::getFirstInstrTerminator() {
185 instr_iterator B = instr_begin(), E = instr_end(), I = E;
186 while (I != B && ((--I)->isTerminator() || I->isDebugValue()))
188 while (I != E && !I->isTerminator())
193 MachineBasicBlock::iterator MachineBasicBlock::getLastNonDebugInstr() {
194 // Skip over end-of-block dbg_value instructions.
195 instr_iterator B = instr_begin(), I = instr_end();
198 // Return instruction that starts a bundle.
199 if (I->isDebugValue() || I->isInsideBundle())
203 // The block is all debug values.
207 MachineBasicBlock::const_iterator
208 MachineBasicBlock::getLastNonDebugInstr() const {
209 // Skip over end-of-block dbg_value instructions.
210 const_instr_iterator B = instr_begin(), I = instr_end();
213 // Return instruction that starts a bundle.
214 if (I->isDebugValue() || I->isInsideBundle())
218 // The block is all debug values.
222 const MachineBasicBlock *MachineBasicBlock::getLandingPadSuccessor() const {
223 // A block with a landing pad successor only has one other successor.
226 for (const_succ_iterator I = succ_begin(), E = succ_end(); I != E; ++I)
227 if ((*I)->isLandingPad())
232 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
233 void MachineBasicBlock::dump() const {
238 StringRef MachineBasicBlock::getName() const {
239 if (const BasicBlock *LBB = getBasicBlock())
240 return LBB->getName();
245 /// Return a hopefully unique identifier for this block.
246 std::string MachineBasicBlock::getFullName() const {
249 Name = (getParent()->getName() + ":").str();
251 Name += getBasicBlock()->getName();
253 Name += (Twine("BB") + Twine(getNumber())).str();
257 void MachineBasicBlock::print(raw_ostream &OS, SlotIndexes *Indexes) const {
258 const MachineFunction *MF = getParent();
260 OS << "Can't print out MachineBasicBlock because parent MachineFunction"
266 OS << Indexes->getMBBStartIdx(this) << '\t';
268 OS << "BB#" << getNumber() << ": ";
270 const char *Comma = "";
271 if (const BasicBlock *LBB = getBasicBlock()) {
272 OS << Comma << "derived from LLVM BB ";
273 WriteAsOperand(OS, LBB, /*PrintType=*/false);
276 if (isLandingPad()) { OS << Comma << "EH LANDING PAD"; Comma = ", "; }
277 if (hasAddressTaken()) { OS << Comma << "ADDRESS TAKEN"; Comma = ", "; }
279 OS << Comma << "Align " << Alignment << " (" << (1u << Alignment)
284 const TargetRegisterInfo *TRI = MF->getTarget().getRegisterInfo();
285 if (!livein_empty()) {
286 if (Indexes) OS << '\t';
288 for (livein_iterator I = livein_begin(),E = livein_end(); I != E; ++I)
289 OS << ' ' << PrintReg(*I, TRI);
292 // Print the preds of this block according to the CFG.
294 if (Indexes) OS << '\t';
295 OS << " Predecessors according to CFG:";
296 for (const_pred_iterator PI = pred_begin(), E = pred_end(); PI != E; ++PI)
297 OS << " BB#" << (*PI)->getNumber();
301 for (const_instr_iterator I = instr_begin(); I != instr_end(); ++I) {
303 if (Indexes->hasIndex(I))
304 OS << Indexes->getInstructionIndex(I);
308 if (I->isInsideBundle())
310 I->print(OS, &getParent()->getTarget());
313 // Print the successors of this block according to the CFG.
315 if (Indexes) OS << '\t';
316 OS << " Successors according to CFG:";
317 for (const_succ_iterator SI = succ_begin(), E = succ_end(); SI != E; ++SI) {
318 OS << " BB#" << (*SI)->getNumber();
319 if (!Weights.empty())
320 OS << '(' << *getWeightIterator(SI) << ')';
326 void MachineBasicBlock::removeLiveIn(unsigned Reg) {
327 std::vector<unsigned>::iterator I =
328 std::find(LiveIns.begin(), LiveIns.end(), Reg);
329 if (I != LiveIns.end())
333 bool MachineBasicBlock::isLiveIn(unsigned Reg) const {
334 livein_iterator I = std::find(livein_begin(), livein_end(), Reg);
335 return I != livein_end();
338 void MachineBasicBlock::moveBefore(MachineBasicBlock *NewAfter) {
339 getParent()->splice(NewAfter, this);
342 void MachineBasicBlock::moveAfter(MachineBasicBlock *NewBefore) {
343 MachineFunction::iterator BBI = NewBefore;
344 getParent()->splice(++BBI, this);
347 void MachineBasicBlock::updateTerminator() {
348 const TargetInstrInfo *TII = getParent()->getTarget().getInstrInfo();
349 // A block with no successors has no concerns with fall-through edges.
350 if (this->succ_empty()) return;
352 MachineBasicBlock *TBB = 0, *FBB = 0;
353 SmallVector<MachineOperand, 4> Cond;
354 DebugLoc dl; // FIXME: this is nowhere
355 bool B = TII->AnalyzeBranch(*this, TBB, FBB, Cond);
357 assert(!B && "UpdateTerminators requires analyzable predecessors!");
360 // The block has an unconditional branch. If its successor is now
361 // its layout successor, delete the branch.
362 if (isLayoutSuccessor(TBB))
363 TII->RemoveBranch(*this);
365 // The block has an unconditional fallthrough. If its successor is not
366 // its layout successor, insert a branch. First we have to locate the
367 // only non-landing-pad successor, as that is the fallthrough block.
368 for (succ_iterator SI = succ_begin(), SE = succ_end(); SI != SE; ++SI) {
369 if ((*SI)->isLandingPad())
371 assert(!TBB && "Found more than one non-landing-pad successor!");
375 // If there is no non-landing-pad successor, the block has no
376 // fall-through edges to be concerned with.
380 // Finally update the unconditional successor to be reached via a branch
381 // if it would not be reached by fallthrough.
382 if (!isLayoutSuccessor(TBB))
383 TII->InsertBranch(*this, TBB, 0, Cond, dl);
387 // The block has a non-fallthrough conditional branch. If one of its
388 // successors is its layout successor, rewrite it to a fallthrough
389 // conditional branch.
390 if (isLayoutSuccessor(TBB)) {
391 if (TII->ReverseBranchCondition(Cond))
393 TII->RemoveBranch(*this);
394 TII->InsertBranch(*this, FBB, 0, Cond, dl);
395 } else if (isLayoutSuccessor(FBB)) {
396 TII->RemoveBranch(*this);
397 TII->InsertBranch(*this, TBB, 0, Cond, dl);
400 // Walk through the successors and find the successor which is not
401 // a landing pad and is not the conditional branch destination (in TBB)
402 // as the fallthrough successor.
403 MachineBasicBlock *FallthroughBB = 0;
404 for (succ_iterator SI = succ_begin(), SE = succ_end(); SI != SE; ++SI) {
405 if ((*SI)->isLandingPad() || *SI == TBB)
407 assert(!FallthroughBB && "Found more than one fallthrough successor.");
410 if (!FallthroughBB && canFallThrough()) {
411 // We fallthrough to the same basic block as the conditional jump
412 // targets. Remove the conditional jump, leaving unconditional
414 // FIXME: This does not seem like a reasonable pattern to support, but it
415 // has been seen in the wild coming out of degenerate ARM test cases.
416 TII->RemoveBranch(*this);
418 // Finally update the unconditional successor to be reached via a branch
419 // if it would not be reached by fallthrough.
420 if (!isLayoutSuccessor(TBB))
421 TII->InsertBranch(*this, TBB, 0, Cond, dl);
425 // The block has a fallthrough conditional branch.
426 if (isLayoutSuccessor(TBB)) {
427 if (TII->ReverseBranchCondition(Cond)) {
428 // We can't reverse the condition, add an unconditional branch.
430 TII->InsertBranch(*this, FallthroughBB, 0, Cond, dl);
433 TII->RemoveBranch(*this);
434 TII->InsertBranch(*this, FallthroughBB, 0, Cond, dl);
435 } else if (!isLayoutSuccessor(FallthroughBB)) {
436 TII->RemoveBranch(*this);
437 TII->InsertBranch(*this, TBB, FallthroughBB, Cond, dl);
443 void MachineBasicBlock::addSuccessor(MachineBasicBlock *succ, uint32_t weight) {
445 // If we see non-zero value for the first time it means we actually use Weight
446 // list, so we fill all Weights with 0's.
447 if (weight != 0 && Weights.empty())
448 Weights.resize(Successors.size());
450 if (weight != 0 || !Weights.empty())
451 Weights.push_back(weight);
453 Successors.push_back(succ);
454 succ->addPredecessor(this);
457 void MachineBasicBlock::removeSuccessor(MachineBasicBlock *succ) {
458 succ->removePredecessor(this);
459 succ_iterator I = std::find(Successors.begin(), Successors.end(), succ);
460 assert(I != Successors.end() && "Not a current successor!");
462 // If Weight list is empty it means we don't use it (disabled optimization).
463 if (!Weights.empty()) {
464 weight_iterator WI = getWeightIterator(I);
471 MachineBasicBlock::succ_iterator
472 MachineBasicBlock::removeSuccessor(succ_iterator I) {
473 assert(I != Successors.end() && "Not a current successor!");
475 // If Weight list is empty it means we don't use it (disabled optimization).
476 if (!Weights.empty()) {
477 weight_iterator WI = getWeightIterator(I);
481 (*I)->removePredecessor(this);
482 return Successors.erase(I);
485 void MachineBasicBlock::replaceSuccessor(MachineBasicBlock *Old,
486 MachineBasicBlock *New) {
490 succ_iterator E = succ_end();
491 succ_iterator NewI = E;
492 succ_iterator OldI = E;
493 for (succ_iterator I = succ_begin(); I != E; ++I) {
505 assert(OldI != E && "Old is not a successor of this block");
506 Old->removePredecessor(this);
508 // If New isn't already a successor, let it take Old's place.
510 New->addPredecessor(this);
515 // New is already a successor.
516 // Update its weight instead of adding a duplicate edge.
517 if (!Weights.empty()) {
518 weight_iterator OldWI = getWeightIterator(OldI);
519 *getWeightIterator(NewI) += *OldWI;
520 Weights.erase(OldWI);
522 Successors.erase(OldI);
525 void MachineBasicBlock::addPredecessor(MachineBasicBlock *pred) {
526 Predecessors.push_back(pred);
529 void MachineBasicBlock::removePredecessor(MachineBasicBlock *pred) {
530 pred_iterator I = std::find(Predecessors.begin(), Predecessors.end(), pred);
531 assert(I != Predecessors.end() && "Pred is not a predecessor of this block!");
532 Predecessors.erase(I);
535 void MachineBasicBlock::transferSuccessors(MachineBasicBlock *fromMBB) {
539 while (!fromMBB->succ_empty()) {
540 MachineBasicBlock *Succ = *fromMBB->succ_begin();
543 // If Weight list is empty it means we don't use it (disabled optimization).
544 if (!fromMBB->Weights.empty())
545 Weight = *fromMBB->Weights.begin();
547 addSuccessor(Succ, Weight);
548 fromMBB->removeSuccessor(Succ);
553 MachineBasicBlock::transferSuccessorsAndUpdatePHIs(MachineBasicBlock *fromMBB) {
557 while (!fromMBB->succ_empty()) {
558 MachineBasicBlock *Succ = *fromMBB->succ_begin();
560 if (!fromMBB->Weights.empty())
561 Weight = *fromMBB->Weights.begin();
562 addSuccessor(Succ, Weight);
563 fromMBB->removeSuccessor(Succ);
565 // Fix up any PHI nodes in the successor.
566 for (MachineBasicBlock::instr_iterator MI = Succ->instr_begin(),
567 ME = Succ->instr_end(); MI != ME && MI->isPHI(); ++MI)
568 for (unsigned i = 2, e = MI->getNumOperands()+1; i != e; i += 2) {
569 MachineOperand &MO = MI->getOperand(i);
570 if (MO.getMBB() == fromMBB)
576 bool MachineBasicBlock::isPredecessor(const MachineBasicBlock *MBB) const {
577 return std::find(pred_begin(), pred_end(), MBB) != pred_end();
580 bool MachineBasicBlock::isSuccessor(const MachineBasicBlock *MBB) const {
581 return std::find(succ_begin(), succ_end(), MBB) != succ_end();
584 bool MachineBasicBlock::isLayoutSuccessor(const MachineBasicBlock *MBB) const {
585 MachineFunction::const_iterator I(this);
586 return llvm::next(I) == MachineFunction::const_iterator(MBB);
589 bool MachineBasicBlock::canFallThrough() {
590 MachineFunction::iterator Fallthrough = this;
592 // If FallthroughBlock is off the end of the function, it can't fall through.
593 if (Fallthrough == getParent()->end())
596 // If FallthroughBlock isn't a successor, no fallthrough is possible.
597 if (!isSuccessor(Fallthrough))
600 // Analyze the branches, if any, at the end of the block.
601 MachineBasicBlock *TBB = 0, *FBB = 0;
602 SmallVector<MachineOperand, 4> Cond;
603 const TargetInstrInfo *TII = getParent()->getTarget().getInstrInfo();
604 if (TII->AnalyzeBranch(*this, TBB, FBB, Cond)) {
605 // If we couldn't analyze the branch, examine the last instruction.
606 // If the block doesn't end in a known control barrier, assume fallthrough
607 // is possible. The isPredicated check is needed because this code can be
608 // called during IfConversion, where an instruction which is normally a
609 // Barrier is predicated and thus no longer an actual control barrier.
610 return empty() || !back().isBarrier() || TII->isPredicated(&back());
613 // If there is no branch, control always falls through.
614 if (TBB == 0) return true;
616 // If there is some explicit branch to the fallthrough block, it can obviously
617 // reach, even though the branch should get folded to fall through implicitly.
618 if (MachineFunction::iterator(TBB) == Fallthrough ||
619 MachineFunction::iterator(FBB) == Fallthrough)
622 // If it's an unconditional branch to some block not the fall through, it
623 // doesn't fall through.
624 if (Cond.empty()) return false;
626 // Otherwise, if it is conditional and has no explicit false block, it falls
632 MachineBasicBlock::SplitCriticalEdge(MachineBasicBlock *Succ, Pass *P) {
633 // Splitting the critical edge to a landing pad block is non-trivial. Don't do
634 // it in this generic function.
635 if (Succ->isLandingPad())
638 MachineFunction *MF = getParent();
639 DebugLoc dl; // FIXME: this is nowhere
641 // We may need to update this's terminator, but we can't do that if
642 // AnalyzeBranch fails. If this uses a jump table, we won't touch it.
643 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
644 MachineBasicBlock *TBB = 0, *FBB = 0;
645 SmallVector<MachineOperand, 4> Cond;
646 if (TII->AnalyzeBranch(*this, TBB, FBB, Cond))
649 // Avoid bugpoint weirdness: A block may end with a conditional branch but
650 // jumps to the same MBB is either case. We have duplicate CFG edges in that
651 // case that we can't handle. Since this never happens in properly optimized
652 // code, just skip those edges.
653 if (TBB && TBB == FBB) {
654 DEBUG(dbgs() << "Won't split critical edge after degenerate BB#"
655 << getNumber() << '\n');
659 MachineBasicBlock *NMBB = MF->CreateMachineBasicBlock();
660 MF->insert(llvm::next(MachineFunction::iterator(this)), NMBB);
661 DEBUG(dbgs() << "Splitting critical edge:"
662 " BB#" << getNumber()
663 << " -- BB#" << NMBB->getNumber()
664 << " -- BB#" << Succ->getNumber() << '\n');
666 // On some targets like Mips, branches may kill virtual registers. Make sure
667 // that LiveVariables is properly updated after updateTerminator replaces the
669 LiveVariables *LV = P->getAnalysisIfAvailable<LiveVariables>();
671 // Collect a list of virtual registers killed by the terminators.
672 SmallVector<unsigned, 4> KilledRegs;
674 for (instr_iterator I = getFirstInstrTerminator(), E = instr_end();
676 MachineInstr *MI = I;
677 for (MachineInstr::mop_iterator OI = MI->operands_begin(),
678 OE = MI->operands_end(); OI != OE; ++OI) {
679 if (!OI->isReg() || OI->getReg() == 0 ||
680 !OI->isUse() || !OI->isKill() || OI->isUndef())
682 unsigned Reg = OI->getReg();
683 if (TargetRegisterInfo::isPhysicalRegister(Reg) ||
684 LV->getVarInfo(Reg).removeKill(MI)) {
685 KilledRegs.push_back(Reg);
686 DEBUG(dbgs() << "Removing terminator kill: " << *MI);
687 OI->setIsKill(false);
692 ReplaceUsesOfBlockWith(Succ, NMBB);
695 // Insert unconditional "jump Succ" instruction in NMBB if necessary.
696 NMBB->addSuccessor(Succ);
697 if (!NMBB->isLayoutSuccessor(Succ)) {
699 MF->getTarget().getInstrInfo()->InsertBranch(*NMBB, Succ, NULL, Cond, dl);
702 // Fix PHI nodes in Succ so they refer to NMBB instead of this
703 for (MachineBasicBlock::instr_iterator
704 i = Succ->instr_begin(),e = Succ->instr_end();
705 i != e && i->isPHI(); ++i)
706 for (unsigned ni = 1, ne = i->getNumOperands(); ni != ne; ni += 2)
707 if (i->getOperand(ni+1).getMBB() == this)
708 i->getOperand(ni+1).setMBB(NMBB);
710 // Inherit live-ins from the successor
711 for (MachineBasicBlock::livein_iterator I = Succ->livein_begin(),
712 E = Succ->livein_end(); I != E; ++I)
715 // Update LiveVariables.
716 const TargetRegisterInfo *TRI = MF->getTarget().getRegisterInfo();
718 // Restore kills of virtual registers that were killed by the terminators.
719 while (!KilledRegs.empty()) {
720 unsigned Reg = KilledRegs.pop_back_val();
721 for (instr_iterator I = instr_end(), E = instr_begin(); I != E;) {
722 if (!(--I)->addRegisterKilled(Reg, TRI, /* addIfNotFound= */ false))
724 if (TargetRegisterInfo::isVirtualRegister(Reg))
725 LV->getVarInfo(Reg).Kills.push_back(I);
726 DEBUG(dbgs() << "Restored terminator kill: " << *I);
730 // Update relevant live-through information.
731 LV->addNewBlock(NMBB, this, Succ);
734 if (MachineDominatorTree *MDT =
735 P->getAnalysisIfAvailable<MachineDominatorTree>()) {
736 // Update dominator information.
737 MachineDomTreeNode *SucccDTNode = MDT->getNode(Succ);
739 bool IsNewIDom = true;
740 for (const_pred_iterator PI = Succ->pred_begin(), E = Succ->pred_end();
742 MachineBasicBlock *PredBB = *PI;
745 if (!MDT->dominates(SucccDTNode, MDT->getNode(PredBB))) {
751 // We know "this" dominates the newly created basic block.
752 MachineDomTreeNode *NewDTNode = MDT->addNewBlock(NMBB, this);
754 // If all the other predecessors of "Succ" are dominated by "Succ" itself
755 // then the new block is the new immediate dominator of "Succ". Otherwise,
756 // the new block doesn't dominate anything.
758 MDT->changeImmediateDominator(SucccDTNode, NewDTNode);
761 if (MachineLoopInfo *MLI = P->getAnalysisIfAvailable<MachineLoopInfo>())
762 if (MachineLoop *TIL = MLI->getLoopFor(this)) {
763 // If one or the other blocks were not in a loop, the new block is not
764 // either, and thus LI doesn't need to be updated.
765 if (MachineLoop *DestLoop = MLI->getLoopFor(Succ)) {
766 if (TIL == DestLoop) {
767 // Both in the same loop, the NMBB joins loop.
768 DestLoop->addBasicBlockToLoop(NMBB, MLI->getBase());
769 } else if (TIL->contains(DestLoop)) {
770 // Edge from an outer loop to an inner loop. Add to the outer loop.
771 TIL->addBasicBlockToLoop(NMBB, MLI->getBase());
772 } else if (DestLoop->contains(TIL)) {
773 // Edge from an inner loop to an outer loop. Add to the outer loop.
774 DestLoop->addBasicBlockToLoop(NMBB, MLI->getBase());
776 // Edge from two loops with no containment relation. Because these
777 // are natural loops, we know that the destination block must be the
778 // header of its loop (adding a branch into a loop elsewhere would
779 // create an irreducible loop).
780 assert(DestLoop->getHeader() == Succ &&
781 "Should not create irreducible loops!");
782 if (MachineLoop *P = DestLoop->getParentLoop())
783 P->addBasicBlockToLoop(NMBB, MLI->getBase());
791 /// Prepare MI to be removed from its bundle. This fixes bundle flags on MI's
792 /// neighboring instructions so the bundle won't be broken by removing MI.
793 static void unbundleSingleMI(MachineInstr *MI) {
794 // Removing the first instruction in a bundle.
795 if (MI->isBundledWithSucc() && !MI->isBundledWithPred())
796 MI->unbundleFromSucc();
797 // Removing the last instruction in a bundle.
798 if (MI->isBundledWithPred() && !MI->isBundledWithSucc())
799 MI->unbundleFromPred();
800 // If MI is not bundled, or if it is internal to a bundle, the neighbor flags
804 MachineBasicBlock::instr_iterator
805 MachineBasicBlock::erase(MachineBasicBlock::instr_iterator I) {
807 return Insts.erase(I);
810 MachineInstr *MachineBasicBlock::remove_instr(MachineInstr *MI) {
811 unbundleSingleMI(MI);
812 MI->clearFlag(MachineInstr::BundledPred);
813 MI->clearFlag(MachineInstr::BundledSucc);
814 return Insts.remove(MI);
817 MachineBasicBlock::instr_iterator
818 MachineBasicBlock::insert(instr_iterator I, MachineInstr *MI) {
819 assert(!MI->isBundledWithPred() && !MI->isBundledWithSucc() &&
820 "Cannot insert instruction with bundle flags");
821 // Set the bundle flags when inserting inside a bundle.
822 if (I != instr_end() && I->isBundledWithPred()) {
823 MI->setFlag(MachineInstr::BundledPred);
824 MI->setFlag(MachineInstr::BundledSucc);
826 return Insts.insert(I, MI);
829 /// removeFromParent - This method unlinks 'this' from the containing function,
830 /// and returns it, but does not delete it.
831 MachineBasicBlock *MachineBasicBlock::removeFromParent() {
832 assert(getParent() && "Not embedded in a function!");
833 getParent()->remove(this);
838 /// eraseFromParent - This method unlinks 'this' from the containing function,
840 void MachineBasicBlock::eraseFromParent() {
841 assert(getParent() && "Not embedded in a function!");
842 getParent()->erase(this);
846 /// ReplaceUsesOfBlockWith - Given a machine basic block that branched to
847 /// 'Old', change the code and CFG so that it branches to 'New' instead.
848 void MachineBasicBlock::ReplaceUsesOfBlockWith(MachineBasicBlock *Old,
849 MachineBasicBlock *New) {
850 assert(Old != New && "Cannot replace self with self!");
852 MachineBasicBlock::instr_iterator I = instr_end();
853 while (I != instr_begin()) {
855 if (!I->isTerminator()) break;
857 // Scan the operands of this machine instruction, replacing any uses of Old
859 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
860 if (I->getOperand(i).isMBB() &&
861 I->getOperand(i).getMBB() == Old)
862 I->getOperand(i).setMBB(New);
865 // Update the successor information.
866 replaceSuccessor(Old, New);
869 /// CorrectExtraCFGEdges - Various pieces of code can cause excess edges in the
870 /// CFG to be inserted. If we have proven that MBB can only branch to DestA and
871 /// DestB, remove any other MBB successors from the CFG. DestA and DestB can be
874 /// Besides DestA and DestB, retain other edges leading to LandingPads
875 /// (currently there can be only one; we don't check or require that here).
876 /// Note it is possible that DestA and/or DestB are LandingPads.
877 bool MachineBasicBlock::CorrectExtraCFGEdges(MachineBasicBlock *DestA,
878 MachineBasicBlock *DestB,
880 // The values of DestA and DestB frequently come from a call to the
881 // 'TargetInstrInfo::AnalyzeBranch' method. We take our meaning of the initial
882 // values from there.
884 // 1. If both DestA and DestB are null, then the block ends with no branches
885 // (it falls through to its successor).
886 // 2. If DestA is set, DestB is null, and isCond is false, then the block ends
887 // with only an unconditional branch.
888 // 3. If DestA is set, DestB is null, and isCond is true, then the block ends
889 // with a conditional branch that falls through to a successor (DestB).
890 // 4. If DestA and DestB is set and isCond is true, then the block ends with a
891 // conditional branch followed by an unconditional branch. DestA is the
892 // 'true' destination and DestB is the 'false' destination.
894 bool Changed = false;
896 MachineFunction::iterator FallThru =
897 llvm::next(MachineFunction::iterator(this));
899 if (DestA == 0 && DestB == 0) {
900 // Block falls through to successor.
903 } else if (DestA != 0 && DestB == 0) {
905 // Block ends in conditional jump that falls through to successor.
908 assert(DestA && DestB && isCond &&
909 "CFG in a bad state. Cannot correct CFG edges");
912 // Remove superfluous edges. I.e., those which aren't destinations of this
913 // basic block, duplicate edges, or landing pads.
914 SmallPtrSet<const MachineBasicBlock*, 8> SeenMBBs;
915 MachineBasicBlock::succ_iterator SI = succ_begin();
916 while (SI != succ_end()) {
917 const MachineBasicBlock *MBB = *SI;
918 if (!SeenMBBs.insert(MBB) ||
919 (MBB != DestA && MBB != DestB && !MBB->isLandingPad())) {
920 // This is a superfluous edge, remove it.
921 SI = removeSuccessor(SI);
931 /// findDebugLoc - find the next valid DebugLoc starting at MBBI, skipping
932 /// any DBG_VALUE instructions. Return UnknownLoc if there is none.
934 MachineBasicBlock::findDebugLoc(instr_iterator MBBI) {
936 instr_iterator E = instr_end();
940 // Skip debug declarations, we don't want a DebugLoc from them.
941 while (MBBI != E && MBBI->isDebugValue())
944 DL = MBBI->getDebugLoc();
948 /// getSuccWeight - Return weight of the edge from this block to MBB.
950 uint32_t MachineBasicBlock::getSuccWeight(const_succ_iterator Succ) const {
954 return *getWeightIterator(Succ);
957 /// getWeightIterator - Return wight iterator corresonding to the I successor
959 MachineBasicBlock::weight_iterator MachineBasicBlock::
960 getWeightIterator(MachineBasicBlock::succ_iterator I) {
961 assert(Weights.size() == Successors.size() && "Async weight list!");
962 size_t index = std::distance(Successors.begin(), I);
963 assert(index < Weights.size() && "Not a current successor!");
964 return Weights.begin() + index;
967 /// getWeightIterator - Return wight iterator corresonding to the I successor
969 MachineBasicBlock::const_weight_iterator MachineBasicBlock::
970 getWeightIterator(MachineBasicBlock::const_succ_iterator I) const {
971 assert(Weights.size() == Successors.size() && "Async weight list!");
972 const size_t index = std::distance(Successors.begin(), I);
973 assert(index < Weights.size() && "Not a current successor!");
974 return Weights.begin() + index;
977 /// Return whether (physical) register "Reg" has been <def>ined and not <kill>ed
978 /// as of just before "MI".
980 /// Search is localised to a neighborhood of
981 /// Neighborhood instructions before (searching for defs or kills) and N
982 /// instructions after (searching just for defs) MI.
983 MachineBasicBlock::LivenessQueryResult
984 MachineBasicBlock::computeRegisterLiveness(const TargetRegisterInfo *TRI,
985 unsigned Reg, MachineInstr *MI,
986 unsigned Neighborhood) {
987 unsigned N = Neighborhood;
988 MachineBasicBlock *MBB = MI->getParent();
990 // Start by searching backwards from MI, looking for kills, reads or defs.
992 MachineBasicBlock::iterator I(MI);
993 // If this is the first insn in the block, don't search backwards.
994 if (I != MBB->begin()) {
998 MachineOperandIteratorBase::PhysRegInfo Analysis =
999 MIOperands(I).analyzePhysReg(Reg, TRI);
1001 if (Analysis.Defines)
1002 // Outputs happen after inputs so they take precedence if both are
1004 return Analysis.DefinesDead ? LQR_Dead : LQR_Live;
1006 if (Analysis.Kills || Analysis.Clobbers)
1007 // Register killed, so isn't live.
1010 else if (Analysis.ReadsOverlap)
1011 // Defined or read without a previous kill - live.
1012 return Analysis.Reads ? LQR_Live : LQR_OverlappingLive;
1014 } while (I != MBB->begin() && --N > 0);
1017 // Did we get to the start of the block?
1018 if (I == MBB->begin()) {
1019 // If so, the register's state is definitely defined by the live-in state.
1020 for (MCRegAliasIterator RAI(Reg, TRI, /*IncludeSelf=*/true);
1021 RAI.isValid(); ++RAI) {
1022 if (MBB->isLiveIn(*RAI))
1023 return (*RAI == Reg) ? LQR_Live : LQR_OverlappingLive;
1031 // Try searching forwards from MI, looking for reads or defs.
1032 I = MachineBasicBlock::iterator(MI);
1033 // If this is the last insn in the block, don't search forwards.
1034 if (I != MBB->end()) {
1035 for (++I; I != MBB->end() && N > 0; ++I, --N) {
1036 MachineOperandIteratorBase::PhysRegInfo Analysis =
1037 MIOperands(I).analyzePhysReg(Reg, TRI);
1039 if (Analysis.ReadsOverlap)
1040 // Used, therefore must have been live.
1041 return (Analysis.Reads) ?
1042 LQR_Live : LQR_OverlappingLive;
1044 else if (Analysis.Clobbers || Analysis.Defines)
1045 // Defined (but not read) therefore cannot have been live.
1050 // At this point we have no idea of the liveness of the register.
1054 void llvm::WriteAsOperand(raw_ostream &OS, const MachineBasicBlock *MBB,
1056 OS << "BB#" << MBB->getNumber();