* Pull BasicBlock::pred_* and BasicBlock::succ_* out of BasicBlock.h and into
[oota-llvm.git] / lib / Transforms / Scalar / DCE.cpp
1 //===- DCE.cpp - Code to perform dead code elimination --------------------===//
2 //
3 // This file implements dead code elimination and basic block merging.
4 //
5 // Specifically, this:
6 //   * removes definitions with no uses
7 //   * removes basic blocks with no predecessors
8 //   * merges a basic block into its predecessor if there is only one and the
9 //     predecessor only has one successor.
10 //   * Eliminates PHI nodes for basic blocks with a single predecessor
11 //   * Eliminates a basic block that only contains an unconditional branch
12 //   * Eliminates method prototypes that are not referenced
13 //
14 // TODO: This should REALLY be worklist driven instead of iterative.  Right now,
15 // we scan linearly through values, removing unused ones as we go.  The problem
16 // is that this may cause other earlier values to become unused.  To make sure
17 // that we get them all, we iterate until things stop changing.  Instead, when 
18 // removing a value, recheck all of its operands to see if they are now unused.
19 // Piece of cake, and more efficient as well.  
20 //
21 // Note, this is not trivial, because we have to worry about invalidating 
22 // iterators.  :(
23 //
24 //===----------------------------------------------------------------------===//
25
26 #include "llvm/Transforms/Scalar/DCE.h"
27 #include "llvm/Module.h"
28 #include "llvm/GlobalVariable.h"
29 #include "llvm/Method.h"
30 #include "llvm/BasicBlock.h"
31 #include "llvm/iTerminators.h"
32 #include "llvm/iPHINode.h"
33 #include "llvm/Assembly/Writer.h"
34 #include "llvm/Support/CFG.h"
35 #include "Support/STLExtras.h"
36 #include <algorithm>
37
38 // dceInstruction - Inspect the instruction at *BBI and figure out if it's
39 // [trivially] dead.  If so, remove the instruction and update the iterator
40 // to point to the instruction that immediately succeeded the original
41 // instruction.
42 //
43 bool DeadCodeElimination::dceInstruction(BasicBlock::InstListType &BBIL,
44                                          BasicBlock::iterator &BBI) {
45   // Look for un"used" definitions...
46   if ((*BBI)->use_empty() && !(*BBI)->hasSideEffects() && 
47       !isa<TerminatorInst>(*BBI)) {
48     delete BBIL.remove(BBI);   // Bye bye
49     return true;
50   }
51   return false;
52 }
53
54 static inline bool RemoveUnusedDefs(BasicBlock::InstListType &Vals) {
55   bool Changed = false;
56   for (BasicBlock::InstListType::iterator DI = Vals.begin(); 
57        DI != Vals.end(); )
58     if (DeadCodeElimination::dceInstruction(Vals, DI))
59       Changed = true;
60     else
61       ++DI;
62   return Changed;
63 }
64
65 bool DeadInstElimination::runOnBasicBlock(BasicBlock *BB) {
66   return RemoveUnusedDefs(BB->getInstList());
67 }
68
69 // RemoveSingularPHIs - This removes PHI nodes from basic blocks that have only
70 // a single predecessor.  This means that the PHI node must only have a single
71 // RHS value and can be eliminated.
72 //
73 // This routine is very simple because we know that PHI nodes must be the first
74 // things in a basic block, if they are present.
75 //
76 static bool RemoveSingularPHIs(BasicBlock *BB) {
77   pred_iterator PI(pred_begin(BB));
78   if (PI == pred_end(BB) || ++PI != pred_end(BB)) 
79     return false;   // More than one predecessor...
80
81   Instruction *I = BB->front();
82   if (!isa<PHINode>(I)) return false;  // No PHI nodes
83
84   //cerr << "Killing PHIs from " << BB;
85   //cerr << "Pred #0 = " << *pred_begin(BB);
86
87   //cerr << "Method == " << BB->getParent();
88
89   do {
90     PHINode *PN = cast<PHINode>(I);
91     assert(PN->getNumOperands() == 2 && "PHI node should only have one value!");
92     Value *V = PN->getOperand(0);
93
94     PN->replaceAllUsesWith(V);      // Replace PHI node with its single value.
95     delete BB->getInstList().remove(BB->begin());
96
97     I = BB->front();
98   } while (isa<PHINode>(I));
99         
100   return true;  // Yes, we nuked at least one phi node
101 }
102
103 static void ReplaceUsesWithConstant(Instruction *I) {
104   Constant *CPV = Constant::getNullConstant(I->getType());
105   
106   // Make all users of this instruction reference the constant instead
107   I->replaceAllUsesWith(CPV);
108 }
109
110 // PropogatePredecessors - This gets "Succ" ready to have the predecessors from
111 // "BB".  This is a little tricky because "Succ" has PHI nodes, which need to
112 // have extra slots added to them to hold the merge edges from BB's
113 // predecessors.  This function returns true (failure) if the Succ BB already
114 // has a predecessor that is a predecessor of BB.
115 //
116 // Assumption: Succ is the single successor for BB.
117 //
118 static bool PropogatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) {
119   assert(*succ_begin(BB) == Succ && "Succ is not successor of BB!");
120   assert(isa<PHINode>(Succ->front()) && "Only works on PHId BBs!");
121
122   // If there is more than one predecessor, and there are PHI nodes in
123   // the successor, then we need to add incoming edges for the PHI nodes
124   //
125   const std::vector<BasicBlock*> BBPreds(pred_begin(BB), pred_end(BB));
126
127   // Check to see if one of the predecessors of BB is already a predecessor of
128   // Succ.  If so, we cannot do the transformation!
129   //
130   for (pred_iterator PI = pred_begin(Succ), PE = pred_end(Succ);
131        PI != PE; ++PI) {
132     if (find(BBPreds.begin(), BBPreds.end(), *PI) != BBPreds.end())
133       return true;
134   }
135
136   BasicBlock::iterator I = Succ->begin();
137   do {                     // Loop over all of the PHI nodes in the successor BB
138     PHINode *PN = cast<PHINode>(*I);
139     Value *OldVal = PN->removeIncomingValue(BB);
140     assert(OldVal && "No entry in PHI for Pred BB!");
141
142     for (std::vector<BasicBlock*>::const_iterator PredI = BBPreds.begin(), 
143            End = BBPreds.end(); PredI != End; ++PredI) {
144       // Add an incoming value for each of the new incoming values...
145       PN->addIncoming(OldVal, *PredI);
146     }
147
148     ++I;
149   } while (isa<PHINode>(*I));
150   return false;
151 }
152
153
154 // SimplifyCFG - This function is used to do simplification of a CFG.  For
155 // example, it adjusts branches to branches to eliminate the extra hop, it
156 // eliminates unreachable basic blocks, and does other "peephole" optimization
157 // of the CFG.  It returns true if a modification was made, and returns an 
158 // iterator that designates the first element remaining after the block that
159 // was deleted.
160 //
161 // WARNING:  The entry node of a method may not be simplified.
162 //
163 bool SimplifyCFG(Method::iterator &BBIt) {
164   BasicBlock *BB = *BBIt;
165   Method *M = BB->getParent();
166
167   assert(BB && BB->getParent() && "Block not embedded in method!");
168   assert(BB->getTerminator() && "Degenerate basic block encountered!");
169   assert(BB->getParent()->front() != BB && "Can't Simplify entry block!");
170
171
172   // Remove basic blocks that have no predecessors... which are unreachable.
173   if (pred_begin(BB) == pred_end(BB) &&
174       !BB->hasConstantReferences()) {
175     //cerr << "Removing BB: \n" << BB;
176
177     // Loop through all of our successors and make sure they know that one
178     // of their predecessors is going away.
179     for_each(succ_begin(BB), succ_end(BB),
180              std::bind2nd(std::mem_fun(&BasicBlock::removePredecessor), BB));
181
182     while (!BB->empty()) {
183       Instruction *I = BB->back();
184       // If this instruction is used, replace uses with an arbitrary
185       // constant value.  Because control flow can't get here, we don't care
186       // what we replace the value with.  Note that since this block is 
187       // unreachable, and all values contained within it must dominate their
188       // uses, that all uses will eventually be removed.
189       if (!I->use_empty()) ReplaceUsesWithConstant(I);
190       
191       // Remove the instruction from the basic block
192       delete BB->getInstList().pop_back();
193     }
194     delete M->getBasicBlocks().remove(BBIt);
195     return true;
196   }
197
198   // Check to see if this block has no instructions and only a single 
199   // successor.  If so, replace block references with successor.
200   succ_iterator SI(succ_begin(BB));
201   if (SI != succ_end(BB) && ++SI == succ_end(BB)) {  // One succ?
202     if (BB->front()->isTerminator()) {   // Terminator is the only instruction!
203       BasicBlock *Succ = *succ_begin(BB); // There is exactly one successor
204       //cerr << "Killing Trivial BB: \n" << BB;
205       
206       if (Succ != BB) {   // Arg, don't hurt infinite loops!
207         // If our successor has PHI nodes, then we need to update them to
208         // include entries for BB's predecessors, not for BB itself.
209         // Be careful though, if this transformation fails (returns true) then
210         // we cannot do this transformation!
211         //
212         if (!isa<PHINode>(Succ->front()) ||
213             !PropogatePredecessorsForPHIs(BB, Succ)) {
214           
215           BB->replaceAllUsesWith(Succ);
216           BB = M->getBasicBlocks().remove(BBIt);
217         
218           if (BB->hasName() && !Succ->hasName())  // Transfer name if we can
219             Succ->setName(BB->getName());
220           delete BB;                              // Delete basic block
221           
222           //cerr << "Method after removal: \n" << M;
223           return true;
224         }
225       }
226     }
227   }
228
229   // Merge basic blocks into their predecessor if there is only one pred, 
230   // and if there is only one successor of the predecessor. 
231   pred_iterator PI(pred_begin(BB));
232   if (PI != pred_end(BB) && *PI != BB &&    // Not empty?  Not same BB?
233       ++PI == pred_end(BB) && !BB->hasConstantReferences()) {
234     BasicBlock *Pred = *pred_begin(BB);
235     TerminatorInst *Term = Pred->getTerminator();
236     assert(Term != 0 && "malformed basic block without terminator!");
237     
238     // Does the predecessor block only have a single successor?
239     succ_iterator SI(succ_begin(Pred));
240     if (++SI == succ_end(Pred)) {
241       //cerr << "Merging: " << BB << "into: " << Pred;
242       
243       // Delete the unconditianal branch from the predecessor...
244       BasicBlock::iterator DI = Pred->end();
245       assert(Pred->getTerminator() && 
246              "Degenerate basic block encountered!");  // Empty bb???      
247       delete Pred->getInstList().remove(--DI);        // Destroy uncond branch
248       
249       // Move all definitions in the succecessor to the predecessor...
250       while (!BB->empty()) {
251         DI = BB->begin();
252         Instruction *Def = BB->getInstList().remove(DI); // Remove from front
253         Pred->getInstList().push_back(Def);              // Add to end...
254       }
255       
256       // Remove basic block from the method... and advance iterator to the
257       // next valid block...
258       BB = M->getBasicBlocks().remove(BBIt);
259
260       // Make all PHI nodes that refered to BB now refer to Pred as their
261       // source...
262       BB->replaceAllUsesWith(Pred);
263       
264       // Inherit predecessors name if it exists...
265       if (BB->hasName() && !Pred->hasName()) Pred->setName(BB->getName());
266       
267       delete BB; // You ARE the weakest link... goodbye
268       return true;
269     }
270   }
271   
272   return false;
273 }
274
275 static bool DoDCEPass(Method *M) {
276   Method::iterator BBIt, BBEnd = M->end();
277   if (M->begin() == BBEnd) return false;  // Nothing to do
278   bool Changed = false;
279
280   // Loop through now and remove instructions that have no uses...
281   for (BBIt = M->begin(); BBIt != BBEnd; ++BBIt) {
282     Changed |= RemoveUnusedDefs((*BBIt)->getInstList());
283     Changed |= RemoveSingularPHIs(*BBIt);
284   }
285
286   // Loop over all of the basic blocks (except the first one) and remove them
287   // if they are unneeded...
288   //
289   for (BBIt = M->begin(), ++BBIt; BBIt != M->end(); ) {
290     if (SimplifyCFG(BBIt)) {
291       Changed = true;
292     } else {
293       ++BBIt;
294     }
295   }
296
297   return Changed;
298 }
299
300
301 // It is possible that we may require multiple passes over the code to fully
302 // eliminate dead code.  Iterate until we are done.
303 //
304 bool DeadCodeElimination::doDCE(Method *M) {
305   bool Changed = false;
306   while (DoDCEPass(M)) Changed = true;
307   return Changed;
308 }
309
310 bool DeadCodeElimination::RemoveUnusedGlobalValues(Module *Mod) {
311   bool Changed = false;
312
313   for (Module::iterator MI = Mod->begin(); MI != Mod->end(); ) {
314     Method *Meth = *MI;
315     if (Meth->isExternal() && Meth->use_size() == 0) {
316       // No references to prototype?
317       //cerr << "Removing method proto: " << Meth->getName() << endl;
318       delete Mod->getMethodList().remove(MI);  // Remove prototype
319       // Remove moves iterator to point to the next one automatically
320       Changed = true;
321     } else {
322       ++MI;                                    // Skip prototype in use.
323     }
324   }
325
326   for (Module::giterator GI = Mod->gbegin(); GI != Mod->gend(); ) {
327     GlobalVariable *GV = *GI;
328     if (!GV->hasInitializer() && GV->use_size() == 0) {
329       // No references to uninitialized global variable?
330       //cerr << "Removing global var: " << GV->getName() << endl;
331       delete Mod->getGlobalList().remove(GI);
332       // Remove moves iterator to point to the next one automatically
333       Changed = true;
334     } else {
335       ++GI;
336     }
337   }
338
339   return Changed;
340 }