blob: 720354a4dfee895aa45aceb043e7340f099e09c6 [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//
13// TODO: This should REALLY be recursive instead of iterative. Right now, we
14// scan linearly through values, removing unused ones as we go. The problem is
15// that this may cause other earlier values to become unused. To make sure that
16// we get them all, we iterate until things stop changing. Instead, when
17// removing a value, recheck all of its operands to see if they are now unused.
18// Piece of cake, and more efficient as well.
19//
20//===----------------------------------------------------------------------===//
21
22#include "llvm/Module.h"
23#include "llvm/Method.h"
24#include "llvm/BasicBlock.h"
25#include "llvm/iTerminators.h"
Chris Lattnerf155e132001-06-07 16:59:26 +000026#include "llvm/iOther.h"
Chris Lattner00950542001-06-06 20:29:01 +000027#include "llvm/Opt/AllOpts.h"
Chris Lattnerf155e132001-06-07 16:59:26 +000028#include "llvm/Assembly/Writer.h"
Chris Lattnerdac6dda2001-06-07 21:18:45 +000029#include "llvm/CFG.h"
Chris Lattner00950542001-06-06 20:29:01 +000030
31struct ConstPoolDCE {
32 enum { EndOffs = 0 };
33 static bool isDCEable(const Value *) { return true; }
34};
35
36struct BasicBlockDCE {
37 enum { EndOffs = 1 };
38 static bool isDCEable(const Instruction *I) {
39 return !I->hasSideEffects();
40 }
41};
42
Chris Lattnerf155e132001-06-07 16:59:26 +000043
Chris Lattner00950542001-06-06 20:29:01 +000044template<class ValueSubclass, class ItemParentType, class DCEController>
45static bool RemoveUnusedDefs(ValueHolder<ValueSubclass, ItemParentType> &Vals,
46 DCEController DCEControl) {
47 bool Changed = false;
48 typedef ValueHolder<ValueSubclass, ItemParentType> Container;
49
50 int Offset = DCEController::EndOffs;
51 for (Container::iterator DI = Vals.begin(); DI != Vals.end()-Offset; ) {
52 // Look for un"used" definitions...
53 if ((*DI)->use_empty() && DCEController::isDCEable(*DI)) {
54 // Bye bye
Chris Lattnerf155e132001-06-07 16:59:26 +000055 //cerr << "Removing: " << *DI;
Chris Lattner00950542001-06-06 20:29:01 +000056 delete Vals.remove(DI);
57 Changed = true;
58 } else {
59 DI++;
60 }
61 }
62 return Changed;
63}
64
Chris Lattnerf155e132001-06-07 16:59:26 +000065// RemoveSingularPHIs - This removes PHI nodes from basic blocks that have only
66// a single predecessor. This means that the PHI node must only have a single
67// RHS value and can be eliminated.
68//
69// This routine is very simple because we know that PHI nodes must be the first
70// things in a basic block, if they are present.
71//
72static bool RemoveSingularPHIs(BasicBlock *BB) {
Chris Lattnerdac6dda2001-06-07 21:18:45 +000073 pred_iterator PI(pred_begin(BB));
74 if (PI == pred_end(BB) || ++PI != pred_end(BB))
Chris Lattnerf155e132001-06-07 16:59:26 +000075 return false; // More than one predecessor...
76
77 Instruction *I = BB->getInstList().front();
78 if (I->getInstType() != Instruction::PHINode) return false; // No PHI nodes
79
Chris Lattneree976f32001-06-11 15:04:40 +000080 //cerr << "Killing PHIs from " << BB;
81 //cerr << "Pred #0 = " << *pred_begin(BB);
Chris Lattnerf155e132001-06-07 16:59:26 +000082
Chris Lattneree976f32001-06-11 15:04:40 +000083 //cerr << "Method == " << BB->getParent();
Chris Lattnerf155e132001-06-07 16:59:26 +000084
85 do {
86 PHINode *PN = (PHINode*)I;
Chris Lattneree976f32001-06-11 15:04:40 +000087 assert(PN->getOperand(2) == 0 && "PHI node should only have one value!");
Chris Lattnerf155e132001-06-07 16:59:26 +000088 Value *V = PN->getOperand(0);
89
90 PN->replaceAllUsesWith(V); // Replace PHI node with its single value.
91 delete BB->getInstList().remove(BB->getInstList().begin());
92
93 I = BB->getInstList().front();
94 } while (I->getInstType() == Instruction::PHINode);
95
96 return true; // Yes, we nuked at least one phi node
97}
Chris Lattner00950542001-06-06 20:29:01 +000098
99bool DoRemoveUnusedConstants(SymTabValue *S) {
100 bool Changed = false;
101 ConstantPool &CP = S->getConstantPool();
102 for (ConstantPool::plane_iterator PI = CP.begin(); PI != CP.end(); ++PI)
103 Changed |= RemoveUnusedDefs(**PI, ConstPoolDCE());
104 return Changed;
105}
106
Chris Lattner00950542001-06-06 20:29:01 +0000107static void ReplaceUsesWithConstant(Instruction *I) {
108 // Get the method level constant pool
109 ConstantPool &CP = I->getParent()->getParent()->getConstantPool();
110
111 ConstPoolVal *CPV = 0;
112 ConstantPool::PlaneType *P;
113 if (!CP.getPlane(I->getType(), P)) { // Does plane exist?
114 // Yes, is it empty?
115 if (!P->empty()) CPV = P->front();
116 }
117
118 if (CPV == 0) { // We don't have an existing constant to reuse. Just add one.
119 CPV = ConstPoolVal::getNullConstant(I->getType()); // Create a new constant
120
121 // Add the new value to the constant pool...
122 CP.insert(CPV);
123 }
124
125 // Make all users of this instruction reference the constant instead
126 I->replaceAllUsesWith(CPV);
127}
128
Chris Lattnerf155e132001-06-07 16:59:26 +0000129// RemovePredecessorFromBlock - This function is called when we are about
130// to remove a predecessor from a basic block. This function takes care of
131// removing the predecessor from the PHI nodes in BB so that after the pred
132// is removed, the number of PHI slots per bb is equal to the number of
133// predecessors.
134//
135static void RemovePredecessorFromBlock(BasicBlock *BB, BasicBlock *Pred) {
Chris Lattnerdac6dda2001-06-07 21:18:45 +0000136 pred_iterator PI(pred_begin(BB)), EI(pred_end(BB));
Chris Lattneree976f32001-06-11 15:04:40 +0000137 unsigned max_idx;
Chris Lattnerf155e132001-06-07 16:59:26 +0000138
Chris Lattneree976f32001-06-11 15:04:40 +0000139 //cerr << "RPFB: " << Pred << "From Block: " << BB;
Chris Lattnerf155e132001-06-07 16:59:26 +0000140
Chris Lattnerf155e132001-06-07 16:59:26 +0000141 // Loop over the rest of the predecssors until we run out, or until we find
142 // out that there are more than 2 predecessors.
Chris Lattneree976f32001-06-11 15:04:40 +0000143 for (max_idx = 0; PI != EI && max_idx < 3; ++PI, ++max_idx) /*empty*/;
Chris Lattnerf155e132001-06-07 16:59:26 +0000144
145 // If there are exactly two predecessors, then we want to nuke the PHI nodes
146 // altogether.
Chris Lattneree976f32001-06-11 15:04:40 +0000147 bool NukePHIs = max_idx == 2;
148 assert(max_idx != 0 && "PHI Node in block with 0 predecessors!?!?!");
Chris Lattnerf155e132001-06-07 16:59:26 +0000149
150 // Okay, now we know that we need to remove predecessor #pred_idx from all
151 // PHI nodes. Iterate over each PHI node fixing them up
152 BasicBlock::InstListType::iterator II(BB->getInstList().begin());
153 for (; (*II)->getInstType() == Instruction::PHINode; ++II) {
154 PHINode *PN = (PHINode*)*II;
Chris Lattneree976f32001-06-11 15:04:40 +0000155 PN->removeIncomingValue(BB);
Chris Lattnerf155e132001-06-07 16:59:26 +0000156
157 if (NukePHIs) { // Destroy the PHI altogether??
158 assert(PN->getOperand(1) == 0 && "PHI node should only have one value!");
159 Value *V = PN->getOperand(0);
160
161 PN->replaceAllUsesWith(V); // Replace PHI node with its single value.
162 delete BB->getInstList().remove(II);
163 }
164 }
165}
166
167// PropogatePredecessors - This gets "Succ" ready to have the predecessors from
168// "BB". This is a little tricky because "Succ" has PHI nodes, which need to
169// have extra slots added to them to hold the merge edges from BB's
170// predecessors.
171//
172// Assumption: BB is the single predecessor of Succ.
173//
174static void PropogatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) {
Chris Lattnerdac6dda2001-06-07 21:18:45 +0000175 assert(BB && Succ && *pred_begin(Succ) == BB && "BB is only pred of Succ" &&
176 ++pred_begin(Succ) == pred_end(Succ));
Chris Lattnerf155e132001-06-07 16:59:26 +0000177
178 // If there is more than one predecessor, and there are PHI nodes in
179 // the successor, then we need to add incoming edges for the PHI nodes
Chris Lattnerdac6dda2001-06-07 21:18:45 +0000180 pred_iterator PI(pred_begin(BB));
181 for (; PI != pred_end(BB); ++PI) {
Chris Lattnerf155e132001-06-07 16:59:26 +0000182 // TODO:
183 }
184}
185
Chris Lattner00950542001-06-06 20:29:01 +0000186static bool DoDCEPass(Method *M) {
Chris Lattner00950542001-06-06 20:29:01 +0000187 Method::BasicBlocksType &BBs = M->getBasicBlocks();
Chris Lattnerf155e132001-06-07 16:59:26 +0000188 Method::BasicBlocksType::iterator BBIt, BBEnd = BBs.end();
189 if (BBs.begin() == BBEnd) return false; // Nothing to do
Chris Lattner00950542001-06-06 20:29:01 +0000190 bool Changed = false;
191
192 // Loop through now and remove instructions that have no uses...
Chris Lattnerf155e132001-06-07 16:59:26 +0000193 for (BBIt = BBs.begin(); BBIt != BBEnd; BBIt++) {
Chris Lattner00950542001-06-06 20:29:01 +0000194 Changed |= RemoveUnusedDefs((*BBIt)->getInstList(), BasicBlockDCE());
Chris Lattnerf155e132001-06-07 16:59:26 +0000195 Changed |= RemoveSingularPHIs(*BBIt);
196 }
Chris Lattner00950542001-06-06 20:29:01 +0000197
Chris Lattnerf155e132001-06-07 16:59:26 +0000198 // Loop over all of the basic blocks (except the first one) and remove them
199 // if they are unneeded...
Chris Lattner00950542001-06-06 20:29:01 +0000200 //
Chris Lattnerf155e132001-06-07 16:59:26 +0000201 for (BBIt = BBs.begin(), ++BBIt; BBIt != BBs.end(); ++BBIt) {
Chris Lattner00950542001-06-06 20:29:01 +0000202 BasicBlock *BB = *BBIt;
Chris Lattnerf155e132001-06-07 16:59:26 +0000203 assert(BB->getTerminator() && "Degenerate basic block encountered!");
Chris Lattner00950542001-06-06 20:29:01 +0000204
Chris Lattnerf155e132001-06-07 16:59:26 +0000205#if 0
206 // Remove basic blocks that have no predecessors... which are unreachable.
Chris Lattnerdac6dda2001-06-07 21:18:45 +0000207 if (pred_begin(BB) == pred_end(BB) &&
Chris Lattnerf155e132001-06-07 16:59:26 +0000208 !BB->hasConstantPoolReferences() && 0) {
209 cerr << "Removing BB: \n" << BB;
210
211 // Loop through all of our successors and make sure they know that one
212 // of their predecessors is going away.
Chris Lattnerdac6dda2001-06-07 21:18:45 +0000213 for (succ_iterator SI = succ_begin(BB), EI = succ_end(BB); SI != EI; ++SI)
Chris Lattnerf155e132001-06-07 16:59:26 +0000214 RemovePredecessorFromBlock(*SI, BB);
Chris Lattner00950542001-06-06 20:29:01 +0000215
216 while (!BB->getInstList().empty()) {
217 Instruction *I = BB->getInstList().front();
218 // If this instruction is used, replace uses with an arbitrary
219 // constant value. Because control flow can't get here, we don't care
220 // what we replace the value with.
221 if (!I->use_empty()) ReplaceUsesWithConstant(I);
222
223 // Remove the instruction from the basic block
Chris Lattnerf155e132001-06-07 16:59:26 +0000224 delete BB->getInstList().remove(BB->getInstList().begin());
Chris Lattner00950542001-06-06 20:29:01 +0000225 }
Chris Lattner00950542001-06-06 20:29:01 +0000226 delete BBs.remove(BBIt);
Chris Lattnerf155e132001-06-07 16:59:26 +0000227 --BBIt; // remove puts use on the next block, we want the previous one
Chris Lattner00950542001-06-06 20:29:01 +0000228 Changed = true;
Chris Lattnerf155e132001-06-07 16:59:26 +0000229 continue;
230 }
231
232 // Check to see if this block has no instructions and only a single
233 // successor. If so, replace block references with successor.
Chris Lattnerdac6dda2001-06-07 21:18:45 +0000234 succ_iterator SI(succ_begin(BB));
235 if (SI != succ_end(BB) && ++SI == succ_end(BB)) { // One succ?
Chris Lattnerf155e132001-06-07 16:59:26 +0000236 Instruction *I = BB->getInstList().front();
237 if (I->isTerminator()) { // Terminator is the only instruction!
238
239 if (Succ->getInstList().front()->getInstType() == Instruction::PHINode){
240 // Add entries to the PHI nodes so that the PHI nodes have the right
241 // number of entries...
242 PropogatePredecessorsForPHIs(BB, Succ);
243 }
244
Chris Lattnerdac6dda2001-06-07 21:18:45 +0000245 BasicBlock *Succ = *succ_begin(BB); // There is exactly one successor
Chris Lattnerf155e132001-06-07 16:59:26 +0000246 BB->replaceAllUsesWith(Succ);
247 cerr << "Killing Trivial BB: \n" << BB;
248
249 BB = BBs.remove(BBIt);
250 --BBIt; // remove puts use on the next block, we want the previous one
251
252 if (BB->hasName() && !Succ->hasName()) // Transfer name if we can
253 Succ->setName(BB->getName());
254 delete BB; // Delete basic block
255
256 cerr << "Method after removal: \n" << M;
257 Changed = true;
258 continue;
259 }
Chris Lattner00950542001-06-06 20:29:01 +0000260 }
Chris Lattnerf155e132001-06-07 16:59:26 +0000261#endif
Chris Lattner00950542001-06-06 20:29:01 +0000262
Chris Lattnerf155e132001-06-07 16:59:26 +0000263 // Merge basic blocks into their predecessor if there is only one pred,
264 // and if there is only one successor of the predecessor.
Chris Lattnerdac6dda2001-06-07 21:18:45 +0000265 pred_iterator PI(pred_begin(BB));
266 if (PI != pred_end(BB) && *PI != BB && // Not empty? Not same BB?
267 ++PI == pred_end(BB) && !BB->hasConstantPoolReferences()) {
268 BasicBlock *Pred = *pred_begin(BB);
Chris Lattner00950542001-06-06 20:29:01 +0000269 TerminatorInst *Term = Pred->getTerminator();
Chris Lattnerf155e132001-06-07 16:59:26 +0000270 assert(Term != 0 && "malformed basic block without terminator!");
Chris Lattner00950542001-06-06 20:29:01 +0000271
Chris Lattnerf155e132001-06-07 16:59:26 +0000272 // Does the predecessor block only have a single successor?
Chris Lattnerdac6dda2001-06-07 21:18:45 +0000273 succ_iterator SI(succ_begin(Pred));
274 if (++SI == succ_end(Pred)) {
Chris Lattnerf155e132001-06-07 16:59:26 +0000275 //cerr << "Merging: " << BB << "into: " << Pred;
Chris Lattner00950542001-06-06 20:29:01 +0000276
Chris Lattnerf155e132001-06-07 16:59:26 +0000277 // Delete the unconditianal branch from the predecessor...
278 BasicBlock::InstListType::iterator DI = Pred->getInstList().end();
279 assert(Pred->getTerminator() &&
280 "Degenerate basic block encountered!"); // Empty bb???
Chris Lattneree976f32001-06-11 15:04:40 +0000281 delete Pred->getInstList().remove(--DI); // Destroy uncond branch
Chris Lattnerf155e132001-06-07 16:59:26 +0000282
283 // Move all definitions in the succecessor to the predecessor...
284 while (!BB->getInstList().empty()) {
285 DI = BB->getInstList().begin();
286 Instruction *Def = BB->getInstList().remove(DI); // Remove from front
287 Pred->getInstList().push_back(Def); // Add to end...
288 }
Chris Lattneree976f32001-06-11 15:04:40 +0000289
Chris Lattnerf155e132001-06-07 16:59:26 +0000290 // Remove basic block from the method... and advance iterator to the
291 // next valid block...
292 BB = BBs.remove(BBIt);
293 --BBIt; // remove puts us on the NEXT bb. We want the prev BB
294 Changed = true;
Chris Lattneree976f32001-06-11 15:04:40 +0000295
296 // Make all PHI nodes that refered to BB now refer to Pred as their
297 // source...
298 BB->replaceAllUsesWith(Pred);
Chris Lattnerf155e132001-06-07 16:59:26 +0000299
300 // Inherit predecessors name if it exists...
301 if (BB->hasName() && !Pred->hasName()) Pred->setName(BB->getName());
302
303 // You ARE the weakest link... goodbye
304 delete BB;
Chris Lattner00950542001-06-06 20:29:01 +0000305 }
Chris Lattner00950542001-06-06 20:29:01 +0000306 }
307 }
308
309 // Remove unused constants
310 Changed |= DoRemoveUnusedConstants(M);
311 return Changed;
312}
313
314
315// It is possible that we may require multiple passes over the code to fully
316// eliminate dead code. Iterate until we are done.
317//
318bool DoDeadCodeElimination(Method *M) {
319 bool Changed = false;
320 while (DoDCEPass(M)) Changed = true;
321 return Changed;
322}
323
324bool DoDeadCodeElimination(Module *C) {
325 bool Val = ApplyOptToAllMethods(C, DoDeadCodeElimination);
326 while (DoRemoveUnusedConstants(C)) Val = true;
327 return Val;
328}