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/Optimizations/DCE.h"
10 #include "llvm/Instruction.h"
11 #include "llvm/Type.h"
12 #include "llvm/Analysis/Dominators.h"
13 #include "llvm/Support/STLExtras.h"
14 #include "llvm/Analysis/Writer.h"
16 #include "llvm/iTerminators.h"
20 //#define DEBUG_ADCE 1
22 //===----------------------------------------------------------------------===//
25 // This class does all of the work of Agressive Dead Code Elimination.
26 // It's public interface consists of a constructor and a doADCE() method.
29 Method *M; // The method that we are working on...
30 vector<Instruction*> WorkList; // Instructions that just became live
31 set<Instruction*> LiveSet; // The set of live instructions
34 //===--------------------------------------------------------------------===//
35 // The public interface for this class
38 // ADCE Ctor - Save the method to operate on...
39 inline ADCE(Method *m) : M(m), MadeChanges(false) {}
41 // doADCE() - Run the Agressive Dead Code Elimination algorithm, returning
42 // true if the method was modified.
45 //===--------------------------------------------------------------------===//
46 // The implementation of this class
49 inline void markInstructionLive(Instruction *I) {
50 if (LiveSet.count(I)) return;
52 cerr << "Insn Live: " << I;
55 WorkList.push_back(I);
58 inline void markTerminatorLive(const BasicBlock *BB) {
60 cerr << "Terminat Live: " << BB->getTerminator();
62 markInstructionLive((Instruction*)BB->getTerminator());
65 // fixupCFG - Walk the CFG in depth first order, eliminating references to
68 BasicBlock *fixupCFG(BasicBlock *Head, set<BasicBlock*> &VisitedBlocks,
69 const set<BasicBlock*> &AliveBlocks);
74 // doADCE() - Run the Agressive Dead Code Elimination algorithm, returning
75 // true if the method was modified.
78 // Compute the control dependence graph... Note that this has a side effect
79 // on the CFG: a new return bb is added and all returns are merged here.
81 cfg::DominanceFrontier CDG(cfg::DominatorSet(M, true));
84 cerr << "Method: " << M;
87 // Iterate over all of the instructions in the method, eliminating trivially
88 // dead instructions, and marking instructions live that are known to be
89 // needed. Perform the walk in depth first order so that we avoid marking any
90 // instructions live in basic blocks that are unreachable. These blocks will
91 // be eliminated later, along with the instructions inside.
93 for (cfg::df_iterator BBI = cfg::df_begin(M), BBE = cfg::df_end(M);
95 BasicBlock *BB = *BBI;
96 for (BasicBlock::iterator II = BB->begin(), EI = BB->end(); II != EI; ) {
99 if (I->hasSideEffects() || I->getOpcode() == Instruction::Ret) {
100 markInstructionLive(I);
102 // Check to see if anything is trivially dead
103 if (I->use_size() == 0 && I->getType() != Type::VoidTy) {
104 // Remove the instruction from it's basic block...
105 delete BB->getInstList().remove(II);
107 continue; // Don't increment the iterator past the current slot
111 ++II; // Increment the inst iterator if the inst wasn't deleted
116 cerr << "Processing work list\n";
119 // AliveBlocks - Set of basic blocks that we know have instructions that are
122 set<BasicBlock*> AliveBlocks;
124 // Process the work list of instructions that just became live... if they
125 // became live, then that means that all of their operands are neccesary as
126 // well... make them live as well.
128 while (!WorkList.empty()) {
129 Instruction *I = WorkList.back(); // Get an instruction that became live...
132 BasicBlock *BB = I->getParent();
133 if (AliveBlocks.count(BB) == 0) { // Basic block not alive yet...
134 // Mark the basic block as being newly ALIVE... and mark all branches that
135 // this block is control dependant on as being alive also...
137 AliveBlocks.insert(BB); // Block is now ALIVE!
138 cfg::DominanceFrontier::const_iterator It = CDG.find(BB);
139 if (It != CDG.end()) {
140 // Get the blocks that this node is control dependant on...
141 const cfg::DominanceFrontier::DomSetType &CDB = It->second;
142 for_each(CDB.begin(), CDB.end(), // Mark all their terminators as live
143 bind_obj(this, &ADCE::markTerminatorLive));
146 // If this basic block is live, then the terminator must be as well!
147 markTerminatorLive(BB);
150 // Loop over all of the operands of the live instruction, making sure that
151 // they are known to be alive as well...
153 for (unsigned op = 0, End = I->getNumOperands(); op != End; ++op) {
154 if (Instruction *Operand = I->getOperand(op)->castInstruction())
155 markInstructionLive(Operand);
160 cerr << "Current Method: X = Live\n";
161 for (Method::inst_iterator IL = M->inst_begin(); IL != M->inst_end(); ++IL) {
162 if (LiveSet.count(*IL)) cerr << "X ";
167 // After the worklist is processed, recursively walk the CFG in depth first
168 // order, patching up references to dead blocks...
170 set<BasicBlock*> VisitedBlocks;
171 BasicBlock *EntryBlock = fixupCFG(M->front(), VisitedBlocks, AliveBlocks);
172 if (EntryBlock && EntryBlock != M->front()) {
173 if (EntryBlock->front()->isPHINode()) {
174 // Cannot make the first block be a block with a PHI node in it! Instead,
175 // strip the first basic block of the method to contain no instructions,
176 // then add a simple branch to the "real" entry node...
178 BasicBlock *E = M->front();
179 if (!E->front()->isTerminator() || // Check for an actual change...
180 ((TerminatorInst*)E->front())->getNumSuccessors() != 1 ||
181 ((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 // We need to move the new entry block to be the first bb of the method.
189 Method::iterator EBI = find(M->begin(), M->end(), EntryBlock);
190 swap(*EBI, *M->begin()); // Exchange old location with start of method
195 // Now go through and tell dead blocks to drop all of their references so they
196 // can be safely deleted.
198 for (Method::iterator BI = M->begin(), BE = M->end(); BI != BE; ++BI) {
199 BasicBlock *BB = *BI;
200 if (!AliveBlocks.count(BB)) {
201 BB->dropAllReferences();
205 // Now loop through all of the blocks and delete them. We can safely do this
206 // now because we know that there are no references to dead blocks (because
207 // they have dropped all of their references...
209 for (Method::iterator BI = M->begin(); BI != M->end();) {
210 if (!AliveBlocks.count(*BI)) {
211 delete M->getBasicBlocks().remove(BI);
213 continue; // Don't increment iterator
215 ++BI; // Increment iterator...
222 // fixupCFG - Walk the CFG in depth first order, eliminating references to
224 // If the BB is alive (in AliveBlocks):
225 // 1. Eliminate all dead instructions in the BB
226 // 2. Recursively traverse all of the successors of the BB:
227 // - If the returned successor is non-null, update our terminator to
228 // reference the returned BB
229 // 3. Return 0 (no update needed)
231 // If the BB is dead (not in AliveBlocks):
232 // 1. Add the BB to the dead set
233 // 2. Recursively traverse all of the successors of the block:
234 // - Only one shall return a nonnull value (or else this block should have
235 // been in the alive set).
236 // 3. Return the nonnull child, or 0 if no non-null children.
238 BasicBlock *ADCE::fixupCFG(BasicBlock *BB, set<BasicBlock*> &VisitedBlocks,
239 const set<BasicBlock*> &AliveBlocks) {
240 if (VisitedBlocks.count(BB)) return 0; // Revisiting a node? No update.
241 VisitedBlocks.insert(BB); // We have now visited this node!
244 cerr << "Fixing up BB: " << BB;
247 if (AliveBlocks.count(BB)) { // Is the block alive?
248 // Yes it's alive: loop through and eliminate all dead instructions in block
249 for (BasicBlock::iterator II = BB->begin(); II != BB->end()-1; ) {
250 Instruction *I = *II;
251 if (!LiveSet.count(I)) { // Is this instruction alive?
252 // Nope... remove the instruction from it's basic block...
253 delete BB->getInstList().remove(II);
255 continue; // Don't increment II
260 // Recursively traverse successors of this basic block.
261 cfg::succ_iterator SI = cfg::succ_begin(BB), SE = cfg::succ_end(BB);
262 for (; SI != SE; ++SI) {
263 BasicBlock *Succ = *SI;
264 BasicBlock *Repl = fixupCFG(Succ, VisitedBlocks, AliveBlocks);
265 if (Repl && Repl != Succ) { // We have to replace the successor
266 Succ->replaceAllUsesWith(Repl);
271 } else { // Otherwise the block is dead...
272 BasicBlock *ReturnBB = 0; // Default to nothing live down here
274 // Recursively traverse successors of this basic block.
275 cfg::succ_iterator SI = cfg::succ_begin(BB), SE = cfg::succ_end(BB);
276 for (; SI != SE; ++SI) {
277 BasicBlock *RetBB = fixupCFG(*SI, VisitedBlocks, AliveBlocks);
279 assert(ReturnBB == 0 && "One one live child allowed!");
283 return ReturnBB; // Return the result of traversal
289 // DoADCE - Execute the Agressive Dead Code Elimination Algorithm
291 bool opt::DoADCE(Method *M) {
292 if (M->isExternal()) return false;