16aa7faa0859f6166f91058989ed24a42e1574b7
[oota-llvm.git] / lib / VMCore / BasicBlock.cpp
1 //===-- BasicBlock.cpp - Implement BasicBlock related methods -------------===//
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 // This file implements the BasicBlock class for the VMCore library.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/BasicBlock.h"
15 #include "llvm/Constants.h"
16 #include "llvm/Instructions.h"
17 #include "llvm/Type.h"
18 #include "llvm/Support/CFG.h"
19 #include "llvm/Support/LeakDetector.h"
20 #include "llvm/Support/Compiler.h"
21 #include "SymbolTableListTraitsImpl.h"
22 #include <algorithm>
23 using namespace llvm;
24
25 inline ValueSymbolTable *
26 ilist_traits<Instruction>::getSymTab(BasicBlock *BB) {
27   if (BB)
28     if (Function *F = BB->getParent())
29       return &F->getValueSymbolTable();
30   return 0;
31 }
32
33
34 namespace {
35   /// DummyInst - An instance of this class is used to mark the end of the
36   /// instruction list.  This is not a real instruction.
37   struct VISIBILITY_HIDDEN DummyInst : public Instruction {
38     // allocate space for exactly zero operands
39     void *operator new(size_t s) {
40       return User::operator new(s, 0);
41     }
42     DummyInst() : Instruction(Type::VoidTy, OtherOpsEnd, 0, 0) {
43       // This should not be garbage monitored.
44       LeakDetector::removeGarbageObject(this);
45     }
46
47     Instruction *clone() const {
48       assert(0 && "Cannot clone EOL");abort();
49       return 0;
50     }
51     const char *getOpcodeName() const { return "*end-of-list-inst*"; }
52
53     // Methods for support type inquiry through isa, cast, and dyn_cast...
54     static inline bool classof(const DummyInst *) { return true; }
55     static inline bool classof(const Instruction *I) {
56       return I->getOpcode() == OtherOpsEnd;
57     }
58     static inline bool classof(const Value *V) {
59       return isa<Instruction>(V) && classof(cast<Instruction>(V));
60     }
61   };
62 }
63
64 Instruction *ilist_traits<Instruction>::createSentinel() {
65   return new DummyInst();
66 }
67 iplist<Instruction> &ilist_traits<Instruction>::getList(BasicBlock *BB) {
68   return BB->getInstList();
69 }
70
71 // Explicit instantiation of SymbolTableListTraits since some of the methods
72 // are not in the public header file...
73 template class SymbolTableListTraits<Instruction, BasicBlock>;
74
75
76 BasicBlock::BasicBlock(const std::string &Name, Function *NewParent,
77                        BasicBlock *InsertBefore, BasicBlock *Dest)
78   : User(Type::LabelTy, Value::BasicBlockVal, &unwindDest, 0/*FIXME*/), Parent(0) {
79
80   // Make sure that we get added to a function
81   LeakDetector::addGarbageObject(this);
82
83   if (InsertBefore) {
84     assert(NewParent &&
85            "Cannot insert block before another block with no function!");
86     NewParent->getBasicBlockList().insert(InsertBefore, this);
87   } else if (NewParent) {
88     NewParent->getBasicBlockList().push_back(this);
89   }
90   
91   setName(Name);
92   unwindDest.init(NULL, this);
93   setUnwindDest(Dest);
94 }
95
96
97 BasicBlock::~BasicBlock() {
98   assert(getParent() == 0 && "BasicBlock still linked into the program!");
99   dropAllReferences();
100   InstList.clear();
101 }
102
103 void BasicBlock::setParent(Function *parent) {
104   if (getParent())
105     LeakDetector::addGarbageObject(this);
106
107   // Set Parent=parent, updating instruction symtab entries as appropriate.
108   InstList.setSymTabObject(&Parent, parent);
109
110   if (getParent())
111     LeakDetector::removeGarbageObject(this);
112 }
113
114 void BasicBlock::removeFromParent() {
115   getParent()->getBasicBlockList().remove(this);
116 }
117
118 void BasicBlock::eraseFromParent() {
119   getParent()->getBasicBlockList().erase(this);
120 }
121
122 const BasicBlock *BasicBlock::getUnwindDest() const {
123   return cast_or_null<const BasicBlock>(unwindDest.get());
124 }
125
126 BasicBlock *BasicBlock::getUnwindDest() {
127   return cast_or_null<BasicBlock>(unwindDest.get());
128 }
129
130 void BasicBlock::setUnwindDest(BasicBlock *dest) {
131   NumOperands = unwindDest ? 1 : 0;
132   unwindDest.set(dest);
133 }
134
135 /// moveBefore - Unlink this basic block from its current function and
136 /// insert it into the function that MovePos lives in, right before MovePos.
137 void BasicBlock::moveBefore(BasicBlock *MovePos) {
138   MovePos->getParent()->getBasicBlockList().splice(MovePos,
139                        getParent()->getBasicBlockList(), this);
140 }
141
142 /// moveAfter - Unlink this basic block from its current function and
143 /// insert it into the function that MovePos lives in, right after MovePos.
144 void BasicBlock::moveAfter(BasicBlock *MovePos) {
145   Function::iterator I = MovePos;
146   MovePos->getParent()->getBasicBlockList().splice(++I,
147                                        getParent()->getBasicBlockList(), this);
148 }
149
150
151 TerminatorInst *BasicBlock::getTerminator() {
152   if (InstList.empty()) return 0;
153   return dyn_cast<TerminatorInst>(&InstList.back());
154 }
155
156 const TerminatorInst *BasicBlock::getTerminator() const {
157   if (InstList.empty()) return 0;
158   return dyn_cast<TerminatorInst>(&InstList.back());
159 }
160
161 Instruction* BasicBlock::getFirstNonPHI()
162 {
163     BasicBlock::iterator i = begin();
164     // All valid basic blocks should have a terminator,
165     // which is not a PHINode. If we have invalid basic
166     // block we'll get assert when dereferencing past-the-end
167     // iterator.
168     while (isa<PHINode>(i)) ++i;
169     return &*i;
170 }
171
172 void BasicBlock::dropAllReferences() {
173   setUnwindDest(NULL);
174   for(iterator I = begin(), E = end(); I != E; ++I)
175     I->dropAllReferences();
176 }
177
178 /// getSinglePredecessor - If this basic block has a single predecessor block,
179 /// return the block, otherwise return a null pointer.
180 BasicBlock *BasicBlock::getSinglePredecessor() {
181   pred_iterator PI = pred_begin(this), E = pred_end(this);
182   if (PI == E) return 0;         // No preds.
183   BasicBlock *ThePred = *PI;
184   ++PI;
185   return (PI == E) ? ThePred : 0 /*multiple preds*/;
186 }
187
188 /// removePredecessor - This method is used to notify a BasicBlock that the
189 /// specified Predecessor of the block is no longer able to reach it.  This is
190 /// actually not used to update the Predecessor list, but is actually used to
191 /// update the PHI nodes that reside in the block.  Note that this should be
192 /// called while the predecessor still refers to this block.
193 ///
194 void BasicBlock::removePredecessor(BasicBlock *Pred,
195                                    bool DontDeleteUselessPHIs,
196                                    bool OnlyDeleteOne) {
197   assert((hasNUsesOrMore(16)||// Reduce cost of this assertion for complex CFGs.
198           find(pred_begin(this), pred_end(this), Pred) != pred_end(this)) &&
199          "removePredecessor: BB is not a predecessor!");
200
201   if (InstList.empty()) return;
202   PHINode *APN = dyn_cast<PHINode>(&front());
203   if (!APN) return;   // Quick exit.
204
205   // If there are exactly two predecessors, then we want to nuke the PHI nodes
206   // altogether.  However, we cannot do this, if this in this case:
207   //
208   //  Loop:
209   //    %x = phi [X, Loop]
210   //    %x2 = add %x, 1         ;; This would become %x2 = add %x2, 1
211   //    br Loop                 ;; %x2 does not dominate all uses
212   //
213   // This is because the PHI node input is actually taken from the predecessor
214   // basic block.  The only case this can happen is with a self loop, so we
215   // check for this case explicitly now.
216   //
217   unsigned max_idx = APN->getNumIncomingValues();
218   assert(max_idx != 0 && "PHI Node in block with 0 predecessors!?!?!");
219   if (max_idx == 2) {
220     BasicBlock *Other = APN->getIncomingBlock(APN->getIncomingBlock(0) == Pred);
221
222     // Disable PHI elimination!
223     if (this == Other) max_idx = 3;
224   }
225
226   // <= Two predecessors BEFORE I remove one?
227   if (max_idx <= 2 && !DontDeleteUselessPHIs) {
228     // Yup, loop through and nuke the PHI nodes
229     while (PHINode *PN = dyn_cast<PHINode>(&front())) {
230       // Remove the predecessor first.
231       if (OnlyDeleteOne) {
232         int idx = PN->getBasicBlockIndex(Pred);
233         PN->removeIncomingValue(idx, !DontDeleteUselessPHIs);
234       } else
235         PN->removeIncomingValue(Pred, !DontDeleteUselessPHIs);
236
237       // If the PHI _HAD_ two uses, replace PHI node with its now *single* value
238       if (max_idx == 2) {
239         if (PN->getOperand(0) != PN)
240           PN->replaceAllUsesWith(PN->getOperand(0));
241         else
242           // We are left with an infinite loop with no entries: kill the PHI.
243           PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
244         getInstList().pop_front();    // Remove the PHI node
245       }
246
247       // If the PHI node already only had one entry, it got deleted by
248       // removeIncomingValue.
249     }
250   } else {
251     // Okay, now we know that we need to remove predecessor #pred_idx from all
252     // PHI nodes.  Iterate over each PHI node fixing them up
253     PHINode *PN;
254     for (iterator II = begin(); (PN = dyn_cast<PHINode>(II)); ) {
255       ++II;
256       if (OnlyDeleteOne) {
257         int idx = PN->getBasicBlockIndex(Pred);
258         PN->removeIncomingValue(idx, false);
259       } else 
260         PN->removeIncomingValue(Pred, false);
261
262       // If all incoming values to the Phi are the same, we can replace the Phi
263       // with that value.
264       Value* PNV = 0;
265       if (!DontDeleteUselessPHIs && (PNV = PN->hasConstantValue())) {
266         PN->replaceAllUsesWith(PNV);
267         PN->eraseFromParent();
268       }
269     }
270   }
271 }
272
273
274 /// splitBasicBlock - This splits a basic block into two at the specified
275 /// instruction.  Note that all instructions BEFORE the specified iterator stay
276 /// as part of the original basic block, an unconditional branch is added to
277 /// the new BB, and the rest of the instructions in the BB are moved to the new
278 /// BB, including the old terminator.  This invalidates the iterator.
279 ///
280 /// Note that this only works on well formed basic blocks (must have a
281 /// terminator), and 'I' must not be the end of instruction list (which would
282 /// cause a degenerate basic block to be formed, having a terminator inside of
283 /// the basic block).
284 ///
285 BasicBlock *BasicBlock::splitBasicBlock(iterator I, const std::string &BBName) {
286   assert(getTerminator() && "Can't use splitBasicBlock on degenerate BB!");
287   assert(I != InstList.end() &&
288          "Trying to get me to create degenerate basic block!");
289
290   BasicBlock *New = new(0/*FIXME*/) BasicBlock(BBName, getParent(), getNext());
291
292   // Move all of the specified instructions from the original basic block into
293   // the new basic block.
294   New->getInstList().splice(New->end(), this->getInstList(), I, end());
295
296   // Add a branch instruction to the newly formed basic block.
297   BranchInst::Create(New, this);
298
299   // Now we must loop through all of the successors of the New block (which
300   // _were_ the successors of the 'this' block), and update any PHI nodes in
301   // successors.  If there were PHI nodes in the successors, then they need to
302   // know that incoming branches will be from New, not from Old.
303   //
304   for (succ_iterator I = succ_begin(New), E = succ_end(New); I != E; ++I) {
305     // Loop over any phi nodes in the basic block, updating the BB field of
306     // incoming values...
307     BasicBlock *Successor = *I;
308     PHINode *PN;
309     for (BasicBlock::iterator II = Successor->begin();
310          (PN = dyn_cast<PHINode>(II)); ++II) {
311       int IDX = PN->getBasicBlockIndex(this);
312       while (IDX != -1) {
313         PN->setIncomingBlock((unsigned)IDX, New);
314         IDX = PN->getBasicBlockIndex(this);
315       }
316     }
317   }
318   return New;
319 }