blob: f1582d3346b0802bf40a2fb4e17e9b9d9972ed30 [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 Lattner00950542001-06-06 20:29:01 +000012//
Chris Lattner25d17a52001-06-29 05:24:28 +000013// TODO: This should REALLY be worklist driven instead of iterative. Right now,
14// we scan linearly through values, removing unused ones as we go. The problem
15// is that this may cause other earlier values to become unused. To make sure
16// that we get them all, we iterate until things stop changing. Instead, when
Chris Lattner00950542001-06-06 20:29:01 +000017// removing a value, recheck all of its operands to see if they are now unused.
Chris Lattnerd36c91c2001-06-13 19:55:22 +000018// Piece of cake, and more efficient as well.
19//
20// Note, this is not trivial, because we have to worry about invalidating
21// iterators. :(
Chris Lattner00950542001-06-06 20:29:01 +000022//
23//===----------------------------------------------------------------------===//
24
Chris Lattner7e02b7e2001-06-30 04:36:40 +000025#include "llvm/Optimizations/DCE.h"
26#include "llvm/Tools/STLExtras.h"
Chris Lattner00950542001-06-06 20:29:01 +000027#include "llvm/Module.h"
28#include "llvm/Method.h"
29#include "llvm/BasicBlock.h"
30#include "llvm/iTerminators.h"
Chris Lattnerf155e132001-06-07 16:59:26 +000031#include "llvm/iOther.h"
Chris Lattnerf155e132001-06-07 16:59:26 +000032#include "llvm/Assembly/Writer.h"
Chris Lattnerdac6dda2001-06-07 21:18:45 +000033#include "llvm/CFG.h"
Chris Lattner25d17a52001-06-29 05:24:28 +000034#include <algorithm>
Chris Lattner00950542001-06-06 20:29:01 +000035
Chris Lattnerd36c91c2001-06-13 19:55:22 +000036using namespace cfg;
37
Chris Lattner00950542001-06-06 20:29:01 +000038struct ConstPoolDCE {
39 enum { EndOffs = 0 };
Chris Lattnerc262f722001-07-09 19:38:52 +000040 static bool isDCEable(const ConstPoolVal *CPV) {
41 // TODO: The bytecode writer requires that all used types are in the
42 // constant pool for the current method. This is messy and is really
43 // irritating. FIXME
44 return CPV->getType() != Type::TypeTy; // Don't DCE Type plane constants!
45 }
Chris Lattner00950542001-06-06 20:29:01 +000046};
47
48struct BasicBlockDCE {
49 enum { EndOffs = 1 };
50 static bool isDCEable(const Instruction *I) {
51 return !I->hasSideEffects();
52 }
53};
54
Chris Lattnerf155e132001-06-07 16:59:26 +000055
Chris Lattner00950542001-06-06 20:29:01 +000056template<class ValueSubclass, class ItemParentType, class DCEController>
57static bool RemoveUnusedDefs(ValueHolder<ValueSubclass, ItemParentType> &Vals,
58 DCEController DCEControl) {
59 bool Changed = false;
60 typedef ValueHolder<ValueSubclass, ItemParentType> Container;
61
62 int Offset = DCEController::EndOffs;
63 for (Container::iterator DI = Vals.begin(); DI != Vals.end()-Offset; ) {
64 // Look for un"used" definitions...
65 if ((*DI)->use_empty() && DCEController::isDCEable(*DI)) {
66 // Bye bye
Chris Lattnerf155e132001-06-07 16:59:26 +000067 //cerr << "Removing: " << *DI;
Chris Lattner00950542001-06-06 20:29:01 +000068 delete Vals.remove(DI);
69 Changed = true;
70 } else {
Chris Lattner7fc9fe32001-06-27 23:41:11 +000071 ++DI;
Chris Lattner00950542001-06-06 20:29:01 +000072 }
73 }
74 return Changed;
75}
76
Chris Lattnerf155e132001-06-07 16:59:26 +000077// RemoveSingularPHIs - This removes PHI nodes from basic blocks that have only
78// a single predecessor. This means that the PHI node must only have a single
79// RHS value and can be eliminated.
80//
81// This routine is very simple because we know that PHI nodes must be the first
82// things in a basic block, if they are present.
83//
84static bool RemoveSingularPHIs(BasicBlock *BB) {
Chris Lattnerdac6dda2001-06-07 21:18:45 +000085 pred_iterator PI(pred_begin(BB));
86 if (PI == pred_end(BB) || ++PI != pred_end(BB))
Chris Lattnerf155e132001-06-07 16:59:26 +000087 return false; // More than one predecessor...
88
Chris Lattner7fc9fe32001-06-27 23:41:11 +000089 Instruction *I = BB->front();
90 if (!I->isPHINode()) return false; // No PHI nodes
Chris Lattnerf155e132001-06-07 16:59:26 +000091
Chris Lattneree976f32001-06-11 15:04:40 +000092 //cerr << "Killing PHIs from " << BB;
93 //cerr << "Pred #0 = " << *pred_begin(BB);
Chris Lattnerf155e132001-06-07 16:59:26 +000094
Chris Lattneree976f32001-06-11 15:04:40 +000095 //cerr << "Method == " << BB->getParent();
Chris Lattnerf155e132001-06-07 16:59:26 +000096
97 do {
98 PHINode *PN = (PHINode*)I;
Chris Lattnerc8b25d42001-07-07 08:36:50 +000099 assert(PN->getNumOperands() == 2 && "PHI node should only have one value!");
Chris Lattnerf155e132001-06-07 16:59:26 +0000100 Value *V = PN->getOperand(0);
101
102 PN->replaceAllUsesWith(V); // Replace PHI node with its single value.
Chris Lattner7fc9fe32001-06-27 23:41:11 +0000103 delete BB->getInstList().remove(BB->begin());
Chris Lattnerf155e132001-06-07 16:59:26 +0000104
Chris Lattner7fc9fe32001-06-27 23:41:11 +0000105 I = BB->front();
106 } while (I->isPHINode());
Chris Lattnerf155e132001-06-07 16:59:26 +0000107
108 return true; // Yes, we nuked at least one phi node
109}
Chris Lattner00950542001-06-06 20:29:01 +0000110
Chris Lattner7e02b7e2001-06-30 04:36:40 +0000111bool opt::DoRemoveUnusedConstants(SymTabValue *S) {
Chris Lattner00950542001-06-06 20:29:01 +0000112 bool Changed = false;
113 ConstantPool &CP = S->getConstantPool();
114 for (ConstantPool::plane_iterator PI = CP.begin(); PI != CP.end(); ++PI)
115 Changed |= RemoveUnusedDefs(**PI, ConstPoolDCE());
116 return Changed;
117}
118
Chris Lattner00950542001-06-06 20:29:01 +0000119static void ReplaceUsesWithConstant(Instruction *I) {
120 // Get the method level constant pool
121 ConstantPool &CP = I->getParent()->getParent()->getConstantPool();
122
123 ConstPoolVal *CPV = 0;
124 ConstantPool::PlaneType *P;
125 if (!CP.getPlane(I->getType(), P)) { // Does plane exist?
126 // Yes, is it empty?
127 if (!P->empty()) CPV = P->front();
128 }
129
130 if (CPV == 0) { // We don't have an existing constant to reuse. Just add one.
131 CPV = ConstPoolVal::getNullConstant(I->getType()); // Create a new constant
132
133 // Add the new value to the constant pool...
134 CP.insert(CPV);
135 }
136
137 // Make all users of this instruction reference the constant instead
138 I->replaceAllUsesWith(CPV);
139}
140
Chris Lattnerf155e132001-06-07 16:59:26 +0000141// PropogatePredecessors - This gets "Succ" ready to have the predecessors from
142// "BB". This is a little tricky because "Succ" has PHI nodes, which need to
143// have extra slots added to them to hold the merge edges from BB's
144// predecessors.
145//
146// Assumption: BB is the single predecessor of Succ.
147//
148static void PropogatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) {
Chris Lattner7fc9fe32001-06-27 23:41:11 +0000149 assert(Succ->front()->isPHINode() && "Only works on PHId BBs!");
Chris Lattnerf155e132001-06-07 16:59:26 +0000150
151 // If there is more than one predecessor, and there are PHI nodes in
152 // the successor, then we need to add incoming edges for the PHI nodes
Chris Lattner7fc9fe32001-06-27 23:41:11 +0000153 //
154 const vector<BasicBlock*> BBPreds(pred_begin(BB), pred_end(BB));
155
156 BasicBlock::iterator I = Succ->begin();
157 do { // Loop over all of the PHI nodes in the successor BB
158 PHINode *PN = (PHINode*)*I;
159 Value *OldVal = PN->removeIncomingValue(BB);
160 assert(OldVal && "No entry in PHI for Pred BB!");
161
162 for (vector<BasicBlock*>::const_iterator PredI = BBPreds.begin(),
163 End = BBPreds.end(); PredI != End; ++PredI) {
164 // Add an incoming value for each of the new incoming values...
165 PN->addIncoming(OldVal, *PredI);
166 }
167
168 ++I;
169 } while ((*I)->isPHINode());
Chris Lattnerf155e132001-06-07 16:59:26 +0000170}
171
Chris Lattner7e02b7e2001-06-30 04:36:40 +0000172
173// SimplifyCFG - This function is used to do simplification of a CFG. For
174// example, it adjusts branches to branches to eliminate the extra hop, it
175// eliminates unreachable basic blocks, and does other "peephole" optimization
176// of the CFG. It returns true if a modification was made, and returns an
177// iterator that designates the first element remaining after the block that
178// was deleted.
179//
180// WARNING: The entry node of a method may not be simplified.
181//
182bool opt::SimplifyCFG(Method::iterator &BBIt) {
183 assert(*BBIt && (*BBIt)->getParent() && "Block not embedded in method!");
184 BasicBlock *BB = *BBIt;
185 Method *M = BB->getParent();
186 assert(BB->getTerminator() && "Degenerate basic block encountered!");
187 assert(BB->getParent()->front() != BB && "Can't Simplify entry block!");
188
189 // Remove basic blocks that have no predecessors... which are unreachable.
190 if (pred_begin(BB) == pred_end(BB) &&
191 !BB->hasConstantPoolReferences()) {
192 //cerr << "Removing BB: \n" << BB;
193
194 // Loop through all of our successors and make sure they know that one
195 // of their predecessors is going away.
196 for_each(succ_begin(BB), succ_end(BB),
197 std::bind2nd(std::mem_fun(&BasicBlock::removePredecessor), BB));
198
199 while (!BB->empty()) {
200 Instruction *I = BB->back();
201 // If this instruction is used, replace uses with an arbitrary
202 // constant value. Because control flow can't get here, we don't care
203 // what we replace the value with. Note that since this block is
204 // unreachable, and all values contained within it must dominate their
205 // uses, that all uses will eventually be removed.
206 if (!I->use_empty()) ReplaceUsesWithConstant(I);
207
208 // Remove the instruction from the basic block
209 delete BB->getInstList().pop_back();
210 }
211 delete M->getBasicBlocks().remove(BBIt);
212 return true;
213 }
214
215 // Check to see if this block has no instructions and only a single
216 // successor. If so, replace block references with successor.
217 succ_iterator SI(succ_begin(BB));
218 if (SI != succ_end(BB) && ++SI == succ_end(BB)) { // One succ?
219 Instruction *I = BB->front();
220 if (I->isTerminator()) { // Terminator is the only instruction!
221 BasicBlock *Succ = *succ_begin(BB); // There is exactly one successor
222 //cerr << "Killing Trivial BB: \n" << BB;
223
224 if (Succ != BB) { // Arg, don't hurt infinite loops!
225 if (Succ->front()->isPHINode()) {
226 // If our successor has PHI nodes, then we need to update them to
227 // include entries for BB's predecessors, not for BB itself.
228 //
229 PropogatePredecessorsForPHIs(BB, Succ);
230 }
231
232 BB->replaceAllUsesWith(Succ);
233 BB = M->getBasicBlocks().remove(BBIt);
234
235 if (BB->hasName() && !Succ->hasName()) // Transfer name if we can
236 Succ->setName(BB->getName());
237 delete BB; // Delete basic block
238
239 //cerr << "Method after removal: \n" << M;
240 return true;
241 }
242 }
243 }
244
245 // Merge basic blocks into their predecessor if there is only one pred,
246 // and if there is only one successor of the predecessor.
247 pred_iterator PI(pred_begin(BB));
248 if (PI != pred_end(BB) && *PI != BB && // Not empty? Not same BB?
249 ++PI == pred_end(BB) && !BB->hasConstantPoolReferences()) {
250 BasicBlock *Pred = *pred_begin(BB);
251 TerminatorInst *Term = Pred->getTerminator();
252 assert(Term != 0 && "malformed basic block without terminator!");
253
254 // Does the predecessor block only have a single successor?
255 succ_iterator SI(succ_begin(Pred));
256 if (++SI == succ_end(Pred)) {
257 //cerr << "Merging: " << BB << "into: " << Pred;
258
259 // Delete the unconditianal branch from the predecessor...
260 BasicBlock::iterator DI = Pred->end();
261 assert(Pred->getTerminator() &&
262 "Degenerate basic block encountered!"); // Empty bb???
263 delete Pred->getInstList().remove(--DI); // Destroy uncond branch
264
265 // Move all definitions in the succecessor to the predecessor...
266 while (!BB->empty()) {
267 DI = BB->begin();
268 Instruction *Def = BB->getInstList().remove(DI); // Remove from front
269 Pred->getInstList().push_back(Def); // Add to end...
270 }
271
272 // Remove basic block from the method... and advance iterator to the
273 // next valid block...
274 BB = M->getBasicBlocks().remove(BBIt);
275
276 // Make all PHI nodes that refered to BB now refer to Pred as their
277 // source...
278 BB->replaceAllUsesWith(Pred);
279
280 // Inherit predecessors name if it exists...
281 if (BB->hasName() && !Pred->hasName()) Pred->setName(BB->getName());
282
283 delete BB; // You ARE the weakest link... goodbye
284 return true;
285 }
286 }
287
288 return false;
289}
290
Chris Lattner00950542001-06-06 20:29:01 +0000291static bool DoDCEPass(Method *M) {
Chris Lattner7fc9fe32001-06-27 23:41:11 +0000292 Method::iterator BBIt, BBEnd = M->end();
293 if (M->begin() == BBEnd) return false; // Nothing to do
Chris Lattner00950542001-06-06 20:29:01 +0000294 bool Changed = false;
295
296 // Loop through now and remove instructions that have no uses...
Chris Lattner7fc9fe32001-06-27 23:41:11 +0000297 for (BBIt = M->begin(); BBIt != BBEnd; ++BBIt) {
Chris Lattner00950542001-06-06 20:29:01 +0000298 Changed |= RemoveUnusedDefs((*BBIt)->getInstList(), BasicBlockDCE());
Chris Lattnerf155e132001-06-07 16:59:26 +0000299 Changed |= RemoveSingularPHIs(*BBIt);
300 }
Chris Lattner00950542001-06-06 20:29:01 +0000301
Chris Lattnerf155e132001-06-07 16:59:26 +0000302 // Loop over all of the basic blocks (except the first one) and remove them
303 // if they are unneeded...
Chris Lattner00950542001-06-06 20:29:01 +0000304 //
Chris Lattner7e02b7e2001-06-30 04:36:40 +0000305 for (BBIt = M->begin(), ++BBIt; BBIt != M->end(); ) {
306 if (opt::SimplifyCFG(BBIt)) {
Chris Lattner00950542001-06-06 20:29:01 +0000307 Changed = true;
Chris Lattner7e02b7e2001-06-30 04:36:40 +0000308 } else {
309 ++BBIt;
Chris Lattner00950542001-06-06 20:29:01 +0000310 }
311 }
312
313 // Remove unused constants
Chris Lattner7e02b7e2001-06-30 04:36:40 +0000314 return Changed | opt::DoRemoveUnusedConstants(M);
Chris Lattner00950542001-06-06 20:29:01 +0000315}
316
317
318// It is possible that we may require multiple passes over the code to fully
319// eliminate dead code. Iterate until we are done.
320//
Chris Lattner7e02b7e2001-06-30 04:36:40 +0000321bool opt::DoDeadCodeElimination(Method *M) {
Chris Lattner00950542001-06-06 20:29:01 +0000322 bool Changed = false;
323 while (DoDCEPass(M)) Changed = true;
324 return Changed;
325}
326
Chris Lattner7e02b7e2001-06-30 04:36:40 +0000327bool opt::DoDeadCodeElimination(Module *C) {
328 bool Val = C->reduceApply(DoDeadCodeElimination);
329
Chris Lattner00950542001-06-06 20:29:01 +0000330 while (DoRemoveUnusedConstants(C)) Val = true;
331 return Val;
332}