s/Method/Function
[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/Function.h"
30 #include "llvm/BasicBlock.h"
31 #include "llvm/iTerminators.h"
32 #include "llvm/iPHINode.h"
33 #include "llvm/Support/CFG.h"
34 #include "llvm/Pass.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 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 (dceInstruction(Vals, DI))
59       Changed = true;
60     else
61       ++DI;
62   return Changed;
63 }
64
65 struct DeadInstElimination : public BasicBlockPass {
66   virtual bool runOnBasicBlock(BasicBlock *BB) {
67     return RemoveUnusedDefs(BB->getInstList());
68   }
69 };
70
71 Pass *createDeadInstEliminationPass() {
72   return new DeadInstElimination();
73 }
74
75 // RemoveSingularPHIs - This removes PHI nodes from basic blocks that have only
76 // a single predecessor.  This means that the PHI node must only have a single
77 // RHS value and can be eliminated.
78 //
79 // This routine is very simple because we know that PHI nodes must be the first
80 // things in a basic block, if they are present.
81 //
82 static bool RemoveSingularPHIs(BasicBlock *BB) {
83   pred_iterator PI(pred_begin(BB));
84   if (PI == pred_end(BB) || ++PI != pred_end(BB)) 
85     return false;   // More than one predecessor...
86
87   Instruction *I = BB->front();
88   if (!isa<PHINode>(I)) return false;  // No PHI nodes
89
90   //cerr << "Killing PHIs from " << BB;
91   //cerr << "Pred #0 = " << *pred_begin(BB);
92
93   //cerr << "Function == " << BB->getParent();
94
95   do {
96     PHINode *PN = cast<PHINode>(I);
97     assert(PN->getNumOperands() == 2 && "PHI node should only have one value!");
98     Value *V = PN->getOperand(0);
99
100     PN->replaceAllUsesWith(V);      // Replace PHI node with its single value.
101     delete BB->getInstList().remove(BB->begin());
102
103     I = BB->front();
104   } while (isa<PHINode>(I));
105         
106   return true;  // Yes, we nuked at least one phi node
107 }
108
109 static void ReplaceUsesWithConstant(Instruction *I) {
110   Constant *CPV = Constant::getNullConstant(I->getType());
111   
112   // Make all users of this instruction reference the constant instead
113   I->replaceAllUsesWith(CPV);
114 }
115
116 // PropogatePredecessors - This gets "Succ" ready to have the predecessors from
117 // "BB".  This is a little tricky because "Succ" has PHI nodes, which need to
118 // have extra slots added to them to hold the merge edges from BB's
119 // predecessors.  This function returns true (failure) if the Succ BB already
120 // has a predecessor that is a predecessor of BB.
121 //
122 // Assumption: Succ is the single successor for BB.
123 //
124 static bool PropogatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) {
125   assert(*succ_begin(BB) == Succ && "Succ is not successor of BB!");
126   assert(isa<PHINode>(Succ->front()) && "Only works on PHId BBs!");
127
128   // If there is more than one predecessor, and there are PHI nodes in
129   // the successor, then we need to add incoming edges for the PHI nodes
130   //
131   const std::vector<BasicBlock*> BBPreds(pred_begin(BB), pred_end(BB));
132
133   // Check to see if one of the predecessors of BB is already a predecessor of
134   // Succ.  If so, we cannot do the transformation!
135   //
136   for (pred_iterator PI = pred_begin(Succ), PE = pred_end(Succ);
137        PI != PE; ++PI) {
138     if (find(BBPreds.begin(), BBPreds.end(), *PI) != BBPreds.end())
139       return true;
140   }
141
142   BasicBlock::iterator I = Succ->begin();
143   do {                     // Loop over all of the PHI nodes in the successor BB
144     PHINode *PN = cast<PHINode>(*I);
145     Value *OldVal = PN->removeIncomingValue(BB);
146     assert(OldVal && "No entry in PHI for Pred BB!");
147
148     for (std::vector<BasicBlock*>::const_iterator PredI = BBPreds.begin(), 
149            End = BBPreds.end(); PredI != End; ++PredI) {
150       // Add an incoming value for each of the new incoming values...
151       PN->addIncoming(OldVal, *PredI);
152     }
153
154     ++I;
155   } while (isa<PHINode>(*I));
156   return false;
157 }
158
159
160 // SimplifyCFG - This function is used to do simplification of a CFG.  For
161 // example, it adjusts branches to branches to eliminate the extra hop, it
162 // eliminates unreachable basic blocks, and does other "peephole" optimization
163 // of the CFG.  It returns true if a modification was made, and returns an 
164 // iterator that designates the first element remaining after the block that
165 // was deleted.
166 //
167 // WARNING:  The entry node of a method may not be simplified.
168 //
169 bool SimplifyCFG(Function::iterator &BBIt) {
170   BasicBlock *BB = *BBIt;
171   Function *M = BB->getParent();
172
173   assert(BB && BB->getParent() && "Block not embedded in method!");
174   assert(BB->getTerminator() && "Degenerate basic block encountered!");
175   assert(BB->getParent()->front() != BB && "Can't Simplify entry block!");
176
177
178   // Remove basic blocks that have no predecessors... which are unreachable.
179   if (pred_begin(BB) == pred_end(BB) &&
180       !BB->hasConstantReferences()) {
181     //cerr << "Removing BB: \n" << BB;
182
183     // Loop through all of our successors and make sure they know that one
184     // of their predecessors is going away.
185     for_each(succ_begin(BB), succ_end(BB),
186              std::bind2nd(std::mem_fun(&BasicBlock::removePredecessor), BB));
187
188     while (!BB->empty()) {
189       Instruction *I = BB->back();
190       // If this instruction is used, replace uses with an arbitrary
191       // constant value.  Because control flow can't get here, we don't care
192       // what we replace the value with.  Note that since this block is 
193       // unreachable, and all values contained within it must dominate their
194       // uses, that all uses will eventually be removed.
195       if (!I->use_empty()) ReplaceUsesWithConstant(I);
196       
197       // Remove the instruction from the basic block
198       delete BB->getInstList().pop_back();
199     }
200     delete M->getBasicBlocks().remove(BBIt);
201     return true;
202   }
203
204   // Check to see if this block has no instructions and only a single 
205   // successor.  If so, replace block references with successor.
206   succ_iterator SI(succ_begin(BB));
207   if (SI != succ_end(BB) && ++SI == succ_end(BB)) {  // One succ?
208     if (BB->front()->isTerminator()) {   // Terminator is the only instruction!
209       BasicBlock *Succ = *succ_begin(BB); // There is exactly one successor
210       //cerr << "Killing Trivial BB: \n" << BB;
211       
212       if (Succ != BB) {   // Arg, don't hurt infinite loops!
213         // If our successor has PHI nodes, then we need to update them to
214         // include entries for BB's predecessors, not for BB itself.
215         // Be careful though, if this transformation fails (returns true) then
216         // we cannot do this transformation!
217         //
218         if (!isa<PHINode>(Succ->front()) ||
219             !PropogatePredecessorsForPHIs(BB, Succ)) {
220           
221           BB->replaceAllUsesWith(Succ);
222           BB = M->getBasicBlocks().remove(BBIt);
223         
224           if (BB->hasName() && !Succ->hasName())  // Transfer name if we can
225             Succ->setName(BB->getName());
226           delete BB;                              // Delete basic block
227           
228           //cerr << "Function after removal: \n" << M;
229           return true;
230         }
231       }
232     }
233   }
234
235   // Merge basic blocks into their predecessor if there is only one pred, 
236   // and if there is only one successor of the predecessor. 
237   pred_iterator PI(pred_begin(BB));
238   if (PI != pred_end(BB) && *PI != BB &&    // Not empty?  Not same BB?
239       ++PI == pred_end(BB) && !BB->hasConstantReferences()) {
240     BasicBlock *Pred = *pred_begin(BB);
241     TerminatorInst *Term = Pred->getTerminator();
242     assert(Term != 0 && "malformed basic block without terminator!");
243     
244     // Does the predecessor block only have a single successor?
245     succ_iterator SI(succ_begin(Pred));
246     if (++SI == succ_end(Pred)) {
247       //cerr << "Merging: " << BB << "into: " << Pred;
248       
249       // Delete the unconditianal branch from the predecessor...
250       BasicBlock::iterator DI = Pred->end();
251       assert(Pred->getTerminator() && 
252              "Degenerate basic block encountered!");  // Empty bb???      
253       delete Pred->getInstList().remove(--DI);        // Destroy uncond branch
254       
255       // Move all definitions in the succecessor to the predecessor...
256       while (!BB->empty()) {
257         DI = BB->begin();
258         Instruction *Def = BB->getInstList().remove(DI); // Remove from front
259         Pred->getInstList().push_back(Def);              // Add to end...
260       }
261       
262       // Remove basic block from the method... and advance iterator to the
263       // next valid block...
264       BB = M->getBasicBlocks().remove(BBIt);
265
266       // Make all PHI nodes that refered to BB now refer to Pred as their
267       // source...
268       BB->replaceAllUsesWith(Pred);
269       
270       // Inherit predecessors name if it exists...
271       if (BB->hasName() && !Pred->hasName()) Pred->setName(BB->getName());
272       
273       delete BB; // You ARE the weakest link... goodbye
274       return true;
275     }
276   }
277   
278   return false;
279 }
280
281 static bool DoDCEPass(Function *F) {
282   Function::iterator BBIt, BBEnd = F->end();
283   if (F->begin() == BBEnd) return false;  // Nothing to do
284   bool Changed = false;
285
286   // Loop through now and remove instructions that have no uses...
287   for (BBIt = F->begin(); BBIt != BBEnd; ++BBIt) {
288     Changed |= RemoveUnusedDefs((*BBIt)->getInstList());
289     Changed |= RemoveSingularPHIs(*BBIt);
290   }
291
292   // Loop over all of the basic blocks (except the first one) and remove them
293   // if they are unneeded...
294   //
295   for (BBIt = F->begin(), ++BBIt; BBIt != F->end(); ) {
296     if (SimplifyCFG(BBIt)) {
297       Changed = true;
298     } else {
299       ++BBIt;
300     }
301   }
302
303   return Changed;
304 }
305
306 // Remove unused global values - This removes unused global values of no
307 // possible value.  This currently includes unused method prototypes and
308 // unitialized global variables.
309 //
310 static bool RemoveUnusedGlobalValues(Module *Mod) {
311   bool Changed = false;
312
313   for (Module::iterator MI = Mod->begin(); MI != Mod->end(); ) {
314     Function *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->getFunctionList().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 }
341
342 namespace {
343   struct DeadCodeElimination : public MethodPass {
344
345     // Pass Interface...
346     virtual bool doInitialization(Module *M) {
347       return RemoveUnusedGlobalValues(M);
348     }
349     
350     // It is possible that we may require multiple passes over the code to fully
351     // eliminate dead code.  Iterate until we are done.
352     //
353     virtual bool runOnMethod(Function *F) {
354       bool Changed = false;
355       while (DoDCEPass(F)) Changed = true;
356       return Changed;
357     }
358     
359     virtual bool doFinalization(Module *M) {
360       return RemoveUnusedGlobalValues(M);
361     }
362   };
363 }
364
365 Pass *createDeadCodeEliminationPass() {
366   return new DeadCodeElimination();
367 }