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/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"
25 static Statistic<> NumBlockRemoved("adce\t\t- Number of basic blocks removed");
26 static Statistic<> NumInstRemoved ("adce\t\t- Number of instructions removed");
30 //===----------------------------------------------------------------------===//
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.
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
41 //===--------------------------------------------------------------------===//
42 // The public interface for this class
45 // Execute the Aggressive Dead Code Elimination Algorithm
47 virtual bool runOnFunction(Function &F) {
49 bool Changed = doADCE();
50 assert(WorkList.empty());
54 // getAnalysisUsage - We require post dominance frontiers (aka Control
56 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
57 AU.addRequired(PostDominatorTree::ID);
58 AU.addRequired(PostDominanceFrontier::ID);
62 //===--------------------------------------------------------------------===//
63 // The implementation of this class
66 // doADCE() - Run the Aggressive Dead Code Elimination algorithm, returning
67 // true if the function was modified.
71 void markBlockAlive(BasicBlock *BB);
73 inline void markInstructionLive(Instruction *I) {
74 if (LiveSet.count(I)) return;
75 DEBUG(cerr << "Insn Live: " << I);
77 WorkList.push_back(I);
80 inline void markTerminatorLive(const BasicBlock *BB) {
81 DEBUG(cerr << "Terminat Live: " << BB->getTerminator());
82 markInstructionLive((Instruction*)BB->getTerminator());
86 RegisterOpt<ADCE> X("adce", "Aggressive Dead Code Elimination");
87 } // End of anonymous namespace
89 Pass *createAggressiveDCEPass() { return new ADCE(); }
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...
95 PostDominanceFrontier &CDG = getAnalysis<PostDominanceFrontier>();
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));
105 // If this basic block is live, then the terminator must be as well!
106 markTerminatorLive(BB);
110 // doADCE() - Run the Aggressive Dead Code Elimination algorithm, returning
111 // true if the function was modified.
113 bool ADCE::doADCE() {
114 bool MadeChanges = false;
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.
122 for (df_iterator<Function*> BBI = df_begin(Func), BBE = df_end(Func);
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);
135 ++II; // Increment the inst iterator if the inst wasn't deleted
140 DEBUG(cerr << "Processing work list\n");
142 // AliveBlocks - Set of basic blocks that we know have instructions that are
145 std::set<BasicBlock*> AliveBlocks;
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.
151 while (!WorkList.empty()) {
152 Instruction *I = WorkList.back(); // Get an instruction that became live...
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!
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.
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!
172 // Loop over all of the operands of the live instruction, making sure that
173 // they are known to be alive as well...
175 for (unsigned op = 0, End = I->getNumOperands(); op != End; ++op)
176 if (Instruction *Operand = dyn_cast<Instruction>(I->getOperand(op)))
177 markInstructionLive(Operand);
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 ";
189 // Find the first postdominator of the entry node that is alive. Make it the
192 PostDominatorTree &DT = getAnalysis<PostDominatorTree>();
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!
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.
207 for (Function::iterator I = Func->begin(), E = Func->end(); I != E; ++I)
208 if (AliveBlocks.count(I)) {
210 TerminatorInst *TI = BB->getTerminator();
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
219 PostDominatorTree::Node *LastNode = DT[TI->getSuccessor(i)];
220 PostDominatorTree::Node *NextNode = LastNode->getIDom();
221 while (!AliveBlocks.count(NextNode->getNode())) {
223 NextNode = NextNode->getIDom();
226 // Get the basic blocks that we need...
227 BasicBlock *LastDead = LastNode->getNode();
228 BasicBlock *NextAlive = NextNode->getNode();
230 // Make the conditional branch now go to the next alive block...
231 TI->getSuccessor(i)->removePredecessor(BB);
232 TI->setSuccessor(i, NextAlive);
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.
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);
245 // Add an incoming value for BB now...
246 PN->addIncoming(InVal, BB);
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.
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...
261 // Loop over all of the basic blocks in the function, dropping references of
262 // the dead basic blocks
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));
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);
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);
286 BB->dropAllReferences();
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.
297 for (Function::iterator BI = Func->begin(); BI != Func->end(); )
298 if (!AliveBlocks.count(BI))
299 BI = Func->getBasicBlockList().erase(BI);
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);
311 ++BI; // Increment iterator...