Fix bug: ADCE/2003-06-24-BadSuccessor.ll
[oota-llvm.git] / lib / Transforms / Scalar / ADCE.cpp
1 //===- ADCE.cpp - Code to perform aggressive dead code elimination --------===//
2 //
3 // This file implements "aggressive" dead code elimination.  ADCE is DCe where
4 // values are assumed to be dead until proven otherwise.  This is similar to 
5 // SCCP, except applied to the liveness of values.
6 //
7 //===----------------------------------------------------------------------===//
8
9 #include "llvm/Transforms/Scalar.h"
10 #include "llvm/Transforms/Utils/Local.h"
11 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
12 #include "llvm/Type.h"
13 #include "llvm/Analysis/PostDominators.h"
14 #include "llvm/iTerminators.h"
15 #include "llvm/iPHINode.h"
16 #include "llvm/Constant.h"
17 #include "llvm/Support/CFG.h"
18 #include "Support/STLExtras.h"
19 #include "Support/DepthFirstIterator.h"
20 #include "Support/Statistic.h"
21 #include <algorithm>
22
23 namespace {
24   Statistic<> NumBlockRemoved("adce", "Number of basic blocks removed");
25   Statistic<> NumInstRemoved ("adce", "Number of instructions removed");
26
27 //===----------------------------------------------------------------------===//
28 // ADCE Class
29 //
30 // This class does all of the work of Aggressive Dead Code Elimination.
31 // It's public interface consists of a constructor and a doADCE() method.
32 //
33 class ADCE : public FunctionPass {
34   Function *Func;                       // The function that we are working on
35   std::vector<Instruction*> WorkList;   // Instructions that just became live
36   std::set<Instruction*>    LiveSet;    // The set of live instructions
37
38   //===--------------------------------------------------------------------===//
39   // The public interface for this class
40   //
41 public:
42   // Execute the Aggressive Dead Code Elimination Algorithm
43   //
44   virtual bool runOnFunction(Function &F) {
45     Func = &F;
46     bool Changed = doADCE();
47     assert(WorkList.empty());
48     LiveSet.clear();
49     return Changed;
50   }
51   // getAnalysisUsage - We require post dominance frontiers (aka Control
52   // Dependence Graph)
53   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
54     AU.addRequired<PostDominatorTree>();
55     AU.addRequired<PostDominanceFrontier>();
56   }
57
58
59   //===--------------------------------------------------------------------===//
60   // The implementation of this class
61   //
62 private:
63   // doADCE() - Run the Aggressive Dead Code Elimination algorithm, returning
64   // true if the function was modified.
65   //
66   bool doADCE();
67
68   void markBlockAlive(BasicBlock *BB);
69
70
71   // dropReferencesOfDeadInstructionsInLiveBlock - Loop over all of the
72   // instructions in the specified basic block, dropping references on
73   // instructions that are dead according to LiveSet.
74   bool dropReferencesOfDeadInstructionsInLiveBlock(BasicBlock *BB);
75
76   TerminatorInst *convertToUnconditionalBranch(TerminatorInst *TI);
77
78   inline void markInstructionLive(Instruction *I) {
79     if (LiveSet.count(I)) return;
80     DEBUG(std::cerr << "Insn Live: " << I);
81     LiveSet.insert(I);
82     WorkList.push_back(I);
83   }
84
85   inline void markTerminatorLive(const BasicBlock *BB) {
86     DEBUG(std::cerr << "Terminat Live: " << BB->getTerminator());
87     markInstructionLive((Instruction*)BB->getTerminator());
88   }
89 };
90
91   RegisterOpt<ADCE> X("adce", "Aggressive Dead Code Elimination");
92 } // End of anonymous namespace
93
94 Pass *createAggressiveDCEPass() { return new ADCE(); }
95
96 void ADCE::markBlockAlive(BasicBlock *BB) {
97   // Mark the basic block as being newly ALIVE... and mark all branches that
98   // this block is control dependant on as being alive also...
99   //
100   PostDominanceFrontier &CDG = getAnalysis<PostDominanceFrontier>();
101
102   PostDominanceFrontier::const_iterator It = CDG.find(BB);
103   if (It != CDG.end()) {
104     // Get the blocks that this node is control dependant on...
105     const PostDominanceFrontier::DomSetType &CDB = It->second;
106     for_each(CDB.begin(), CDB.end(),   // Mark all their terminators as live
107              bind_obj(this, &ADCE::markTerminatorLive));
108   }
109   
110   // If this basic block is live, and it ends in an unconditional branch, then
111   // the branch is alive as well...
112   if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator()))
113     if (BI->isUnconditional())
114       markTerminatorLive(BB);
115 }
116
117 // dropReferencesOfDeadInstructionsInLiveBlock - Loop over all of the
118 // instructions in the specified basic block, dropping references on
119 // instructions that are dead according to LiveSet.
120 bool ADCE::dropReferencesOfDeadInstructionsInLiveBlock(BasicBlock *BB) {
121   bool Changed = false;
122   for (BasicBlock::iterator I = BB->begin(), E = --BB->end(); I != E; )
123     if (!LiveSet.count(I)) {              // Is this instruction alive?
124       I->dropAllReferences();             // Nope, drop references... 
125       if (PHINode *PN = dyn_cast<PHINode>(I)) {
126         // We don't want to leave PHI nodes in the program that have
127         // #arguments != #predecessors, so we remove them now.
128         //
129         PN->replaceAllUsesWith(Constant::getNullValue(PN->getType()));
130         
131         // Delete the instruction...
132         I = BB->getInstList().erase(I);
133         Changed = true;
134       } else {
135         ++I;
136       }
137     } else {
138       ++I;
139     }
140   return Changed;
141 }
142
143
144 /// convertToUnconditionalBranch - Transform this conditional terminator
145 /// instruction into an unconditional branch because we don't care which of the
146 /// successors it goes to.  This eliminate a use of the condition as well.
147 ///
148 TerminatorInst *ADCE::convertToUnconditionalBranch(TerminatorInst *TI) {
149   BranchInst *NB = new BranchInst(TI->getSuccessor(0), TI);
150   BasicBlock *BB = TI->getParent();
151
152   // Remove entries from PHI nodes to avoid confusing ourself later...
153   for (unsigned i = 1, e = TI->getNumSuccessors(); i != e; ++i)
154     TI->getSuccessor(i)->removePredecessor(BB);
155   
156   // Delete the old branch itself...
157   BB->getInstList().erase(TI);
158   return NB;
159 }
160
161
162 // doADCE() - Run the Aggressive Dead Code Elimination algorithm, returning
163 // true if the function was modified.
164 //
165 bool ADCE::doADCE() {
166   bool MadeChanges = false;
167
168   // Iterate over all of the instructions in the function, eliminating trivially
169   // dead instructions, and marking instructions live that are known to be 
170   // needed.  Perform the walk in depth first order so that we avoid marking any
171   // instructions live in basic blocks that are unreachable.  These blocks will
172   // be eliminated later, along with the instructions inside.
173   //
174   for (df_iterator<Function*> BBI = df_begin(Func), BBE = df_end(Func);
175        BBI != BBE; ++BBI) {
176     BasicBlock *BB = *BBI;
177     for (BasicBlock::iterator II = BB->begin(), EI = BB->end(); II != EI; ) {
178       if (II->mayWriteToMemory() || II->getOpcode() == Instruction::Ret) {
179         markInstructionLive(II);
180         ++II;  // Increment the inst iterator if the inst wasn't deleted
181       } else if (isInstructionTriviallyDead(II)) {
182         // Remove the instruction from it's basic block...
183         II = BB->getInstList().erase(II);
184         ++NumInstRemoved;
185         MadeChanges = true;
186       } else {
187         ++II;  // Increment the inst iterator if the inst wasn't deleted
188       }
189     }
190   }
191
192   // Check to ensure we have an exit node for this CFG.  If we don't, we won't
193   // have any post-dominance information, thus we cannot perform our
194   // transformations safely.
195   //
196   PostDominatorTree &DT = getAnalysis<PostDominatorTree>();
197   if (DT[&Func->getEntryNode()] == 0) {
198     WorkList.clear();
199     return MadeChanges;
200   }
201
202   DEBUG(std::cerr << "Processing work list\n");
203
204   // AliveBlocks - Set of basic blocks that we know have instructions that are
205   // alive in them...
206   //
207   std::set<BasicBlock*> AliveBlocks;
208
209   // Process the work list of instructions that just became live... if they
210   // became live, then that means that all of their operands are neccesary as
211   // well... make them live as well.
212   //
213   while (!WorkList.empty()) {
214     Instruction *I = WorkList.back(); // Get an instruction that became live...
215     WorkList.pop_back();
216
217     BasicBlock *BB = I->getParent();
218     if (!AliveBlocks.count(BB)) {     // Basic block not alive yet...
219       AliveBlocks.insert(BB);         // Block is now ALIVE!
220       markBlockAlive(BB);             // Make it so now!
221     }
222
223     // PHI nodes are a special case, because the incoming values are actually
224     // defined in the predecessor nodes of this block, meaning that the PHI
225     // makes the predecessors alive.
226     //
227     if (PHINode *PN = dyn_cast<PHINode>(I))
228       for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI)
229         if (!AliveBlocks.count(*PI)) {
230           AliveBlocks.insert(BB);         // Block is now ALIVE!
231           markBlockAlive(*PI);
232         }
233
234     // Loop over all of the operands of the live instruction, making sure that
235     // they are known to be alive as well...
236     //
237     for (unsigned op = 0, End = I->getNumOperands(); op != End; ++op)
238       if (Instruction *Operand = dyn_cast<Instruction>(I->getOperand(op)))
239         markInstructionLive(Operand);
240   }
241
242   DEBUG(
243     std::cerr << "Current Function: X = Live\n";
244     for (Function::iterator I = Func->begin(), E = Func->end(); I != E; ++I){
245       std::cerr << I->getName() << ":\t"
246                 << (AliveBlocks.count(I) ? "LIVE\n" : "DEAD\n");
247       for (BasicBlock::iterator BI = I->begin(), BE = I->end(); BI != BE; ++BI){
248         if (LiveSet.count(BI)) std::cerr << "X ";
249         std::cerr << *BI;
250       }
251     });
252
253   // Find the first postdominator of the entry node that is alive.  Make it the
254   // new entry node...
255   //
256   if (AliveBlocks.size() == Func->size()) {  // No dead blocks?
257     for (Function::iterator I = Func->begin(), E = Func->end(); I != E; ++I) {
258       // Loop over all of the instructions in the function, telling dead
259       // instructions to drop their references.  This is so that the next sweep
260       // over the program can safely delete dead instructions without other dead
261       // instructions still refering to them.
262       //
263       dropReferencesOfDeadInstructionsInLiveBlock(I);
264
265       // Check to make sure the terminator instruction is live.  If it isn't,
266       // this means that the condition that it branches on (we know it is not an
267       // unconditional branch), is not needed to make the decision of where to
268       // go to, because all outgoing edges go to the same place.  We must remove
269       // the use of the condition (because it's probably dead), so we convert
270       // the terminator to a conditional branch.
271       //
272       TerminatorInst *TI = I->getTerminator();
273       if (!LiveSet.count(TI))
274         convertToUnconditionalBranch(TI);
275     }
276     
277   } else {                                   // If there are some blocks dead...
278     // If the entry node is dead, insert a new entry node to eliminate the entry
279     // node as a special case.
280     //
281     if (!AliveBlocks.count(&Func->front())) {
282       BasicBlock *NewEntry = new BasicBlock();
283       NewEntry->getInstList().push_back(new BranchInst(&Func->front()));
284       Func->getBasicBlockList().push_front(NewEntry);
285       AliveBlocks.insert(NewEntry);    // This block is always alive!
286       LiveSet.insert(NewEntry->getTerminator());  // The branch is live
287     }
288     
289     // Loop over all of the alive blocks in the function.  If any successor
290     // blocks are not alive, we adjust the outgoing branches to branch to the
291     // first live postdominator of the live block, adjusting any PHI nodes in
292     // the block to reflect this.
293     //
294     for (Function::iterator I = Func->begin(), E = Func->end(); I != E; ++I)
295       if (AliveBlocks.count(I)) {
296         BasicBlock *BB = I;
297         TerminatorInst *TI = BB->getTerminator();
298       
299         // If the terminator instruction is alive, but the block it is contained
300         // in IS alive, this means that this terminator is a conditional branch
301         // on a condition that doesn't matter.  Make it an unconditional branch
302         // to ONE of the successors.  This has the side effect of dropping a use
303         // of the conditional value, which may also be dead.
304         if (!LiveSet.count(TI))
305           TI = convertToUnconditionalBranch(TI);
306
307         // Loop over all of the successors, looking for ones that are not alive.
308         // We cannot save the number of successors in the terminator instruction
309         // here because we may remove them if we don't have a postdominator...
310         //
311         for (unsigned i = 0; i != TI->getNumSuccessors(); ++i)
312           if (!AliveBlocks.count(TI->getSuccessor(i))) {
313             // Scan up the postdominator tree, looking for the first
314             // postdominator that is alive, and the last postdominator that is
315             // dead...
316             //
317             PostDominatorTree::Node *LastNode = DT[TI->getSuccessor(i)];
318
319             // There is a special case here... if there IS no post-dominator for
320             // the block we have no owhere to point our branch to.  Instead,
321             // convert it to a return.  This can only happen if the code
322             // branched into an infinite loop.  Note that this may not be
323             // desirable, because we _are_ altering the behavior of the code.
324             // This is a well known drawback of ADCE, so in the future if we
325             // choose to revisit the decision, this is where it should be.
326             //
327             if (LastNode == 0) {        // No postdominator!
328               // Call RemoveSuccessor to transmogrify the terminator instruction
329               // to not contain the outgoing branch, or to create a new
330               // terminator if the form fundementally changes (ie unconditional
331               // branch to return).  Note that this will change a branch into an
332               // infinite loop into a return instruction!
333               //
334               RemoveSuccessor(TI, i);
335
336               // RemoveSuccessor may replace TI... make sure we have a fresh
337               // pointer... and e variable.
338               //
339               TI = BB->getTerminator();
340
341               // Rescan this successor...
342               --i;
343             } else {
344               PostDominatorTree::Node *NextNode = LastNode->getIDom();
345
346               while (!AliveBlocks.count(NextNode->getNode())) {
347                 LastNode = NextNode;
348                 NextNode = NextNode->getIDom();
349               }
350             
351               // Get the basic blocks that we need...
352               BasicBlock *LastDead = LastNode->getNode();
353               BasicBlock *NextAlive = NextNode->getNode();
354
355               // Make the conditional branch now go to the next alive block...
356               TI->getSuccessor(i)->removePredecessor(BB);
357               TI->setSuccessor(i, NextAlive);
358
359               // If there are PHI nodes in NextAlive, we need to add entries to
360               // the PHI nodes for the new incoming edge.  The incoming values
361               // should be identical to the incoming values for LastDead.
362               //
363               for (BasicBlock::iterator II = NextAlive->begin();
364                    PHINode *PN = dyn_cast<PHINode>(II); ++II)
365                 if (LiveSet.count(PN)) {  // Only modify live phi nodes
366                   // Get the incoming value for LastDead...
367                   int OldIdx = PN->getBasicBlockIndex(LastDead);
368                   assert(OldIdx != -1 &&"LastDead is not a pred of NextAlive!");
369                   Value *InVal = PN->getIncomingValue(OldIdx);
370                   
371                   // Add an incoming value for BB now...
372                   PN->addIncoming(InVal, BB);
373                 }
374             }
375           }
376
377         // Now loop over all of the instructions in the basic block, telling
378         // dead instructions to drop their references.  This is so that the next
379         // sweep over the program can safely delete dead instructions without
380         // other dead instructions still refering to them.
381         //
382         dropReferencesOfDeadInstructionsInLiveBlock(BB);
383       }
384   }
385
386   // We make changes if there are any dead blocks in the function...
387   if (unsigned NumDeadBlocks = Func->size() - AliveBlocks.size()) {
388     MadeChanges = true;
389     NumBlockRemoved += NumDeadBlocks;
390   }
391
392   // Loop over all of the basic blocks in the function, removing control flow
393   // edges to live blocks (also eliminating any entries in PHI functions in
394   // referenced blocks).
395   //
396   for (Function::iterator BB = Func->begin(), E = Func->end(); BB != E; ++BB)
397     if (!AliveBlocks.count(BB)) {
398       // Remove all outgoing edges from this basic block and convert the
399       // terminator into a return instruction.
400       std::vector<BasicBlock*> Succs(succ_begin(BB), succ_end(BB));
401       
402       if (!Succs.empty()) {
403         // Loop over all of the successors, removing this block from PHI node
404         // entries that might be in the block...
405         while (!Succs.empty()) {
406           Succs.back()->removePredecessor(BB);
407           Succs.pop_back();
408         }
409         
410         // Delete the old terminator instruction...
411         BB->getInstList().pop_back();
412         const Type *RetTy = Func->getReturnType();
413         BB->getInstList().push_back(new ReturnInst(RetTy != Type::VoidTy ?
414                                            Constant::getNullValue(RetTy) : 0));
415       }
416     }
417
418
419   // Loop over all of the basic blocks in the function, dropping references of
420   // the dead basic blocks.  We must do this after the previous step to avoid
421   // dropping references to PHIs which still have entries...
422   //
423   for (Function::iterator BB = Func->begin(), E = Func->end(); BB != E; ++BB)
424     if (!AliveBlocks.count(BB))
425       BB->dropAllReferences();
426
427   // Now loop through all of the blocks and delete the dead ones.  We can safely
428   // do this now because we know that there are no references to dead blocks
429   // (because they have dropped all of their references...  we also remove dead
430   // instructions from alive blocks.
431   //
432   for (Function::iterator BI = Func->begin(); BI != Func->end(); )
433     if (!AliveBlocks.count(BI)) {                // Delete dead blocks...
434       BI = Func->getBasicBlockList().erase(BI);
435     } else {                                     // Scan alive blocks...
436       for (BasicBlock::iterator II = BI->begin(); II != --BI->end(); )
437         if (!LiveSet.count(II)) {             // Is this instruction alive?
438           // Nope... remove the instruction from it's basic block...
439           II = BI->getInstList().erase(II);
440           ++NumInstRemoved;
441           MadeChanges = true;
442         } else {
443           ++II;
444         }
445
446       ++BI;                                           // Increment iterator...
447     }
448
449   return MadeChanges;
450 }