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