blob: 0d6f293cd06d8bd1e650de28ed788c2e50bc9dd8 [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 Lattnerf57b8452002-04-27 06:56:12 +000012// * Eliminates function 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 Lattner79df7c02002-03-26 18:01:55 +000029#include "llvm/Function.h"
Chris Lattner00950542001-06-06 20:29:01 +000030#include "llvm/BasicBlock.h"
31#include "llvm/iTerminators.h"
Chris Lattner7061dc52001-12-03 18:02:31 +000032#include "llvm/iPHINode.h"
Chris Lattner42a41272002-04-09 18:37:46 +000033#include "llvm/ConstantVals.h"
Chris Lattner455889a2002-02-12 22:39:50 +000034#include "llvm/Support/CFG.h"
Chris Lattnerbd0ef772002-02-26 21:46:54 +000035#include "llvm/Pass.h"
Chris Lattnercee8f9a2001-11-27 00:03:19 +000036#include "Support/STLExtras.h"
Chris Lattner25d17a52001-06-29 05:24:28 +000037#include <algorithm>
Chris Lattner00950542001-06-06 20:29:01 +000038
Chris Lattnera1f6e642001-11-01 07:00:27 +000039// dceInstruction - Inspect the instruction at *BBI and figure out if it's
40// [trivially] dead. If so, remove the instruction and update the iterator
41// to point to the instruction that immediately succeeded the original
42// instruction.
43//
Chris Lattnerbd0ef772002-02-26 21:46:54 +000044bool dceInstruction(BasicBlock::InstListType &BBIL,
45 BasicBlock::iterator &BBI) {
Chris Lattnera1f6e642001-11-01 07:00:27 +000046 // Look for un"used" definitions...
47 if ((*BBI)->use_empty() && !(*BBI)->hasSideEffects() &&
48 !isa<TerminatorInst>(*BBI)) {
49 delete BBIL.remove(BBI); // Bye bye
50 return true;
51 }
52 return false;
53}
54
55static inline bool RemoveUnusedDefs(BasicBlock::InstListType &Vals) {
Chris Lattner00950542001-06-06 20:29:01 +000056 bool Changed = false;
Chris Lattneredefaa12001-11-01 05:55:29 +000057 for (BasicBlock::InstListType::iterator DI = Vals.begin();
Chris Lattnera1f6e642001-11-01 07:00:27 +000058 DI != Vals.end(); )
Chris Lattnerbd0ef772002-02-26 21:46:54 +000059 if (dceInstruction(Vals, DI))
Chris Lattner00950542001-06-06 20:29:01 +000060 Changed = true;
Chris Lattnera1f6e642001-11-01 07:00:27 +000061 else
Chris Lattner7fc9fe32001-06-27 23:41:11 +000062 ++DI;
Chris Lattner00950542001-06-06 20:29:01 +000063 return Changed;
64}
65
Chris Lattnerbd0ef772002-02-26 21:46:54 +000066struct DeadInstElimination : public BasicBlockPass {
67 virtual bool runOnBasicBlock(BasicBlock *BB) {
68 return RemoveUnusedDefs(BB->getInstList());
69 }
70};
71
72Pass *createDeadInstEliminationPass() {
73 return new DeadInstElimination();
Chris Lattnerc560f882002-01-23 05:48:24 +000074}
75
Chris Lattnerf155e132001-06-07 16:59:26 +000076// RemoveSingularPHIs - This removes PHI nodes from basic blocks that have only
77// a single predecessor. This means that the PHI node must only have a single
78// RHS value and can be eliminated.
79//
80// This routine is very simple because we know that PHI nodes must be the first
81// things in a basic block, if they are present.
82//
83static bool RemoveSingularPHIs(BasicBlock *BB) {
Chris Lattner455889a2002-02-12 22:39:50 +000084 pred_iterator PI(pred_begin(BB));
85 if (PI == pred_end(BB) || ++PI != pred_end(BB))
Chris Lattnerf155e132001-06-07 16:59:26 +000086 return false; // More than one predecessor...
87
Chris Lattner7fc9fe32001-06-27 23:41:11 +000088 Instruction *I = BB->front();
Chris Lattnerb00c5822001-10-02 03:41:24 +000089 if (!isa<PHINode>(I)) return false; // No PHI nodes
Chris Lattnerf155e132001-06-07 16:59:26 +000090
Chris Lattneree976f32001-06-11 15:04:40 +000091 //cerr << "Killing PHIs from " << BB;
Chris Lattner455889a2002-02-12 22:39:50 +000092 //cerr << "Pred #0 = " << *pred_begin(BB);
Chris Lattnerf155e132001-06-07 16:59:26 +000093
Chris Lattner79df7c02002-03-26 18:01:55 +000094 //cerr << "Function == " << BB->getParent();
Chris Lattnerf155e132001-06-07 16:59:26 +000095
96 do {
Chris Lattnerb00c5822001-10-02 03:41:24 +000097 PHINode *PN = cast<PHINode>(I);
Chris Lattnerc8b25d42001-07-07 08:36:50 +000098 assert(PN->getNumOperands() == 2 && "PHI node should only have one value!");
Chris Lattnerf155e132001-06-07 16:59:26 +000099 Value *V = PN->getOperand(0);
100
101 PN->replaceAllUsesWith(V); // Replace PHI node with its single value.
Chris Lattner7fc9fe32001-06-27 23:41:11 +0000102 delete BB->getInstList().remove(BB->begin());
Chris Lattnerf155e132001-06-07 16:59:26 +0000103
Chris Lattner7fc9fe32001-06-27 23:41:11 +0000104 I = BB->front();
Chris Lattnerb00c5822001-10-02 03:41:24 +0000105 } while (isa<PHINode>(I));
Chris Lattnerf155e132001-06-07 16:59:26 +0000106
107 return true; // Yes, we nuked at least one phi node
108}
Chris Lattner00950542001-06-06 20:29:01 +0000109
Chris Lattner00950542001-06-06 20:29:01 +0000110static void ReplaceUsesWithConstant(Instruction *I) {
Chris Lattner00950542001-06-06 20:29:01 +0000111 // Make all users of this instruction reference the constant instead
Chris Lattner1a18b7c2002-04-27 02:25:14 +0000112 I->replaceAllUsesWith(Constant::getNullValue(I->getType()));
Chris Lattner00950542001-06-06 20:29:01 +0000113}
114
Chris Lattnerf155e132001-06-07 16:59:26 +0000115// PropogatePredecessors - This gets "Succ" ready to have the predecessors from
116// "BB". This is a little tricky because "Succ" has PHI nodes, which need to
117// have extra slots added to them to hold the merge edges from BB's
Chris Lattner081431a2001-11-03 21:30:22 +0000118// predecessors. This function returns true (failure) if the Succ BB already
119// has a predecessor that is a predecessor of BB.
Chris Lattnerf155e132001-06-07 16:59:26 +0000120//
Chris Lattner081431a2001-11-03 21:30:22 +0000121// Assumption: Succ is the single successor for BB.
Chris Lattnerf155e132001-06-07 16:59:26 +0000122//
Chris Lattner081431a2001-11-03 21:30:22 +0000123static bool PropogatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) {
Chris Lattner455889a2002-02-12 22:39:50 +0000124 assert(*succ_begin(BB) == Succ && "Succ is not successor of BB!");
Chris Lattnerb00c5822001-10-02 03:41:24 +0000125 assert(isa<PHINode>(Succ->front()) && "Only works on PHId BBs!");
Chris Lattnerf155e132001-06-07 16:59:26 +0000126
127 // If there is more than one predecessor, and there are PHI nodes in
128 // the successor, then we need to add incoming edges for the PHI nodes
Chris Lattner7fc9fe32001-06-27 23:41:11 +0000129 //
Chris Lattner455889a2002-02-12 22:39:50 +0000130 const std::vector<BasicBlock*> BBPreds(pred_begin(BB), pred_end(BB));
Chris Lattner7fc9fe32001-06-27 23:41:11 +0000131
Chris Lattner081431a2001-11-03 21:30:22 +0000132 // Check to see if one of the predecessors of BB is already a predecessor of
133 // Succ. If so, we cannot do the transformation!
134 //
Chris Lattner455889a2002-02-12 22:39:50 +0000135 for (pred_iterator PI = pred_begin(Succ), PE = pred_end(Succ);
136 PI != PE; ++PI) {
Chris Lattner081431a2001-11-03 21:30:22 +0000137 if (find(BBPreds.begin(), BBPreds.end(), *PI) != BBPreds.end())
138 return true;
139 }
140
Chris Lattner7fc9fe32001-06-27 23:41:11 +0000141 BasicBlock::iterator I = Succ->begin();
142 do { // Loop over all of the PHI nodes in the successor BB
Chris Lattnerb00c5822001-10-02 03:41:24 +0000143 PHINode *PN = cast<PHINode>(*I);
Chris Lattner7fc9fe32001-06-27 23:41:11 +0000144 Value *OldVal = PN->removeIncomingValue(BB);
145 assert(OldVal && "No entry in PHI for Pred BB!");
146
Chris Lattner697954c2002-01-20 22:54:45 +0000147 for (std::vector<BasicBlock*>::const_iterator PredI = BBPreds.begin(),
Chris Lattner7fc9fe32001-06-27 23:41:11 +0000148 End = BBPreds.end(); PredI != End; ++PredI) {
149 // Add an incoming value for each of the new incoming values...
150 PN->addIncoming(OldVal, *PredI);
151 }
152
153 ++I;
Chris Lattnerb00c5822001-10-02 03:41:24 +0000154 } while (isa<PHINode>(*I));
Chris Lattner081431a2001-11-03 21:30:22 +0000155 return false;
Chris Lattnerf155e132001-06-07 16:59:26 +0000156}
157
Chris Lattner7e02b7e2001-06-30 04:36:40 +0000158
159// SimplifyCFG - This function is used to do simplification of a CFG. For
160// example, it adjusts branches to branches to eliminate the extra hop, it
161// eliminates unreachable basic blocks, and does other "peephole" optimization
162// of the CFG. It returns true if a modification was made, and returns an
163// iterator that designates the first element remaining after the block that
164// was deleted.
165//
Chris Lattnerf57b8452002-04-27 06:56:12 +0000166// WARNING: The entry node of a function may not be simplified.
Chris Lattner7e02b7e2001-06-30 04:36:40 +0000167//
Chris Lattner79df7c02002-03-26 18:01:55 +0000168bool SimplifyCFG(Function::iterator &BBIt) {
Chris Lattner7e02b7e2001-06-30 04:36:40 +0000169 BasicBlock *BB = *BBIt;
Chris Lattner79df7c02002-03-26 18:01:55 +0000170 Function *M = BB->getParent();
Chris Lattner2f11a9d2001-09-07 16:42:08 +0000171
Chris Lattnerf57b8452002-04-27 06:56:12 +0000172 assert(BB && BB->getParent() && "Block not embedded in function!");
Chris Lattner7e02b7e2001-06-30 04:36:40 +0000173 assert(BB->getTerminator() && "Degenerate basic block encountered!");
174 assert(BB->getParent()->front() != BB && "Can't Simplify entry block!");
175
Chris Lattner2f11a9d2001-09-07 16:42:08 +0000176
Chris Lattner7e02b7e2001-06-30 04:36:40 +0000177 // Remove basic blocks that have no predecessors... which are unreachable.
Chris Lattner455889a2002-02-12 22:39:50 +0000178 if (pred_begin(BB) == pred_end(BB) &&
Chris Lattnere9bb2df2001-12-03 22:26:30 +0000179 !BB->hasConstantReferences()) {
Chris Lattner7e02b7e2001-06-30 04:36:40 +0000180 //cerr << "Removing BB: \n" << BB;
181
182 // Loop through all of our successors and make sure they know that one
183 // of their predecessors is going away.
Chris Lattner455889a2002-02-12 22:39:50 +0000184 for_each(succ_begin(BB), succ_end(BB),
Chris Lattner7e02b7e2001-06-30 04:36:40 +0000185 std::bind2nd(std::mem_fun(&BasicBlock::removePredecessor), BB));
186
187 while (!BB->empty()) {
188 Instruction *I = BB->back();
189 // If this instruction is used, replace uses with an arbitrary
190 // constant value. Because control flow can't get here, we don't care
191 // what we replace the value with. Note that since this block is
192 // unreachable, and all values contained within it must dominate their
193 // uses, that all uses will eventually be removed.
194 if (!I->use_empty()) ReplaceUsesWithConstant(I);
195
196 // Remove the instruction from the basic block
197 delete BB->getInstList().pop_back();
198 }
199 delete M->getBasicBlocks().remove(BBIt);
200 return true;
Chris Lattner2f11a9d2001-09-07 16:42:08 +0000201 }
Chris Lattner7e02b7e2001-06-30 04:36:40 +0000202
203 // Check to see if this block has no instructions and only a single
204 // successor. If so, replace block references with successor.
Chris Lattner455889a2002-02-12 22:39:50 +0000205 succ_iterator SI(succ_begin(BB));
206 if (SI != succ_end(BB) && ++SI == succ_end(BB)) { // One succ?
Chris Lattner081431a2001-11-03 21:30:22 +0000207 if (BB->front()->isTerminator()) { // Terminator is the only instruction!
Chris Lattner455889a2002-02-12 22:39:50 +0000208 BasicBlock *Succ = *succ_begin(BB); // There is exactly one successor
Chris Lattner7e02b7e2001-06-30 04:36:40 +0000209 //cerr << "Killing Trivial BB: \n" << BB;
210
211 if (Succ != BB) { // Arg, don't hurt infinite loops!
Chris Lattner081431a2001-11-03 21:30:22 +0000212 // If our successor has PHI nodes, then we need to update them to
213 // include entries for BB's predecessors, not for BB itself.
214 // Be careful though, if this transformation fails (returns true) then
215 // we cannot do this transformation!
216 //
217 if (!isa<PHINode>(Succ->front()) ||
218 !PropogatePredecessorsForPHIs(BB, Succ)) {
219
220 BB->replaceAllUsesWith(Succ);
221 BB = M->getBasicBlocks().remove(BBIt);
222
223 if (BB->hasName() && !Succ->hasName()) // Transfer name if we can
224 Succ->setName(BB->getName());
225 delete BB; // Delete basic block
226
Chris Lattner79df7c02002-03-26 18:01:55 +0000227 //cerr << "Function after removal: \n" << M;
Chris Lattner081431a2001-11-03 21:30:22 +0000228 return true;
Chris Lattner7e02b7e2001-06-30 04:36:40 +0000229 }
Chris Lattner7e02b7e2001-06-30 04:36:40 +0000230 }
231 }
232 }
233
234 // Merge basic blocks into their predecessor if there is only one pred,
235 // and if there is only one successor of the predecessor.
Chris Lattner455889a2002-02-12 22:39:50 +0000236 pred_iterator PI(pred_begin(BB));
237 if (PI != pred_end(BB) && *PI != BB && // Not empty? Not same BB?
238 ++PI == pred_end(BB) && !BB->hasConstantReferences()) {
239 BasicBlock *Pred = *pred_begin(BB);
Chris Lattner7e02b7e2001-06-30 04:36:40 +0000240 TerminatorInst *Term = Pred->getTerminator();
241 assert(Term != 0 && "malformed basic block without terminator!");
242
243 // Does the predecessor block only have a single successor?
Chris Lattner455889a2002-02-12 22:39:50 +0000244 succ_iterator SI(succ_begin(Pred));
245 if (++SI == succ_end(Pred)) {
Chris Lattner7e02b7e2001-06-30 04:36:40 +0000246 //cerr << "Merging: " << BB << "into: " << Pred;
247
248 // Delete the unconditianal branch from the predecessor...
249 BasicBlock::iterator DI = Pred->end();
250 assert(Pred->getTerminator() &&
251 "Degenerate basic block encountered!"); // Empty bb???
252 delete Pred->getInstList().remove(--DI); // Destroy uncond branch
253
254 // Move all definitions in the succecessor to the predecessor...
255 while (!BB->empty()) {
256 DI = BB->begin();
257 Instruction *Def = BB->getInstList().remove(DI); // Remove from front
258 Pred->getInstList().push_back(Def); // Add to end...
259 }
260
Chris Lattnerf57b8452002-04-27 06:56:12 +0000261 // Remove basic block from the function... and advance iterator to the
Chris Lattner7e02b7e2001-06-30 04:36:40 +0000262 // next valid block...
263 BB = M->getBasicBlocks().remove(BBIt);
264
265 // Make all PHI nodes that refered to BB now refer to Pred as their
266 // source...
267 BB->replaceAllUsesWith(Pred);
268
269 // Inherit predecessors name if it exists...
270 if (BB->hasName() && !Pred->hasName()) Pred->setName(BB->getName());
271
272 delete BB; // You ARE the weakest link... goodbye
273 return true;
274 }
275 }
276
277 return false;
278}
279
Chris Lattner79df7c02002-03-26 18:01:55 +0000280static bool DoDCEPass(Function *F) {
281 Function::iterator BBIt, BBEnd = F->end();
282 if (F->begin() == BBEnd) return false; // Nothing to do
Chris Lattner00950542001-06-06 20:29:01 +0000283 bool Changed = false;
284
285 // Loop through now and remove instructions that have no uses...
Chris Lattner79df7c02002-03-26 18:01:55 +0000286 for (BBIt = F->begin(); BBIt != BBEnd; ++BBIt) {
Chris Lattneredefaa12001-11-01 05:55:29 +0000287 Changed |= RemoveUnusedDefs((*BBIt)->getInstList());
Chris Lattnerf155e132001-06-07 16:59:26 +0000288 Changed |= RemoveSingularPHIs(*BBIt);
289 }
Chris Lattner00950542001-06-06 20:29:01 +0000290
Chris Lattnerf155e132001-06-07 16:59:26 +0000291 // Loop over all of the basic blocks (except the first one) and remove them
292 // if they are unneeded...
Chris Lattner00950542001-06-06 20:29:01 +0000293 //
Chris Lattner79df7c02002-03-26 18:01:55 +0000294 for (BBIt = F->begin(), ++BBIt; BBIt != F->end(); ) {
Chris Lattner59b6b8e2002-01-21 23:17:48 +0000295 if (SimplifyCFG(BBIt)) {
Chris Lattner00950542001-06-06 20:29:01 +0000296 Changed = true;
Chris Lattner7e02b7e2001-06-30 04:36:40 +0000297 } else {
298 ++BBIt;
Chris Lattner00950542001-06-06 20:29:01 +0000299 }
300 }
301
Chris Lattner2f11a9d2001-09-07 16:42:08 +0000302 return Changed;
Chris Lattner00950542001-06-06 20:29:01 +0000303}
304
Chris Lattnerbd0ef772002-02-26 21:46:54 +0000305// Remove unused global values - This removes unused global values of no
Chris Lattnerf57b8452002-04-27 06:56:12 +0000306// possible value. This currently includes unused function prototypes and
Chris Lattnerbd0ef772002-02-26 21:46:54 +0000307// unitialized global variables.
Chris Lattner00950542001-06-06 20:29:01 +0000308//
Chris Lattnerbd0ef772002-02-26 21:46:54 +0000309static bool 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(); ) {
Chris Lattner79df7c02002-03-26 18:01:55 +0000313 Function *Meth = *MI;
Chris Lattner5680ee62001-10-18 01:32:34 +0000314 if (Meth->isExternal() && Meth->use_size() == 0) {
315 // No references to prototype?
Chris Lattnerf57b8452002-04-27 06:56:12 +0000316 //cerr << "Removing function proto: " << Meth->getName() << endl;
Chris Lattner79df7c02002-03-26 18:01:55 +0000317 delete Mod->getFunctionList().remove(MI); // Remove prototype
Chris Lattneree7cb292001-07-28 17:51:49 +0000318 // 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}
Chris Lattnerbd0ef772002-02-26 21:46:54 +0000340
341namespace {
Chris Lattnerf57b8452002-04-27 06:56:12 +0000342 struct DeadCodeElimination : public FunctionPass {
Chris Lattnerbd0ef772002-02-26 21:46:54 +0000343
344 // Pass Interface...
345 virtual bool doInitialization(Module *M) {
346 return RemoveUnusedGlobalValues(M);
347 }
348
349 // It is possible that we may require multiple passes over the code to fully
350 // eliminate dead code. Iterate until we are done.
351 //
Chris Lattnerf57b8452002-04-27 06:56:12 +0000352 virtual bool runOnFunction(Function *F) {
Chris Lattnerbd0ef772002-02-26 21:46:54 +0000353 bool Changed = false;
Chris Lattner79df7c02002-03-26 18:01:55 +0000354 while (DoDCEPass(F)) Changed = true;
Chris Lattnerbd0ef772002-02-26 21:46:54 +0000355 return Changed;
356 }
357
358 virtual bool doFinalization(Module *M) {
359 return RemoveUnusedGlobalValues(M);
360 }
361 };
362}
363
364Pass *createDeadCodeEliminationPass() {
365 return new DeadCodeElimination();
366}