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