4d1370aed9827230e372df060405881a31d61894
[oota-llvm.git] / lib / CodeGen / MachineBasicBlock.cpp
1 //===-- llvm/CodeGen/MachineBasicBlock.cpp ----------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // Collect the sequence of machine instructions for a basic block.
11 //
12 //===----------------------------------------------------------------------===//
13
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/TargetMachine.h"
21 #include "llvm/Support/LeakDetector.h"
22 #include "llvm/Support/raw_ostream.h"
23 #include <algorithm>
24 using namespace llvm;
25
26 MachineBasicBlock::MachineBasicBlock(MachineFunction &mf, const BasicBlock *bb)
27   : BB(bb), Number(-1), xParent(&mf), Alignment(0), IsLandingPad(false),
28     AddressTaken(false) {
29   Insts.Parent = this;
30 }
31
32 MachineBasicBlock::~MachineBasicBlock() {
33   LeakDetector::removeGarbageObject(this);
34 }
35
36 raw_ostream &llvm::operator<<(raw_ostream &OS, const MachineBasicBlock &MBB) {
37   MBB.print(OS);
38   return OS;
39 }
40
41 /// addNodeToList (MBB) - When an MBB is added to an MF, we need to update the 
42 /// parent pointer of the MBB, the MBB numbering, and any instructions in the
43 /// MBB to be on the right operand list for registers.
44 ///
45 /// MBBs start out as #-1. When a MBB is added to a MachineFunction, it
46 /// gets the next available unique MBB number. If it is removed from a
47 /// MachineFunction, it goes back to being #-1.
48 void ilist_traits<MachineBasicBlock>::addNodeToList(MachineBasicBlock *N) {
49   MachineFunction &MF = *N->getParent();
50   N->Number = MF.addToMBBNumbering(N);
51
52   // Make sure the instructions have their operands in the reginfo lists.
53   MachineRegisterInfo &RegInfo = MF.getRegInfo();
54   for (MachineBasicBlock::iterator I = N->begin(), E = N->end(); I != E; ++I)
55     I->AddRegOperandsToUseLists(RegInfo);
56
57   LeakDetector::removeGarbageObject(N);
58 }
59
60 void ilist_traits<MachineBasicBlock>::removeNodeFromList(MachineBasicBlock *N) {
61   N->getParent()->removeFromMBBNumbering(N->Number);
62   N->Number = -1;
63   LeakDetector::addGarbageObject(N);
64 }
65
66
67 /// addNodeToList (MI) - When we add an instruction to a basic block
68 /// list, we update its parent pointer and add its operands from reg use/def
69 /// lists if appropriate.
70 void ilist_traits<MachineInstr>::addNodeToList(MachineInstr *N) {
71   assert(N->getParent() == 0 && "machine instruction already in a basic block");
72   N->setParent(Parent);
73   
74   // Add the instruction's register operands to their corresponding
75   // use/def lists.
76   MachineFunction *MF = Parent->getParent();
77   N->AddRegOperandsToUseLists(MF->getRegInfo());
78
79   LeakDetector::removeGarbageObject(N);
80 }
81
82 /// removeNodeFromList (MI) - When we remove an instruction from a basic block
83 /// list, we update its parent pointer and remove its operands from reg use/def
84 /// lists if appropriate.
85 void ilist_traits<MachineInstr>::removeNodeFromList(MachineInstr *N) {
86   assert(N->getParent() != 0 && "machine instruction not in a basic block");
87
88   // Remove from the use/def lists.
89   N->RemoveRegOperandsFromUseLists();
90   
91   N->setParent(0);
92
93   LeakDetector::addGarbageObject(N);
94 }
95
96 /// transferNodesFromList (MI) - When moving a range of instructions from one
97 /// MBB list to another, we need to update the parent pointers and the use/def
98 /// lists.
99 void ilist_traits<MachineInstr>::
100 transferNodesFromList(ilist_traits<MachineInstr> &fromList,
101                       MachineBasicBlock::iterator first,
102                       MachineBasicBlock::iterator last) {
103   assert(Parent->getParent() == fromList.Parent->getParent() &&
104         "MachineInstr parent mismatch!");
105
106   // Splice within the same MBB -> no change.
107   if (Parent == fromList.Parent) return;
108
109   // If splicing between two blocks within the same function, just update the
110   // parent pointers.
111   for (; first != last; ++first)
112     first->setParent(Parent);
113 }
114
115 void ilist_traits<MachineInstr>::deleteNode(MachineInstr* MI) {
116   assert(!MI->getParent() && "MI is still in a block!");
117   Parent->getParent()->DeleteMachineInstr(MI);
118 }
119
120 MachineBasicBlock::iterator MachineBasicBlock::getFirstTerminator() {
121   iterator I = end();
122   while (I != begin() && (--I)->getDesc().isTerminator())
123     ; /*noop */
124   if (I != end() && !I->getDesc().isTerminator()) ++I;
125   return I;
126 }
127
128 /// isOnlyReachableViaFallthough - Return true if this basic block has
129 /// exactly one predecessor and the control transfer mechanism between
130 /// the predecessor and this block is a fall-through.
131 bool MachineBasicBlock::isOnlyReachableByFallthrough() const {
132   // If this is a landing pad, it isn't a fall through.  If it has no preds,
133   // then nothing falls through to it.
134   if (isLandingPad() || pred_empty())
135     return false;
136   
137   // If there isn't exactly one predecessor, it can't be a fall through.
138   const_pred_iterator PI = pred_begin(), PI2 = PI;
139   ++PI2;
140   if (PI2 != pred_end())
141     return false;
142   
143   // The predecessor has to be immediately before this block.
144   const MachineBasicBlock *Pred = *PI;
145   
146   if (!Pred->isLayoutSuccessor(this))
147     return false;
148   
149   // If the block is completely empty, then it definitely does fall through.
150   if (Pred->empty())
151     return true;
152   
153   // Otherwise, check the last instruction.
154   const MachineInstr &LastInst = Pred->back();
155   return !LastInst.getDesc().isBarrier();
156 }
157
158 void MachineBasicBlock::dump() const {
159   print(errs());
160 }
161
162 static inline void OutputReg(raw_ostream &os, unsigned RegNo,
163                              const TargetRegisterInfo *TRI = 0) {
164   if (!RegNo || TargetRegisterInfo::isPhysicalRegister(RegNo)) {
165     if (TRI)
166       os << " %" << TRI->get(RegNo).Name;
167     else
168       os << " %mreg(" << RegNo << ")";
169   } else
170     os << " %reg" << RegNo;
171 }
172
173 void MachineBasicBlock::print(raw_ostream &OS) const {
174   const MachineFunction *MF = getParent();
175   if (!MF) {
176     OS << "Can't print out MachineBasicBlock because parent MachineFunction"
177        << " is null\n";
178     return;
179   }
180
181   const BasicBlock *LBB = getBasicBlock();
182   OS << '\n';
183   if (LBB) OS << LBB->getName() << ": ";
184   OS << (const void*)this
185      << ", LLVM BB @" << (const void*) LBB << ", ID#" << getNumber();
186   if (Alignment) OS << ", Alignment " << Alignment;
187   if (isLandingPad()) OS << ", EH LANDING PAD";
188   if (hasAddressTaken()) OS << ", ADDRESS TAKEN";
189   OS << ":\n";
190
191   const TargetRegisterInfo *TRI = MF->getTarget().getRegisterInfo();  
192   if (!livein_empty()) {
193     OS << "Live Ins:";
194     for (const_livein_iterator I = livein_begin(),E = livein_end(); I != E; ++I)
195       OutputReg(OS, *I, TRI);
196     OS << '\n';
197   }
198   // Print the preds of this block according to the CFG.
199   if (!pred_empty()) {
200     OS << "    Predecessors according to CFG:";
201     for (const_pred_iterator PI = pred_begin(), E = pred_end(); PI != E; ++PI)
202       OS << ' ' << *PI << " (#" << (*PI)->getNumber() << ')';
203     OS << '\n';
204   }
205   
206   for (const_iterator I = begin(); I != end(); ++I) {
207     OS << '\t';
208     I->print(OS, &getParent()->getTarget());
209   }
210
211   // Print the successors of this block according to the CFG.
212   if (!succ_empty()) {
213     OS << "    Successors according to CFG:";
214     for (const_succ_iterator SI = succ_begin(), E = succ_end(); SI != E; ++SI)
215       OS << ' ' << *SI << " (#" << (*SI)->getNumber() << ')';
216     OS << '\n';
217   }
218 }
219
220 void MachineBasicBlock::removeLiveIn(unsigned Reg) {
221   livein_iterator I = std::find(livein_begin(), livein_end(), Reg);
222   assert(I != livein_end() && "Not a live in!");
223   LiveIns.erase(I);
224 }
225
226 bool MachineBasicBlock::isLiveIn(unsigned Reg) const {
227   const_livein_iterator I = std::find(livein_begin(), livein_end(), Reg);
228   return I != livein_end();
229 }
230
231 void MachineBasicBlock::moveBefore(MachineBasicBlock *NewAfter) {
232   getParent()->splice(NewAfter, this);
233 }
234
235 void MachineBasicBlock::moveAfter(MachineBasicBlock *NewBefore) {
236   MachineFunction::iterator BBI = NewBefore;
237   getParent()->splice(++BBI, this);
238 }
239
240
241 void MachineBasicBlock::addSuccessor(MachineBasicBlock *succ) {
242   Successors.push_back(succ);
243   succ->addPredecessor(this);
244 }
245
246 void MachineBasicBlock::removeSuccessor(MachineBasicBlock *succ) {
247   succ->removePredecessor(this);
248   succ_iterator I = std::find(Successors.begin(), Successors.end(), succ);
249   assert(I != Successors.end() && "Not a current successor!");
250   Successors.erase(I);
251 }
252
253 MachineBasicBlock::succ_iterator 
254 MachineBasicBlock::removeSuccessor(succ_iterator I) {
255   assert(I != Successors.end() && "Not a current successor!");
256   (*I)->removePredecessor(this);
257   return Successors.erase(I);
258 }
259
260 void MachineBasicBlock::addPredecessor(MachineBasicBlock *pred) {
261   Predecessors.push_back(pred);
262 }
263
264 void MachineBasicBlock::removePredecessor(MachineBasicBlock *pred) {
265   std::vector<MachineBasicBlock *>::iterator I =
266     std::find(Predecessors.begin(), Predecessors.end(), pred);
267   assert(I != Predecessors.end() && "Pred is not a predecessor of this block!");
268   Predecessors.erase(I);
269 }
270
271 void MachineBasicBlock::transferSuccessors(MachineBasicBlock *fromMBB) {
272   if (this == fromMBB)
273     return;
274   
275   for (MachineBasicBlock::succ_iterator I = fromMBB->succ_begin(), 
276        E = fromMBB->succ_end(); I != E; ++I)
277     addSuccessor(*I);
278   
279   while (!fromMBB->succ_empty())
280     fromMBB->removeSuccessor(fromMBB->succ_begin());
281 }
282
283 bool MachineBasicBlock::isSuccessor(const MachineBasicBlock *MBB) const {
284   std::vector<MachineBasicBlock *>::const_iterator I =
285     std::find(Successors.begin(), Successors.end(), MBB);
286   return I != Successors.end();
287 }
288
289 bool MachineBasicBlock::isLayoutSuccessor(const MachineBasicBlock *MBB) const {
290   MachineFunction::const_iterator I(this);
291   return next(I) == MachineFunction::const_iterator(MBB);
292 }
293
294 /// removeFromParent - This method unlinks 'this' from the containing function,
295 /// and returns it, but does not delete it.
296 MachineBasicBlock *MachineBasicBlock::removeFromParent() {
297   assert(getParent() && "Not embedded in a function!");
298   getParent()->remove(this);
299   return this;
300 }
301
302
303 /// eraseFromParent - This method unlinks 'this' from the containing function,
304 /// and deletes it.
305 void MachineBasicBlock::eraseFromParent() {
306   assert(getParent() && "Not embedded in a function!");
307   getParent()->erase(this);
308 }
309
310
311 /// ReplaceUsesOfBlockWith - Given a machine basic block that branched to
312 /// 'Old', change the code and CFG so that it branches to 'New' instead.
313 void MachineBasicBlock::ReplaceUsesOfBlockWith(MachineBasicBlock *Old,
314                                                MachineBasicBlock *New) {
315   assert(Old != New && "Cannot replace self with self!");
316
317   MachineBasicBlock::iterator I = end();
318   while (I != begin()) {
319     --I;
320     if (!I->getDesc().isTerminator()) break;
321
322     // Scan the operands of this machine instruction, replacing any uses of Old
323     // with New.
324     for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
325       if (I->getOperand(i).isMBB() &&
326           I->getOperand(i).getMBB() == Old)
327         I->getOperand(i).setMBB(New);
328   }
329
330   // Update the successor information.
331   removeSuccessor(Old);
332   addSuccessor(New);
333 }
334
335 /// CorrectExtraCFGEdges - Various pieces of code can cause excess edges in the
336 /// CFG to be inserted.  If we have proven that MBB can only branch to DestA and
337 /// DestB, remove any other MBB successors from the CFG.  DestA and DestB can
338 /// be null.
339 /// Besides DestA and DestB, retain other edges leading to LandingPads
340 /// (currently there can be only one; we don't check or require that here).
341 /// Note it is possible that DestA and/or DestB are LandingPads.
342 bool MachineBasicBlock::CorrectExtraCFGEdges(MachineBasicBlock *DestA,
343                                              MachineBasicBlock *DestB,
344                                              bool isCond) {
345   bool MadeChange = false;
346   bool AddedFallThrough = false;
347
348   MachineFunction::iterator FallThru = next(MachineFunction::iterator(this));
349   
350   // If this block ends with a conditional branch that falls through to its
351   // successor, set DestB as the successor.
352   if (isCond) {
353     if (DestB == 0 && FallThru != getParent()->end()) {
354       DestB = FallThru;
355       AddedFallThrough = true;
356     }
357   } else {
358     // If this is an unconditional branch with no explicit dest, it must just be
359     // a fallthrough into DestB.
360     if (DestA == 0 && FallThru != getParent()->end()) {
361       DestA = FallThru;
362       AddedFallThrough = true;
363     }
364   }
365   
366   MachineBasicBlock::succ_iterator SI = succ_begin();
367   MachineBasicBlock *OrigDestA = DestA, *OrigDestB = DestB;
368   while (SI != succ_end()) {
369     if (*SI == DestA && DestA == DestB) {
370       DestA = DestB = 0;
371       ++SI;
372     } else if (*SI == DestA) {
373       DestA = 0;
374       ++SI;
375     } else if (*SI == DestB) {
376       DestB = 0;
377       ++SI;
378     } else if ((*SI)->isLandingPad() && 
379                *SI!=OrigDestA && *SI!=OrigDestB) {
380       ++SI;
381     } else {
382       // Otherwise, this is a superfluous edge, remove it.
383       SI = removeSuccessor(SI);
384       MadeChange = true;
385     }
386   }
387   if (!AddedFallThrough) {
388     assert(DestA == 0 && DestB == 0 &&
389            "MachineCFG is missing edges!");
390   } else if (isCond) {
391     assert(DestA == 0 && "MachineCFG is missing edges!");
392   }
393   return MadeChange;
394 }