Convert optimizations to the pass infrastructure
[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 (including unused constants)
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/Optimizations/DCE.h"
27 #include "llvm/Support/STLExtras.h"
28 #include "llvm/Module.h"
29 #include "llvm/GlobalVariable.h"
30 #include "llvm/Method.h"
31 #include "llvm/BasicBlock.h"
32 #include "llvm/iTerminators.h"
33 #include "llvm/iOther.h"
34 #include "llvm/Assembly/Writer.h"
35 #include <algorithm>
36
37 struct ConstPoolDCE { 
38   enum { EndOffs = 0 };
39   static bool isDCEable(const ConstPoolVal *CPV) {
40     // TODO: The bytecode writer requires that all used types are in the
41     // constant pool for the current method.  This is messy and is really
42     // irritating. FIXME
43     return CPV->getType() != Type::TypeTy;  // Don't DCE Type plane constants!
44   }
45 };
46
47 struct BasicBlockDCE {
48   enum { EndOffs = 1 };
49   static bool isDCEable(const Instruction *I) {
50     return !I->hasSideEffects();
51   }
52 };
53
54
55 template<class Container, class DCEController>
56 static bool RemoveUnusedDefs(Container &Vals, DCEController DCEControl) {
57   bool Changed = false;
58   int Offset = DCEController::EndOffs;
59
60   for (typename Container::iterator DI = Vals.begin(); 
61        DI != Vals.end()-Offset; ) {
62     // Look for un"used" definitions...
63     if ((*DI)->use_empty() && DCEController::isDCEable(*DI)) {
64       // Bye bye
65       //cerr << "Removing: " << *DI;
66       delete Vals.remove(DI);
67       Changed = true;
68     } else {
69       ++DI;
70     }
71   }
72   return Changed;
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   BasicBlock::pred_iterator PI(BB->pred_begin());
84   if (PI == BB->pred_end() || ++PI != BB->pred_end()) 
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 = " << *BB->pred_begin();
92
93   //cerr << "Method == " << 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   ConstPoolVal *CPV = ConstPoolVal::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.
120 //
121 // Assumption: BB is the single predecessor of Succ.
122 //
123 static void PropogatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) {
124   assert(isa<PHINode>(Succ->front()) && "Only works on PHId BBs!");
125
126   // If there is more than one predecessor, and there are PHI nodes in
127   // the successor, then we need to add incoming edges for the PHI nodes
128   //
129   const vector<BasicBlock*> BBPreds(BB->pred_begin(), BB->pred_end());
130
131   BasicBlock::iterator I = Succ->begin();
132   do {                     // Loop over all of the PHI nodes in the successor BB
133     PHINode *PN = cast<PHINode>(*I);
134     Value *OldVal = PN->removeIncomingValue(BB);
135     assert(OldVal && "No entry in PHI for Pred BB!");
136
137     for (vector<BasicBlock*>::const_iterator PredI = BBPreds.begin(), 
138            End = BBPreds.end(); PredI != End; ++PredI) {
139       // Add an incoming value for each of the new incoming values...
140       PN->addIncoming(OldVal, *PredI);
141     }
142
143     ++I;
144   } while (isa<PHINode>(*I));
145 }
146
147
148 // SimplifyCFG - This function is used to do simplification of a CFG.  For
149 // example, it adjusts branches to branches to eliminate the extra hop, it
150 // eliminates unreachable basic blocks, and does other "peephole" optimization
151 // of the CFG.  It returns true if a modification was made, and returns an 
152 // iterator that designates the first element remaining after the block that
153 // was deleted.
154 //
155 // WARNING:  The entry node of a method may not be simplified.
156 //
157 bool opt::SimplifyCFG(Method::iterator &BBIt) {
158   BasicBlock *BB = *BBIt;
159   Method *M = BB->getParent();
160
161   assert(BB && BB->getParent() && "Block not embedded in method!");
162   assert(BB->getTerminator() && "Degenerate basic block encountered!");
163   assert(BB->getParent()->front() != BB && "Can't Simplify entry block!");
164
165
166   // Remove basic blocks that have no predecessors... which are unreachable.
167   if (BB->pred_begin() == BB->pred_end() &&
168       !BB->hasConstantPoolReferences()) {
169     //cerr << "Removing BB: \n" << BB;
170
171     // Loop through all of our successors and make sure they know that one
172     // of their predecessors is going away.
173     for_each(BB->succ_begin(), BB->succ_end(),
174              std::bind2nd(std::mem_fun(&BasicBlock::removePredecessor), BB));
175
176     while (!BB->empty()) {
177       Instruction *I = BB->back();
178       // If this instruction is used, replace uses with an arbitrary
179       // constant value.  Because control flow can't get here, we don't care
180       // what we replace the value with.  Note that since this block is 
181       // unreachable, and all values contained within it must dominate their
182       // uses, that all uses will eventually be removed.
183       if (!I->use_empty()) ReplaceUsesWithConstant(I);
184       
185       // Remove the instruction from the basic block
186       delete BB->getInstList().pop_back();
187     }
188     delete M->getBasicBlocks().remove(BBIt);
189     return true;
190   }
191
192   // Check to see if this block has no instructions and only a single 
193   // successor.  If so, replace block references with successor.
194   BasicBlock::succ_iterator SI(BB->succ_begin());
195   if (SI != BB->succ_end() && ++SI == BB->succ_end()) {  // One succ?
196     Instruction *I = BB->front();
197     if (I->isTerminator()) {   // Terminator is the only instruction!
198       BasicBlock *Succ = *BB->succ_begin(); // There is exactly one successor
199       //cerr << "Killing Trivial BB: \n" << BB;
200       
201       if (Succ != BB) {   // Arg, don't hurt infinite loops!
202         if (isa<PHINode>(Succ->front())) {
203           // If our successor has PHI nodes, then we need to update them to
204           // include entries for BB's predecessors, not for BB itself.
205           //
206           PropogatePredecessorsForPHIs(BB, Succ);
207         }
208         
209         BB->replaceAllUsesWith(Succ);
210         BB = M->getBasicBlocks().remove(BBIt);
211         
212         if (BB->hasName() && !Succ->hasName())  // Transfer name if we can
213           Succ->setName(BB->getName());
214         delete BB;                              // Delete basic block
215         
216         //cerr << "Method after removal: \n" << M;
217         return true;
218       }
219     }
220   }
221
222   // Merge basic blocks into their predecessor if there is only one pred, 
223   // and if there is only one successor of the predecessor. 
224   BasicBlock::pred_iterator PI(BB->pred_begin());
225   if (PI != BB->pred_end() && *PI != BB &&    // Not empty?  Not same BB?
226       ++PI == BB->pred_end() && !BB->hasConstantPoolReferences()) {
227     BasicBlock *Pred = *BB->pred_begin();
228     TerminatorInst *Term = Pred->getTerminator();
229     assert(Term != 0 && "malformed basic block without terminator!");
230     
231     // Does the predecessor block only have a single successor?
232     BasicBlock::succ_iterator SI(Pred->succ_begin());
233     if (++SI == Pred->succ_end()) {
234       //cerr << "Merging: " << BB << "into: " << Pred;
235       
236       // Delete the unconditianal branch from the predecessor...
237       BasicBlock::iterator DI = Pred->end();
238       assert(Pred->getTerminator() && 
239              "Degenerate basic block encountered!");  // Empty bb???      
240       delete Pred->getInstList().remove(--DI);        // Destroy uncond branch
241       
242       // Move all definitions in the succecessor to the predecessor...
243       while (!BB->empty()) {
244         DI = BB->begin();
245         Instruction *Def = BB->getInstList().remove(DI); // Remove from front
246         Pred->getInstList().push_back(Def);              // Add to end...
247       }
248       
249       // Remove basic block from the method... and advance iterator to the
250       // next valid block...
251       BB = M->getBasicBlocks().remove(BBIt);
252
253       // Make all PHI nodes that refered to BB now refer to Pred as their
254       // source...
255       BB->replaceAllUsesWith(Pred);
256       
257       // Inherit predecessors name if it exists...
258       if (BB->hasName() && !Pred->hasName()) Pred->setName(BB->getName());
259       
260       delete BB; // You ARE the weakest link... goodbye
261       return true;
262     }
263   }
264   
265   return false;
266 }
267
268 static bool DoDCEPass(Method *M) {
269   Method::iterator BBIt, BBEnd = M->end();
270   if (M->begin() == BBEnd) return false;  // Nothing to do
271   bool Changed = false;
272
273   // Loop through now and remove instructions that have no uses...
274   for (BBIt = M->begin(); BBIt != BBEnd; ++BBIt) {
275     Changed |= RemoveUnusedDefs((*BBIt)->getInstList(), BasicBlockDCE());
276     Changed |= RemoveSingularPHIs(*BBIt);
277   }
278
279   // Loop over all of the basic blocks (except the first one) and remove them
280   // if they are unneeded...
281   //
282   for (BBIt = M->begin(), ++BBIt; BBIt != M->end(); ) {
283     if (opt::SimplifyCFG(BBIt)) {
284       Changed = true;
285     } else {
286       ++BBIt;
287     }
288   }
289
290   return Changed;
291 }
292
293
294 // It is possible that we may require multiple passes over the code to fully
295 // eliminate dead code.  Iterate until we are done.
296 //
297 bool opt::DeadCodeElimination::doDCE(Method *M) {
298   bool Changed = false;
299   while (DoDCEPass(M)) Changed = true;
300   return Changed;
301 }
302
303 bool opt::DeadCodeElimination::RemoveUnusedGlobalValues(Module *Mod) {
304   bool Changed = false;
305
306   for (Module::iterator MI = Mod->begin(); MI != Mod->end(); ) {
307     Method *Meth = *MI;
308     if (Meth->isExternal() && Meth->use_size() == 0) {
309       // No references to prototype?
310       //cerr << "Removing method proto: " << Meth->getName() << endl;
311       delete Mod->getMethodList().remove(MI);  // Remove prototype
312       // Remove moves iterator to point to the next one automatically
313       Changed = true;
314     } else {
315       ++MI;                                    // Skip prototype in use.
316     }
317   }
318
319   for (Module::giterator GI = Mod->gbegin(); GI != Mod->gend(); ) {
320     GlobalVariable *GV = *GI;
321     if (!GV->hasInitializer() && GV->use_size() == 0) {
322       // No references to uninitialized global variable?
323       //cerr << "Removing global var: " << GV->getName() << endl;
324       delete Mod->getGlobalList().remove(GI);
325       // Remove moves iterator to point to the next one automatically
326       Changed = true;
327     } else {
328       ++GI;
329     }
330   }
331
332   return Changed;
333 }