blob: b2f6463cd0dbb61e6578ccfd5a951a5016f79686 [file] [log] [blame]
Chris Lattnerb28986f2001-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
Chris Lattnerb4cfa7f2002-05-07 20:03:00 +00009#include "llvm/Transforms/Scalar.h"
Chris Lattnerb28986f2001-06-30 06:39:11 +000010#include "llvm/Type.h"
Chris Lattner8024bde2001-07-06 16:32:07 +000011#include "llvm/Analysis/Dominators.h"
Chris Lattner8024bde2001-07-06 16:32:07 +000012#include "llvm/Analysis/Writer.h"
Chris Lattneracfd27d2001-09-09 22:26:47 +000013#include "llvm/iTerminators.h"
Chris Lattnerfb5ae022001-12-03 18:02:31 +000014#include "llvm/iPHINode.h"
Chris Lattner60a65912002-02-12 21:07:25 +000015#include "llvm/Support/CFG.h"
Chris Lattner5de22042001-11-27 00:03:19 +000016#include "Support/STLExtras.h"
17#include "Support/DepthFirstIterator.h"
Chris Lattnerfb8ed0c2001-07-08 18:38:36 +000018#include <algorithm>
Chris Lattner7f74a562002-01-20 22:54:45 +000019#include <iostream>
20using std::cerr;
Chris Lattnerb28986f2001-06-30 06:39:11 +000021
Chris Lattnerb271be32001-09-28 00:06:42 +000022#define DEBUG_ADCE 1
Chris Lattneracfd27d2001-09-09 22:26:47 +000023
Chris Lattner019f3642002-05-06 17:27:57 +000024namespace {
25
Chris Lattnerb28986f2001-06-30 06:39:11 +000026//===----------------------------------------------------------------------===//
27// ADCE Class
28//
29// This class does all of the work of Agressive Dead Code Elimination.
30// It's public interface consists of a constructor and a doADCE() method.
31//
Chris Lattner019f3642002-05-06 17:27:57 +000032class ADCE : public FunctionPass {
33 Function *Func; // The function that we are working on
Chris Lattner7f74a562002-01-20 22:54:45 +000034 std::vector<Instruction*> WorkList; // Instructions that just became live
35 std::set<Instruction*> LiveSet; // The set of live instructions
Chris Lattneracfd27d2001-09-09 22:26:47 +000036 bool MadeChanges;
Chris Lattnerb28986f2001-06-30 06:39:11 +000037
38 //===--------------------------------------------------------------------===//
39 // The public interface for this class
40 //
41public:
Chris Lattner019f3642002-05-06 17:27:57 +000042 const char *getPassName() const { return "Aggressive Dead Code Elimination"; }
43
44 // doADCE - Execute the Agressive Dead Code Elimination Algorithm
45 //
46 virtual bool runOnFunction(Function *F) {
47 Func = F; MadeChanges = false;
48 doADCE(getAnalysis<DominanceFrontier>(DominanceFrontier::PostDomID));
49 assert(WorkList.empty());
50 LiveSet.clear();
51 return MadeChanges;
52 }
53 // getAnalysisUsage - We require post dominance frontiers (aka Control
54 // Dependence Graph)
55 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
56 AU.addRequired(DominanceFrontier::PostDomID);
57 }
Chris Lattnerb28986f2001-06-30 06:39:11 +000058
Chris Lattnerb28986f2001-06-30 06:39:11 +000059
60 //===--------------------------------------------------------------------===//
61 // The implementation of this class
62 //
63private:
Chris Lattner019f3642002-05-06 17:27:57 +000064 // doADCE() - Run the Agressive Dead Code Elimination algorithm, returning
65 // true if the function was modified.
66 //
67 void doADCE(DominanceFrontier &CDG);
68
Chris Lattnerb28986f2001-06-30 06:39:11 +000069 inline void markInstructionLive(Instruction *I) {
70 if (LiveSet.count(I)) return;
Chris Lattneracfd27d2001-09-09 22:26:47 +000071#ifdef DEBUG_ADCE
Chris Lattnerb28986f2001-06-30 06:39:11 +000072 cerr << "Insn Live: " << I;
Chris Lattneracfd27d2001-09-09 22:26:47 +000073#endif
Chris Lattnerb28986f2001-06-30 06:39:11 +000074 LiveSet.insert(I);
75 WorkList.push_back(I);
76 }
77
Chris Lattnerfb8ed0c2001-07-08 18:38:36 +000078 inline void markTerminatorLive(const BasicBlock *BB) {
Chris Lattneracfd27d2001-09-09 22:26:47 +000079#ifdef DEBUG_ADCE
80 cerr << "Terminat Live: " << BB->getTerminator();
81#endif
82 markInstructionLive((Instruction*)BB->getTerminator());
Chris Lattnerfb8ed0c2001-07-08 18:38:36 +000083 }
Chris Lattneracfd27d2001-09-09 22:26:47 +000084
85 // fixupCFG - Walk the CFG in depth first order, eliminating references to
86 // dead blocks.
87 //
Chris Lattner7f74a562002-01-20 22:54:45 +000088 BasicBlock *fixupCFG(BasicBlock *Head, std::set<BasicBlock*> &VisitedBlocks,
89 const std::set<BasicBlock*> &AliveBlocks);
Chris Lattnerb28986f2001-06-30 06:39:11 +000090};
91
Chris Lattner019f3642002-05-06 17:27:57 +000092} // End of anonymous namespace
93
94Pass *createAgressiveDCEPass() {
95 return new ADCE();
96}
Chris Lattnerb28986f2001-06-30 06:39:11 +000097
98
99// doADCE() - Run the Agressive Dead Code Elimination algorithm, returning
Chris Lattnerc8e66542002-04-27 06:56:12 +0000100// true if the function was modified.
Chris Lattnerb28986f2001-06-30 06:39:11 +0000101//
Chris Lattner019f3642002-05-06 17:27:57 +0000102void ADCE::doADCE(DominanceFrontier &CDG) {
Chris Lattneracfd27d2001-09-09 22:26:47 +0000103#ifdef DEBUG_ADCE
Chris Lattner019f3642002-05-06 17:27:57 +0000104 cerr << "Function: " << Func;
Chris Lattneracfd27d2001-09-09 22:26:47 +0000105#endif
106
Chris Lattnerc8e66542002-04-27 06:56:12 +0000107 // Iterate over all of the instructions in the function, eliminating trivially
Chris Lattneracfd27d2001-09-09 22:26:47 +0000108 // dead instructions, and marking instructions live that are known to be
109 // needed. Perform the walk in depth first order so that we avoid marking any
110 // instructions live in basic blocks that are unreachable. These blocks will
111 // be eliminated later, along with the instructions inside.
112 //
Chris Lattner019f3642002-05-06 17:27:57 +0000113 for (df_iterator<Function*> BBI = df_begin(Func), BBE = df_end(Func);
Chris Lattneracfd27d2001-09-09 22:26:47 +0000114 BBI != BBE; ++BBI) {
115 BasicBlock *BB = *BBI;
116 for (BasicBlock::iterator II = BB->begin(), EI = BB->end(); II != EI; ) {
117 Instruction *I = *II;
118
119 if (I->hasSideEffects() || I->getOpcode() == Instruction::Ret) {
120 markInstructionLive(I);
121 } else {
122 // Check to see if anything is trivially dead
123 if (I->use_size() == 0 && I->getType() != Type::VoidTy) {
124 // Remove the instruction from it's basic block...
125 delete BB->getInstList().remove(II);
126 MadeChanges = true;
127 continue; // Don't increment the iterator past the current slot
128 }
129 }
130
131 ++II; // Increment the inst iterator if the inst wasn't deleted
132 }
133 }
134
135#ifdef DEBUG_ADCE
Chris Lattnerb28986f2001-06-30 06:39:11 +0000136 cerr << "Processing work list\n";
Chris Lattneracfd27d2001-09-09 22:26:47 +0000137#endif
Chris Lattnerb28986f2001-06-30 06:39:11 +0000138
Chris Lattnerfb8ed0c2001-07-08 18:38:36 +0000139 // AliveBlocks - Set of basic blocks that we know have instructions that are
140 // alive in them...
141 //
Chris Lattner7f74a562002-01-20 22:54:45 +0000142 std::set<BasicBlock*> AliveBlocks;
Chris Lattnerfb8ed0c2001-07-08 18:38:36 +0000143
Chris Lattnerb28986f2001-06-30 06:39:11 +0000144 // Process the work list of instructions that just became live... if they
145 // became live, then that means that all of their operands are neccesary as
146 // well... make them live as well.
147 //
148 while (!WorkList.empty()) {
Chris Lattnerfb8ed0c2001-07-08 18:38:36 +0000149 Instruction *I = WorkList.back(); // Get an instruction that became live...
Chris Lattnerb28986f2001-06-30 06:39:11 +0000150 WorkList.pop_back();
151
Chris Lattnerfb8ed0c2001-07-08 18:38:36 +0000152 BasicBlock *BB = I->getParent();
153 if (AliveBlocks.count(BB) == 0) { // Basic block not alive yet...
154 // Mark the basic block as being newly ALIVE... and mark all branches that
155 // this block is control dependant on as being alive also...
156 //
157 AliveBlocks.insert(BB); // Block is now ALIVE!
Chris Lattner78dd56f2002-04-28 16:21:30 +0000158 DominanceFrontier::const_iterator It = CDG.find(BB);
Chris Lattnerfb8ed0c2001-07-08 18:38:36 +0000159 if (It != CDG.end()) {
160 // Get the blocks that this node is control dependant on...
Chris Lattner78dd56f2002-04-28 16:21:30 +0000161 const DominanceFrontier::DomSetType &CDB = It->second;
Chris Lattnerfb8ed0c2001-07-08 18:38:36 +0000162 for_each(CDB.begin(), CDB.end(), // Mark all their terminators as live
163 bind_obj(this, &ADCE::markTerminatorLive));
164 }
Chris Lattneracfd27d2001-09-09 22:26:47 +0000165
166 // If this basic block is live, then the terminator must be as well!
167 markTerminatorLive(BB);
Chris Lattnerfb8ed0c2001-07-08 18:38:36 +0000168 }
169
Chris Lattneracfd27d2001-09-09 22:26:47 +0000170 // Loop over all of the operands of the live instruction, making sure that
171 // they are known to be alive as well...
172 //
Chris Lattnerfb8ed0c2001-07-08 18:38:36 +0000173 for (unsigned op = 0, End = I->getNumOperands(); op != End; ++op) {
Chris Lattner4b717c02001-10-01 16:18:37 +0000174 if (Instruction *Operand = dyn_cast<Instruction>(I->getOperand(op)))
Chris Lattneracfd27d2001-09-09 22:26:47 +0000175 markInstructionLive(Operand);
Chris Lattnerb28986f2001-06-30 06:39:11 +0000176 }
177 }
178
Chris Lattneracfd27d2001-09-09 22:26:47 +0000179#ifdef DEBUG_ADCE
Chris Lattnerf8e4dc32002-04-08 22:03:00 +0000180 cerr << "Current Function: X = Live\n";
Chris Lattner019f3642002-05-06 17:27:57 +0000181 for (Function::iterator I = Func->begin(), E = Func->end(); I != E; ++I)
Chris Lattner60a65912002-02-12 21:07:25 +0000182 for (BasicBlock::iterator BI = (*I)->begin(), BE = (*I)->end();
183 BI != BE; ++BI) {
184 if (LiveSet.count(*BI)) cerr << "X ";
185 cerr << *BI;
186 }
Chris Lattneracfd27d2001-09-09 22:26:47 +0000187#endif
188
189 // After the worklist is processed, recursively walk the CFG in depth first
190 // order, patching up references to dead blocks...
Chris Lattnerb28986f2001-06-30 06:39:11 +0000191 //
Chris Lattner7f74a562002-01-20 22:54:45 +0000192 std::set<BasicBlock*> VisitedBlocks;
Chris Lattner019f3642002-05-06 17:27:57 +0000193 BasicBlock *EntryBlock = fixupCFG(Func->front(), VisitedBlocks, AliveBlocks);
194 if (EntryBlock && EntryBlock != Func->front()) {
Chris Lattnerda558102001-10-02 03:41:24 +0000195 if (isa<PHINode>(EntryBlock->front())) {
Chris Lattneracfd27d2001-09-09 22:26:47 +0000196 // Cannot make the first block be a block with a PHI node in it! Instead,
Chris Lattnerc8e66542002-04-27 06:56:12 +0000197 // strip the first basic block of the function to contain no instructions,
Chris Lattneracfd27d2001-09-09 22:26:47 +0000198 // then add a simple branch to the "real" entry node...
199 //
Chris Lattner019f3642002-05-06 17:27:57 +0000200 BasicBlock *E = Func->front();
Chris Lattnerda558102001-10-02 03:41:24 +0000201 if (!isa<TerminatorInst>(E->front()) || // Check for an actual change...
202 cast<TerminatorInst>(E->front())->getNumSuccessors() != 1 ||
203 cast<TerminatorInst>(E->front())->getSuccessor(0) != EntryBlock) {
Chris Lattneracfd27d2001-09-09 22:26:47 +0000204 E->getInstList().delete_all(); // Delete all instructions in block
205 E->getInstList().push_back(new BranchInst(EntryBlock));
206 MadeChanges = true;
207 }
208 AliveBlocks.insert(E);
Chris Lattnerb271be32001-09-28 00:06:42 +0000209
210 // Next we need to change any PHI nodes in the entry block to refer to the
211 // new predecessor node...
212
213
Chris Lattneracfd27d2001-09-09 22:26:47 +0000214 } else {
Chris Lattnerc8e66542002-04-27 06:56:12 +0000215 // We need to move the new entry block to be the first bb of the function
Chris Lattner019f3642002-05-06 17:27:57 +0000216 Function::iterator EBI = find(Func->begin(), Func->end(), EntryBlock);
217 std::swap(*EBI, *Func->begin()); // Exchange old location with start of fn
Chris Lattneracfd27d2001-09-09 22:26:47 +0000218 MadeChanges = true;
Chris Lattnerb28986f2001-06-30 06:39:11 +0000219 }
Chris Lattnerb28986f2001-06-30 06:39:11 +0000220 }
221
Chris Lattneracfd27d2001-09-09 22:26:47 +0000222 // Now go through and tell dead blocks to drop all of their references so they
223 // can be safely deleted.
224 //
Chris Lattner019f3642002-05-06 17:27:57 +0000225 for (Function::iterator BI = Func->begin(), BE = Func->end(); BI != BE; ++BI){
Chris Lattneracfd27d2001-09-09 22:26:47 +0000226 BasicBlock *BB = *BI;
227 if (!AliveBlocks.count(BB)) {
228 BB->dropAllReferences();
229 }
230 }
231
232 // Now loop through all of the blocks and delete them. We can safely do this
233 // now because we know that there are no references to dead blocks (because
234 // they have dropped all of their references...
235 //
Chris Lattner019f3642002-05-06 17:27:57 +0000236 for (Function::iterator BI = Func->begin(); BI != Func->end();) {
Chris Lattneracfd27d2001-09-09 22:26:47 +0000237 if (!AliveBlocks.count(*BI)) {
Chris Lattner019f3642002-05-06 17:27:57 +0000238 delete Func->getBasicBlocks().remove(BI);
Chris Lattneracfd27d2001-09-09 22:26:47 +0000239 MadeChanges = true;
240 continue; // Don't increment iterator
241 }
242 ++BI; // Increment iterator...
243 }
Chris Lattnerb28986f2001-06-30 06:39:11 +0000244}
245
246
Chris Lattneracfd27d2001-09-09 22:26:47 +0000247// fixupCFG - Walk the CFG in depth first order, eliminating references to
248// dead blocks:
249// If the BB is alive (in AliveBlocks):
250// 1. Eliminate all dead instructions in the BB
251// 2. Recursively traverse all of the successors of the BB:
252// - If the returned successor is non-null, update our terminator to
253// reference the returned BB
254// 3. Return 0 (no update needed)
255//
256// If the BB is dead (not in AliveBlocks):
257// 1. Add the BB to the dead set
258// 2. Recursively traverse all of the successors of the block:
259// - Only one shall return a nonnull value (or else this block should have
260// been in the alive set).
261// 3. Return the nonnull child, or 0 if no non-null children.
262//
Chris Lattner7f74a562002-01-20 22:54:45 +0000263BasicBlock *ADCE::fixupCFG(BasicBlock *BB, std::set<BasicBlock*> &VisitedBlocks,
264 const std::set<BasicBlock*> &AliveBlocks) {
Chris Lattneracfd27d2001-09-09 22:26:47 +0000265 if (VisitedBlocks.count(BB)) return 0; // Revisiting a node? No update.
266 VisitedBlocks.insert(BB); // We have now visited this node!
267
268#ifdef DEBUG_ADCE
269 cerr << "Fixing up BB: " << BB;
270#endif
271
272 if (AliveBlocks.count(BB)) { // Is the block alive?
273 // Yes it's alive: loop through and eliminate all dead instructions in block
274 for (BasicBlock::iterator II = BB->begin(); II != BB->end()-1; ) {
275 Instruction *I = *II;
276 if (!LiveSet.count(I)) { // Is this instruction alive?
277 // Nope... remove the instruction from it's basic block...
278 delete BB->getInstList().remove(II);
279 MadeChanges = true;
280 continue; // Don't increment II
281 }
282 ++II;
283 }
284
285 // Recursively traverse successors of this basic block.
Chris Lattner83d485b2002-02-12 22:39:50 +0000286 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI) {
Chris Lattneracfd27d2001-09-09 22:26:47 +0000287 BasicBlock *Succ = *SI;
288 BasicBlock *Repl = fixupCFG(Succ, VisitedBlocks, AliveBlocks);
289 if (Repl && Repl != Succ) { // We have to replace the successor
290 Succ->replaceAllUsesWith(Repl);
291 MadeChanges = true;
292 }
293 }
294 return BB;
295 } else { // Otherwise the block is dead...
296 BasicBlock *ReturnBB = 0; // Default to nothing live down here
297
298 // Recursively traverse successors of this basic block.
Chris Lattner83d485b2002-02-12 22:39:50 +0000299 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI) {
Chris Lattneracfd27d2001-09-09 22:26:47 +0000300 BasicBlock *RetBB = fixupCFG(*SI, VisitedBlocks, AliveBlocks);
301 if (RetBB) {
302 assert(ReturnBB == 0 && "One one live child allowed!");
303 ReturnBB = RetBB;
304 }
305 }
306 return ReturnBB; // Return the result of traversal
307 }
308}
309