blob: 237c4589b2a8b8d42d2a7fffd81536a22c937c8d [file] [log] [blame]
Chris Lattnerc1496bda2002-05-07 22:11:39 +00001//===- ADCE.cpp - Code to perform aggressive dead code elimination --------===//
Chris Lattnerb28986f2001-06-30 06:39:11 +00002//
Chris Lattnerc1496bda2002-05-07 22:11:39 +00003// This file implements "aggressive" dead code elimination. ADCE is DCe where
Chris Lattnerb28986f2001-06-30 06:39:11 +00004// 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 Lattnerc1496bda2002-05-07 22:11:39 +000010#include "llvm/Transforms/Utils/Local.h"
Chris Lattnerb28986f2001-06-30 06:39:11 +000011#include "llvm/Type.h"
Chris Lattner8024bde2001-07-06 16:32:07 +000012#include "llvm/Analysis/Dominators.h"
Chris Lattner8024bde2001-07-06 16:32:07 +000013#include "llvm/Analysis/Writer.h"
Chris Lattneracfd27d2001-09-09 22:26:47 +000014#include "llvm/iTerminators.h"
Chris Lattnerfb5ae022001-12-03 18:02:31 +000015#include "llvm/iPHINode.h"
Chris Lattner559f0ee2002-05-22 21:32:16 +000016#include "llvm/Constant.h"
Chris Lattner60a65912002-02-12 21:07:25 +000017#include "llvm/Support/CFG.h"
Chris Lattner5de22042001-11-27 00:03:19 +000018#include "Support/STLExtras.h"
19#include "Support/DepthFirstIterator.h"
Chris Lattner71cbd422002-05-22 17:17:27 +000020#include "Support/StatisticReporter.h"
Chris Lattnerfb8ed0c2001-07-08 18:38:36 +000021#include <algorithm>
Chris Lattner7f74a562002-01-20 22:54:45 +000022#include <iostream>
23using std::cerr;
Chris Lattnerb28986f2001-06-30 06:39:11 +000024
Chris Lattner559f0ee2002-05-22 21:32:16 +000025static Statistic<> NumBlockRemoved("adce\t\t- Number of basic blocks removed");
26static Statistic<> NumInstRemoved ("adce\t\t- Number of instructions removed");
27
Chris Lattner019f3642002-05-06 17:27:57 +000028namespace {
29
Chris Lattnerb28986f2001-06-30 06:39:11 +000030//===----------------------------------------------------------------------===//
31// ADCE Class
32//
Chris Lattnerc1496bda2002-05-07 22:11:39 +000033// This class does all of the work of Aggressive Dead Code Elimination.
Chris Lattnerb28986f2001-06-30 06:39:11 +000034// It's public interface consists of a constructor and a doADCE() method.
35//
Chris Lattner019f3642002-05-06 17:27:57 +000036class ADCE : public FunctionPass {
37 Function *Func; // The function that we are working on
Chris Lattner7f74a562002-01-20 22:54:45 +000038 std::vector<Instruction*> WorkList; // Instructions that just became live
39 std::set<Instruction*> LiveSet; // The set of live instructions
Chris Lattnerb28986f2001-06-30 06:39:11 +000040
41 //===--------------------------------------------------------------------===//
42 // The public interface for this class
43 //
44public:
Chris Lattner019f3642002-05-06 17:27:57 +000045 const char *getPassName() const { return "Aggressive Dead Code Elimination"; }
46
Chris Lattner559f0ee2002-05-22 21:32:16 +000047 // Execute the Aggressive Dead Code Elimination Algorithm
Chris Lattner019f3642002-05-06 17:27:57 +000048 //
Chris Lattner113f4f42002-06-25 16:13:24 +000049 virtual bool runOnFunction(Function &F) {
50 Func = &F;
Chris Lattner559f0ee2002-05-22 21:32:16 +000051 bool Changed = doADCE();
Chris Lattner019f3642002-05-06 17:27:57 +000052 assert(WorkList.empty());
53 LiveSet.clear();
Chris Lattner559f0ee2002-05-22 21:32:16 +000054 return Changed;
Chris Lattner019f3642002-05-06 17:27:57 +000055 }
56 // getAnalysisUsage - We require post dominance frontiers (aka Control
57 // Dependence Graph)
58 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner559f0ee2002-05-22 21:32:16 +000059 AU.addRequired(DominatorTree::PostDomID);
Chris Lattner019f3642002-05-06 17:27:57 +000060 AU.addRequired(DominanceFrontier::PostDomID);
61 }
Chris Lattnerb28986f2001-06-30 06:39:11 +000062
Chris Lattnerb28986f2001-06-30 06:39:11 +000063
64 //===--------------------------------------------------------------------===//
65 // The implementation of this class
66 //
67private:
Chris Lattnerc1496bda2002-05-07 22:11:39 +000068 // doADCE() - Run the Aggressive Dead Code Elimination algorithm, returning
Chris Lattner019f3642002-05-06 17:27:57 +000069 // true if the function was modified.
70 //
Chris Lattner559f0ee2002-05-22 21:32:16 +000071 bool doADCE();
72
73 void markBlockAlive(BasicBlock *BB);
Chris Lattner019f3642002-05-06 17:27:57 +000074
Chris Lattnerb28986f2001-06-30 06:39:11 +000075 inline void markInstructionLive(Instruction *I) {
76 if (LiveSet.count(I)) return;
Chris Lattner71cbd422002-05-22 17:17:27 +000077 DEBUG(cerr << "Insn Live: " << I);
Chris Lattnerb28986f2001-06-30 06:39:11 +000078 LiveSet.insert(I);
79 WorkList.push_back(I);
80 }
81
Chris Lattnerfb8ed0c2001-07-08 18:38:36 +000082 inline void markTerminatorLive(const BasicBlock *BB) {
Chris Lattner71cbd422002-05-22 17:17:27 +000083 DEBUG(cerr << "Terminat Live: " << BB->getTerminator());
Chris Lattneracfd27d2001-09-09 22:26:47 +000084 markInstructionLive((Instruction*)BB->getTerminator());
Chris Lattnerfb8ed0c2001-07-08 18:38:36 +000085 }
Chris Lattnerb28986f2001-06-30 06:39:11 +000086};
87
Chris Lattner019f3642002-05-06 17:27:57 +000088} // End of anonymous namespace
89
Chris Lattner559f0ee2002-05-22 21:32:16 +000090Pass *createAggressiveDCEPass() { return new ADCE(); }
91
92
93void ADCE::markBlockAlive(BasicBlock *BB) {
94 // Mark the basic block as being newly ALIVE... and mark all branches that
95 // this block is control dependant on as being alive also...
96 //
97 DominanceFrontier &CDG =
98 getAnalysis<DominanceFrontier>(DominanceFrontier::PostDomID);
99
100 DominanceFrontier::const_iterator It = CDG.find(BB);
101 if (It != CDG.end()) {
102 // Get the blocks that this node is control dependant on...
103 const DominanceFrontier::DomSetType &CDB = It->second;
104 for_each(CDB.begin(), CDB.end(), // Mark all their terminators as live
105 bind_obj(this, &ADCE::markTerminatorLive));
106 }
107
108 // If this basic block is live, then the terminator must be as well!
109 markTerminatorLive(BB);
Chris Lattner019f3642002-05-06 17:27:57 +0000110}
Chris Lattnerb28986f2001-06-30 06:39:11 +0000111
112
Chris Lattnerc1496bda2002-05-07 22:11:39 +0000113// doADCE() - Run the Aggressive Dead Code Elimination algorithm, returning
Chris Lattnerc8e66542002-04-27 06:56:12 +0000114// true if the function was modified.
Chris Lattnerb28986f2001-06-30 06:39:11 +0000115//
Chris Lattner559f0ee2002-05-22 21:32:16 +0000116bool ADCE::doADCE() {
117 bool MadeChanges = false;
Chris Lattneracfd27d2001-09-09 22:26:47 +0000118
Chris Lattnerc8e66542002-04-27 06:56:12 +0000119 // Iterate over all of the instructions in the function, eliminating trivially
Chris Lattneracfd27d2001-09-09 22:26:47 +0000120 // dead instructions, and marking instructions live that are known to be
121 // needed. Perform the walk in depth first order so that we avoid marking any
122 // instructions live in basic blocks that are unreachable. These blocks will
123 // be eliminated later, along with the instructions inside.
124 //
Chris Lattner019f3642002-05-06 17:27:57 +0000125 for (df_iterator<Function*> BBI = df_begin(Func), BBE = df_end(Func);
Chris Lattneracfd27d2001-09-09 22:26:47 +0000126 BBI != BBE; ++BBI) {
127 BasicBlock *BB = *BBI;
128 for (BasicBlock::iterator II = BB->begin(), EI = BB->end(); II != EI; ) {
Chris Lattner113f4f42002-06-25 16:13:24 +0000129 if (II->hasSideEffects() || II->getOpcode() == Instruction::Ret) {
130 markInstructionLive(II);
Chris Lattnerc1496bda2002-05-07 22:11:39 +0000131 ++II; // Increment the inst iterator if the inst wasn't deleted
Chris Lattner113f4f42002-06-25 16:13:24 +0000132 } else if (isInstructionTriviallyDead(II)) {
Chris Lattnerc1496bda2002-05-07 22:11:39 +0000133 // Remove the instruction from it's basic block...
Chris Lattner113f4f42002-06-25 16:13:24 +0000134 II = BB->getInstList().erase(II);
Chris Lattner559f0ee2002-05-22 21:32:16 +0000135 ++NumInstRemoved;
Chris Lattnerc1496bda2002-05-07 22:11:39 +0000136 MadeChanges = true;
Chris Lattneracfd27d2001-09-09 22:26:47 +0000137 } else {
Chris Lattnerc1496bda2002-05-07 22:11:39 +0000138 ++II; // Increment the inst iterator if the inst wasn't deleted
Chris Lattneracfd27d2001-09-09 22:26:47 +0000139 }
Chris Lattneracfd27d2001-09-09 22:26:47 +0000140 }
141 }
142
Chris Lattner71cbd422002-05-22 17:17:27 +0000143 DEBUG(cerr << "Processing work list\n");
Chris Lattnerb28986f2001-06-30 06:39:11 +0000144
Chris Lattnerfb8ed0c2001-07-08 18:38:36 +0000145 // AliveBlocks - Set of basic blocks that we know have instructions that are
146 // alive in them...
147 //
Chris Lattner7f74a562002-01-20 22:54:45 +0000148 std::set<BasicBlock*> AliveBlocks;
Chris Lattnerfb8ed0c2001-07-08 18:38:36 +0000149
Chris Lattnerb28986f2001-06-30 06:39:11 +0000150 // Process the work list of instructions that just became live... if they
151 // became live, then that means that all of their operands are neccesary as
152 // well... make them live as well.
153 //
154 while (!WorkList.empty()) {
Chris Lattnerfb8ed0c2001-07-08 18:38:36 +0000155 Instruction *I = WorkList.back(); // Get an instruction that became live...
Chris Lattnerb28986f2001-06-30 06:39:11 +0000156 WorkList.pop_back();
157
Chris Lattnerfb8ed0c2001-07-08 18:38:36 +0000158 BasicBlock *BB = I->getParent();
Chris Lattner559f0ee2002-05-22 21:32:16 +0000159 if (!AliveBlocks.count(BB)) { // Basic block not alive yet...
160 AliveBlocks.insert(BB); // Block is now ALIVE!
161 markBlockAlive(BB); // Make it so now!
Chris Lattnerfb8ed0c2001-07-08 18:38:36 +0000162 }
163
Chris Lattner559f0ee2002-05-22 21:32:16 +0000164 // PHI nodes are a special case, because the incoming values are actually
165 // defined in the predecessor nodes of this block, meaning that the PHI
166 // makes the predecessors alive.
167 //
168 if (PHINode *PN = dyn_cast<PHINode>(I))
169 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI)
170 if (!AliveBlocks.count(*PI)) {
171 AliveBlocks.insert(BB); // Block is now ALIVE!
172 markBlockAlive(*PI);
173 }
174
Chris Lattneracfd27d2001-09-09 22:26:47 +0000175 // Loop over all of the operands of the live instruction, making sure that
176 // they are known to be alive as well...
177 //
Chris Lattnerc1496bda2002-05-07 22:11:39 +0000178 for (unsigned op = 0, End = I->getNumOperands(); op != End; ++op)
Chris Lattner4b717c02001-10-01 16:18:37 +0000179 if (Instruction *Operand = dyn_cast<Instruction>(I->getOperand(op)))
Chris Lattneracfd27d2001-09-09 22:26:47 +0000180 markInstructionLive(Operand);
Chris Lattnerb28986f2001-06-30 06:39:11 +0000181 }
182
Chris Lattner71cbd422002-05-22 17:17:27 +0000183 if (DebugFlag) {
184 cerr << "Current Function: X = Live\n";
185 for (Function::iterator I = Func->begin(), E = Func->end(); I != E; ++I)
Chris Lattner113f4f42002-06-25 16:13:24 +0000186 for (BasicBlock::iterator BI = I->begin(), BE = I->end(); BI != BE; ++BI){
187 if (LiveSet.count(BI)) cerr << "X ";
Chris Lattner71cbd422002-05-22 17:17:27 +0000188 cerr << *BI;
189 }
190 }
Chris Lattneracfd27d2001-09-09 22:26:47 +0000191
Chris Lattner559f0ee2002-05-22 21:32:16 +0000192 // Find the first postdominator of the entry node that is alive. Make it the
193 // new entry node...
Chris Lattnerb28986f2001-06-30 06:39:11 +0000194 //
Chris Lattner559f0ee2002-05-22 21:32:16 +0000195 DominatorTree &DT = getAnalysis<DominatorTree>(DominatorTree::PostDomID);
Chris Lattnerb28986f2001-06-30 06:39:11 +0000196
Chris Lattner559f0ee2002-05-22 21:32:16 +0000197 // If there are some blocks dead...
198 if (AliveBlocks.size() != Func->size()) {
199 // Insert a new entry node to eliminate the entry node as a special case.
200 BasicBlock *NewEntry = new BasicBlock();
Chris Lattner113f4f42002-06-25 16:13:24 +0000201 NewEntry->getInstList().push_back(new BranchInst(&Func->front()));
202 Func->getBasicBlockList().push_front(NewEntry);
Chris Lattner559f0ee2002-05-22 21:32:16 +0000203 AliveBlocks.insert(NewEntry); // This block is always alive!
204
205 // Loop over all of the alive blocks in the function. If any successor
206 // blocks are not alive, we adjust the outgoing branches to branch to the
207 // first live postdominator of the live block, adjusting any PHI nodes in
208 // the block to reflect this.
209 //
210 for (Function::iterator I = Func->begin(), E = Func->end(); I != E; ++I)
Chris Lattner113f4f42002-06-25 16:13:24 +0000211 if (AliveBlocks.count(I)) {
212 BasicBlock *BB = I;
Chris Lattner559f0ee2002-05-22 21:32:16 +0000213 TerminatorInst *TI = BB->getTerminator();
214
215 // Loop over all of the successors, looking for ones that are not alive
216 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
217 if (!AliveBlocks.count(TI->getSuccessor(i))) {
218 // Scan up the postdominator tree, looking for the first
219 // postdominator that is alive, and the last postdominator that is
220 // dead...
221 //
222 DominatorTree::Node *LastNode = DT[TI->getSuccessor(i)];
223 DominatorTree::Node *NextNode = LastNode->getIDom();
224 while (!AliveBlocks.count(NextNode->getNode())) {
225 LastNode = NextNode;
226 NextNode = NextNode->getIDom();
227 }
228
229 // Get the basic blocks that we need...
230 BasicBlock *LastDead = LastNode->getNode();
231 BasicBlock *NextAlive = NextNode->getNode();
232
233 // Make the conditional branch now go to the next alive block...
234 TI->getSuccessor(i)->removePredecessor(BB);
235 TI->setSuccessor(i, NextAlive);
236
237 // If there are PHI nodes in NextAlive, we need to add entries to
238 // the PHI nodes for the new incoming edge. The incoming values
239 // should be identical to the incoming values for LastDead.
240 //
241 for (BasicBlock::iterator II = NextAlive->begin();
Chris Lattner113f4f42002-06-25 16:13:24 +0000242 PHINode *PN = dyn_cast<PHINode>(&*II); ++II) {
Chris Lattner559f0ee2002-05-22 21:32:16 +0000243 // Get the incoming value for LastDead...
244 int OldIdx = PN->getBasicBlockIndex(LastDead);
245 assert(OldIdx != -1 && "LastDead is not a pred of NextAlive!");
246 Value *InVal = PN->getIncomingValue(OldIdx);
247
248 // Add an incoming value for BB now...
249 PN->addIncoming(InVal, BB);
250 }
251 }
Chris Lattnerbad1b4d2002-05-10 15:37:35 +0000252
Chris Lattner559f0ee2002-05-22 21:32:16 +0000253 // Now loop over all of the instructions in the basic block, telling
254 // dead instructions to drop their references. This is so that the next
255 // sweep over the program can safely delete dead instructions without
256 // other dead instructions still refering to them.
257 //
Chris Lattner113f4f42002-06-25 16:13:24 +0000258 for (BasicBlock::iterator I = BB->begin(), E = --BB->end(); I != E; ++I)
259 if (!LiveSet.count(I)) // Is this instruction alive?
260 I->dropAllReferences(); // Nope, drop references...
Chris Lattner559f0ee2002-05-22 21:32:16 +0000261 }
Chris Lattneracfd27d2001-09-09 22:26:47 +0000262 }
263
Chris Lattner194138c2002-05-28 21:38:16 +0000264 // Loop over all of the basic blocks in the function, dropping references of
265 // the dead basic blocks
Chris Lattner559f0ee2002-05-22 21:32:16 +0000266 //
Chris Lattner113f4f42002-06-25 16:13:24 +0000267 for (Function::iterator BB = Func->begin(), E = Func->end(); BB != E; ++BB) {
Chris Lattner194138c2002-05-28 21:38:16 +0000268 if (!AliveBlocks.count(BB)) {
Chris Lattner559f0ee2002-05-22 21:32:16 +0000269 // Remove all outgoing edges from this basic block and convert the
270 // terminator into a return instruction.
271 vector<BasicBlock*> Succs(succ_begin(BB), succ_end(BB));
272
273 if (!Succs.empty()) {
274 // Loop over all of the successors, removing this block from PHI node
275 // entries that might be in the block...
276 while (!Succs.empty()) {
277 Succs.back()->removePredecessor(BB);
278 Succs.pop_back();
279 }
280
281 // Delete the old terminator instruction...
Chris Lattner113f4f42002-06-25 16:13:24 +0000282 BB->getInstList().pop_back();
Chris Lattner559f0ee2002-05-22 21:32:16 +0000283 const Type *RetTy = Func->getReturnType();
284 Instruction *New = new ReturnInst(RetTy != Type::VoidTy ?
285 Constant::getNullValue(RetTy) : 0);
286 BB->getInstList().push_back(New);
287 }
288
289 BB->dropAllReferences();
290 ++NumBlockRemoved;
291 MadeChanges = true;
292 }
293 }
Chris Lattnerbad1b4d2002-05-10 15:37:35 +0000294
Chris Lattner194138c2002-05-28 21:38:16 +0000295 // Now loop through all of the blocks and delete the dead ones. We can safely
296 // do this now because we know that there are no references to dead blocks
297 // (because they have dropped all of their references... we also remove dead
298 // instructions from alive blocks.
Chris Lattneracfd27d2001-09-09 22:26:47 +0000299 //
Chris Lattner559f0ee2002-05-22 21:32:16 +0000300 for (Function::iterator BI = Func->begin(); BI != Func->end(); )
Chris Lattner113f4f42002-06-25 16:13:24 +0000301 if (!AliveBlocks.count(BI))
302 BI = Func->getBasicBlockList().erase(BI);
Chris Lattner194138c2002-05-28 21:38:16 +0000303 else {
Chris Lattner113f4f42002-06-25 16:13:24 +0000304 for (BasicBlock::iterator II = BI->begin(); II != --BI->end(); )
305 if (!LiveSet.count(II)) { // Is this instruction alive?
Chris Lattner194138c2002-05-28 21:38:16 +0000306 // Nope... remove the instruction from it's basic block...
Chris Lattner113f4f42002-06-25 16:13:24 +0000307 II = BI->getInstList().erase(II);
Chris Lattner194138c2002-05-28 21:38:16 +0000308 ++NumInstRemoved;
309 MadeChanges = true;
310 } else {
311 ++II;
312 }
313
Chris Lattner559f0ee2002-05-22 21:32:16 +0000314 ++BI; // Increment iterator...
Chris Lattner194138c2002-05-28 21:38:16 +0000315 }
Chris Lattnerbad1b4d2002-05-10 15:37:35 +0000316
Chris Lattner559f0ee2002-05-22 21:32:16 +0000317 return MadeChanges;
Chris Lattnerb28986f2001-06-30 06:39:11 +0000318}