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