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/BasicBlock.h"
16 #include "llvm/CodeGen/MachineFunction.h"
17 #include "llvm/Target/TargetRegisterInfo.h"
18 #include "llvm/Target/TargetData.h"
19 #include "llvm/Target/TargetInstrDesc.h"
20 #include "llvm/Target/TargetInstrInfo.h"
21 #include "llvm/Target/TargetMachine.h"
22 #include "llvm/Support/LeakDetector.h"
23 #include "llvm/Support/raw_ostream.h"
24 #include "llvm/Assembly/Writer.h"
28 MachineBasicBlock::MachineBasicBlock(MachineFunction &mf, const BasicBlock *bb)
29 : BB(bb), Number(-1), xParent(&mf), Alignment(0), IsLandingPad(false),
34 MachineBasicBlock::~MachineBasicBlock() {
35 LeakDetector::removeGarbageObject(this);
38 raw_ostream &llvm::operator<<(raw_ostream &OS, const MachineBasicBlock &MBB) {
43 /// addNodeToList (MBB) - When an MBB is added to an MF, we need to update the
44 /// parent pointer of the MBB, the MBB numbering, and any instructions in the
45 /// MBB to be on the right operand list for registers.
47 /// MBBs start out as #-1. When a MBB is added to a MachineFunction, it
48 /// gets the next available unique MBB number. If it is removed from a
49 /// MachineFunction, it goes back to being #-1.
50 void ilist_traits<MachineBasicBlock>::addNodeToList(MachineBasicBlock *N) {
51 MachineFunction &MF = *N->getParent();
52 N->Number = MF.addToMBBNumbering(N);
54 // Make sure the instructions have their operands in the reginfo lists.
55 MachineRegisterInfo &RegInfo = MF.getRegInfo();
56 for (MachineBasicBlock::iterator I = N->begin(), E = N->end(); I != E; ++I)
57 I->AddRegOperandsToUseLists(RegInfo);
59 LeakDetector::removeGarbageObject(N);
62 void ilist_traits<MachineBasicBlock>::removeNodeFromList(MachineBasicBlock *N) {
63 N->getParent()->removeFromMBBNumbering(N->Number);
65 LeakDetector::addGarbageObject(N);
69 /// addNodeToList (MI) - When we add an instruction to a basic block
70 /// list, we update its parent pointer and add its operands from reg use/def
71 /// lists if appropriate.
72 void ilist_traits<MachineInstr>::addNodeToList(MachineInstr *N) {
73 assert(N->getParent() == 0 && "machine instruction already in a basic block");
76 // Add the instruction's register operands to their corresponding
78 MachineFunction *MF = Parent->getParent();
79 N->AddRegOperandsToUseLists(MF->getRegInfo());
81 LeakDetector::removeGarbageObject(N);
84 /// removeNodeFromList (MI) - When we remove an instruction from a basic block
85 /// list, we update its parent pointer and remove its operands from reg use/def
86 /// lists if appropriate.
87 void ilist_traits<MachineInstr>::removeNodeFromList(MachineInstr *N) {
88 assert(N->getParent() != 0 && "machine instruction not in a basic block");
90 // Remove from the use/def lists.
91 N->RemoveRegOperandsFromUseLists();
95 LeakDetector::addGarbageObject(N);
98 /// transferNodesFromList (MI) - When moving a range of instructions from one
99 /// MBB list to another, we need to update the parent pointers and the use/def
101 void ilist_traits<MachineInstr>::
102 transferNodesFromList(ilist_traits<MachineInstr> &fromList,
103 MachineBasicBlock::iterator first,
104 MachineBasicBlock::iterator last) {
105 assert(Parent->getParent() == fromList.Parent->getParent() &&
106 "MachineInstr parent mismatch!");
108 // Splice within the same MBB -> no change.
109 if (Parent == fromList.Parent) return;
111 // If splicing between two blocks within the same function, just update the
113 for (; first != last; ++first)
114 first->setParent(Parent);
117 void ilist_traits<MachineInstr>::deleteNode(MachineInstr* MI) {
118 assert(!MI->getParent() && "MI is still in a block!");
119 Parent->getParent()->DeleteMachineInstr(MI);
122 MachineBasicBlock::iterator MachineBasicBlock::getFirstTerminator() {
124 while (I != begin() && (--I)->getDesc().isTerminator())
126 if (I != end() && !I->getDesc().isTerminator()) ++I;
130 /// isOnlyReachableViaFallthough - Return true if this basic block has
131 /// exactly one predecessor and the control transfer mechanism between
132 /// the predecessor and this block is a fall-through.
133 bool MachineBasicBlock::isOnlyReachableByFallthrough() const {
134 // If this is a landing pad, it isn't a fall through. If it has no preds,
135 // then nothing falls through to it.
136 if (isLandingPad() || pred_empty())
139 // If there isn't exactly one predecessor, it can't be a fall through.
140 const_pred_iterator PI = pred_begin(), PI2 = PI;
142 if (PI2 != pred_end())
145 // The predecessor has to be immediately before this block.
146 const MachineBasicBlock *Pred = *PI;
148 if (!Pred->isLayoutSuccessor(this))
151 // If the block is completely empty, then it definitely does fall through.
155 // Otherwise, check the last instruction.
156 const MachineInstr &LastInst = Pred->back();
157 return !LastInst.getDesc().isBarrier();
160 void MachineBasicBlock::dump() const {
164 static inline void OutputReg(raw_ostream &os, unsigned RegNo,
165 const TargetRegisterInfo *TRI = 0) {
166 if (RegNo != 0 && TargetRegisterInfo::isPhysicalRegister(RegNo)) {
168 os << " %" << TRI->get(RegNo).Name;
170 os << " %physreg" << RegNo;
172 os << " %reg" << RegNo;
175 void MachineBasicBlock::print(raw_ostream &OS) const {
176 const MachineFunction *MF = getParent();
178 OS << "Can't print out MachineBasicBlock because parent MachineFunction"
183 if (Alignment) { OS << "Alignment " << Alignment << "\n"; }
185 OS << "BB#" << getNumber() << ": ";
187 const char *Comma = "";
188 if (const BasicBlock *LBB = getBasicBlock()) {
189 OS << Comma << "derived from LLVM BB ";
190 WriteAsOperand(OS, LBB, /*PrintType=*/false);
193 if (isLandingPad()) { OS << Comma << "EH LANDING PAD"; Comma = ", "; }
194 if (hasAddressTaken()) { OS << Comma << "ADDRESS TAKEN"; Comma = ", "; }
197 const TargetRegisterInfo *TRI = MF->getTarget().getRegisterInfo();
198 if (!livein_empty()) {
200 for (const_livein_iterator I = livein_begin(),E = livein_end(); I != E; ++I)
201 OutputReg(OS, *I, TRI);
204 // Print the preds of this block according to the CFG.
206 OS << " Predecessors according to CFG:";
207 for (const_pred_iterator PI = pred_begin(), E = pred_end(); PI != E; ++PI)
208 OS << " BB#" << (*PI)->getNumber();
212 for (const_iterator I = begin(); I != end(); ++I) {
214 I->print(OS, &getParent()->getTarget());
217 // Print the successors of this block according to the CFG.
219 OS << " Successors according to CFG:";
220 for (const_succ_iterator SI = succ_begin(), E = succ_end(); SI != E; ++SI)
221 OS << " BB#" << (*SI)->getNumber();
226 void MachineBasicBlock::removeLiveIn(unsigned Reg) {
227 livein_iterator I = std::find(livein_begin(), livein_end(), Reg);
228 assert(I != livein_end() && "Not a live in!");
232 bool MachineBasicBlock::isLiveIn(unsigned Reg) const {
233 const_livein_iterator I = std::find(livein_begin(), livein_end(), Reg);
234 return I != livein_end();
237 void MachineBasicBlock::moveBefore(MachineBasicBlock *NewAfter) {
238 getParent()->splice(NewAfter, this);
241 void MachineBasicBlock::moveAfter(MachineBasicBlock *NewBefore) {
242 MachineFunction::iterator BBI = NewBefore;
243 getParent()->splice(++BBI, this);
246 void MachineBasicBlock::updateTerminator() {
247 const TargetInstrInfo *TII = getParent()->getTarget().getInstrInfo();
248 // A block with no successors has no concerns with fall-through edges.
249 if (this->succ_empty()) return;
251 MachineBasicBlock *TBB = 0, *FBB = 0;
252 SmallVector<MachineOperand, 4> Cond;
253 bool B = TII->AnalyzeBranch(*this, TBB, FBB, Cond);
255 assert(!B && "UpdateTerminators requires analyzable predecessors!");
258 // The block has an unconditional branch. If its successor is now
259 // its layout successor, delete the branch.
260 if (isLayoutSuccessor(TBB))
261 TII->RemoveBranch(*this);
263 // The block has an unconditional fallthrough. If its successor is not
264 // its layout successor, insert a branch.
266 if (!isLayoutSuccessor(TBB))
267 TII->InsertBranch(*this, TBB, 0, Cond);
271 // The block has a non-fallthrough conditional branch. If one of its
272 // successors is its layout successor, rewrite it to a fallthrough
273 // conditional branch.
274 if (isLayoutSuccessor(TBB)) {
275 TII->RemoveBranch(*this);
276 TII->ReverseBranchCondition(Cond);
277 TII->InsertBranch(*this, FBB, 0, Cond);
278 } else if (isLayoutSuccessor(FBB)) {
279 TII->RemoveBranch(*this);
280 TII->InsertBranch(*this, TBB, 0, Cond);
283 // The block has a fallthrough conditional branch.
284 MachineBasicBlock *MBBA = *succ_begin();
285 MachineBasicBlock *MBBB = *next(succ_begin());
286 if (MBBA == TBB) std::swap(MBBB, MBBA);
287 if (isLayoutSuccessor(TBB)) {
288 TII->RemoveBranch(*this);
289 TII->ReverseBranchCondition(Cond);
290 TII->InsertBranch(*this, MBBA, 0, Cond);
291 } else if (!isLayoutSuccessor(MBBA)) {
292 TII->RemoveBranch(*this);
293 TII->InsertBranch(*this, TBB, MBBA, Cond);
299 void MachineBasicBlock::addSuccessor(MachineBasicBlock *succ) {
300 Successors.push_back(succ);
301 succ->addPredecessor(this);
304 void MachineBasicBlock::removeSuccessor(MachineBasicBlock *succ) {
305 succ->removePredecessor(this);
306 succ_iterator I = std::find(Successors.begin(), Successors.end(), succ);
307 assert(I != Successors.end() && "Not a current successor!");
311 MachineBasicBlock::succ_iterator
312 MachineBasicBlock::removeSuccessor(succ_iterator I) {
313 assert(I != Successors.end() && "Not a current successor!");
314 (*I)->removePredecessor(this);
315 return Successors.erase(I);
318 void MachineBasicBlock::addPredecessor(MachineBasicBlock *pred) {
319 Predecessors.push_back(pred);
322 void MachineBasicBlock::removePredecessor(MachineBasicBlock *pred) {
323 std::vector<MachineBasicBlock *>::iterator I =
324 std::find(Predecessors.begin(), Predecessors.end(), pred);
325 assert(I != Predecessors.end() && "Pred is not a predecessor of this block!");
326 Predecessors.erase(I);
329 void MachineBasicBlock::transferSuccessors(MachineBasicBlock *fromMBB) {
333 for (MachineBasicBlock::succ_iterator I = fromMBB->succ_begin(),
334 E = fromMBB->succ_end(); I != E; ++I)
337 while (!fromMBB->succ_empty())
338 fromMBB->removeSuccessor(fromMBB->succ_begin());
341 bool MachineBasicBlock::isSuccessor(const MachineBasicBlock *MBB) const {
342 std::vector<MachineBasicBlock *>::const_iterator I =
343 std::find(Successors.begin(), Successors.end(), MBB);
344 return I != Successors.end();
347 bool MachineBasicBlock::isLayoutSuccessor(const MachineBasicBlock *MBB) const {
348 MachineFunction::const_iterator I(this);
349 return next(I) == MachineFunction::const_iterator(MBB);
352 /// removeFromParent - This method unlinks 'this' from the containing function,
353 /// and returns it, but does not delete it.
354 MachineBasicBlock *MachineBasicBlock::removeFromParent() {
355 assert(getParent() && "Not embedded in a function!");
356 getParent()->remove(this);
361 /// eraseFromParent - This method unlinks 'this' from the containing function,
363 void MachineBasicBlock::eraseFromParent() {
364 assert(getParent() && "Not embedded in a function!");
365 getParent()->erase(this);
369 /// ReplaceUsesOfBlockWith - Given a machine basic block that branched to
370 /// 'Old', change the code and CFG so that it branches to 'New' instead.
371 void MachineBasicBlock::ReplaceUsesOfBlockWith(MachineBasicBlock *Old,
372 MachineBasicBlock *New) {
373 assert(Old != New && "Cannot replace self with self!");
375 MachineBasicBlock::iterator I = end();
376 while (I != begin()) {
378 if (!I->getDesc().isTerminator()) break;
380 // Scan the operands of this machine instruction, replacing any uses of Old
382 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
383 if (I->getOperand(i).isMBB() &&
384 I->getOperand(i).getMBB() == Old)
385 I->getOperand(i).setMBB(New);
388 // Update the successor information.
389 removeSuccessor(Old);
393 /// CorrectExtraCFGEdges - Various pieces of code can cause excess edges in the
394 /// CFG to be inserted. If we have proven that MBB can only branch to DestA and
395 /// DestB, remove any other MBB successors from the CFG. DestA and DestB can
397 /// Besides DestA and DestB, retain other edges leading to LandingPads
398 /// (currently there can be only one; we don't check or require that here).
399 /// Note it is possible that DestA and/or DestB are LandingPads.
400 bool MachineBasicBlock::CorrectExtraCFGEdges(MachineBasicBlock *DestA,
401 MachineBasicBlock *DestB,
403 bool MadeChange = false;
404 bool AddedFallThrough = false;
406 MachineFunction::iterator FallThru = next(MachineFunction::iterator(this));
408 // If this block ends with a conditional branch that falls through to its
409 // successor, set DestB as the successor.
411 if (DestB == 0 && FallThru != getParent()->end()) {
413 AddedFallThrough = true;
416 // If this is an unconditional branch with no explicit dest, it must just be
417 // a fallthrough into DestB.
418 if (DestA == 0 && FallThru != getParent()->end()) {
420 AddedFallThrough = true;
424 MachineBasicBlock::succ_iterator SI = succ_begin();
425 MachineBasicBlock *OrigDestA = DestA, *OrigDestB = DestB;
426 while (SI != succ_end()) {
430 } else if (*SI == DestB) {
433 } else if ((*SI)->isLandingPad() &&
434 *SI!=OrigDestA && *SI!=OrigDestB) {
437 // Otherwise, this is a superfluous edge, remove it.
438 SI = removeSuccessor(SI);
442 if (!AddedFallThrough) {
443 assert(DestA == 0 && DestB == 0 &&
444 "MachineCFG is missing edges!");
446 assert(DestA == 0 && "MachineCFG is missing edges!");
451 void llvm::WriteAsOperand(raw_ostream &OS, const MachineBasicBlock *MBB,
453 OS << "BB#" << MBB->getNumber();