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/Instruction.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 "Support/STLExtras.h"
17 #include "Support/DepthFirstIterator.h"
25 //===----------------------------------------------------------------------===//
28 // This class does all of the work of Agressive Dead Code Elimination.
29 // It's public interface consists of a constructor and a doADCE() method.
32 Method *M; // The method that we are working on...
33 std::vector<Instruction*> WorkList; // Instructions that just became live
34 std::set<Instruction*> LiveSet; // The set of live instructions
37 //===--------------------------------------------------------------------===//
38 // The public interface for this class
41 // ADCE Ctor - Save the method to operate on...
42 inline ADCE(Method *m) : M(m), MadeChanges(false) {}
44 // doADCE() - Run the Agressive Dead Code Elimination algorithm, returning
45 // true if the method was modified.
48 //===--------------------------------------------------------------------===//
49 // The implementation of this class
52 inline void markInstructionLive(Instruction *I) {
53 if (LiveSet.count(I)) return;
55 cerr << "Insn Live: " << I;
58 WorkList.push_back(I);
61 inline void markTerminatorLive(const BasicBlock *BB) {
63 cerr << "Terminat Live: " << BB->getTerminator();
65 markInstructionLive((Instruction*)BB->getTerminator());
68 // fixupCFG - Walk the CFG in depth first order, eliminating references to
71 BasicBlock *fixupCFG(BasicBlock *Head, std::set<BasicBlock*> &VisitedBlocks,
72 const std::set<BasicBlock*> &AliveBlocks);
77 // doADCE() - Run the Agressive Dead Code Elimination algorithm, returning
78 // true if the method was modified.
81 // Compute the control dependence graph... Note that this has a side effect
82 // on the CFG: a new return bb is added and all returns are merged here.
84 cfg::DominanceFrontier CDG(cfg::DominatorSet(M, true));
87 cerr << "Method: " << M;
90 // Iterate over all of the instructions in the method, eliminating trivially
91 // dead instructions, and marking instructions live that are known to be
92 // needed. Perform the walk in depth first order so that we avoid marking any
93 // instructions live in basic blocks that are unreachable. These blocks will
94 // be eliminated later, along with the instructions inside.
96 for (df_iterator<Method*> BBI = df_begin(M),
99 BasicBlock *BB = *BBI;
100 for (BasicBlock::iterator II = BB->begin(), EI = BB->end(); II != EI; ) {
101 Instruction *I = *II;
103 if (I->hasSideEffects() || I->getOpcode() == Instruction::Ret) {
104 markInstructionLive(I);
106 // Check to see if anything is trivially dead
107 if (I->use_size() == 0 && I->getType() != Type::VoidTy) {
108 // Remove the instruction from it's basic block...
109 delete BB->getInstList().remove(II);
111 continue; // Don't increment the iterator past the current slot
115 ++II; // Increment the inst iterator if the inst wasn't deleted
120 cerr << "Processing work list\n";
123 // AliveBlocks - Set of basic blocks that we know have instructions that are
126 std::set<BasicBlock*> AliveBlocks;
128 // Process the work list of instructions that just became live... if they
129 // became live, then that means that all of their operands are neccesary as
130 // well... make them live as well.
132 while (!WorkList.empty()) {
133 Instruction *I = WorkList.back(); // Get an instruction that became live...
136 BasicBlock *BB = I->getParent();
137 if (AliveBlocks.count(BB) == 0) { // Basic block not alive yet...
138 // Mark the basic block as being newly ALIVE... and mark all branches that
139 // this block is control dependant on as being alive also...
141 AliveBlocks.insert(BB); // Block is now ALIVE!
142 cfg::DominanceFrontier::const_iterator It = CDG.find(BB);
143 if (It != CDG.end()) {
144 // Get the blocks that this node is control dependant on...
145 const cfg::DominanceFrontier::DomSetType &CDB = It->second;
146 for_each(CDB.begin(), CDB.end(), // Mark all their terminators as live
147 bind_obj(this, &ADCE::markTerminatorLive));
150 // If this basic block is live, then the terminator must be as well!
151 markTerminatorLive(BB);
154 // Loop over all of the operands of the live instruction, making sure that
155 // they are known to be alive as well...
157 for (unsigned op = 0, End = I->getNumOperands(); op != End; ++op) {
158 if (Instruction *Operand = dyn_cast<Instruction>(I->getOperand(op)))
159 markInstructionLive(Operand);
164 cerr << "Current Method: X = Live\n";
165 for (Method::inst_iterator IL = M->inst_begin(); IL != M->inst_end(); ++IL) {
166 if (LiveSet.count(*IL)) cerr << "X ";
171 // After the worklist is processed, recursively walk the CFG in depth first
172 // order, patching up references to dead blocks...
174 std::set<BasicBlock*> VisitedBlocks;
175 BasicBlock *EntryBlock = fixupCFG(M->front(), VisitedBlocks, AliveBlocks);
176 if (EntryBlock && EntryBlock != M->front()) {
177 if (isa<PHINode>(EntryBlock->front())) {
178 // Cannot make the first block be a block with a PHI node in it! Instead,
179 // strip the first basic block of the method to contain no instructions,
180 // then add a simple branch to the "real" entry node...
182 BasicBlock *E = M->front();
183 if (!isa<TerminatorInst>(E->front()) || // Check for an actual change...
184 cast<TerminatorInst>(E->front())->getNumSuccessors() != 1 ||
185 cast<TerminatorInst>(E->front())->getSuccessor(0) != EntryBlock) {
186 E->getInstList().delete_all(); // Delete all instructions in block
187 E->getInstList().push_back(new BranchInst(EntryBlock));
190 AliveBlocks.insert(E);
192 // Next we need to change any PHI nodes in the entry block to refer to the
193 // new predecessor node...
197 // We need to move the new entry block to be the first bb of the method.
198 Method::iterator EBI = find(M->begin(), M->end(), EntryBlock);
199 std::swap(*EBI, *M->begin());// Exchange old location with start of method
204 // Now go through and tell dead blocks to drop all of their references so they
205 // can be safely deleted.
207 for (Method::iterator BI = M->begin(), BE = M->end(); BI != BE; ++BI) {
208 BasicBlock *BB = *BI;
209 if (!AliveBlocks.count(BB)) {
210 BB->dropAllReferences();
214 // Now loop through all of the blocks and delete them. We can safely do this
215 // now because we know that there are no references to dead blocks (because
216 // they have dropped all of their references...
218 for (Method::iterator BI = M->begin(); BI != M->end();) {
219 if (!AliveBlocks.count(*BI)) {
220 delete M->getBasicBlocks().remove(BI);
222 continue; // Don't increment iterator
224 ++BI; // Increment iterator...
231 // fixupCFG - Walk the CFG in depth first order, eliminating references to
233 // If the BB is alive (in AliveBlocks):
234 // 1. Eliminate all dead instructions in the BB
235 // 2. Recursively traverse all of the successors of the BB:
236 // - If the returned successor is non-null, update our terminator to
237 // reference the returned BB
238 // 3. Return 0 (no update needed)
240 // If the BB is dead (not in AliveBlocks):
241 // 1. Add the BB to the dead set
242 // 2. Recursively traverse all of the successors of the block:
243 // - Only one shall return a nonnull value (or else this block should have
244 // been in the alive set).
245 // 3. Return the nonnull child, or 0 if no non-null children.
247 BasicBlock *ADCE::fixupCFG(BasicBlock *BB, std::set<BasicBlock*> &VisitedBlocks,
248 const std::set<BasicBlock*> &AliveBlocks) {
249 if (VisitedBlocks.count(BB)) return 0; // Revisiting a node? No update.
250 VisitedBlocks.insert(BB); // We have now visited this node!
253 cerr << "Fixing up BB: " << BB;
256 if (AliveBlocks.count(BB)) { // Is the block alive?
257 // Yes it's alive: loop through and eliminate all dead instructions in block
258 for (BasicBlock::iterator II = BB->begin(); II != BB->end()-1; ) {
259 Instruction *I = *II;
260 if (!LiveSet.count(I)) { // Is this instruction alive?
261 // Nope... remove the instruction from it's basic block...
262 delete BB->getInstList().remove(II);
264 continue; // Don't increment II
269 // Recursively traverse successors of this basic block.
270 BasicBlock::succ_iterator SI = BB->succ_begin(), SE = BB->succ_end();
271 for (; SI != SE; ++SI) {
272 BasicBlock *Succ = *SI;
273 BasicBlock *Repl = fixupCFG(Succ, VisitedBlocks, AliveBlocks);
274 if (Repl && Repl != Succ) { // We have to replace the successor
275 Succ->replaceAllUsesWith(Repl);
280 } else { // Otherwise the block is dead...
281 BasicBlock *ReturnBB = 0; // Default to nothing live down here
283 // Recursively traverse successors of this basic block.
284 BasicBlock::succ_iterator SI = BB->succ_begin(), SE = BB->succ_end();
285 for (; SI != SE; ++SI) {
286 BasicBlock *RetBB = fixupCFG(*SI, VisitedBlocks, AliveBlocks);
288 assert(ReturnBB == 0 && "One one live child allowed!");
292 return ReturnBB; // Return the result of traversal
298 // doADCE - Execute the Agressive Dead Code Elimination Algorithm
300 bool AgressiveDCE::doADCE(Method *M) {
301 if (M->isExternal()) return false;