* Standardize how analysis results/passes as printed with the print() virtual
[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/Type.h"
12 #include "llvm/Analysis/Dominators.h"
13 #include "llvm/iTerminators.h"
14 #include "llvm/iPHINode.h"
15 #include "llvm/Constant.h"
16 #include "llvm/Support/CFG.h"
17 #include "Support/STLExtras.h"
18 #include "Support/DepthFirstIterator.h"
19 #include "Support/StatisticReporter.h"
20 #include <algorithm>
21 #include <iostream>
22 using std::cerr;
23 using std::vector;
24
25 static Statistic<> NumBlockRemoved("adce\t\t- Number of basic blocks removed");
26 static Statistic<> NumInstRemoved ("adce\t\t- Number of instructions removed");
27
28 namespace {
29
30 //===----------------------------------------------------------------------===//
31 // ADCE Class
32 //
33 // This class does all of the work of Aggressive Dead Code Elimination.
34 // It's public interface consists of a constructor and a doADCE() method.
35 //
36 class ADCE : public FunctionPass {
37   Function *Func;                       // The function that we are working on
38   std::vector<Instruction*> WorkList;   // Instructions that just became live
39   std::set<Instruction*>    LiveSet;    // The set of live instructions
40
41   //===--------------------------------------------------------------------===//
42   // The public interface for this class
43   //
44 public:
45   // Execute the Aggressive Dead Code Elimination Algorithm
46   //
47   virtual bool runOnFunction(Function &F) {
48     Func = &F;
49     bool Changed = doADCE();
50     assert(WorkList.empty());
51     LiveSet.clear();
52     return Changed;
53   }
54   // getAnalysisUsage - We require post dominance frontiers (aka Control
55   // Dependence Graph)
56   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
57     AU.addRequired(PostDominatorTree::ID);
58     AU.addRequired(PostDominanceFrontier::ID);
59   }
60
61
62   //===--------------------------------------------------------------------===//
63   // The implementation of this class
64   //
65 private:
66   // doADCE() - Run the Aggressive Dead Code Elimination algorithm, returning
67   // true if the function was modified.
68   //
69   bool doADCE();
70
71   void markBlockAlive(BasicBlock *BB);
72
73   inline void markInstructionLive(Instruction *I) {
74     if (LiveSet.count(I)) return;
75     DEBUG(cerr << "Insn Live: " << I);
76     LiveSet.insert(I);
77     WorkList.push_back(I);
78   }
79
80   inline void markTerminatorLive(const BasicBlock *BB) {
81     DEBUG(cerr << "Terminat Live: " << BB->getTerminator());
82     markInstructionLive((Instruction*)BB->getTerminator());
83   }
84 };
85
86   RegisterOpt<ADCE> X("adce", "Aggressive Dead Code Elimination");
87 } // End of anonymous namespace
88
89 Pass *createAggressiveDCEPass() { return new ADCE(); }
90
91 void ADCE::markBlockAlive(BasicBlock *BB) {
92   // Mark the basic block as being newly ALIVE... and mark all branches that
93   // this block is control dependant on as being alive also...
94   //
95   PostDominanceFrontier &CDG = getAnalysis<PostDominanceFrontier>();
96
97   PostDominanceFrontier::const_iterator It = CDG.find(BB);
98   if (It != CDG.end()) {
99     // Get the blocks that this node is control dependant on...
100     const PostDominanceFrontier::DomSetType &CDB = It->second;
101     for_each(CDB.begin(), CDB.end(),   // Mark all their terminators as live
102              bind_obj(this, &ADCE::markTerminatorLive));
103   }
104   
105   // If this basic block is live, then the terminator must be as well!
106   markTerminatorLive(BB);
107 }
108
109
110 // doADCE() - Run the Aggressive Dead Code Elimination algorithm, returning
111 // true if the function was modified.
112 //
113 bool ADCE::doADCE() {
114   bool MadeChanges = false;
115
116   // Iterate over all of the instructions in the function, eliminating trivially
117   // dead instructions, and marking instructions live that are known to be 
118   // needed.  Perform the walk in depth first order so that we avoid marking any
119   // instructions live in basic blocks that are unreachable.  These blocks will
120   // be eliminated later, along with the instructions inside.
121   //
122   for (df_iterator<Function*> BBI = df_begin(Func), BBE = df_end(Func);
123        BBI != BBE; ++BBI) {
124     BasicBlock *BB = *BBI;
125     for (BasicBlock::iterator II = BB->begin(), EI = BB->end(); II != EI; ) {
126       if (II->hasSideEffects() || II->getOpcode() == Instruction::Ret) {
127         markInstructionLive(II);
128         ++II;  // Increment the inst iterator if the inst wasn't deleted
129       } else if (isInstructionTriviallyDead(II)) {
130         // Remove the instruction from it's basic block...
131         II = BB->getInstList().erase(II);
132         ++NumInstRemoved;
133         MadeChanges = true;
134       } else {
135         ++II;  // Increment the inst iterator if the inst wasn't deleted
136       }
137     }
138   }
139
140   DEBUG(cerr << "Processing work list\n");
141
142   // AliveBlocks - Set of basic blocks that we know have instructions that are
143   // alive in them...
144   //
145   std::set<BasicBlock*> AliveBlocks;
146
147   // Process the work list of instructions that just became live... if they
148   // became live, then that means that all of their operands are neccesary as
149   // well... make them live as well.
150   //
151   while (!WorkList.empty()) {
152     Instruction *I = WorkList.back(); // Get an instruction that became live...
153     WorkList.pop_back();
154
155     BasicBlock *BB = I->getParent();
156     if (!AliveBlocks.count(BB)) {     // Basic block not alive yet...
157       AliveBlocks.insert(BB);         // Block is now ALIVE!
158       markBlockAlive(BB);             // Make it so now!
159     }
160
161     // PHI nodes are a special case, because the incoming values are actually
162     // defined in the predecessor nodes of this block, meaning that the PHI
163     // makes the predecessors alive.
164     //
165     if (PHINode *PN = dyn_cast<PHINode>(I))
166       for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI)
167         if (!AliveBlocks.count(*PI)) {
168           AliveBlocks.insert(BB);         // Block is now ALIVE!
169           markBlockAlive(*PI);
170         }
171
172     // Loop over all of the operands of the live instruction, making sure that
173     // they are known to be alive as well...
174     //
175     for (unsigned op = 0, End = I->getNumOperands(); op != End; ++op)
176       if (Instruction *Operand = dyn_cast<Instruction>(I->getOperand(op)))
177         markInstructionLive(Operand);
178   }
179
180   if (DebugFlag) {
181     cerr << "Current Function: X = Live\n";
182     for (Function::iterator I = Func->begin(), E = Func->end(); I != E; ++I)
183       for (BasicBlock::iterator BI = I->begin(), BE = I->end(); BI != BE; ++BI){
184         if (LiveSet.count(BI)) cerr << "X ";
185         cerr << *BI;
186       }
187   }
188
189   // Find the first postdominator of the entry node that is alive.  Make it the
190   // new entry node...
191   //
192   PostDominatorTree &DT = getAnalysis<PostDominatorTree>();
193
194   // If there are some blocks dead...
195   if (AliveBlocks.size() != Func->size()) {
196     // Insert a new entry node to eliminate the entry node as a special case.
197     BasicBlock *NewEntry = new BasicBlock();
198     NewEntry->getInstList().push_back(new BranchInst(&Func->front()));
199     Func->getBasicBlockList().push_front(NewEntry);
200     AliveBlocks.insert(NewEntry);    // This block is always alive!
201     
202     // Loop over all of the alive blocks in the function.  If any successor
203     // blocks are not alive, we adjust the outgoing branches to branch to the
204     // first live postdominator of the live block, adjusting any PHI nodes in
205     // the block to reflect this.
206     //
207     for (Function::iterator I = Func->begin(), E = Func->end(); I != E; ++I)
208       if (AliveBlocks.count(I)) {
209         BasicBlock *BB = I;
210         TerminatorInst *TI = BB->getTerminator();
211       
212         // Loop over all of the successors, looking for ones that are not alive
213         for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
214           if (!AliveBlocks.count(TI->getSuccessor(i))) {
215             // Scan up the postdominator tree, looking for the first
216             // postdominator that is alive, and the last postdominator that is
217             // dead...
218             //
219             PostDominatorTree::Node *LastNode = DT[TI->getSuccessor(i)];
220             PostDominatorTree::Node *NextNode = LastNode->getIDom();
221             while (!AliveBlocks.count(NextNode->getNode())) {
222               LastNode = NextNode;
223               NextNode = NextNode->getIDom();
224             }
225             
226             // Get the basic blocks that we need...
227             BasicBlock *LastDead = LastNode->getNode();
228             BasicBlock *NextAlive = NextNode->getNode();
229             
230             // Make the conditional branch now go to the next alive block...
231             TI->getSuccessor(i)->removePredecessor(BB);
232             TI->setSuccessor(i, NextAlive);
233             
234             // If there are PHI nodes in NextAlive, we need to add entries to
235             // the PHI nodes for the new incoming edge.  The incoming values
236             // should be identical to the incoming values for LastDead.
237             //
238             for (BasicBlock::iterator II = NextAlive->begin();
239                  PHINode *PN = dyn_cast<PHINode>(&*II); ++II) {
240               // Get the incoming value for LastDead...
241               int OldIdx = PN->getBasicBlockIndex(LastDead);
242               assert(OldIdx != -1 && "LastDead is not a pred of NextAlive!");
243               Value *InVal = PN->getIncomingValue(OldIdx);
244               
245               // Add an incoming value for BB now...
246               PN->addIncoming(InVal, BB);
247             }
248           }
249
250         // Now loop over all of the instructions in the basic block, telling
251         // dead instructions to drop their references.  This is so that the next
252         // sweep over the program can safely delete dead instructions without
253         // other dead instructions still refering to them.
254         //
255         for (BasicBlock::iterator I = BB->begin(), E = --BB->end(); I != E; ++I)
256           if (!LiveSet.count(I))                // Is this instruction alive?
257             I->dropAllReferences();             // Nope, drop references... 
258       }
259   }
260
261   // Loop over all of the basic blocks in the function, dropping references of
262   // the dead basic blocks
263   //
264   for (Function::iterator BB = Func->begin(), E = Func->end(); BB != E; ++BB) {
265     if (!AliveBlocks.count(BB)) {
266       // Remove all outgoing edges from this basic block and convert the
267       // terminator into a return instruction.
268       vector<BasicBlock*> Succs(succ_begin(BB), succ_end(BB));
269       
270       if (!Succs.empty()) {
271         // Loop over all of the successors, removing this block from PHI node
272         // entries that might be in the block...
273         while (!Succs.empty()) {
274           Succs.back()->removePredecessor(BB);
275           Succs.pop_back();
276         }
277         
278         // Delete the old terminator instruction...
279         BB->getInstList().pop_back();
280         const Type *RetTy = Func->getReturnType();
281         Instruction *New = new ReturnInst(RetTy != Type::VoidTy ?
282                                           Constant::getNullValue(RetTy) : 0);
283         BB->getInstList().push_back(New);
284       }
285
286       BB->dropAllReferences();
287       ++NumBlockRemoved;
288       MadeChanges = true;
289     }
290   }
291
292   // Now loop through all of the blocks and delete the dead ones.  We can safely
293   // do this now because we know that there are no references to dead blocks
294   // (because they have dropped all of their references...  we also remove dead
295   // instructions from alive blocks.
296   //
297   for (Function::iterator BI = Func->begin(); BI != Func->end(); )
298     if (!AliveBlocks.count(BI))
299       BI = Func->getBasicBlockList().erase(BI);
300     else {
301       for (BasicBlock::iterator II = BI->begin(); II != --BI->end(); )
302         if (!LiveSet.count(II)) {             // Is this instruction alive?
303           // Nope... remove the instruction from it's basic block...
304           II = BI->getInstList().erase(II);
305           ++NumInstRemoved;
306           MadeChanges = true;
307         } else {
308           ++II;
309         }
310
311       ++BI;                                           // Increment iterator...
312     }
313
314   return MadeChanges;
315 }