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