blob: 71a7f5ae26b6f0dcacf5390953302c21c99ab5d8 [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
Chris Lattneredefaa12001-11-01 05:55:29 +000037static bool RemoveUnusedDefs(BasicBlock::InstListType &Vals) {
Chris Lattner00950542001-06-06 20:29:01 +000038 bool Changed = false;
Chris Lattneredefaa12001-11-01 05:55:29 +000039 for (BasicBlock::InstListType::iterator DI = Vals.begin();
40 DI != Vals.end()-1; ) {
Chris Lattner00950542001-06-06 20:29:01 +000041 // Look for un"used" definitions...
Chris Lattneredefaa12001-11-01 05:55:29 +000042 if ((*DI)->use_empty() && !(*DI)->hasSideEffects()) {
Chris Lattner00950542001-06-06 20:29:01 +000043 // Bye bye
Chris Lattnerf155e132001-06-07 16:59:26 +000044 //cerr << "Removing: " << *DI;
Chris Lattner00950542001-06-06 20:29:01 +000045 delete Vals.remove(DI);
46 Changed = true;
47 } else {
Chris Lattner7fc9fe32001-06-27 23:41:11 +000048 ++DI;
Chris Lattner00950542001-06-06 20:29:01 +000049 }
50 }
51 return Changed;
52}
53
Chris Lattnerf155e132001-06-07 16:59:26 +000054// RemoveSingularPHIs - This removes PHI nodes from basic blocks that have only
55// a single predecessor. This means that the PHI node must only have a single
56// RHS value and can be eliminated.
57//
58// This routine is very simple because we know that PHI nodes must be the first
59// things in a basic block, if they are present.
60//
61static bool RemoveSingularPHIs(BasicBlock *BB) {
Chris Lattnerf0604b82001-10-01 13:19:53 +000062 BasicBlock::pred_iterator PI(BB->pred_begin());
63 if (PI == BB->pred_end() || ++PI != BB->pred_end())
Chris Lattnerf155e132001-06-07 16:59:26 +000064 return false; // More than one predecessor...
65
Chris Lattner7fc9fe32001-06-27 23:41:11 +000066 Instruction *I = BB->front();
Chris Lattnerb00c5822001-10-02 03:41:24 +000067 if (!isa<PHINode>(I)) return false; // No PHI nodes
Chris Lattnerf155e132001-06-07 16:59:26 +000068
Chris Lattneree976f32001-06-11 15:04:40 +000069 //cerr << "Killing PHIs from " << BB;
Chris Lattnerf0604b82001-10-01 13:19:53 +000070 //cerr << "Pred #0 = " << *BB->pred_begin();
Chris Lattnerf155e132001-06-07 16:59:26 +000071
Chris Lattneree976f32001-06-11 15:04:40 +000072 //cerr << "Method == " << BB->getParent();
Chris Lattnerf155e132001-06-07 16:59:26 +000073
74 do {
Chris Lattnerb00c5822001-10-02 03:41:24 +000075 PHINode *PN = cast<PHINode>(I);
Chris Lattnerc8b25d42001-07-07 08:36:50 +000076 assert(PN->getNumOperands() == 2 && "PHI node should only have one value!");
Chris Lattnerf155e132001-06-07 16:59:26 +000077 Value *V = PN->getOperand(0);
78
79 PN->replaceAllUsesWith(V); // Replace PHI node with its single value.
Chris Lattner7fc9fe32001-06-27 23:41:11 +000080 delete BB->getInstList().remove(BB->begin());
Chris Lattnerf155e132001-06-07 16:59:26 +000081
Chris Lattner7fc9fe32001-06-27 23:41:11 +000082 I = BB->front();
Chris Lattnerb00c5822001-10-02 03:41:24 +000083 } while (isa<PHINode>(I));
Chris Lattnerf155e132001-06-07 16:59:26 +000084
85 return true; // Yes, we nuked at least one phi node
86}
Chris Lattner00950542001-06-06 20:29:01 +000087
Chris Lattner00950542001-06-06 20:29:01 +000088static void ReplaceUsesWithConstant(Instruction *I) {
Chris Lattner2f11a9d2001-09-07 16:42:08 +000089 ConstPoolVal *CPV = ConstPoolVal::getNullConstant(I->getType());
Chris Lattner00950542001-06-06 20:29:01 +000090
91 // Make all users of this instruction reference the constant instead
92 I->replaceAllUsesWith(CPV);
93}
94
Chris Lattnerf155e132001-06-07 16:59:26 +000095// PropogatePredecessors - This gets "Succ" ready to have the predecessors from
96// "BB". This is a little tricky because "Succ" has PHI nodes, which need to
97// have extra slots added to them to hold the merge edges from BB's
98// predecessors.
99//
100// Assumption: BB is the single predecessor of Succ.
101//
102static void PropogatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) {
Chris Lattnerb00c5822001-10-02 03:41:24 +0000103 assert(isa<PHINode>(Succ->front()) && "Only works on PHId BBs!");
Chris Lattnerf155e132001-06-07 16:59:26 +0000104
105 // If there is more than one predecessor, and there are PHI nodes in
106 // the successor, then we need to add incoming edges for the PHI nodes
Chris Lattner7fc9fe32001-06-27 23:41:11 +0000107 //
Chris Lattnerf0604b82001-10-01 13:19:53 +0000108 const vector<BasicBlock*> BBPreds(BB->pred_begin(), BB->pred_end());
Chris Lattner7fc9fe32001-06-27 23:41:11 +0000109
110 BasicBlock::iterator I = Succ->begin();
111 do { // Loop over all of the PHI nodes in the successor BB
Chris Lattnerb00c5822001-10-02 03:41:24 +0000112 PHINode *PN = cast<PHINode>(*I);
Chris Lattner7fc9fe32001-06-27 23:41:11 +0000113 Value *OldVal = PN->removeIncomingValue(BB);
114 assert(OldVal && "No entry in PHI for Pred BB!");
115
116 for (vector<BasicBlock*>::const_iterator PredI = BBPreds.begin(),
117 End = BBPreds.end(); PredI != End; ++PredI) {
118 // Add an incoming value for each of the new incoming values...
119 PN->addIncoming(OldVal, *PredI);
120 }
121
122 ++I;
Chris Lattnerb00c5822001-10-02 03:41:24 +0000123 } while (isa<PHINode>(*I));
Chris Lattnerf155e132001-06-07 16:59:26 +0000124}
125
Chris Lattner7e02b7e2001-06-30 04:36:40 +0000126
127// SimplifyCFG - This function is used to do simplification of a CFG. For
128// example, it adjusts branches to branches to eliminate the extra hop, it
129// eliminates unreachable basic blocks, and does other "peephole" optimization
130// of the CFG. It returns true if a modification was made, and returns an
131// iterator that designates the first element remaining after the block that
132// was deleted.
133//
134// WARNING: The entry node of a method may not be simplified.
135//
136bool opt::SimplifyCFG(Method::iterator &BBIt) {
Chris Lattner7e02b7e2001-06-30 04:36:40 +0000137 BasicBlock *BB = *BBIt;
138 Method *M = BB->getParent();
Chris Lattner2f11a9d2001-09-07 16:42:08 +0000139
140 assert(BB && BB->getParent() && "Block not embedded in method!");
Chris Lattner7e02b7e2001-06-30 04:36:40 +0000141 assert(BB->getTerminator() && "Degenerate basic block encountered!");
142 assert(BB->getParent()->front() != BB && "Can't Simplify entry block!");
143
Chris Lattner2f11a9d2001-09-07 16:42:08 +0000144
Chris Lattner7e02b7e2001-06-30 04:36:40 +0000145 // Remove basic blocks that have no predecessors... which are unreachable.
Chris Lattnerf0604b82001-10-01 13:19:53 +0000146 if (BB->pred_begin() == BB->pred_end() &&
Chris Lattner7e02b7e2001-06-30 04:36:40 +0000147 !BB->hasConstantPoolReferences()) {
148 //cerr << "Removing BB: \n" << BB;
149
150 // Loop through all of our successors and make sure they know that one
151 // of their predecessors is going away.
Chris Lattnerf0604b82001-10-01 13:19:53 +0000152 for_each(BB->succ_begin(), BB->succ_end(),
Chris Lattner7e02b7e2001-06-30 04:36:40 +0000153 std::bind2nd(std::mem_fun(&BasicBlock::removePredecessor), BB));
154
155 while (!BB->empty()) {
156 Instruction *I = BB->back();
157 // If this instruction is used, replace uses with an arbitrary
158 // constant value. Because control flow can't get here, we don't care
159 // what we replace the value with. Note that since this block is
160 // unreachable, and all values contained within it must dominate their
161 // uses, that all uses will eventually be removed.
162 if (!I->use_empty()) ReplaceUsesWithConstant(I);
163
164 // Remove the instruction from the basic block
165 delete BB->getInstList().pop_back();
166 }
167 delete M->getBasicBlocks().remove(BBIt);
168 return true;
Chris Lattner2f11a9d2001-09-07 16:42:08 +0000169 }
Chris Lattner7e02b7e2001-06-30 04:36:40 +0000170
171 // Check to see if this block has no instructions and only a single
172 // successor. If so, replace block references with successor.
Chris Lattnerf0604b82001-10-01 13:19:53 +0000173 BasicBlock::succ_iterator SI(BB->succ_begin());
174 if (SI != BB->succ_end() && ++SI == BB->succ_end()) { // One succ?
Chris Lattner7e02b7e2001-06-30 04:36:40 +0000175 Instruction *I = BB->front();
176 if (I->isTerminator()) { // Terminator is the only instruction!
Chris Lattnerf0604b82001-10-01 13:19:53 +0000177 BasicBlock *Succ = *BB->succ_begin(); // There is exactly one successor
Chris Lattner7e02b7e2001-06-30 04:36:40 +0000178 //cerr << "Killing Trivial BB: \n" << BB;
179
180 if (Succ != BB) { // Arg, don't hurt infinite loops!
Chris Lattnerb00c5822001-10-02 03:41:24 +0000181 if (isa<PHINode>(Succ->front())) {
Chris Lattner7e02b7e2001-06-30 04:36:40 +0000182 // If our successor has PHI nodes, then we need to update them to
183 // include entries for BB's predecessors, not for BB itself.
184 //
185 PropogatePredecessorsForPHIs(BB, Succ);
186 }
187
188 BB->replaceAllUsesWith(Succ);
189 BB = M->getBasicBlocks().remove(BBIt);
190
191 if (BB->hasName() && !Succ->hasName()) // Transfer name if we can
192 Succ->setName(BB->getName());
193 delete BB; // Delete basic block
194
195 //cerr << "Method after removal: \n" << M;
196 return true;
197 }
198 }
199 }
200
201 // Merge basic blocks into their predecessor if there is only one pred,
202 // and if there is only one successor of the predecessor.
Chris Lattnerf0604b82001-10-01 13:19:53 +0000203 BasicBlock::pred_iterator PI(BB->pred_begin());
204 if (PI != BB->pred_end() && *PI != BB && // Not empty? Not same BB?
205 ++PI == BB->pred_end() && !BB->hasConstantPoolReferences()) {
206 BasicBlock *Pred = *BB->pred_begin();
Chris Lattner7e02b7e2001-06-30 04:36:40 +0000207 TerminatorInst *Term = Pred->getTerminator();
208 assert(Term != 0 && "malformed basic block without terminator!");
209
210 // Does the predecessor block only have a single successor?
Chris Lattnerf0604b82001-10-01 13:19:53 +0000211 BasicBlock::succ_iterator SI(Pred->succ_begin());
212 if (++SI == Pred->succ_end()) {
Chris Lattner7e02b7e2001-06-30 04:36:40 +0000213 //cerr << "Merging: " << BB << "into: " << Pred;
214
215 // Delete the unconditianal branch from the predecessor...
216 BasicBlock::iterator DI = Pred->end();
217 assert(Pred->getTerminator() &&
218 "Degenerate basic block encountered!"); // Empty bb???
219 delete Pred->getInstList().remove(--DI); // Destroy uncond branch
220
221 // Move all definitions in the succecessor to the predecessor...
222 while (!BB->empty()) {
223 DI = BB->begin();
224 Instruction *Def = BB->getInstList().remove(DI); // Remove from front
225 Pred->getInstList().push_back(Def); // Add to end...
226 }
227
228 // Remove basic block from the method... and advance iterator to the
229 // next valid block...
230 BB = M->getBasicBlocks().remove(BBIt);
231
232 // Make all PHI nodes that refered to BB now refer to Pred as their
233 // source...
234 BB->replaceAllUsesWith(Pred);
235
236 // Inherit predecessors name if it exists...
237 if (BB->hasName() && !Pred->hasName()) Pred->setName(BB->getName());
238
239 delete BB; // You ARE the weakest link... goodbye
240 return true;
241 }
242 }
243
244 return false;
245}
246
Chris Lattner00950542001-06-06 20:29:01 +0000247static bool DoDCEPass(Method *M) {
Chris Lattner7fc9fe32001-06-27 23:41:11 +0000248 Method::iterator BBIt, BBEnd = M->end();
249 if (M->begin() == BBEnd) return false; // Nothing to do
Chris Lattner00950542001-06-06 20:29:01 +0000250 bool Changed = false;
251
252 // Loop through now and remove instructions that have no uses...
Chris Lattner7fc9fe32001-06-27 23:41:11 +0000253 for (BBIt = M->begin(); BBIt != BBEnd; ++BBIt) {
Chris Lattneredefaa12001-11-01 05:55:29 +0000254 Changed |= RemoveUnusedDefs((*BBIt)->getInstList());
Chris Lattnerf155e132001-06-07 16:59:26 +0000255 Changed |= RemoveSingularPHIs(*BBIt);
256 }
Chris Lattner00950542001-06-06 20:29:01 +0000257
Chris Lattnerf155e132001-06-07 16:59:26 +0000258 // Loop over all of the basic blocks (except the first one) and remove them
259 // if they are unneeded...
Chris Lattner00950542001-06-06 20:29:01 +0000260 //
Chris Lattner7e02b7e2001-06-30 04:36:40 +0000261 for (BBIt = M->begin(), ++BBIt; BBIt != M->end(); ) {
262 if (opt::SimplifyCFG(BBIt)) {
Chris Lattner00950542001-06-06 20:29:01 +0000263 Changed = true;
Chris Lattner7e02b7e2001-06-30 04:36:40 +0000264 } else {
265 ++BBIt;
Chris Lattner00950542001-06-06 20:29:01 +0000266 }
267 }
268
Chris Lattner2f11a9d2001-09-07 16:42:08 +0000269 return Changed;
Chris Lattner00950542001-06-06 20:29:01 +0000270}
271
272
273// It is possible that we may require multiple passes over the code to fully
274// eliminate dead code. Iterate until we are done.
275//
Chris Lattner5680ee62001-10-18 01:32:34 +0000276bool opt::DeadCodeElimination::doDCE(Method *M) {
Chris Lattner00950542001-06-06 20:29:01 +0000277 bool Changed = false;
278 while (DoDCEPass(M)) Changed = true;
279 return Changed;
280}
281
Chris Lattner5680ee62001-10-18 01:32:34 +0000282bool opt::DeadCodeElimination::RemoveUnusedGlobalValues(Module *Mod) {
Chris Lattneree7cb292001-07-28 17:51:49 +0000283 bool Changed = false;
Chris Lattner7e02b7e2001-06-30 04:36:40 +0000284
Chris Lattneree7cb292001-07-28 17:51:49 +0000285 for (Module::iterator MI = Mod->begin(); MI != Mod->end(); ) {
286 Method *Meth = *MI;
Chris Lattner5680ee62001-10-18 01:32:34 +0000287 if (Meth->isExternal() && Meth->use_size() == 0) {
288 // No references to prototype?
Chris Lattneree7cb292001-07-28 17:51:49 +0000289 //cerr << "Removing method proto: " << Meth->getName() << endl;
290 delete Mod->getMethodList().remove(MI); // Remove prototype
291 // Remove moves iterator to point to the next one automatically
Chris Lattner5680ee62001-10-18 01:32:34 +0000292 Changed = true;
Chris Lattneree7cb292001-07-28 17:51:49 +0000293 } else {
294 ++MI; // Skip prototype in use.
295 }
296 }
297
Chris Lattner5680ee62001-10-18 01:32:34 +0000298 for (Module::giterator GI = Mod->gbegin(); GI != Mod->gend(); ) {
299 GlobalVariable *GV = *GI;
300 if (!GV->hasInitializer() && GV->use_size() == 0) {
301 // No references to uninitialized global variable?
302 //cerr << "Removing global var: " << GV->getName() << endl;
303 delete Mod->getGlobalList().remove(GI);
304 // Remove moves iterator to point to the next one automatically
305 Changed = true;
306 } else {
307 ++GI;
308 }
309 }
310
Chris Lattneree7cb292001-07-28 17:51:49 +0000311 return Changed;
Chris Lattner00950542001-06-06 20:29:01 +0000312}