1 //===- ADCE.cpp - Code to perform aggressive dead code elimination --------===//
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.
7 //===----------------------------------------------------------------------===//
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/Analysis/Writer.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/StatisticReporter.h"
26 static Statistic<> NumBlockRemoved("adce\t\t- Number of basic blocks removed");
27 static Statistic<> NumInstRemoved ("adce\t\t- Number of instructions removed");
31 //===----------------------------------------------------------------------===//
34 // This class does all of the work of Aggressive Dead Code Elimination.
35 // It's public interface consists of a constructor and a doADCE() method.
37 class ADCE : public FunctionPass {
38 Function *Func; // The function that we are working on
39 std::vector<Instruction*> WorkList; // Instructions that just became live
40 std::set<Instruction*> LiveSet; // The set of live instructions
42 //===--------------------------------------------------------------------===//
43 // The public interface for this class
46 // Execute the Aggressive Dead Code Elimination Algorithm
48 virtual bool runOnFunction(Function &F) {
50 bool Changed = doADCE();
51 assert(WorkList.empty());
55 // getAnalysisUsage - We require post dominance frontiers (aka Control
57 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
58 AU.addRequired(DominatorTree::PostDomID);
59 AU.addRequired(DominanceFrontier::PostDomID);
63 //===--------------------------------------------------------------------===//
64 // The implementation of this class
67 // doADCE() - Run the Aggressive Dead Code Elimination algorithm, returning
68 // true if the function was modified.
72 void markBlockAlive(BasicBlock *BB);
74 inline void markInstructionLive(Instruction *I) {
75 if (LiveSet.count(I)) return;
76 DEBUG(cerr << "Insn Live: " << I);
78 WorkList.push_back(I);
81 inline void markTerminatorLive(const BasicBlock *BB) {
82 DEBUG(cerr << "Terminat Live: " << BB->getTerminator());
83 markInstructionLive((Instruction*)BB->getTerminator());
87 RegisterPass<ADCE> X("adce", "Aggressive Dead Code Elimination");
88 } // End of anonymous namespace
90 Pass *createAggressiveDCEPass() { return new ADCE(); }
92 void ADCE::markBlockAlive(BasicBlock *BB) {
93 // Mark the basic block as being newly ALIVE... and mark all branches that
94 // this block is control dependant on as being alive also...
96 DominanceFrontier &CDG =
97 getAnalysis<DominanceFrontier>(DominanceFrontier::PostDomID);
99 DominanceFrontier::const_iterator It = CDG.find(BB);
100 if (It != CDG.end()) {
101 // Get the blocks that this node is control dependant on...
102 const DominanceFrontier::DomSetType &CDB = It->second;
103 for_each(CDB.begin(), CDB.end(), // Mark all their terminators as live
104 bind_obj(this, &ADCE::markTerminatorLive));
107 // If this basic block is live, then the terminator must be as well!
108 markTerminatorLive(BB);
112 // doADCE() - Run the Aggressive Dead Code Elimination algorithm, returning
113 // true if the function was modified.
115 bool ADCE::doADCE() {
116 bool MadeChanges = false;
118 // Iterate over all of the instructions in the function, eliminating trivially
119 // dead instructions, and marking instructions live that are known to be
120 // needed. Perform the walk in depth first order so that we avoid marking any
121 // instructions live in basic blocks that are unreachable. These blocks will
122 // be eliminated later, along with the instructions inside.
124 for (df_iterator<Function*> BBI = df_begin(Func), BBE = df_end(Func);
126 BasicBlock *BB = *BBI;
127 for (BasicBlock::iterator II = BB->begin(), EI = BB->end(); II != EI; ) {
128 if (II->hasSideEffects() || II->getOpcode() == Instruction::Ret) {
129 markInstructionLive(II);
130 ++II; // Increment the inst iterator if the inst wasn't deleted
131 } else if (isInstructionTriviallyDead(II)) {
132 // Remove the instruction from it's basic block...
133 II = BB->getInstList().erase(II);
137 ++II; // Increment the inst iterator if the inst wasn't deleted
142 DEBUG(cerr << "Processing work list\n");
144 // AliveBlocks - Set of basic blocks that we know have instructions that are
147 std::set<BasicBlock*> AliveBlocks;
149 // Process the work list of instructions that just became live... if they
150 // became live, then that means that all of their operands are neccesary as
151 // well... make them live as well.
153 while (!WorkList.empty()) {
154 Instruction *I = WorkList.back(); // Get an instruction that became live...
157 BasicBlock *BB = I->getParent();
158 if (!AliveBlocks.count(BB)) { // Basic block not alive yet...
159 AliveBlocks.insert(BB); // Block is now ALIVE!
160 markBlockAlive(BB); // Make it so now!
163 // PHI nodes are a special case, because the incoming values are actually
164 // defined in the predecessor nodes of this block, meaning that the PHI
165 // makes the predecessors alive.
167 if (PHINode *PN = dyn_cast<PHINode>(I))
168 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI)
169 if (!AliveBlocks.count(*PI)) {
170 AliveBlocks.insert(BB); // Block is now ALIVE!
174 // Loop over all of the operands of the live instruction, making sure that
175 // they are known to be alive as well...
177 for (unsigned op = 0, End = I->getNumOperands(); op != End; ++op)
178 if (Instruction *Operand = dyn_cast<Instruction>(I->getOperand(op)))
179 markInstructionLive(Operand);
183 cerr << "Current Function: X = Live\n";
184 for (Function::iterator I = Func->begin(), E = Func->end(); I != E; ++I)
185 for (BasicBlock::iterator BI = I->begin(), BE = I->end(); BI != BE; ++BI){
186 if (LiveSet.count(BI)) cerr << "X ";
191 // Find the first postdominator of the entry node that is alive. Make it the
194 DominatorTree &DT = getAnalysis<DominatorTree>(DominatorTree::PostDomID);
196 // If there are some blocks dead...
197 if (AliveBlocks.size() != Func->size()) {
198 // Insert a new entry node to eliminate the entry node as a special case.
199 BasicBlock *NewEntry = new BasicBlock();
200 NewEntry->getInstList().push_back(new BranchInst(&Func->front()));
201 Func->getBasicBlockList().push_front(NewEntry);
202 AliveBlocks.insert(NewEntry); // This block is always alive!
204 // Loop over all of the alive blocks in the function. If any successor
205 // blocks are not alive, we adjust the outgoing branches to branch to the
206 // first live postdominator of the live block, adjusting any PHI nodes in
207 // the block to reflect this.
209 for (Function::iterator I = Func->begin(), E = Func->end(); I != E; ++I)
210 if (AliveBlocks.count(I)) {
212 TerminatorInst *TI = BB->getTerminator();
214 // Loop over all of the successors, looking for ones that are not alive
215 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
216 if (!AliveBlocks.count(TI->getSuccessor(i))) {
217 // Scan up the postdominator tree, looking for the first
218 // postdominator that is alive, and the last postdominator that is
221 DominatorTree::Node *LastNode = DT[TI->getSuccessor(i)];
222 DominatorTree::Node *NextNode = LastNode->getIDom();
223 while (!AliveBlocks.count(NextNode->getNode())) {
225 NextNode = NextNode->getIDom();
228 // Get the basic blocks that we need...
229 BasicBlock *LastDead = LastNode->getNode();
230 BasicBlock *NextAlive = NextNode->getNode();
232 // Make the conditional branch now go to the next alive block...
233 TI->getSuccessor(i)->removePredecessor(BB);
234 TI->setSuccessor(i, NextAlive);
236 // If there are PHI nodes in NextAlive, we need to add entries to
237 // the PHI nodes for the new incoming edge. The incoming values
238 // should be identical to the incoming values for LastDead.
240 for (BasicBlock::iterator II = NextAlive->begin();
241 PHINode *PN = dyn_cast<PHINode>(&*II); ++II) {
242 // Get the incoming value for LastDead...
243 int OldIdx = PN->getBasicBlockIndex(LastDead);
244 assert(OldIdx != -1 && "LastDead is not a pred of NextAlive!");
245 Value *InVal = PN->getIncomingValue(OldIdx);
247 // Add an incoming value for BB now...
248 PN->addIncoming(InVal, BB);
252 // Now loop over all of the instructions in the basic block, telling
253 // dead instructions to drop their references. This is so that the next
254 // sweep over the program can safely delete dead instructions without
255 // other dead instructions still refering to them.
257 for (BasicBlock::iterator I = BB->begin(), E = --BB->end(); I != E; ++I)
258 if (!LiveSet.count(I)) // Is this instruction alive?
259 I->dropAllReferences(); // Nope, drop references...
263 // Loop over all of the basic blocks in the function, dropping references of
264 // the dead basic blocks
266 for (Function::iterator BB = Func->begin(), E = Func->end(); BB != E; ++BB) {
267 if (!AliveBlocks.count(BB)) {
268 // Remove all outgoing edges from this basic block and convert the
269 // terminator into a return instruction.
270 vector<BasicBlock*> Succs(succ_begin(BB), succ_end(BB));
272 if (!Succs.empty()) {
273 // Loop over all of the successors, removing this block from PHI node
274 // entries that might be in the block...
275 while (!Succs.empty()) {
276 Succs.back()->removePredecessor(BB);
280 // Delete the old terminator instruction...
281 BB->getInstList().pop_back();
282 const Type *RetTy = Func->getReturnType();
283 Instruction *New = new ReturnInst(RetTy != Type::VoidTy ?
284 Constant::getNullValue(RetTy) : 0);
285 BB->getInstList().push_back(New);
288 BB->dropAllReferences();
294 // Now loop through all of the blocks and delete the dead ones. We can safely
295 // do this now because we know that there are no references to dead blocks
296 // (because they have dropped all of their references... we also remove dead
297 // instructions from alive blocks.
299 for (Function::iterator BI = Func->begin(); BI != Func->end(); )
300 if (!AliveBlocks.count(BI))
301 BI = Func->getBasicBlockList().erase(BI);
303 for (BasicBlock::iterator II = BI->begin(); II != --BI->end(); )
304 if (!LiveSet.count(II)) { // Is this instruction alive?
305 // Nope... remove the instruction from it's basic block...
306 II = BI->getInstList().erase(II);
313 ++BI; // Increment iterator...