1 //===- ADCE.cpp - Code to perform agressive dead code elimination ---------===//
3 // This file implements "agressive" 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/DCE.h"
10 #include "llvm/Type.h"
11 #include "llvm/Analysis/Dominators.h"
12 #include "llvm/Analysis/Writer.h"
13 #include "llvm/iTerminators.h"
14 #include "llvm/iPHINode.h"
15 #include "llvm/Support/CFG.h"
16 #include "Support/STLExtras.h"
17 #include "Support/DepthFirstIterator.h"
24 //===----------------------------------------------------------------------===//
27 // This class does all of the work of Agressive Dead Code Elimination.
28 // It's public interface consists of a constructor and a doADCE() method.
31 Function *M; // The function that we are working on
32 std::vector<Instruction*> WorkList; // Instructions that just became live
33 std::set<Instruction*> LiveSet; // The set of live instructions
36 //===--------------------------------------------------------------------===//
37 // The public interface for this class
40 // ADCE Ctor - Save the function to operate on...
41 inline ADCE(Function *f) : M(f), MadeChanges(false) {}
43 // doADCE() - Run the Agressive Dead Code Elimination algorithm, returning
44 // true if the function was modified.
45 bool doADCE(DominanceFrontier &CDG);
47 //===--------------------------------------------------------------------===//
48 // The implementation of this class
51 inline void markInstructionLive(Instruction *I) {
52 if (LiveSet.count(I)) return;
54 cerr << "Insn Live: " << I;
57 WorkList.push_back(I);
60 inline void markTerminatorLive(const BasicBlock *BB) {
62 cerr << "Terminat Live: " << BB->getTerminator();
64 markInstructionLive((Instruction*)BB->getTerminator());
67 // fixupCFG - Walk the CFG in depth first order, eliminating references to
70 BasicBlock *fixupCFG(BasicBlock *Head, std::set<BasicBlock*> &VisitedBlocks,
71 const std::set<BasicBlock*> &AliveBlocks);
76 // doADCE() - Run the Agressive Dead Code Elimination algorithm, returning
77 // true if the function was modified.
79 bool ADCE::doADCE(DominanceFrontier &CDG) {
81 cerr << "Function: " << M;
84 // Iterate over all of the instructions in the function, eliminating trivially
85 // dead instructions, and marking instructions live that are known to be
86 // needed. Perform the walk in depth first order so that we avoid marking any
87 // instructions live in basic blocks that are unreachable. These blocks will
88 // be eliminated later, along with the instructions inside.
90 for (df_iterator<Function*> BBI = df_begin(M),
93 BasicBlock *BB = *BBI;
94 for (BasicBlock::iterator II = BB->begin(), EI = BB->end(); II != EI; ) {
97 if (I->hasSideEffects() || I->getOpcode() == Instruction::Ret) {
98 markInstructionLive(I);
100 // Check to see if anything is trivially dead
101 if (I->use_size() == 0 && I->getType() != Type::VoidTy) {
102 // Remove the instruction from it's basic block...
103 delete BB->getInstList().remove(II);
105 continue; // Don't increment the iterator past the current slot
109 ++II; // Increment the inst iterator if the inst wasn't deleted
114 cerr << "Processing work list\n";
117 // AliveBlocks - Set of basic blocks that we know have instructions that are
120 std::set<BasicBlock*> AliveBlocks;
122 // Process the work list of instructions that just became live... if they
123 // became live, then that means that all of their operands are neccesary as
124 // well... make them live as well.
126 while (!WorkList.empty()) {
127 Instruction *I = WorkList.back(); // Get an instruction that became live...
130 BasicBlock *BB = I->getParent();
131 if (AliveBlocks.count(BB) == 0) { // Basic block not alive yet...
132 // Mark the basic block as being newly ALIVE... and mark all branches that
133 // this block is control dependant on as being alive also...
135 AliveBlocks.insert(BB); // Block is now ALIVE!
136 DominanceFrontier::const_iterator It = CDG.find(BB);
137 if (It != CDG.end()) {
138 // Get the blocks that this node is control dependant on...
139 const DominanceFrontier::DomSetType &CDB = It->second;
140 for_each(CDB.begin(), CDB.end(), // Mark all their terminators as live
141 bind_obj(this, &ADCE::markTerminatorLive));
144 // If this basic block is live, then the terminator must be as well!
145 markTerminatorLive(BB);
148 // Loop over all of the operands of the live instruction, making sure that
149 // they are known to be alive as well...
151 for (unsigned op = 0, End = I->getNumOperands(); op != End; ++op) {
152 if (Instruction *Operand = dyn_cast<Instruction>(I->getOperand(op)))
153 markInstructionLive(Operand);
158 cerr << "Current Function: X = Live\n";
159 for (Function::iterator I = M->begin(), E = M->end(); I != E; ++I)
160 for (BasicBlock::iterator BI = (*I)->begin(), BE = (*I)->end();
162 if (LiveSet.count(*BI)) cerr << "X ";
167 // After the worklist is processed, recursively walk the CFG in depth first
168 // order, patching up references to dead blocks...
170 std::set<BasicBlock*> VisitedBlocks;
171 BasicBlock *EntryBlock = fixupCFG(M->front(), VisitedBlocks, AliveBlocks);
172 if (EntryBlock && EntryBlock != M->front()) {
173 if (isa<PHINode>(EntryBlock->front())) {
174 // Cannot make the first block be a block with a PHI node in it! Instead,
175 // strip the first basic block of the function to contain no instructions,
176 // then add a simple branch to the "real" entry node...
178 BasicBlock *E = M->front();
179 if (!isa<TerminatorInst>(E->front()) || // Check for an actual change...
180 cast<TerminatorInst>(E->front())->getNumSuccessors() != 1 ||
181 cast<TerminatorInst>(E->front())->getSuccessor(0) != EntryBlock) {
182 E->getInstList().delete_all(); // Delete all instructions in block
183 E->getInstList().push_back(new BranchInst(EntryBlock));
186 AliveBlocks.insert(E);
188 // Next we need to change any PHI nodes in the entry block to refer to the
189 // new predecessor node...
193 // We need to move the new entry block to be the first bb of the function
194 Function::iterator EBI = find(M->begin(), M->end(), EntryBlock);
195 std::swap(*EBI, *M->begin()); // Exchange old location with start of fn
200 // Now go through and tell dead blocks to drop all of their references so they
201 // can be safely deleted.
203 for (Function::iterator BI = M->begin(), BE = M->end(); BI != BE; ++BI) {
204 BasicBlock *BB = *BI;
205 if (!AliveBlocks.count(BB)) {
206 BB->dropAllReferences();
210 // Now loop through all of the blocks and delete them. We can safely do this
211 // now because we know that there are no references to dead blocks (because
212 // they have dropped all of their references...
214 for (Function::iterator BI = M->begin(); BI != M->end();) {
215 if (!AliveBlocks.count(*BI)) {
216 delete M->getBasicBlocks().remove(BI);
218 continue; // Don't increment iterator
220 ++BI; // Increment iterator...
227 // fixupCFG - Walk the CFG in depth first order, eliminating references to
229 // If the BB is alive (in AliveBlocks):
230 // 1. Eliminate all dead instructions in the BB
231 // 2. Recursively traverse all of the successors of the BB:
232 // - If the returned successor is non-null, update our terminator to
233 // reference the returned BB
234 // 3. Return 0 (no update needed)
236 // If the BB is dead (not in AliveBlocks):
237 // 1. Add the BB to the dead set
238 // 2. Recursively traverse all of the successors of the block:
239 // - Only one shall return a nonnull value (or else this block should have
240 // been in the alive set).
241 // 3. Return the nonnull child, or 0 if no non-null children.
243 BasicBlock *ADCE::fixupCFG(BasicBlock *BB, std::set<BasicBlock*> &VisitedBlocks,
244 const std::set<BasicBlock*> &AliveBlocks) {
245 if (VisitedBlocks.count(BB)) return 0; // Revisiting a node? No update.
246 VisitedBlocks.insert(BB); // We have now visited this node!
249 cerr << "Fixing up BB: " << BB;
252 if (AliveBlocks.count(BB)) { // Is the block alive?
253 // Yes it's alive: loop through and eliminate all dead instructions in block
254 for (BasicBlock::iterator II = BB->begin(); II != BB->end()-1; ) {
255 Instruction *I = *II;
256 if (!LiveSet.count(I)) { // Is this instruction alive?
257 // Nope... remove the instruction from it's basic block...
258 delete BB->getInstList().remove(II);
260 continue; // Don't increment II
265 // Recursively traverse successors of this basic block.
266 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI) {
267 BasicBlock *Succ = *SI;
268 BasicBlock *Repl = fixupCFG(Succ, VisitedBlocks, AliveBlocks);
269 if (Repl && Repl != Succ) { // We have to replace the successor
270 Succ->replaceAllUsesWith(Repl);
275 } else { // Otherwise the block is dead...
276 BasicBlock *ReturnBB = 0; // Default to nothing live down here
278 // Recursively traverse successors of this basic block.
279 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI) {
280 BasicBlock *RetBB = fixupCFG(*SI, VisitedBlocks, AliveBlocks);
282 assert(ReturnBB == 0 && "One one live child allowed!");
286 return ReturnBB; // Return the result of traversal
291 struct AgressiveDCE : public FunctionPass {
292 const char *getPassName() const {return "Aggressive Dead Code Elimination";}
294 // doADCE - Execute the Agressive Dead Code Elimination Algorithm
296 virtual bool runOnFunction(Function *F) {
297 return ADCE(F).doADCE(
298 getAnalysis<DominanceFrontier>(DominanceFrontier::PostDomID));
300 // getAnalysisUsage - We require post dominance frontiers (aka Control
302 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
303 AU.addRequired(DominanceFrontier::PostDomID);
308 Pass *createAgressiveDCEPass() {
309 return new AgressiveDCE();