blob: e089525eca4a597e7d804779a0138f9e07d5402d [file] [log] [blame]
Chris Lattner00950542001-06-06 20:29:01 +00001//===- 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.
Chris Lattnerf155e132001-06-07 16:59:26 +000010// * Eliminates PHI nodes for basic blocks with a single predecessor
11// * Eliminates a basic block that only contains an unconditional branch
Chris Lattneree7cb292001-07-28 17:51:49 +000012// * Eliminates method prototypes that are not referenced
Chris Lattner00950542001-06-06 20:29:01 +000013//
Chris Lattner25d17a52001-06-29 05:24:28 +000014// 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
Chris Lattner00950542001-06-06 20:29:01 +000018// removing a value, recheck all of its operands to see if they are now unused.
Chris Lattnerd36c91c2001-06-13 19:55:22 +000019// Piece of cake, and more efficient as well.
20//
21// Note, this is not trivial, because we have to worry about invalidating
22// iterators. :(
Chris Lattner00950542001-06-06 20:29:01 +000023//
24//===----------------------------------------------------------------------===//
25
Chris Lattner7e02b7e2001-06-30 04:36:40 +000026#include "llvm/Optimizations/DCE.h"
Chris Lattner57dbb3a2001-07-23 17:46:59 +000027#include "llvm/Support/STLExtras.h"
Chris Lattner00950542001-06-06 20:29:01 +000028#include "llvm/Module.h"
Chris Lattner5680ee62001-10-18 01:32:34 +000029#include "llvm/GlobalVariable.h"
Chris Lattner00950542001-06-06 20:29:01 +000030#include "llvm/Method.h"
31#include "llvm/BasicBlock.h"
32#include "llvm/iTerminators.h"
Chris Lattnerf155e132001-06-07 16:59:26 +000033#include "llvm/iOther.h"
Chris Lattnerf155e132001-06-07 16:59:26 +000034#include "llvm/Assembly/Writer.h"
Chris Lattner25d17a52001-06-29 05:24:28 +000035#include <algorithm>
Chris Lattner00950542001-06-06 20:29:01 +000036
37struct ConstPoolDCE {
38 enum { EndOffs = 0 };
Chris Lattnerc262f722001-07-09 19:38:52 +000039 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 }
Chris Lattner00950542001-06-06 20:29:01 +000045};
46
47struct BasicBlockDCE {
48 enum { EndOffs = 1 };
49 static bool isDCEable(const Instruction *I) {
50 return !I->hasSideEffects();
51 }
52};
53
Chris Lattnerf155e132001-06-07 16:59:26 +000054
Chris Lattner20a155f2001-07-14 06:11:26 +000055template<class Container, class DCEController>
56static bool RemoveUnusedDefs(Container &Vals, DCEController DCEControl) {
Chris Lattner00950542001-06-06 20:29:01 +000057 bool Changed = false;
Chris Lattner00950542001-06-06 20:29:01 +000058 int Offset = DCEController::EndOffs;
Chris Lattner20a155f2001-07-14 06:11:26 +000059
60 for (typename Container::iterator DI = Vals.begin();
61 DI != Vals.end()-Offset; ) {
Chris Lattner00950542001-06-06 20:29:01 +000062 // Look for un"used" definitions...
63 if ((*DI)->use_empty() && DCEController::isDCEable(*DI)) {
64 // Bye bye
Chris Lattnerf155e132001-06-07 16:59:26 +000065 //cerr << "Removing: " << *DI;
Chris Lattner00950542001-06-06 20:29:01 +000066 delete Vals.remove(DI);
67 Changed = true;
68 } else {
Chris Lattner7fc9fe32001-06-27 23:41:11 +000069 ++DI;
Chris Lattner00950542001-06-06 20:29:01 +000070 }
71 }
72 return Changed;
73}
74
Chris Lattnerf155e132001-06-07 16:59:26 +000075// 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//
82static bool RemoveSingularPHIs(BasicBlock *BB) {
Chris Lattnerf0604b82001-10-01 13:19:53 +000083 BasicBlock::pred_iterator PI(BB->pred_begin());
84 if (PI == BB->pred_end() || ++PI != BB->pred_end())
Chris Lattnerf155e132001-06-07 16:59:26 +000085 return false; // More than one predecessor...
86
Chris Lattner7fc9fe32001-06-27 23:41:11 +000087 Instruction *I = BB->front();
Chris Lattnerb00c5822001-10-02 03:41:24 +000088 if (!isa<PHINode>(I)) return false; // No PHI nodes
Chris Lattnerf155e132001-06-07 16:59:26 +000089
Chris Lattneree976f32001-06-11 15:04:40 +000090 //cerr << "Killing PHIs from " << BB;
Chris Lattnerf0604b82001-10-01 13:19:53 +000091 //cerr << "Pred #0 = " << *BB->pred_begin();
Chris Lattnerf155e132001-06-07 16:59:26 +000092
Chris Lattneree976f32001-06-11 15:04:40 +000093 //cerr << "Method == " << BB->getParent();
Chris Lattnerf155e132001-06-07 16:59:26 +000094
95 do {
Chris Lattnerb00c5822001-10-02 03:41:24 +000096 PHINode *PN = cast<PHINode>(I);
Chris Lattnerc8b25d42001-07-07 08:36:50 +000097 assert(PN->getNumOperands() == 2 && "PHI node should only have one value!");
Chris Lattnerf155e132001-06-07 16:59:26 +000098 Value *V = PN->getOperand(0);
99
100 PN->replaceAllUsesWith(V); // Replace PHI node with its single value.
Chris Lattner7fc9fe32001-06-27 23:41:11 +0000101 delete BB->getInstList().remove(BB->begin());
Chris Lattnerf155e132001-06-07 16:59:26 +0000102
Chris Lattner7fc9fe32001-06-27 23:41:11 +0000103 I = BB->front();
Chris Lattnerb00c5822001-10-02 03:41:24 +0000104 } while (isa<PHINode>(I));
Chris Lattnerf155e132001-06-07 16:59:26 +0000105
106 return true; // Yes, we nuked at least one phi node
107}
Chris Lattner00950542001-06-06 20:29:01 +0000108
Chris Lattner00950542001-06-06 20:29:01 +0000109static void ReplaceUsesWithConstant(Instruction *I) {
Chris Lattner2f11a9d2001-09-07 16:42:08 +0000110 ConstPoolVal *CPV = ConstPoolVal::getNullConstant(I->getType());
Chris Lattner00950542001-06-06 20:29:01 +0000111
112 // Make all users of this instruction reference the constant instead
113 I->replaceAllUsesWith(CPV);
114}
115
Chris Lattnerf155e132001-06-07 16:59:26 +0000116// 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//
123static void PropogatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) {
Chris Lattnerb00c5822001-10-02 03:41:24 +0000124 assert(isa<PHINode>(Succ->front()) && "Only works on PHId BBs!");
Chris Lattnerf155e132001-06-07 16:59:26 +0000125
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
Chris Lattner7fc9fe32001-06-27 23:41:11 +0000128 //
Chris Lattnerf0604b82001-10-01 13:19:53 +0000129 const vector<BasicBlock*> BBPreds(BB->pred_begin(), BB->pred_end());
Chris Lattner7fc9fe32001-06-27 23:41:11 +0000130
131 BasicBlock::iterator I = Succ->begin();
132 do { // Loop over all of the PHI nodes in the successor BB
Chris Lattnerb00c5822001-10-02 03:41:24 +0000133 PHINode *PN = cast<PHINode>(*I);
Chris Lattner7fc9fe32001-06-27 23:41:11 +0000134 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;
Chris Lattnerb00c5822001-10-02 03:41:24 +0000144 } while (isa<PHINode>(*I));
Chris Lattnerf155e132001-06-07 16:59:26 +0000145}
146
Chris Lattner7e02b7e2001-06-30 04:36:40 +0000147
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//
157bool opt::SimplifyCFG(Method::iterator &BBIt) {
Chris Lattner7e02b7e2001-06-30 04:36:40 +0000158 BasicBlock *BB = *BBIt;
159 Method *M = BB->getParent();
Chris Lattner2f11a9d2001-09-07 16:42:08 +0000160
161 assert(BB && BB->getParent() && "Block not embedded in method!");
Chris Lattner7e02b7e2001-06-30 04:36:40 +0000162 assert(BB->getTerminator() && "Degenerate basic block encountered!");
163 assert(BB->getParent()->front() != BB && "Can't Simplify entry block!");
164
Chris Lattner2f11a9d2001-09-07 16:42:08 +0000165
Chris Lattner7e02b7e2001-06-30 04:36:40 +0000166 // Remove basic blocks that have no predecessors... which are unreachable.
Chris Lattnerf0604b82001-10-01 13:19:53 +0000167 if (BB->pred_begin() == BB->pred_end() &&
Chris Lattner7e02b7e2001-06-30 04:36:40 +0000168 !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.
Chris Lattnerf0604b82001-10-01 13:19:53 +0000173 for_each(BB->succ_begin(), BB->succ_end(),
Chris Lattner7e02b7e2001-06-30 04:36:40 +0000174 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;
Chris Lattner2f11a9d2001-09-07 16:42:08 +0000190 }
Chris Lattner7e02b7e2001-06-30 04:36:40 +0000191
192 // Check to see if this block has no instructions and only a single
193 // successor. If so, replace block references with successor.
Chris Lattnerf0604b82001-10-01 13:19:53 +0000194 BasicBlock::succ_iterator SI(BB->succ_begin());
195 if (SI != BB->succ_end() && ++SI == BB->succ_end()) { // One succ?
Chris Lattner7e02b7e2001-06-30 04:36:40 +0000196 Instruction *I = BB->front();
197 if (I->isTerminator()) { // Terminator is the only instruction!
Chris Lattnerf0604b82001-10-01 13:19:53 +0000198 BasicBlock *Succ = *BB->succ_begin(); // There is exactly one successor
Chris Lattner7e02b7e2001-06-30 04:36:40 +0000199 //cerr << "Killing Trivial BB: \n" << BB;
200
201 if (Succ != BB) { // Arg, don't hurt infinite loops!
Chris Lattnerb00c5822001-10-02 03:41:24 +0000202 if (isa<PHINode>(Succ->front())) {
Chris Lattner7e02b7e2001-06-30 04:36:40 +0000203 // 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.
Chris Lattnerf0604b82001-10-01 13:19:53 +0000224 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();
Chris Lattner7e02b7e2001-06-30 04:36:40 +0000228 TerminatorInst *Term = Pred->getTerminator();
229 assert(Term != 0 && "malformed basic block without terminator!");
230
231 // Does the predecessor block only have a single successor?
Chris Lattnerf0604b82001-10-01 13:19:53 +0000232 BasicBlock::succ_iterator SI(Pred->succ_begin());
233 if (++SI == Pred->succ_end()) {
Chris Lattner7e02b7e2001-06-30 04:36:40 +0000234 //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
Chris Lattner00950542001-06-06 20:29:01 +0000268static bool DoDCEPass(Method *M) {
Chris Lattner7fc9fe32001-06-27 23:41:11 +0000269 Method::iterator BBIt, BBEnd = M->end();
270 if (M->begin() == BBEnd) return false; // Nothing to do
Chris Lattner00950542001-06-06 20:29:01 +0000271 bool Changed = false;
272
273 // Loop through now and remove instructions that have no uses...
Chris Lattner7fc9fe32001-06-27 23:41:11 +0000274 for (BBIt = M->begin(); BBIt != BBEnd; ++BBIt) {
Chris Lattner00950542001-06-06 20:29:01 +0000275 Changed |= RemoveUnusedDefs((*BBIt)->getInstList(), BasicBlockDCE());
Chris Lattnerf155e132001-06-07 16:59:26 +0000276 Changed |= RemoveSingularPHIs(*BBIt);
277 }
Chris Lattner00950542001-06-06 20:29:01 +0000278
Chris Lattnerf155e132001-06-07 16:59:26 +0000279 // Loop over all of the basic blocks (except the first one) and remove them
280 // if they are unneeded...
Chris Lattner00950542001-06-06 20:29:01 +0000281 //
Chris Lattner7e02b7e2001-06-30 04:36:40 +0000282 for (BBIt = M->begin(), ++BBIt; BBIt != M->end(); ) {
283 if (opt::SimplifyCFG(BBIt)) {
Chris Lattner00950542001-06-06 20:29:01 +0000284 Changed = true;
Chris Lattner7e02b7e2001-06-30 04:36:40 +0000285 } else {
286 ++BBIt;
Chris Lattner00950542001-06-06 20:29:01 +0000287 }
288 }
289
Chris Lattner2f11a9d2001-09-07 16:42:08 +0000290 return Changed;
Chris Lattner00950542001-06-06 20:29:01 +0000291}
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//
Chris Lattner5680ee62001-10-18 01:32:34 +0000297bool opt::DeadCodeElimination::doDCE(Method *M) {
Chris Lattner00950542001-06-06 20:29:01 +0000298 bool Changed = false;
299 while (DoDCEPass(M)) Changed = true;
300 return Changed;
301}
302
Chris Lattner5680ee62001-10-18 01:32:34 +0000303bool opt::DeadCodeElimination::RemoveUnusedGlobalValues(Module *Mod) {
Chris Lattneree7cb292001-07-28 17:51:49 +0000304 bool Changed = false;
Chris Lattner7e02b7e2001-06-30 04:36:40 +0000305
Chris Lattneree7cb292001-07-28 17:51:49 +0000306 for (Module::iterator MI = Mod->begin(); MI != Mod->end(); ) {
307 Method *Meth = *MI;
Chris Lattner5680ee62001-10-18 01:32:34 +0000308 if (Meth->isExternal() && Meth->use_size() == 0) {
309 // No references to prototype?
Chris Lattneree7cb292001-07-28 17:51:49 +0000310 //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
Chris Lattner5680ee62001-10-18 01:32:34 +0000313 Changed = true;
Chris Lattneree7cb292001-07-28 17:51:49 +0000314 } else {
315 ++MI; // Skip prototype in use.
316 }
317 }
318
Chris Lattner5680ee62001-10-18 01:32:34 +0000319 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
Chris Lattneree7cb292001-07-28 17:51:49 +0000332 return Changed;
Chris Lattner00950542001-06-06 20:29:01 +0000333}