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