Add a hasAddressTaken for BasicBlock.
[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   assert(getParent() == 0 && "BasicBlock still linked into the program!");
62   dropAllReferences();
63   InstList.clear();
64 }
65
66 void BasicBlock::setParent(Function *parent) {
67   if (getParent())
68     LeakDetector::addGarbageObject(this);
69
70   // Set Parent=parent, updating instruction symtab entries as appropriate.
71   InstList.setSymTabObject(&Parent, parent);
72
73   if (getParent())
74     LeakDetector::removeGarbageObject(this);
75 }
76
77 void BasicBlock::removeFromParent() {
78   getParent()->getBasicBlockList().remove(this);
79 }
80
81 void BasicBlock::eraseFromParent() {
82   getParent()->getBasicBlockList().erase(this);
83 }
84
85 /// moveBefore - Unlink this basic block from its current function and
86 /// insert it into the function that MovePos lives in, right before MovePos.
87 void BasicBlock::moveBefore(BasicBlock *MovePos) {
88   MovePos->getParent()->getBasicBlockList().splice(MovePos,
89                        getParent()->getBasicBlockList(), this);
90 }
91
92 /// moveAfter - Unlink this basic block from its current function and
93 /// insert it into the function that MovePos lives in, right after MovePos.
94 void BasicBlock::moveAfter(BasicBlock *MovePos) {
95   Function::iterator I = MovePos;
96   MovePos->getParent()->getBasicBlockList().splice(++I,
97                                        getParent()->getBasicBlockList(), this);
98 }
99
100
101 TerminatorInst *BasicBlock::getTerminator() {
102   if (InstList.empty()) return 0;
103   return dyn_cast<TerminatorInst>(&InstList.back());
104 }
105
106 const TerminatorInst *BasicBlock::getTerminator() const {
107   if (InstList.empty()) return 0;
108   return dyn_cast<TerminatorInst>(&InstList.back());
109 }
110
111 Instruction* BasicBlock::getFirstNonPHI() {
112   BasicBlock::iterator i = begin();
113   // All valid basic blocks should have a terminator,
114   // which is not a PHINode. If we have an invalid basic
115   // block we'll get an assertion failure when dereferencing
116   // a past-the-end iterator.
117   while (isa<PHINode>(i)) ++i;
118   return &*i;
119 }
120
121 void BasicBlock::dropAllReferences() {
122   for(iterator I = begin(), E = end(); I != E; ++I)
123     I->dropAllReferences();
124 }
125
126 /// getSinglePredecessor - If this basic block has a single predecessor block,
127 /// return the block, otherwise return a null pointer.
128 BasicBlock *BasicBlock::getSinglePredecessor() {
129   pred_iterator PI = pred_begin(this), E = pred_end(this);
130   if (PI == E) return 0;         // No preds.
131   BasicBlock *ThePred = *PI;
132   ++PI;
133   return (PI == E) ? ThePred : 0 /*multiple preds*/;
134 }
135
136 /// getUniquePredecessor - If this basic block has a unique predecessor block,
137 /// return the block, otherwise return a null pointer.
138 /// Note that unique predecessor doesn't mean single edge, there can be 
139 /// multiple edges from the unique predecessor to this block (for example 
140 /// a switch statement with multiple cases having the same destination).
141 BasicBlock *BasicBlock::getUniquePredecessor() {
142   pred_iterator PI = pred_begin(this), E = pred_end(this);
143   if (PI == E) return 0; // No preds.
144   BasicBlock *PredBB = *PI;
145   ++PI;
146   for (;PI != E; ++PI) {
147     if (*PI != PredBB)
148       return 0;
149     // The same predecessor appears multiple times in the predecessor list.
150     // This is OK.
151   }
152   return PredBB;
153 }
154
155 /// removePredecessor - This method is used to notify a BasicBlock that the
156 /// specified Predecessor of the block is no longer able to reach it.  This is
157 /// actually not used to update the Predecessor list, but is actually used to
158 /// update the PHI nodes that reside in the block.  Note that this should be
159 /// called while the predecessor still refers to this block.
160 ///
161 void BasicBlock::removePredecessor(BasicBlock *Pred,
162                                    bool DontDeleteUselessPHIs) {
163   assert((hasNUsesOrMore(16)||// Reduce cost of this assertion for complex CFGs.
164           find(pred_begin(this), pred_end(this), Pred) != pred_end(this)) &&
165          "removePredecessor: BB is not a predecessor!");
166
167   if (InstList.empty()) return;
168   PHINode *APN = dyn_cast<PHINode>(&front());
169   if (!APN) return;   // Quick exit.
170
171   // If there are exactly two predecessors, then we want to nuke the PHI nodes
172   // altogether.  However, we cannot do this, if this in this case:
173   //
174   //  Loop:
175   //    %x = phi [X, Loop]
176   //    %x2 = add %x, 1         ;; This would become %x2 = add %x2, 1
177   //    br Loop                 ;; %x2 does not dominate all uses
178   //
179   // This is because the PHI node input is actually taken from the predecessor
180   // basic block.  The only case this can happen is with a self loop, so we
181   // check for this case explicitly now.
182   //
183   unsigned max_idx = APN->getNumIncomingValues();
184   assert(max_idx != 0 && "PHI Node in block with 0 predecessors!?!?!");
185   if (max_idx == 2) {
186     BasicBlock *Other = APN->getIncomingBlock(APN->getIncomingBlock(0) == Pred);
187
188     // Disable PHI elimination!
189     if (this == Other) max_idx = 3;
190   }
191
192   // <= Two predecessors BEFORE I remove one?
193   if (max_idx <= 2 && !DontDeleteUselessPHIs) {
194     // Yup, loop through and nuke the PHI nodes
195     while (PHINode *PN = dyn_cast<PHINode>(&front())) {
196       // Remove the predecessor first.
197       PN->removeIncomingValue(Pred, !DontDeleteUselessPHIs);
198
199       // If the PHI _HAD_ two uses, replace PHI node with its now *single* value
200       if (max_idx == 2) {
201         if (PN->getOperand(0) != PN)
202           PN->replaceAllUsesWith(PN->getOperand(0));
203         else
204           // We are left with an infinite loop with no entries: kill the PHI.
205           PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
206         getInstList().pop_front();    // Remove the PHI node
207       }
208
209       // If the PHI node already only had one entry, it got deleted by
210       // removeIncomingValue.
211     }
212   } else {
213     // Okay, now we know that we need to remove predecessor #pred_idx from all
214     // PHI nodes.  Iterate over each PHI node fixing them up
215     PHINode *PN;
216     for (iterator II = begin(); (PN = dyn_cast<PHINode>(II)); ) {
217       ++II;
218       PN->removeIncomingValue(Pred, false);
219       // If all incoming values to the Phi are the same, we can replace the Phi
220       // with that value.
221       Value* PNV = 0;
222       if (!DontDeleteUselessPHIs && (PNV = PN->hasConstantValue())) {
223         PN->replaceAllUsesWith(PNV);
224         PN->eraseFromParent();
225       }
226     }
227   }
228 }
229
230
231 /// splitBasicBlock - This splits a basic block into two at the specified
232 /// instruction.  Note that all instructions BEFORE the specified iterator stay
233 /// as part of the original basic block, an unconditional branch is added to
234 /// the new BB, and the rest of the instructions in the BB are moved to the new
235 /// BB, including the old terminator.  This invalidates the iterator.
236 ///
237 /// Note that this only works on well formed basic blocks (must have a
238 /// terminator), and 'I' must not be the end of instruction list (which would
239 /// cause a degenerate basic block to be formed, having a terminator inside of
240 /// the basic block).
241 ///
242 BasicBlock *BasicBlock::splitBasicBlock(iterator I, const Twine &BBName) {
243   assert(getTerminator() && "Can't use splitBasicBlock on degenerate BB!");
244   assert(I != InstList.end() &&
245          "Trying to get me to create degenerate basic block!");
246
247   BasicBlock *InsertBefore = next(Function::iterator(this))
248                                .getNodePtrUnchecked();
249   BasicBlock *New = BasicBlock::Create(getContext(), BBName,
250                                        getParent(), InsertBefore);
251
252   // Move all of the specified instructions from the original basic block into
253   // the new basic block.
254   New->getInstList().splice(New->end(), this->getInstList(), I, end());
255
256   // Add a branch instruction to the newly formed basic block.
257   BranchInst::Create(New, this);
258
259   // Now we must loop through all of the successors of the New block (which
260   // _were_ the successors of the 'this' block), and update any PHI nodes in
261   // successors.  If there were PHI nodes in the successors, then they need to
262   // know that incoming branches will be from New, not from Old.
263   //
264   for (succ_iterator I = succ_begin(New), E = succ_end(New); I != E; ++I) {
265     // Loop over any phi nodes in the basic block, updating the BB field of
266     // incoming values...
267     BasicBlock *Successor = *I;
268     PHINode *PN;
269     for (BasicBlock::iterator II = Successor->begin();
270          (PN = dyn_cast<PHINode>(II)); ++II) {
271       int IDX = PN->getBasicBlockIndex(this);
272       while (IDX != -1) {
273         PN->setIncomingBlock((unsigned)IDX, New);
274         IDX = PN->getBasicBlockIndex(this);
275       }
276     }
277   }
278   return New;
279 }
280
281 /// hasAddressTaken - returns true if there are any uses of this basic block
282 /// other than direct branches, switches, etc. to it.
283 bool BasicBlock::hasAddressTaken() const {
284   for (Value::use_const_iterator I = use_begin(), E = use_end(); I != E; ++I)
285     if (isa<BlockAddress>(*I))
286       return true;
287   return false;
288 }