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