Beginning of the Great Exception Handling Rewrite.
[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/IntrinsicInst.h"
18 #include "llvm/LLVMContext.h"
19 #include "llvm/Type.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/Support/CFG.h"
22 #include "llvm/Support/LeakDetector.h"
23 #include "SymbolTableListTraitsImpl.h"
24 #include <algorithm>
25 using namespace llvm;
26
27 ValueSymbolTable *BasicBlock::getValueSymbolTable() {
28   if (Function *F = getParent())
29     return &F->getValueSymbolTable();
30   return 0;
31 }
32
33 LLVMContext &BasicBlock::getContext() const {
34   return getType()->getContext();
35 }
36
37 // Explicit instantiation of SymbolTableListTraits since some of the methods
38 // are not in the public header file...
39 template class llvm::SymbolTableListTraits<Instruction, BasicBlock>;
40
41 BasicBlock::BasicBlock(LLVMContext &C, const Twine &Name, Function *NewParent,
42                        BasicBlock *InsertBefore)
43   : Value(Type::getLabelTy(C), Value::BasicBlockVal), Parent(0),
44     IsLandingPad(false) {
45
46   // Make sure that we get added to a function
47   LeakDetector::addGarbageObject(this);
48
49   if (InsertBefore) {
50     assert(NewParent &&
51            "Cannot insert block before another block with no function!");
52     NewParent->getBasicBlockList().insert(InsertBefore, this);
53   } else if (NewParent) {
54     NewParent->getBasicBlockList().push_back(this);
55   }
56   
57   setName(Name);
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 Instruction* BasicBlock::getFirstNonPHIOrDbg() {
140   BasicBlock::iterator i = begin();
141   // All valid basic blocks should have a terminator,
142   // which is not a PHINode. If we have an invalid basic
143   // block we'll get an assertion failure when dereferencing
144   // a past-the-end iterator.
145   while (isa<PHINode>(i) || isa<DbgInfoIntrinsic>(i)) ++i;
146   return &*i;
147 }
148
149 void BasicBlock::dropAllReferences() {
150   for(iterator I = begin(), E = end(); I != E; ++I)
151     I->dropAllReferences();
152 }
153
154 /// getSinglePredecessor - If this basic block has a single predecessor block,
155 /// return the block, otherwise return a null pointer.
156 BasicBlock *BasicBlock::getSinglePredecessor() {
157   pred_iterator PI = pred_begin(this), E = pred_end(this);
158   if (PI == E) return 0;         // No preds.
159   BasicBlock *ThePred = *PI;
160   ++PI;
161   return (PI == E) ? ThePred : 0 /*multiple preds*/;
162 }
163
164 /// getUniquePredecessor - If this basic block has a unique predecessor block,
165 /// return the block, otherwise return a null pointer.
166 /// Note that unique predecessor doesn't mean single edge, there can be 
167 /// multiple edges from the unique predecessor to this block (for example 
168 /// a switch statement with multiple cases having the same destination).
169 BasicBlock *BasicBlock::getUniquePredecessor() {
170   pred_iterator PI = pred_begin(this), E = pred_end(this);
171   if (PI == E) return 0; // No preds.
172   BasicBlock *PredBB = *PI;
173   ++PI;
174   for (;PI != E; ++PI) {
175     if (*PI != PredBB)
176       return 0;
177     // The same predecessor appears multiple times in the predecessor list.
178     // This is OK.
179   }
180   return PredBB;
181 }
182
183 /// removePredecessor - This method is used to notify a BasicBlock that the
184 /// specified Predecessor of the block is no longer able to reach it.  This is
185 /// actually not used to update the Predecessor list, but is actually used to
186 /// update the PHI nodes that reside in the block.  Note that this should be
187 /// called while the predecessor still refers to this block.
188 ///
189 void BasicBlock::removePredecessor(BasicBlock *Pred,
190                                    bool DontDeleteUselessPHIs) {
191   assert((hasNUsesOrMore(16)||// Reduce cost of this assertion for complex CFGs.
192           find(pred_begin(this), pred_end(this), Pred) != pred_end(this)) &&
193          "removePredecessor: BB is not a predecessor!");
194
195   if (InstList.empty()) return;
196   PHINode *APN = dyn_cast<PHINode>(&front());
197   if (!APN) return;   // Quick exit.
198
199   // If there are exactly two predecessors, then we want to nuke the PHI nodes
200   // altogether.  However, we cannot do this, if this in this case:
201   //
202   //  Loop:
203   //    %x = phi [X, Loop]
204   //    %x2 = add %x, 1         ;; This would become %x2 = add %x2, 1
205   //    br Loop                 ;; %x2 does not dominate all uses
206   //
207   // This is because the PHI node input is actually taken from the predecessor
208   // basic block.  The only case this can happen is with a self loop, so we
209   // check for this case explicitly now.
210   //
211   unsigned max_idx = APN->getNumIncomingValues();
212   assert(max_idx != 0 && "PHI Node in block with 0 predecessors!?!?!");
213   if (max_idx == 2) {
214     BasicBlock *Other = APN->getIncomingBlock(APN->getIncomingBlock(0) == Pred);
215
216     // Disable PHI elimination!
217     if (this == Other) max_idx = 3;
218   }
219
220   // <= Two predecessors BEFORE I remove one?
221   if (max_idx <= 2 && !DontDeleteUselessPHIs) {
222     // Yup, loop through and nuke the PHI nodes
223     while (PHINode *PN = dyn_cast<PHINode>(&front())) {
224       // Remove the predecessor first.
225       PN->removeIncomingValue(Pred, !DontDeleteUselessPHIs);
226
227       // If the PHI _HAD_ two uses, replace PHI node with its now *single* value
228       if (max_idx == 2) {
229         if (PN->getOperand(0) != PN)
230           PN->replaceAllUsesWith(PN->getOperand(0));
231         else
232           // We are left with an infinite loop with no entries: kill the PHI.
233           PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
234         getInstList().pop_front();    // Remove the PHI node
235       }
236
237       // If the PHI node already only had one entry, it got deleted by
238       // removeIncomingValue.
239     }
240   } else {
241     // Okay, now we know that we need to remove predecessor #pred_idx from all
242     // PHI nodes.  Iterate over each PHI node fixing them up
243     PHINode *PN;
244     for (iterator II = begin(); (PN = dyn_cast<PHINode>(II)); ) {
245       ++II;
246       PN->removeIncomingValue(Pred, false);
247       // If all incoming values to the Phi are the same, we can replace the Phi
248       // with that value.
249       Value* PNV = 0;
250       if (!DontDeleteUselessPHIs && (PNV = PN->hasConstantValue()))
251         if (PNV != PN) {
252           PN->replaceAllUsesWith(PNV);
253           PN->eraseFromParent();
254         }
255     }
256   }
257 }
258
259
260 /// splitBasicBlock - This splits a basic block into two at the specified
261 /// instruction.  Note that all instructions BEFORE the specified iterator stay
262 /// as part of the original basic block, an unconditional branch is added to
263 /// the new BB, and the rest of the instructions in the BB are moved to the new
264 /// BB, including the old terminator.  This invalidates the iterator.
265 ///
266 /// Note that this only works on well formed basic blocks (must have a
267 /// terminator), and 'I' must not be the end of instruction list (which would
268 /// cause a degenerate basic block to be formed, having a terminator inside of
269 /// the basic block).
270 ///
271 BasicBlock *BasicBlock::splitBasicBlock(iterator I, const Twine &BBName) {
272   assert(getTerminator() && "Can't use splitBasicBlock on degenerate BB!");
273   assert(I != InstList.end() &&
274          "Trying to get me to create degenerate basic block!");
275
276   BasicBlock *InsertBefore = llvm::next(Function::iterator(this))
277                                .getNodePtrUnchecked();
278   BasicBlock *New = BasicBlock::Create(getContext(), BBName,
279                                        getParent(), InsertBefore);
280
281   // Move all of the specified instructions from the original basic block into
282   // the new basic block.
283   New->getInstList().splice(New->end(), this->getInstList(), I, end());
284
285   // Add a branch instruction to the newly formed basic block.
286   BranchInst::Create(New, this);
287
288   // Now we must loop through all of the successors of the New block (which
289   // _were_ the successors of the 'this' block), and update any PHI nodes in
290   // successors.  If there were PHI nodes in the successors, then they need to
291   // know that incoming branches will be from New, not from Old.
292   //
293   for (succ_iterator I = succ_begin(New), E = succ_end(New); I != E; ++I) {
294     // Loop over any phi nodes in the basic block, updating the BB field of
295     // incoming values...
296     BasicBlock *Successor = *I;
297     PHINode *PN;
298     for (BasicBlock::iterator II = Successor->begin();
299          (PN = dyn_cast<PHINode>(II)); ++II) {
300       int IDX = PN->getBasicBlockIndex(this);
301       while (IDX != -1) {
302         PN->setIncomingBlock((unsigned)IDX, New);
303         IDX = PN->getBasicBlockIndex(this);
304       }
305     }
306   }
307   return New;
308 }
309