blob: 89cf45aa7e603cffaaf270f7b46f44e4f93b3ff7 [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:
Chris Lattnerc560f882002-01-23 05:48:24 +00006// * removes definitions with no uses
Chris Lattner00950542001-06-06 20:29:01 +00007// * 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 Lattner59b6b8e2002-01-21 23:17:48 +000026#include "llvm/Transforms/Scalar/DCE.h"
Chris Lattner00950542001-06-06 20:29:01 +000027#include "llvm/Module.h"
Chris Lattner5680ee62001-10-18 01:32:34 +000028#include "llvm/GlobalVariable.h"
Chris Lattner00950542001-06-06 20:29:01 +000029#include "llvm/Method.h"
30#include "llvm/BasicBlock.h"
31#include "llvm/iTerminators.h"
Chris Lattner7061dc52001-12-03 18:02:31 +000032#include "llvm/iPHINode.h"
Chris Lattnerf155e132001-06-07 16:59:26 +000033#include "llvm/Assembly/Writer.h"
Chris Lattnercee8f9a2001-11-27 00:03:19 +000034#include "Support/STLExtras.h"
Chris Lattner25d17a52001-06-29 05:24:28 +000035#include <algorithm>
Chris Lattner00950542001-06-06 20:29:01 +000036
Chris Lattnera1f6e642001-11-01 07:00:27 +000037// dceInstruction - Inspect the instruction at *BBI and figure out if it's
38// [trivially] dead. If so, remove the instruction and update the iterator
39// to point to the instruction that immediately succeeded the original
40// instruction.
41//
Chris Lattner59b6b8e2002-01-21 23:17:48 +000042bool DeadCodeElimination::dceInstruction(BasicBlock::InstListType &BBIL,
43 BasicBlock::iterator &BBI) {
Chris Lattnera1f6e642001-11-01 07:00:27 +000044 // Look for un"used" definitions...
45 if ((*BBI)->use_empty() && !(*BBI)->hasSideEffects() &&
46 !isa<TerminatorInst>(*BBI)) {
47 delete BBIL.remove(BBI); // Bye bye
48 return true;
49 }
50 return false;
51}
52
53static inline bool RemoveUnusedDefs(BasicBlock::InstListType &Vals) {
Chris Lattner00950542001-06-06 20:29:01 +000054 bool Changed = false;
Chris Lattneredefaa12001-11-01 05:55:29 +000055 for (BasicBlock::InstListType::iterator DI = Vals.begin();
Chris Lattnera1f6e642001-11-01 07:00:27 +000056 DI != Vals.end(); )
Chris Lattner59b6b8e2002-01-21 23:17:48 +000057 if (DeadCodeElimination::dceInstruction(Vals, DI))
Chris Lattner00950542001-06-06 20:29:01 +000058 Changed = true;
Chris Lattnera1f6e642001-11-01 07:00:27 +000059 else
Chris Lattner7fc9fe32001-06-27 23:41:11 +000060 ++DI;
Chris Lattner00950542001-06-06 20:29:01 +000061 return Changed;
62}
63
Chris Lattnerc560f882002-01-23 05:48:24 +000064bool DeadInstElimination::runOnBasicBlock(BasicBlock *BB) {
65 return RemoveUnusedDefs(BB->getInstList());
66}
67
Chris Lattnerf155e132001-06-07 16:59:26 +000068// RemoveSingularPHIs - This removes PHI nodes from basic blocks that have only
69// a single predecessor. This means that the PHI node must only have a single
70// RHS value and can be eliminated.
71//
72// This routine is very simple because we know that PHI nodes must be the first
73// things in a basic block, if they are present.
74//
75static bool RemoveSingularPHIs(BasicBlock *BB) {
Chris Lattnerf0604b82001-10-01 13:19:53 +000076 BasicBlock::pred_iterator PI(BB->pred_begin());
77 if (PI == BB->pred_end() || ++PI != BB->pred_end())
Chris Lattnerf155e132001-06-07 16:59:26 +000078 return false; // More than one predecessor...
79
Chris Lattner7fc9fe32001-06-27 23:41:11 +000080 Instruction *I = BB->front();
Chris Lattnerb00c5822001-10-02 03:41:24 +000081 if (!isa<PHINode>(I)) return false; // No PHI nodes
Chris Lattnerf155e132001-06-07 16:59:26 +000082
Chris Lattneree976f32001-06-11 15:04:40 +000083 //cerr << "Killing PHIs from " << BB;
Chris Lattnerf0604b82001-10-01 13:19:53 +000084 //cerr << "Pred #0 = " << *BB->pred_begin();
Chris Lattnerf155e132001-06-07 16:59:26 +000085
Chris Lattneree976f32001-06-11 15:04:40 +000086 //cerr << "Method == " << BB->getParent();
Chris Lattnerf155e132001-06-07 16:59:26 +000087
88 do {
Chris Lattnerb00c5822001-10-02 03:41:24 +000089 PHINode *PN = cast<PHINode>(I);
Chris Lattnerc8b25d42001-07-07 08:36:50 +000090 assert(PN->getNumOperands() == 2 && "PHI node should only have one value!");
Chris Lattnerf155e132001-06-07 16:59:26 +000091 Value *V = PN->getOperand(0);
92
93 PN->replaceAllUsesWith(V); // Replace PHI node with its single value.
Chris Lattner7fc9fe32001-06-27 23:41:11 +000094 delete BB->getInstList().remove(BB->begin());
Chris Lattnerf155e132001-06-07 16:59:26 +000095
Chris Lattner7fc9fe32001-06-27 23:41:11 +000096 I = BB->front();
Chris Lattnerb00c5822001-10-02 03:41:24 +000097 } while (isa<PHINode>(I));
Chris Lattnerf155e132001-06-07 16:59:26 +000098
99 return true; // Yes, we nuked at least one phi node
100}
Chris Lattner00950542001-06-06 20:29:01 +0000101
Chris Lattner00950542001-06-06 20:29:01 +0000102static void ReplaceUsesWithConstant(Instruction *I) {
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000103 Constant *CPV = Constant::getNullConstant(I->getType());
Chris Lattner00950542001-06-06 20:29:01 +0000104
105 // Make all users of this instruction reference the constant instead
106 I->replaceAllUsesWith(CPV);
107}
108
Chris Lattnerf155e132001-06-07 16:59:26 +0000109// PropogatePredecessors - This gets "Succ" ready to have the predecessors from
110// "BB". This is a little tricky because "Succ" has PHI nodes, which need to
111// have extra slots added to them to hold the merge edges from BB's
Chris Lattner081431a2001-11-03 21:30:22 +0000112// predecessors. This function returns true (failure) if the Succ BB already
113// has a predecessor that is a predecessor of BB.
Chris Lattnerf155e132001-06-07 16:59:26 +0000114//
Chris Lattner081431a2001-11-03 21:30:22 +0000115// Assumption: Succ is the single successor for BB.
Chris Lattnerf155e132001-06-07 16:59:26 +0000116//
Chris Lattner081431a2001-11-03 21:30:22 +0000117static bool PropogatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) {
118 assert(*BB->succ_begin() == Succ && "Succ is not successor of BB!");
Chris Lattnerb00c5822001-10-02 03:41:24 +0000119 assert(isa<PHINode>(Succ->front()) && "Only works on PHId BBs!");
Chris Lattnerf155e132001-06-07 16:59:26 +0000120
121 // If there is more than one predecessor, and there are PHI nodes in
122 // the successor, then we need to add incoming edges for the PHI nodes
Chris Lattner7fc9fe32001-06-27 23:41:11 +0000123 //
Chris Lattner697954c2002-01-20 22:54:45 +0000124 const std::vector<BasicBlock*> BBPreds(BB->pred_begin(), BB->pred_end());
Chris Lattner7fc9fe32001-06-27 23:41:11 +0000125
Chris Lattner081431a2001-11-03 21:30:22 +0000126 // Check to see if one of the predecessors of BB is already a predecessor of
127 // Succ. If so, we cannot do the transformation!
128 //
129 for (BasicBlock::pred_iterator PI = Succ->pred_begin(), PE = Succ->pred_end();
130 PI != PE; ++PI) {
131 if (find(BBPreds.begin(), BBPreds.end(), *PI) != BBPreds.end())
132 return true;
133 }
134
Chris Lattner7fc9fe32001-06-27 23:41:11 +0000135 BasicBlock::iterator I = Succ->begin();
136 do { // Loop over all of the PHI nodes in the successor BB
Chris Lattnerb00c5822001-10-02 03:41:24 +0000137 PHINode *PN = cast<PHINode>(*I);
Chris Lattner7fc9fe32001-06-27 23:41:11 +0000138 Value *OldVal = PN->removeIncomingValue(BB);
139 assert(OldVal && "No entry in PHI for Pred BB!");
140
Chris Lattner697954c2002-01-20 22:54:45 +0000141 for (std::vector<BasicBlock*>::const_iterator PredI = BBPreds.begin(),
Chris Lattner7fc9fe32001-06-27 23:41:11 +0000142 End = BBPreds.end(); PredI != End; ++PredI) {
143 // Add an incoming value for each of the new incoming values...
144 PN->addIncoming(OldVal, *PredI);
145 }
146
147 ++I;
Chris Lattnerb00c5822001-10-02 03:41:24 +0000148 } while (isa<PHINode>(*I));
Chris Lattner081431a2001-11-03 21:30:22 +0000149 return false;
Chris Lattnerf155e132001-06-07 16:59:26 +0000150}
151
Chris Lattner7e02b7e2001-06-30 04:36:40 +0000152
153// SimplifyCFG - This function is used to do simplification of a CFG. For
154// example, it adjusts branches to branches to eliminate the extra hop, it
155// eliminates unreachable basic blocks, and does other "peephole" optimization
156// of the CFG. It returns true if a modification was made, and returns an
157// iterator that designates the first element remaining after the block that
158// was deleted.
159//
160// WARNING: The entry node of a method may not be simplified.
161//
Chris Lattner59b6b8e2002-01-21 23:17:48 +0000162bool SimplifyCFG(Method::iterator &BBIt) {
Chris Lattner7e02b7e2001-06-30 04:36:40 +0000163 BasicBlock *BB = *BBIt;
164 Method *M = BB->getParent();
Chris Lattner2f11a9d2001-09-07 16:42:08 +0000165
166 assert(BB && BB->getParent() && "Block not embedded in method!");
Chris Lattner7e02b7e2001-06-30 04:36:40 +0000167 assert(BB->getTerminator() && "Degenerate basic block encountered!");
168 assert(BB->getParent()->front() != BB && "Can't Simplify entry block!");
169
Chris Lattner2f11a9d2001-09-07 16:42:08 +0000170
Chris Lattner7e02b7e2001-06-30 04:36:40 +0000171 // Remove basic blocks that have no predecessors... which are unreachable.
Chris Lattnerf0604b82001-10-01 13:19:53 +0000172 if (BB->pred_begin() == BB->pred_end() &&
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000173 !BB->hasConstantReferences()) {
Chris Lattner7e02b7e2001-06-30 04:36:40 +0000174 //cerr << "Removing BB: \n" << BB;
175
176 // Loop through all of our successors and make sure they know that one
177 // of their predecessors is going away.
Chris Lattnerf0604b82001-10-01 13:19:53 +0000178 for_each(BB->succ_begin(), BB->succ_end(),
Chris Lattner7e02b7e2001-06-30 04:36:40 +0000179 std::bind2nd(std::mem_fun(&BasicBlock::removePredecessor), BB));
180
181 while (!BB->empty()) {
182 Instruction *I = BB->back();
183 // If this instruction is used, replace uses with an arbitrary
184 // constant value. Because control flow can't get here, we don't care
185 // what we replace the value with. Note that since this block is
186 // unreachable, and all values contained within it must dominate their
187 // uses, that all uses will eventually be removed.
188 if (!I->use_empty()) ReplaceUsesWithConstant(I);
189
190 // Remove the instruction from the basic block
191 delete BB->getInstList().pop_back();
192 }
193 delete M->getBasicBlocks().remove(BBIt);
194 return true;
Chris Lattner2f11a9d2001-09-07 16:42:08 +0000195 }
Chris Lattner7e02b7e2001-06-30 04:36:40 +0000196
197 // Check to see if this block has no instructions and only a single
198 // successor. If so, replace block references with successor.
Chris Lattnerf0604b82001-10-01 13:19:53 +0000199 BasicBlock::succ_iterator SI(BB->succ_begin());
200 if (SI != BB->succ_end() && ++SI == BB->succ_end()) { // One succ?
Chris Lattner081431a2001-11-03 21:30:22 +0000201 if (BB->front()->isTerminator()) { // Terminator is the only instruction!
Chris Lattnerf0604b82001-10-01 13:19:53 +0000202 BasicBlock *Succ = *BB->succ_begin(); // There is exactly one successor
Chris Lattner7e02b7e2001-06-30 04:36:40 +0000203 //cerr << "Killing Trivial BB: \n" << BB;
204
205 if (Succ != BB) { // Arg, don't hurt infinite loops!
Chris Lattner081431a2001-11-03 21:30:22 +0000206 // If our successor has PHI nodes, then we need to update them to
207 // include entries for BB's predecessors, not for BB itself.
208 // Be careful though, if this transformation fails (returns true) then
209 // we cannot do this transformation!
210 //
211 if (!isa<PHINode>(Succ->front()) ||
212 !PropogatePredecessorsForPHIs(BB, Succ)) {
213
214 BB->replaceAllUsesWith(Succ);
215 BB = M->getBasicBlocks().remove(BBIt);
216
217 if (BB->hasName() && !Succ->hasName()) // Transfer name if we can
218 Succ->setName(BB->getName());
219 delete BB; // Delete basic block
220
221 //cerr << "Method after removal: \n" << M;
222 return true;
Chris Lattner7e02b7e2001-06-30 04:36:40 +0000223 }
Chris Lattner7e02b7e2001-06-30 04:36:40 +0000224 }
225 }
226 }
227
228 // Merge basic blocks into their predecessor if there is only one pred,
229 // and if there is only one successor of the predecessor.
Chris Lattnerf0604b82001-10-01 13:19:53 +0000230 BasicBlock::pred_iterator PI(BB->pred_begin());
231 if (PI != BB->pred_end() && *PI != BB && // Not empty? Not same BB?
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000232 ++PI == BB->pred_end() && !BB->hasConstantReferences()) {
Chris Lattnerf0604b82001-10-01 13:19:53 +0000233 BasicBlock *Pred = *BB->pred_begin();
Chris Lattner7e02b7e2001-06-30 04:36:40 +0000234 TerminatorInst *Term = Pred->getTerminator();
235 assert(Term != 0 && "malformed basic block without terminator!");
236
237 // Does the predecessor block only have a single successor?
Chris Lattnerf0604b82001-10-01 13:19:53 +0000238 BasicBlock::succ_iterator SI(Pred->succ_begin());
239 if (++SI == Pred->succ_end()) {
Chris Lattner7e02b7e2001-06-30 04:36:40 +0000240 //cerr << "Merging: " << BB << "into: " << Pred;
241
242 // Delete the unconditianal branch from the predecessor...
243 BasicBlock::iterator DI = Pred->end();
244 assert(Pred->getTerminator() &&
245 "Degenerate basic block encountered!"); // Empty bb???
246 delete Pred->getInstList().remove(--DI); // Destroy uncond branch
247
248 // Move all definitions in the succecessor to the predecessor...
249 while (!BB->empty()) {
250 DI = BB->begin();
251 Instruction *Def = BB->getInstList().remove(DI); // Remove from front
252 Pred->getInstList().push_back(Def); // Add to end...
253 }
254
255 // Remove basic block from the method... and advance iterator to the
256 // next valid block...
257 BB = M->getBasicBlocks().remove(BBIt);
258
259 // Make all PHI nodes that refered to BB now refer to Pred as their
260 // source...
261 BB->replaceAllUsesWith(Pred);
262
263 // Inherit predecessors name if it exists...
264 if (BB->hasName() && !Pred->hasName()) Pred->setName(BB->getName());
265
266 delete BB; // You ARE the weakest link... goodbye
267 return true;
268 }
269 }
270
271 return false;
272}
273
Chris Lattner00950542001-06-06 20:29:01 +0000274static bool DoDCEPass(Method *M) {
Chris Lattner7fc9fe32001-06-27 23:41:11 +0000275 Method::iterator BBIt, BBEnd = M->end();
276 if (M->begin() == BBEnd) return false; // Nothing to do
Chris Lattner00950542001-06-06 20:29:01 +0000277 bool Changed = false;
278
279 // Loop through now and remove instructions that have no uses...
Chris Lattner7fc9fe32001-06-27 23:41:11 +0000280 for (BBIt = M->begin(); BBIt != BBEnd; ++BBIt) {
Chris Lattneredefaa12001-11-01 05:55:29 +0000281 Changed |= RemoveUnusedDefs((*BBIt)->getInstList());
Chris Lattnerf155e132001-06-07 16:59:26 +0000282 Changed |= RemoveSingularPHIs(*BBIt);
283 }
Chris Lattner00950542001-06-06 20:29:01 +0000284
Chris Lattnerf155e132001-06-07 16:59:26 +0000285 // Loop over all of the basic blocks (except the first one) and remove them
286 // if they are unneeded...
Chris Lattner00950542001-06-06 20:29:01 +0000287 //
Chris Lattner7e02b7e2001-06-30 04:36:40 +0000288 for (BBIt = M->begin(), ++BBIt; BBIt != M->end(); ) {
Chris Lattner59b6b8e2002-01-21 23:17:48 +0000289 if (SimplifyCFG(BBIt)) {
Chris Lattner00950542001-06-06 20:29:01 +0000290 Changed = true;
Chris Lattner7e02b7e2001-06-30 04:36:40 +0000291 } else {
292 ++BBIt;
Chris Lattner00950542001-06-06 20:29:01 +0000293 }
294 }
295
Chris Lattner2f11a9d2001-09-07 16:42:08 +0000296 return Changed;
Chris Lattner00950542001-06-06 20:29:01 +0000297}
298
299
300// It is possible that we may require multiple passes over the code to fully
301// eliminate dead code. Iterate until we are done.
302//
Chris Lattner59b6b8e2002-01-21 23:17:48 +0000303bool DeadCodeElimination::doDCE(Method *M) {
Chris Lattner00950542001-06-06 20:29:01 +0000304 bool Changed = false;
305 while (DoDCEPass(M)) Changed = true;
306 return Changed;
307}
308
Chris Lattner59b6b8e2002-01-21 23:17:48 +0000309bool DeadCodeElimination::RemoveUnusedGlobalValues(Module *Mod) {
Chris Lattneree7cb292001-07-28 17:51:49 +0000310 bool Changed = false;
Chris Lattner7e02b7e2001-06-30 04:36:40 +0000311
Chris Lattneree7cb292001-07-28 17:51:49 +0000312 for (Module::iterator MI = Mod->begin(); MI != Mod->end(); ) {
313 Method *Meth = *MI;
Chris Lattner5680ee62001-10-18 01:32:34 +0000314 if (Meth->isExternal() && Meth->use_size() == 0) {
315 // No references to prototype?
Chris Lattneree7cb292001-07-28 17:51:49 +0000316 //cerr << "Removing method proto: " << Meth->getName() << endl;
317 delete Mod->getMethodList().remove(MI); // Remove prototype
318 // Remove moves iterator to point to the next one automatically
Chris Lattner5680ee62001-10-18 01:32:34 +0000319 Changed = true;
Chris Lattneree7cb292001-07-28 17:51:49 +0000320 } else {
321 ++MI; // Skip prototype in use.
322 }
323 }
324
Chris Lattner5680ee62001-10-18 01:32:34 +0000325 for (Module::giterator GI = Mod->gbegin(); GI != Mod->gend(); ) {
326 GlobalVariable *GV = *GI;
327 if (!GV->hasInitializer() && GV->use_size() == 0) {
328 // No references to uninitialized global variable?
329 //cerr << "Removing global var: " << GV->getName() << endl;
330 delete Mod->getGlobalList().remove(GI);
331 // Remove moves iterator to point to the next one automatically
332 Changed = true;
333 } else {
334 ++GI;
335 }
336 }
337
Chris Lattneree7cb292001-07-28 17:51:49 +0000338 return Changed;
Chris Lattner00950542001-06-06 20:29:01 +0000339}