blob: a38dbc56176fa621f0bb3c56c5a2d74c99483760 [file] [log] [blame]
Chris Lattner02e90d52001-06-30 06:39:11 +00001//===- ADCE.cpp - Code to perform agressive dead code elimination ---------===//
2//
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.
6//
7//===----------------------------------------------------------------------===//
8
9#include "llvm/Optimizations/DCE.h"
10#include "llvm/Instruction.h"
11#include "llvm/Type.h"
Chris Lattnerd8183122001-07-06 16:32:07 +000012#include "llvm/Analysis/Dominators.h"
Chris Lattnerd8183122001-07-06 16:32:07 +000013#include "llvm/Analysis/Writer.h"
Chris Lattnerb8259dd2001-09-09 22:26:47 +000014#include "llvm/iTerminators.h"
Chris Lattner7061dc52001-12-03 18:02:31 +000015#include "llvm/iPHINode.h"
Chris Lattnercee8f9a2001-11-27 00:03:19 +000016#include "Support/STLExtras.h"
17#include "Support/DepthFirstIterator.h"
Chris Lattner72f1e992001-07-08 18:38:36 +000018#include <set>
19#include <algorithm>
Chris Lattner02e90d52001-06-30 06:39:11 +000020
Chris Lattner8a396e52001-09-28 00:06:42 +000021#define DEBUG_ADCE 1
Chris Lattnerb8259dd2001-09-09 22:26:47 +000022
Chris Lattner02e90d52001-06-30 06:39:11 +000023//===----------------------------------------------------------------------===//
24// ADCE Class
25//
26// This class does all of the work of Agressive Dead Code Elimination.
27// It's public interface consists of a constructor and a doADCE() method.
28//
29class ADCE {
30 Method *M; // The method that we are working on...
31 vector<Instruction*> WorkList; // Instructions that just became live
32 set<Instruction*> LiveSet; // The set of live instructions
Chris Lattnerb8259dd2001-09-09 22:26:47 +000033 bool MadeChanges;
Chris Lattner02e90d52001-06-30 06:39:11 +000034
35 //===--------------------------------------------------------------------===//
36 // The public interface for this class
37 //
38public:
39 // ADCE Ctor - Save the method to operate on...
Chris Lattnerb8259dd2001-09-09 22:26:47 +000040 inline ADCE(Method *m) : M(m), MadeChanges(false) {}
Chris Lattner02e90d52001-06-30 06:39:11 +000041
42 // doADCE() - Run the Agressive Dead Code Elimination algorithm, returning
43 // true if the method was modified.
44 bool doADCE();
45
46 //===--------------------------------------------------------------------===//
47 // The implementation of this class
48 //
49private:
50 inline void markInstructionLive(Instruction *I) {
51 if (LiveSet.count(I)) return;
Chris Lattnerb8259dd2001-09-09 22:26:47 +000052#ifdef DEBUG_ADCE
Chris Lattner02e90d52001-06-30 06:39:11 +000053 cerr << "Insn Live: " << I;
Chris Lattnerb8259dd2001-09-09 22:26:47 +000054#endif
Chris Lattner02e90d52001-06-30 06:39:11 +000055 LiveSet.insert(I);
56 WorkList.push_back(I);
57 }
58
Chris Lattner72f1e992001-07-08 18:38:36 +000059 inline void markTerminatorLive(const BasicBlock *BB) {
Chris Lattnerb8259dd2001-09-09 22:26:47 +000060#ifdef DEBUG_ADCE
61 cerr << "Terminat Live: " << BB->getTerminator();
62#endif
63 markInstructionLive((Instruction*)BB->getTerminator());
Chris Lattner72f1e992001-07-08 18:38:36 +000064 }
Chris Lattnerb8259dd2001-09-09 22:26:47 +000065
66 // fixupCFG - Walk the CFG in depth first order, eliminating references to
67 // dead blocks.
68 //
69 BasicBlock *fixupCFG(BasicBlock *Head, set<BasicBlock*> &VisitedBlocks,
70 const set<BasicBlock*> &AliveBlocks);
Chris Lattner02e90d52001-06-30 06:39:11 +000071};
72
73
74
75// doADCE() - Run the Agressive Dead Code Elimination algorithm, returning
76// true if the method was modified.
77//
78bool ADCE::doADCE() {
Chris Lattnerb8259dd2001-09-09 22:26:47 +000079 // Compute the control dependence graph... Note that this has a side effect
80 // on the CFG: a new return bb is added and all returns are merged here.
Chris Lattner02e90d52001-06-30 06:39:11 +000081 //
Chris Lattner72f1e992001-07-08 18:38:36 +000082 cfg::DominanceFrontier CDG(cfg::DominatorSet(M, true));
Chris Lattner02e90d52001-06-30 06:39:11 +000083
Chris Lattnerb8259dd2001-09-09 22:26:47 +000084#ifdef DEBUG_ADCE
85 cerr << "Method: " << M;
86#endif
87
88 // Iterate over all of the instructions in the method, eliminating trivially
89 // dead instructions, and marking instructions live that are known to be
90 // needed. Perform the walk in depth first order so that we avoid marking any
91 // instructions live in basic blocks that are unreachable. These blocks will
92 // be eliminated later, along with the instructions inside.
93 //
Chris Lattner3ff43872001-09-28 22:56:31 +000094 for (df_iterator<Method*> BBI = df_begin(M),
95 BBE = df_end(M);
Chris Lattnerb8259dd2001-09-09 22:26:47 +000096 BBI != BBE; ++BBI) {
97 BasicBlock *BB = *BBI;
98 for (BasicBlock::iterator II = BB->begin(), EI = BB->end(); II != EI; ) {
99 Instruction *I = *II;
100
101 if (I->hasSideEffects() || I->getOpcode() == Instruction::Ret) {
102 markInstructionLive(I);
103 } else {
104 // Check to see if anything is trivially dead
105 if (I->use_size() == 0 && I->getType() != Type::VoidTy) {
106 // Remove the instruction from it's basic block...
107 delete BB->getInstList().remove(II);
108 MadeChanges = true;
109 continue; // Don't increment the iterator past the current slot
110 }
111 }
112
113 ++II; // Increment the inst iterator if the inst wasn't deleted
114 }
115 }
116
117#ifdef DEBUG_ADCE
Chris Lattner02e90d52001-06-30 06:39:11 +0000118 cerr << "Processing work list\n";
Chris Lattnerb8259dd2001-09-09 22:26:47 +0000119#endif
Chris Lattner02e90d52001-06-30 06:39:11 +0000120
Chris Lattner72f1e992001-07-08 18:38:36 +0000121 // AliveBlocks - Set of basic blocks that we know have instructions that are
122 // alive in them...
123 //
124 set<BasicBlock*> AliveBlocks;
125
Chris Lattner02e90d52001-06-30 06:39:11 +0000126 // Process the work list of instructions that just became live... if they
127 // became live, then that means that all of their operands are neccesary as
128 // well... make them live as well.
129 //
130 while (!WorkList.empty()) {
Chris Lattner72f1e992001-07-08 18:38:36 +0000131 Instruction *I = WorkList.back(); // Get an instruction that became live...
Chris Lattner02e90d52001-06-30 06:39:11 +0000132 WorkList.pop_back();
133
Chris Lattner72f1e992001-07-08 18:38:36 +0000134 BasicBlock *BB = I->getParent();
135 if (AliveBlocks.count(BB) == 0) { // Basic block not alive yet...
136 // Mark the basic block as being newly ALIVE... and mark all branches that
137 // this block is control dependant on as being alive also...
138 //
139 AliveBlocks.insert(BB); // Block is now ALIVE!
140 cfg::DominanceFrontier::const_iterator It = CDG.find(BB);
141 if (It != CDG.end()) {
142 // Get the blocks that this node is control dependant on...
143 const cfg::DominanceFrontier::DomSetType &CDB = It->second;
144 for_each(CDB.begin(), CDB.end(), // Mark all their terminators as live
145 bind_obj(this, &ADCE::markTerminatorLive));
146 }
Chris Lattnerb8259dd2001-09-09 22:26:47 +0000147
148 // If this basic block is live, then the terminator must be as well!
149 markTerminatorLive(BB);
Chris Lattner72f1e992001-07-08 18:38:36 +0000150 }
151
Chris Lattnerb8259dd2001-09-09 22:26:47 +0000152 // Loop over all of the operands of the live instruction, making sure that
153 // they are known to be alive as well...
154 //
Chris Lattner72f1e992001-07-08 18:38:36 +0000155 for (unsigned op = 0, End = I->getNumOperands(); op != End; ++op) {
Chris Lattner9636a912001-10-01 16:18:37 +0000156 if (Instruction *Operand = dyn_cast<Instruction>(I->getOperand(op)))
Chris Lattnerb8259dd2001-09-09 22:26:47 +0000157 markInstructionLive(Operand);
Chris Lattner02e90d52001-06-30 06:39:11 +0000158 }
159 }
160
Chris Lattnerb8259dd2001-09-09 22:26:47 +0000161#ifdef DEBUG_ADCE
162 cerr << "Current Method: X = Live\n";
163 for (Method::inst_iterator IL = M->inst_begin(); IL != M->inst_end(); ++IL) {
164 if (LiveSet.count(*IL)) cerr << "X ";
165 cerr << *IL;
166 }
167#endif
168
169 // After the worklist is processed, recursively walk the CFG in depth first
170 // order, patching up references to dead blocks...
Chris Lattner02e90d52001-06-30 06:39:11 +0000171 //
Chris Lattnerb8259dd2001-09-09 22:26:47 +0000172 set<BasicBlock*> VisitedBlocks;
173 BasicBlock *EntryBlock = fixupCFG(M->front(), VisitedBlocks, AliveBlocks);
174 if (EntryBlock && EntryBlock != M->front()) {
Chris Lattnerb00c5822001-10-02 03:41:24 +0000175 if (isa<PHINode>(EntryBlock->front())) {
Chris Lattnerb8259dd2001-09-09 22:26:47 +0000176 // Cannot make the first block be a block with a PHI node in it! Instead,
177 // strip the first basic block of the method to contain no instructions,
178 // then add a simple branch to the "real" entry node...
179 //
180 BasicBlock *E = M->front();
Chris Lattnerb00c5822001-10-02 03:41:24 +0000181 if (!isa<TerminatorInst>(E->front()) || // Check for an actual change...
182 cast<TerminatorInst>(E->front())->getNumSuccessors() != 1 ||
183 cast<TerminatorInst>(E->front())->getSuccessor(0) != EntryBlock) {
Chris Lattnerb8259dd2001-09-09 22:26:47 +0000184 E->getInstList().delete_all(); // Delete all instructions in block
185 E->getInstList().push_back(new BranchInst(EntryBlock));
186 MadeChanges = true;
187 }
188 AliveBlocks.insert(E);
Chris Lattner8a396e52001-09-28 00:06:42 +0000189
190 // Next we need to change any PHI nodes in the entry block to refer to the
191 // new predecessor node...
192
193
Chris Lattnerb8259dd2001-09-09 22:26:47 +0000194 } else {
195 // We need to move the new entry block to be the first bb of the method.
196 Method::iterator EBI = find(M->begin(), M->end(), EntryBlock);
197 swap(*EBI, *M->begin()); // Exchange old location with start of method
198 MadeChanges = true;
Chris Lattner02e90d52001-06-30 06:39:11 +0000199 }
Chris Lattner02e90d52001-06-30 06:39:11 +0000200 }
201
Chris Lattnerb8259dd2001-09-09 22:26:47 +0000202 // Now go through and tell dead blocks to drop all of their references so they
203 // can be safely deleted.
204 //
205 for (Method::iterator BI = M->begin(), BE = M->end(); BI != BE; ++BI) {
206 BasicBlock *BB = *BI;
207 if (!AliveBlocks.count(BB)) {
208 BB->dropAllReferences();
209 }
210 }
211
212 // Now loop through all of the blocks and delete them. We can safely do this
213 // now because we know that there are no references to dead blocks (because
214 // they have dropped all of their references...
215 //
216 for (Method::iterator BI = M->begin(); BI != M->end();) {
217 if (!AliveBlocks.count(*BI)) {
218 delete M->getBasicBlocks().remove(BI);
219 MadeChanges = true;
220 continue; // Don't increment iterator
221 }
222 ++BI; // Increment iterator...
223 }
224
225 return MadeChanges;
Chris Lattner02e90d52001-06-30 06:39:11 +0000226}
227
228
Chris Lattnerb8259dd2001-09-09 22:26:47 +0000229// fixupCFG - Walk the CFG in depth first order, eliminating references to
230// dead blocks:
231// If the BB is alive (in AliveBlocks):
232// 1. Eliminate all dead instructions in the BB
233// 2. Recursively traverse all of the successors of the BB:
234// - If the returned successor is non-null, update our terminator to
235// reference the returned BB
236// 3. Return 0 (no update needed)
237//
238// If the BB is dead (not in AliveBlocks):
239// 1. Add the BB to the dead set
240// 2. Recursively traverse all of the successors of the block:
241// - Only one shall return a nonnull value (or else this block should have
242// been in the alive set).
243// 3. Return the nonnull child, or 0 if no non-null children.
244//
245BasicBlock *ADCE::fixupCFG(BasicBlock *BB, set<BasicBlock*> &VisitedBlocks,
246 const set<BasicBlock*> &AliveBlocks) {
247 if (VisitedBlocks.count(BB)) return 0; // Revisiting a node? No update.
248 VisitedBlocks.insert(BB); // We have now visited this node!
249
250#ifdef DEBUG_ADCE
251 cerr << "Fixing up BB: " << BB;
252#endif
253
254 if (AliveBlocks.count(BB)) { // Is the block alive?
255 // Yes it's alive: loop through and eliminate all dead instructions in block
256 for (BasicBlock::iterator II = BB->begin(); II != BB->end()-1; ) {
257 Instruction *I = *II;
258 if (!LiveSet.count(I)) { // Is this instruction alive?
259 // Nope... remove the instruction from it's basic block...
260 delete BB->getInstList().remove(II);
261 MadeChanges = true;
262 continue; // Don't increment II
263 }
264 ++II;
265 }
266
267 // Recursively traverse successors of this basic block.
Chris Lattnerf0604b82001-10-01 13:19:53 +0000268 BasicBlock::succ_iterator SI = BB->succ_begin(), SE = BB->succ_end();
Chris Lattnerb8259dd2001-09-09 22:26:47 +0000269 for (; SI != SE; ++SI) {
270 BasicBlock *Succ = *SI;
271 BasicBlock *Repl = fixupCFG(Succ, VisitedBlocks, AliveBlocks);
272 if (Repl && Repl != Succ) { // We have to replace the successor
273 Succ->replaceAllUsesWith(Repl);
274 MadeChanges = true;
275 }
276 }
277 return BB;
278 } else { // Otherwise the block is dead...
279 BasicBlock *ReturnBB = 0; // Default to nothing live down here
280
281 // Recursively traverse successors of this basic block.
Chris Lattnerf0604b82001-10-01 13:19:53 +0000282 BasicBlock::succ_iterator SI = BB->succ_begin(), SE = BB->succ_end();
Chris Lattnerb8259dd2001-09-09 22:26:47 +0000283 for (; SI != SE; ++SI) {
284 BasicBlock *RetBB = fixupCFG(*SI, VisitedBlocks, AliveBlocks);
285 if (RetBB) {
286 assert(ReturnBB == 0 && "One one live child allowed!");
287 ReturnBB = RetBB;
288 }
289 }
290 return ReturnBB; // Return the result of traversal
291 }
292}
293
294
295
Chris Lattner5680ee62001-10-18 01:32:34 +0000296// doADCE - Execute the Agressive Dead Code Elimination Algorithm
Chris Lattner02e90d52001-06-30 06:39:11 +0000297//
Chris Lattner5680ee62001-10-18 01:32:34 +0000298bool opt::AgressiveDCE::doADCE(Method *M) {
Chris Lattnerb8259dd2001-09-09 22:26:47 +0000299 if (M->isExternal()) return false;
Chris Lattner02e90d52001-06-30 06:39:11 +0000300 ADCE DCE(M);
301 return DCE.doADCE();
302}