blob: 8f351a1431ccd4a974ffbace01f3b63a9f5cbf8f [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 Lattner455889a2002-02-12 22:39:50 +000034#include "llvm/Support/CFG.h"
Chris Lattnercee8f9a2001-11-27 00:03:19 +000035#include "Support/STLExtras.h"
Chris Lattner25d17a52001-06-29 05:24:28 +000036#include <algorithm>
Chris Lattner00950542001-06-06 20:29:01 +000037
Chris Lattnera1f6e642001-11-01 07:00:27 +000038// 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//
Chris Lattner59b6b8e2002-01-21 23:17:48 +000043bool DeadCodeElimination::dceInstruction(BasicBlock::InstListType &BBIL,
44 BasicBlock::iterator &BBI) {
Chris Lattnera1f6e642001-11-01 07:00:27 +000045 // 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
54static inline bool RemoveUnusedDefs(BasicBlock::InstListType &Vals) {
Chris Lattner00950542001-06-06 20:29:01 +000055 bool Changed = false;
Chris Lattneredefaa12001-11-01 05:55:29 +000056 for (BasicBlock::InstListType::iterator DI = Vals.begin();
Chris Lattnera1f6e642001-11-01 07:00:27 +000057 DI != Vals.end(); )
Chris Lattner59b6b8e2002-01-21 23:17:48 +000058 if (DeadCodeElimination::dceInstruction(Vals, DI))
Chris Lattner00950542001-06-06 20:29:01 +000059 Changed = true;
Chris Lattnera1f6e642001-11-01 07:00:27 +000060 else
Chris Lattner7fc9fe32001-06-27 23:41:11 +000061 ++DI;
Chris Lattner00950542001-06-06 20:29:01 +000062 return Changed;
63}
64
Chris Lattnerc560f882002-01-23 05:48:24 +000065bool DeadInstElimination::runOnBasicBlock(BasicBlock *BB) {
66 return RemoveUnusedDefs(BB->getInstList());
67}
68
Chris Lattnerf155e132001-06-07 16:59:26 +000069// 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//
76static bool RemoveSingularPHIs(BasicBlock *BB) {
Chris Lattner455889a2002-02-12 22:39:50 +000077 pred_iterator PI(pred_begin(BB));
78 if (PI == pred_end(BB) || ++PI != pred_end(BB))
Chris Lattnerf155e132001-06-07 16:59:26 +000079 return false; // More than one predecessor...
80
Chris Lattner7fc9fe32001-06-27 23:41:11 +000081 Instruction *I = BB->front();
Chris Lattnerb00c5822001-10-02 03:41:24 +000082 if (!isa<PHINode>(I)) return false; // No PHI nodes
Chris Lattnerf155e132001-06-07 16:59:26 +000083
Chris Lattneree976f32001-06-11 15:04:40 +000084 //cerr << "Killing PHIs from " << BB;
Chris Lattner455889a2002-02-12 22:39:50 +000085 //cerr << "Pred #0 = " << *pred_begin(BB);
Chris Lattnerf155e132001-06-07 16:59:26 +000086
Chris Lattneree976f32001-06-11 15:04:40 +000087 //cerr << "Method == " << BB->getParent();
Chris Lattnerf155e132001-06-07 16:59:26 +000088
89 do {
Chris Lattnerb00c5822001-10-02 03:41:24 +000090 PHINode *PN = cast<PHINode>(I);
Chris Lattnerc8b25d42001-07-07 08:36:50 +000091 assert(PN->getNumOperands() == 2 && "PHI node should only have one value!");
Chris Lattnerf155e132001-06-07 16:59:26 +000092 Value *V = PN->getOperand(0);
93
94 PN->replaceAllUsesWith(V); // Replace PHI node with its single value.
Chris Lattner7fc9fe32001-06-27 23:41:11 +000095 delete BB->getInstList().remove(BB->begin());
Chris Lattnerf155e132001-06-07 16:59:26 +000096
Chris Lattner7fc9fe32001-06-27 23:41:11 +000097 I = BB->front();
Chris Lattnerb00c5822001-10-02 03:41:24 +000098 } while (isa<PHINode>(I));
Chris Lattnerf155e132001-06-07 16:59:26 +000099
100 return true; // Yes, we nuked at least one phi node
101}
Chris Lattner00950542001-06-06 20:29:01 +0000102
Chris Lattner00950542001-06-06 20:29:01 +0000103static void ReplaceUsesWithConstant(Instruction *I) {
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000104 Constant *CPV = Constant::getNullConstant(I->getType());
Chris Lattner00950542001-06-06 20:29:01 +0000105
106 // Make all users of this instruction reference the constant instead
107 I->replaceAllUsesWith(CPV);
108}
109
Chris Lattnerf155e132001-06-07 16:59:26 +0000110// 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
Chris Lattner081431a2001-11-03 21:30:22 +0000113// predecessors. This function returns true (failure) if the Succ BB already
114// has a predecessor that is a predecessor of BB.
Chris Lattnerf155e132001-06-07 16:59:26 +0000115//
Chris Lattner081431a2001-11-03 21:30:22 +0000116// Assumption: Succ is the single successor for BB.
Chris Lattnerf155e132001-06-07 16:59:26 +0000117//
Chris Lattner081431a2001-11-03 21:30:22 +0000118static bool PropogatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) {
Chris Lattner455889a2002-02-12 22:39:50 +0000119 assert(*succ_begin(BB) == Succ && "Succ is not successor of BB!");
Chris Lattnerb00c5822001-10-02 03:41:24 +0000120 assert(isa<PHINode>(Succ->front()) && "Only works on PHId BBs!");
Chris Lattnerf155e132001-06-07 16:59:26 +0000121
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
Chris Lattner7fc9fe32001-06-27 23:41:11 +0000124 //
Chris Lattner455889a2002-02-12 22:39:50 +0000125 const std::vector<BasicBlock*> BBPreds(pred_begin(BB), pred_end(BB));
Chris Lattner7fc9fe32001-06-27 23:41:11 +0000126
Chris Lattner081431a2001-11-03 21:30:22 +0000127 // 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 //
Chris Lattner455889a2002-02-12 22:39:50 +0000130 for (pred_iterator PI = pred_begin(Succ), PE = pred_end(Succ);
131 PI != PE; ++PI) {
Chris Lattner081431a2001-11-03 21:30:22 +0000132 if (find(BBPreds.begin(), BBPreds.end(), *PI) != BBPreds.end())
133 return true;
134 }
135
Chris Lattner7fc9fe32001-06-27 23:41:11 +0000136 BasicBlock::iterator I = Succ->begin();
137 do { // Loop over all of the PHI nodes in the successor BB
Chris Lattnerb00c5822001-10-02 03:41:24 +0000138 PHINode *PN = cast<PHINode>(*I);
Chris Lattner7fc9fe32001-06-27 23:41:11 +0000139 Value *OldVal = PN->removeIncomingValue(BB);
140 assert(OldVal && "No entry in PHI for Pred BB!");
141
Chris Lattner697954c2002-01-20 22:54:45 +0000142 for (std::vector<BasicBlock*>::const_iterator PredI = BBPreds.begin(),
Chris Lattner7fc9fe32001-06-27 23:41:11 +0000143 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;
Chris Lattnerb00c5822001-10-02 03:41:24 +0000149 } while (isa<PHINode>(*I));
Chris Lattner081431a2001-11-03 21:30:22 +0000150 return false;
Chris Lattnerf155e132001-06-07 16:59:26 +0000151}
152
Chris Lattner7e02b7e2001-06-30 04:36:40 +0000153
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//
Chris Lattner59b6b8e2002-01-21 23:17:48 +0000163bool SimplifyCFG(Method::iterator &BBIt) {
Chris Lattner7e02b7e2001-06-30 04:36:40 +0000164 BasicBlock *BB = *BBIt;
165 Method *M = BB->getParent();
Chris Lattner2f11a9d2001-09-07 16:42:08 +0000166
167 assert(BB && BB->getParent() && "Block not embedded in method!");
Chris Lattner7e02b7e2001-06-30 04:36:40 +0000168 assert(BB->getTerminator() && "Degenerate basic block encountered!");
169 assert(BB->getParent()->front() != BB && "Can't Simplify entry block!");
170
Chris Lattner2f11a9d2001-09-07 16:42:08 +0000171
Chris Lattner7e02b7e2001-06-30 04:36:40 +0000172 // Remove basic blocks that have no predecessors... which are unreachable.
Chris Lattner455889a2002-02-12 22:39:50 +0000173 if (pred_begin(BB) == pred_end(BB) &&
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000174 !BB->hasConstantReferences()) {
Chris Lattner7e02b7e2001-06-30 04:36:40 +0000175 //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.
Chris Lattner455889a2002-02-12 22:39:50 +0000179 for_each(succ_begin(BB), succ_end(BB),
Chris Lattner7e02b7e2001-06-30 04:36:40 +0000180 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;
Chris Lattner2f11a9d2001-09-07 16:42:08 +0000196 }
Chris Lattner7e02b7e2001-06-30 04:36:40 +0000197
198 // Check to see if this block has no instructions and only a single
199 // successor. If so, replace block references with successor.
Chris Lattner455889a2002-02-12 22:39:50 +0000200 succ_iterator SI(succ_begin(BB));
201 if (SI != succ_end(BB) && ++SI == succ_end(BB)) { // One succ?
Chris Lattner081431a2001-11-03 21:30:22 +0000202 if (BB->front()->isTerminator()) { // Terminator is the only instruction!
Chris Lattner455889a2002-02-12 22:39:50 +0000203 BasicBlock *Succ = *succ_begin(BB); // There is exactly one successor
Chris Lattner7e02b7e2001-06-30 04:36:40 +0000204 //cerr << "Killing Trivial BB: \n" << BB;
205
206 if (Succ != BB) { // Arg, don't hurt infinite loops!
Chris Lattner081431a2001-11-03 21:30:22 +0000207 // 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;
Chris Lattner7e02b7e2001-06-30 04:36:40 +0000224 }
Chris Lattner7e02b7e2001-06-30 04:36:40 +0000225 }
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.
Chris Lattner455889a2002-02-12 22:39:50 +0000231 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);
Chris Lattner7e02b7e2001-06-30 04:36:40 +0000235 TerminatorInst *Term = Pred->getTerminator();
236 assert(Term != 0 && "malformed basic block without terminator!");
237
238 // Does the predecessor block only have a single successor?
Chris Lattner455889a2002-02-12 22:39:50 +0000239 succ_iterator SI(succ_begin(Pred));
240 if (++SI == succ_end(Pred)) {
Chris Lattner7e02b7e2001-06-30 04:36:40 +0000241 //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
Chris Lattner00950542001-06-06 20:29:01 +0000275static bool DoDCEPass(Method *M) {
Chris Lattner7fc9fe32001-06-27 23:41:11 +0000276 Method::iterator BBIt, BBEnd = M->end();
277 if (M->begin() == BBEnd) return false; // Nothing to do
Chris Lattner00950542001-06-06 20:29:01 +0000278 bool Changed = false;
279
280 // Loop through now and remove instructions that have no uses...
Chris Lattner7fc9fe32001-06-27 23:41:11 +0000281 for (BBIt = M->begin(); BBIt != BBEnd; ++BBIt) {
Chris Lattneredefaa12001-11-01 05:55:29 +0000282 Changed |= RemoveUnusedDefs((*BBIt)->getInstList());
Chris Lattnerf155e132001-06-07 16:59:26 +0000283 Changed |= RemoveSingularPHIs(*BBIt);
284 }
Chris Lattner00950542001-06-06 20:29:01 +0000285
Chris Lattnerf155e132001-06-07 16:59:26 +0000286 // Loop over all of the basic blocks (except the first one) and remove them
287 // if they are unneeded...
Chris Lattner00950542001-06-06 20:29:01 +0000288 //
Chris Lattner7e02b7e2001-06-30 04:36:40 +0000289 for (BBIt = M->begin(), ++BBIt; BBIt != M->end(); ) {
Chris Lattner59b6b8e2002-01-21 23:17:48 +0000290 if (SimplifyCFG(BBIt)) {
Chris Lattner00950542001-06-06 20:29:01 +0000291 Changed = true;
Chris Lattner7e02b7e2001-06-30 04:36:40 +0000292 } else {
293 ++BBIt;
Chris Lattner00950542001-06-06 20:29:01 +0000294 }
295 }
296
Chris Lattner2f11a9d2001-09-07 16:42:08 +0000297 return Changed;
Chris Lattner00950542001-06-06 20:29:01 +0000298}
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//
Chris Lattner59b6b8e2002-01-21 23:17:48 +0000304bool DeadCodeElimination::doDCE(Method *M) {
Chris Lattner00950542001-06-06 20:29:01 +0000305 bool Changed = false;
306 while (DoDCEPass(M)) Changed = true;
307 return Changed;
308}
309
Chris Lattner59b6b8e2002-01-21 23:17:48 +0000310bool DeadCodeElimination::RemoveUnusedGlobalValues(Module *Mod) {
Chris Lattneree7cb292001-07-28 17:51:49 +0000311 bool Changed = false;
Chris Lattner7e02b7e2001-06-30 04:36:40 +0000312
Chris Lattneree7cb292001-07-28 17:51:49 +0000313 for (Module::iterator MI = Mod->begin(); MI != Mod->end(); ) {
314 Method *Meth = *MI;
Chris Lattner5680ee62001-10-18 01:32:34 +0000315 if (Meth->isExternal() && Meth->use_size() == 0) {
316 // No references to prototype?
Chris Lattneree7cb292001-07-28 17:51:49 +0000317 //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
Chris Lattner5680ee62001-10-18 01:32:34 +0000320 Changed = true;
Chris Lattneree7cb292001-07-28 17:51:49 +0000321 } else {
322 ++MI; // Skip prototype in use.
323 }
324 }
325
Chris Lattner5680ee62001-10-18 01:32:34 +0000326 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
Chris Lattneree7cb292001-07-28 17:51:49 +0000339 return Changed;
Chris Lattner00950542001-06-06 20:29:01 +0000340}