1 //===- DCE.cpp - Code to perform dead code elimination --------------------===//
3 // This file implements dead code elimination and basic block merging.
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.
10 // * Eliminates PHI nodes for basic blocks with a single predecessor
11 // * Eliminates a basic block that only contains an unconditional branch
12 // * Eliminates method prototypes that are not referenced
14 // 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
18 // removing a value, recheck all of its operands to see if they are now unused.
19 // Piece of cake, and more efficient as well.
21 // Note, this is not trivial, because we have to worry about invalidating
24 //===----------------------------------------------------------------------===//
26 #include "llvm/Optimizations/DCE.h"
27 #include "llvm/Support/STLExtras.h"
28 #include "llvm/Module.h"
29 #include "llvm/Method.h"
30 #include "llvm/BasicBlock.h"
31 #include "llvm/iTerminators.h"
32 #include "llvm/iOther.h"
33 #include "llvm/Assembly/Writer.h"
41 static bool isDCEable(const ConstPoolVal *CPV) {
42 // TODO: The bytecode writer requires that all used types are in the
43 // constant pool for the current method. This is messy and is really
45 return CPV->getType() != Type::TypeTy; // Don't DCE Type plane constants!
49 struct BasicBlockDCE {
51 static bool isDCEable(const Instruction *I) {
52 return !I->hasSideEffects();
57 template<class Container, class DCEController>
58 static bool RemoveUnusedDefs(Container &Vals, DCEController DCEControl) {
60 int Offset = DCEController::EndOffs;
62 for (typename Container::iterator DI = Vals.begin();
63 DI != Vals.end()-Offset; ) {
64 // Look for un"used" definitions...
65 if ((*DI)->use_empty() && DCEController::isDCEable(*DI)) {
67 //cerr << "Removing: " << *DI;
68 delete Vals.remove(DI);
77 // 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.
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.
84 static bool RemoveSingularPHIs(BasicBlock *BB) {
85 pred_iterator PI(pred_begin(BB));
86 if (PI == pred_end(BB) || ++PI != pred_end(BB))
87 return false; // More than one predecessor...
89 Instruction *I = BB->front();
90 if (!I->isPHINode()) return false; // No PHI nodes
92 //cerr << "Killing PHIs from " << BB;
93 //cerr << "Pred #0 = " << *pred_begin(BB);
95 //cerr << "Method == " << BB->getParent();
98 PHINode *PN = (PHINode*)I;
99 assert(PN->getNumOperands() == 2 && "PHI node should only have one value!");
100 Value *V = PN->getOperand(0);
102 PN->replaceAllUsesWith(V); // Replace PHI node with its single value.
103 delete BB->getInstList().remove(BB->begin());
106 } while (I->isPHINode());
108 return true; // Yes, we nuked at least one phi node
111 static void ReplaceUsesWithConstant(Instruction *I) {
112 ConstPoolVal *CPV = ConstPoolVal::getNullConstant(I->getType());
114 // Make all users of this instruction reference the constant instead
115 I->replaceAllUsesWith(CPV);
118 // PropogatePredecessors - This gets "Succ" ready to have the predecessors from
119 // "BB". This is a little tricky because "Succ" has PHI nodes, which need to
120 // have extra slots added to them to hold the merge edges from BB's
123 // Assumption: BB is the single predecessor of Succ.
125 static void PropogatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) {
126 assert(Succ->front()->isPHINode() && "Only works on PHId BBs!");
128 // If there is more than one predecessor, and there are PHI nodes in
129 // the successor, then we need to add incoming edges for the PHI nodes
131 const vector<BasicBlock*> BBPreds(pred_begin(BB), pred_end(BB));
133 BasicBlock::iterator I = Succ->begin();
134 do { // Loop over all of the PHI nodes in the successor BB
135 PHINode *PN = (PHINode*)*I;
136 Value *OldVal = PN->removeIncomingValue(BB);
137 assert(OldVal && "No entry in PHI for Pred BB!");
139 for (vector<BasicBlock*>::const_iterator PredI = BBPreds.begin(),
140 End = BBPreds.end(); PredI != End; ++PredI) {
141 // Add an incoming value for each of the new incoming values...
142 PN->addIncoming(OldVal, *PredI);
146 } while ((*I)->isPHINode());
150 // SimplifyCFG - This function is used to do simplification of a CFG. For
151 // example, it adjusts branches to branches to eliminate the extra hop, it
152 // eliminates unreachable basic blocks, and does other "peephole" optimization
153 // of the CFG. It returns true if a modification was made, and returns an
154 // iterator that designates the first element remaining after the block that
157 // WARNING: The entry node of a method may not be simplified.
159 bool opt::SimplifyCFG(Method::iterator &BBIt) {
160 BasicBlock *BB = *BBIt;
161 Method *M = BB->getParent();
163 assert(BB && BB->getParent() && "Block not embedded in method!");
164 assert(BB->getTerminator() && "Degenerate basic block encountered!");
165 assert(BB->getParent()->front() != BB && "Can't Simplify entry block!");
168 // Remove basic blocks that have no predecessors... which are unreachable.
169 if (pred_begin(BB) == pred_end(BB) &&
170 !BB->hasConstantPoolReferences()) {
171 //cerr << "Removing BB: \n" << BB;
173 // Loop through all of our successors and make sure they know that one
174 // of their predecessors is going away.
175 for_each(succ_begin(BB), succ_end(BB),
176 std::bind2nd(std::mem_fun(&BasicBlock::removePredecessor), BB));
178 while (!BB->empty()) {
179 Instruction *I = BB->back();
180 // If this instruction is used, replace uses with an arbitrary
181 // constant value. Because control flow can't get here, we don't care
182 // what we replace the value with. Note that since this block is
183 // unreachable, and all values contained within it must dominate their
184 // uses, that all uses will eventually be removed.
185 if (!I->use_empty()) ReplaceUsesWithConstant(I);
187 // Remove the instruction from the basic block
188 delete BB->getInstList().pop_back();
190 delete M->getBasicBlocks().remove(BBIt);
194 // Check to see if this block has no instructions and only a single
195 // successor. If so, replace block references with successor.
196 succ_iterator SI(succ_begin(BB));
197 if (SI != succ_end(BB) && ++SI == succ_end(BB)) { // One succ?
198 Instruction *I = BB->front();
199 if (I->isTerminator()) { // Terminator is the only instruction!
200 BasicBlock *Succ = *succ_begin(BB); // There is exactly one successor
201 //cerr << "Killing Trivial BB: \n" << BB;
203 if (Succ != BB) { // Arg, don't hurt infinite loops!
204 if (Succ->front()->isPHINode()) {
205 // If our successor has PHI nodes, then we need to update them to
206 // include entries for BB's predecessors, not for BB itself.
208 PropogatePredecessorsForPHIs(BB, Succ);
211 BB->replaceAllUsesWith(Succ);
212 BB = M->getBasicBlocks().remove(BBIt);
214 if (BB->hasName() && !Succ->hasName()) // Transfer name if we can
215 Succ->setName(BB->getName());
216 delete BB; // Delete basic block
218 //cerr << "Method after removal: \n" << M;
224 // Merge basic blocks into their predecessor if there is only one pred,
225 // and if there is only one successor of the predecessor.
226 pred_iterator PI(pred_begin(BB));
227 if (PI != pred_end(BB) && *PI != BB && // Not empty? Not same BB?
228 ++PI == pred_end(BB) && !BB->hasConstantPoolReferences()) {
229 BasicBlock *Pred = *pred_begin(BB);
230 TerminatorInst *Term = Pred->getTerminator();
231 assert(Term != 0 && "malformed basic block without terminator!");
233 // Does the predecessor block only have a single successor?
234 succ_iterator SI(succ_begin(Pred));
235 if (++SI == succ_end(Pred)) {
236 //cerr << "Merging: " << BB << "into: " << Pred;
238 // Delete the unconditianal branch from the predecessor...
239 BasicBlock::iterator DI = Pred->end();
240 assert(Pred->getTerminator() &&
241 "Degenerate basic block encountered!"); // Empty bb???
242 delete Pred->getInstList().remove(--DI); // Destroy uncond branch
244 // Move all definitions in the succecessor to the predecessor...
245 while (!BB->empty()) {
247 Instruction *Def = BB->getInstList().remove(DI); // Remove from front
248 Pred->getInstList().push_back(Def); // Add to end...
251 // Remove basic block from the method... and advance iterator to the
252 // next valid block...
253 BB = M->getBasicBlocks().remove(BBIt);
255 // Make all PHI nodes that refered to BB now refer to Pred as their
257 BB->replaceAllUsesWith(Pred);
259 // Inherit predecessors name if it exists...
260 if (BB->hasName() && !Pred->hasName()) Pred->setName(BB->getName());
262 delete BB; // You ARE the weakest link... goodbye
270 static bool DoDCEPass(Method *M) {
271 Method::iterator BBIt, BBEnd = M->end();
272 if (M->begin() == BBEnd) return false; // Nothing to do
273 bool Changed = false;
275 // Loop through now and remove instructions that have no uses...
276 for (BBIt = M->begin(); BBIt != BBEnd; ++BBIt) {
277 Changed |= RemoveUnusedDefs((*BBIt)->getInstList(), BasicBlockDCE());
278 Changed |= RemoveSingularPHIs(*BBIt);
281 // Loop over all of the basic blocks (except the first one) and remove them
282 // if they are unneeded...
284 for (BBIt = M->begin(), ++BBIt; BBIt != M->end(); ) {
285 if (opt::SimplifyCFG(BBIt)) {
296 // It is possible that we may require multiple passes over the code to fully
297 // eliminate dead code. Iterate until we are done.
299 bool opt::DoDeadCodeElimination(Method *M) {
300 bool Changed = false;
301 while (DoDCEPass(M)) Changed = true;
305 bool opt::DoDeadCodeElimination(Module *Mod) {
306 bool Changed = false;
308 for (Module::iterator MI = Mod->begin(); MI != Mod->end(); ) {
310 if (!Meth->isExternal()) { // DCE normal methods
311 Changed |= DoDeadCodeElimination(Meth);
312 ++MI; // Next method please
313 } else if (Meth->use_size() == 0) { // No references to prototype?
314 //cerr << "Removing method proto: " << Meth->getName() << endl;
315 delete Mod->getMethodList().remove(MI); // Remove prototype
316 // Remove moves iterator to point to the next one automatically
318 ++MI; // Skip prototype in use.