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
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 function 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/Transforms/Scalar/DCE.h"
27 #include "llvm/Module.h"
28 #include "llvm/GlobalVariable.h"
29 #include "llvm/iTerminators.h"
30 #include "llvm/iPHINode.h"
31 #include "llvm/Constant.h"
32 #include "llvm/Support/CFG.h"
33 #include "llvm/Pass.h"
34 #include "Support/STLExtras.h"
37 // dceInstruction - Inspect the instruction at *BBI and figure out if it's
38 // [trivially] dead. If so, remove the instruction and update the iterator
39 // to point to the instruction that immediately succeeded the original
42 bool dceInstruction(BasicBlock::InstListType &BBIL,
43 BasicBlock::iterator &BBI) {
44 // Look for un"used" definitions...
45 if ((*BBI)->use_empty() && !(*BBI)->hasSideEffects() &&
46 !isa<TerminatorInst>(*BBI)) {
47 delete BBIL.remove(BBI); // Bye bye
53 static inline bool RemoveUnusedDefs(BasicBlock::InstListType &Vals) {
55 for (BasicBlock::InstListType::iterator DI = Vals.begin();
57 if (dceInstruction(Vals, DI))
64 struct DeadInstElimination : public BasicBlockPass {
65 const char *getPassName() const { return "Dead Instruction Elimination"; }
67 virtual bool runOnBasicBlock(BasicBlock *BB) {
68 return RemoveUnusedDefs(BB->getInstList());
72 Pass *createDeadInstEliminationPass() {
73 return new DeadInstElimination();
76 // 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.
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.
83 static bool RemoveSingularPHIs(BasicBlock *BB) {
84 pred_iterator PI(pred_begin(BB));
85 if (PI == pred_end(BB) || ++PI != pred_end(BB))
86 return false; // More than one predecessor...
88 Instruction *I = BB->front();
89 if (!isa<PHINode>(I)) return false; // No PHI nodes
91 //cerr << "Killing PHIs from " << BB;
92 //cerr << "Pred #0 = " << *pred_begin(BB);
94 //cerr << "Function == " << BB->getParent();
97 PHINode *PN = cast<PHINode>(I);
98 assert(PN->getNumOperands() == 2 && "PHI node should only have one value!");
99 Value *V = PN->getOperand(0);
101 PN->replaceAllUsesWith(V); // Replace PHI node with its single value.
102 delete BB->getInstList().remove(BB->begin());
105 } while (isa<PHINode>(I));
107 return true; // Yes, we nuked at least one phi node
110 static void ReplaceUsesWithConstant(Instruction *I) {
111 // Make all users of this instruction reference the constant instead
112 I->replaceAllUsesWith(Constant::getNullValue(I->getType()));
115 // 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
118 // predecessors. This function returns true (failure) if the Succ BB already
119 // has a predecessor that is a predecessor of BB.
121 // Assumption: Succ is the single successor for BB.
123 static bool PropogatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) {
124 assert(*succ_begin(BB) == Succ && "Succ is not successor of BB!");
125 assert(isa<PHINode>(Succ->front()) && "Only works on PHId BBs!");
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
130 const std::vector<BasicBlock*> BBPreds(pred_begin(BB), pred_end(BB));
132 // Check to see if one of the predecessors of BB is already a predecessor of
133 // Succ. If so, we cannot do the transformation!
135 for (pred_iterator PI = pred_begin(Succ), PE = pred_end(Succ);
137 if (find(BBPreds.begin(), BBPreds.end(), *PI) != BBPreds.end())
141 BasicBlock::iterator I = Succ->begin();
142 do { // Loop over all of the PHI nodes in the successor BB
143 PHINode *PN = cast<PHINode>(*I);
144 Value *OldVal = PN->removeIncomingValue(BB);
145 assert(OldVal && "No entry in PHI for Pred BB!");
147 for (std::vector<BasicBlock*>::const_iterator PredI = BBPreds.begin(),
148 End = BBPreds.end(); PredI != End; ++PredI) {
149 // Add an incoming value for each of the new incoming values...
150 PN->addIncoming(OldVal, *PredI);
154 } while (isa<PHINode>(*I));
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
166 // WARNING: The entry node of a function may not be simplified.
168 bool SimplifyCFG(Function::iterator &BBIt) {
169 BasicBlock *BB = *BBIt;
170 Function *M = BB->getParent();
172 assert(BB && BB->getParent() && "Block not embedded in function!");
173 assert(BB->getTerminator() && "Degenerate basic block encountered!");
174 assert(BB->getParent()->front() != BB && "Can't Simplify entry block!");
177 // Remove basic blocks that have no predecessors... which are unreachable.
178 if (pred_begin(BB) == pred_end(BB) &&
179 !BB->hasConstantReferences()) {
180 //cerr << "Removing BB: \n" << BB;
182 // Loop through all of our successors and make sure they know that one
183 // of their predecessors is going away.
184 for_each(succ_begin(BB), succ_end(BB),
185 std::bind2nd(std::mem_fun(&BasicBlock::removePredecessor), BB));
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);
196 // Remove the instruction from the basic block
197 delete BB->getInstList().pop_back();
199 delete M->getBasicBlocks().remove(BBIt);
203 // Check to see if this block has no instructions and only a single
204 // successor. If so, replace block references with successor.
205 succ_iterator SI(succ_begin(BB));
206 if (SI != succ_end(BB) && ++SI == succ_end(BB)) { // One succ?
207 if (BB->front()->isTerminator()) { // Terminator is the only instruction!
208 BasicBlock *Succ = *succ_begin(BB); // There is exactly one successor
209 //cerr << "Killing Trivial BB: \n" << BB;
211 if (Succ != BB) { // Arg, don't hurt infinite loops!
212 // 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!
217 if (!isa<PHINode>(Succ->front()) ||
218 !PropogatePredecessorsForPHIs(BB, Succ)) {
220 BB->replaceAllUsesWith(Succ);
221 BB = M->getBasicBlocks().remove(BBIt);
223 if (BB->hasName() && !Succ->hasName()) // Transfer name if we can
224 Succ->setName(BB->getName());
225 delete BB; // Delete basic block
227 //cerr << "Function after removal: \n" << M;
234 // Merge basic blocks into their predecessor if there is only one distinct
235 // pred, and if there is only one distinct successor of the predecessor, and
236 // if there are no PHI nodes.
238 if (!isa<PHINode>(BB->front()) && !BB->hasConstantReferences()) {
239 pred_iterator PI(pred_begin(BB)), PE(pred_end(BB));
240 BasicBlock *OnlyPred = *PI++;
241 for (; PI != PE; ++PI) // Search all predecessors, see if they are all same
242 if (*PI != OnlyPred) {
243 OnlyPred = 0; // There are multiple different predecessors...
247 BasicBlock *OnlySucc = 0;
248 if (OnlyPred && OnlyPred != BB) { // Don't break self loops
249 // Check to see if there is only one distinct successor...
250 succ_iterator SI(succ_begin(OnlyPred)), SE(succ_end(OnlyPred));
252 for (; SI != SE; ++SI)
253 if (*SI != OnlySucc) {
254 OnlySucc = 0; // There are multiple distinct successors!
260 //cerr << "Merging: " << BB << "into: " << Pred;
261 TerminatorInst *Term = OnlyPred->getTerminator();
263 // Delete the unconditional branch from the predecessor...
264 BasicBlock::iterator DI = OnlyPred->end();
265 delete OnlyPred->getInstList().remove(--DI); // Destroy branch
267 // Move all definitions in the succecessor to the predecessor...
268 std::vector<Instruction*> Insts(BB->begin(), BB->end());
269 BB->getInstList().remove(BB->begin(), BB->end());
270 OnlyPred->getInstList().insert(OnlyPred->end(),
271 Insts.begin(), Insts.end());
273 // Remove basic block from the function... and advance iterator to the
274 // next valid block...
275 M->getBasicBlocks().remove(BBIt);
277 // Make all PHI nodes that refered to BB now refer to Pred as their
279 BB->replaceAllUsesWith(OnlyPred);
281 // Inherit predecessors name if it exists...
282 if (BB->hasName() && !OnlyPred->hasName())
283 OnlyPred->setName(BB->getName());
285 delete BB; // You ARE the weakest link... goodbye
293 static bool DoDCEPass(Function *F) {
294 Function::iterator BBIt, BBEnd = F->end();
295 if (F->begin() == BBEnd) return false; // Nothing to do
296 bool Changed = false;
298 // Loop through now and remove instructions that have no uses...
299 for (BBIt = F->begin(); BBIt != BBEnd; ++BBIt) {
300 Changed |= RemoveUnusedDefs((*BBIt)->getInstList());
301 Changed |= RemoveSingularPHIs(*BBIt);
304 // Loop over all of the basic blocks (except the first one) and remove them
305 // if they are unneeded...
307 for (BBIt = F->begin(), ++BBIt; BBIt != F->end(); ) {
308 if (SimplifyCFG(BBIt)) {
318 // Remove unused global values - This removes unused global values of no
319 // possible value. This currently includes unused function prototypes and
320 // unitialized global variables.
322 static bool RemoveUnusedGlobalValues(Module *Mod) {
323 bool Changed = false;
325 for (Module::iterator MI = Mod->begin(); MI != Mod->end(); ) {
326 Function *Meth = *MI;
327 if (Meth->isExternal() && Meth->use_size() == 0) {
328 // No references to prototype?
329 //cerr << "Removing function proto: " << Meth->getName() << endl;
330 delete Mod->getFunctionList().remove(MI); // Remove prototype
331 // Remove moves iterator to point to the next one automatically
334 ++MI; // Skip prototype in use.
338 for (Module::giterator GI = Mod->gbegin(); GI != Mod->gend(); ) {
339 GlobalVariable *GV = *GI;
340 if (!GV->hasInitializer() && GV->use_size() == 0) {
341 // No references to uninitialized global variable?
342 //cerr << "Removing global var: " << GV->getName() << endl;
343 delete Mod->getGlobalList().remove(GI);
344 // Remove moves iterator to point to the next one automatically
355 struct DeadCodeElimination : public FunctionPass {
356 const char *getPassName() const { return "Dead Code Elimination"; }
359 virtual bool doInitialization(Module *M) {
360 return RemoveUnusedGlobalValues(M);
363 // It is possible that we may require multiple passes over the code to fully
364 // eliminate dead code. Iterate until we are done.
366 virtual bool runOnFunction(Function *F) {
367 bool Changed = false;
368 while (DoDCEPass(F)) Changed = true;
372 virtual bool doFinalization(Module *M) {
373 return RemoveUnusedGlobalValues(M);
378 Pass *createDeadCodeEliminationPass() {
379 return new DeadCodeElimination();