blob: 18c11c3adee12d82a41f3ebdb693b7767cbb9442 [file] [log] [blame]
Chris Lattnerc1496bda2002-05-07 22:11:39 +00001//===- ADCE.cpp - Code to perform aggressive dead code elimination --------===//
John Criswell482202a2003-10-20 19:43:21 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
Chris Lattnerb28986f2001-06-30 06:39:11 +00009//
Chris Lattnerc1496bda2002-05-07 22:11:39 +000010// This file implements "aggressive" dead code elimination. ADCE is DCe where
Chris Lattnerb28986f2001-06-30 06:39:11 +000011// values are assumed to be dead until proven otherwise. This is similar to
12// SCCP, except applied to the liveness of values.
13//
14//===----------------------------------------------------------------------===//
15
Chris Lattnerb4cfa7f2002-05-07 20:03:00 +000016#include "llvm/Transforms/Scalar.h"
Chris Lattner559f0ee2002-05-22 21:32:16 +000017#include "llvm/Constant.h"
Chris Lattnercfa1adc2004-04-10 06:53:09 +000018#include "llvm/Instructions.h"
19#include "llvm/Type.h"
20#include "llvm/Analysis/AliasAnalysis.h"
21#include "llvm/Analysis/PostDominators.h"
Chris Lattner60a65912002-02-12 21:07:25 +000022#include "llvm/Support/CFG.h"
Chris Lattnerfc7bdac2003-12-19 09:08:34 +000023#include "llvm/Transforms/Utils/BasicBlockUtils.h"
24#include "llvm/Transforms/Utils/Local.h"
25#include "llvm/Transforms/Utils/UnifyFunctionExitNodes.h"
Chris Lattner8abcd562003-08-01 22:15:03 +000026#include "Support/Debug.h"
Chris Lattner5de22042001-11-27 00:03:19 +000027#include "Support/DepthFirstIterator.h"
Chris Lattnerbf3a0992002-10-01 22:38:41 +000028#include "Support/Statistic.h"
Chris Lattner8abcd562003-08-01 22:15:03 +000029#include "Support/STLExtras.h"
Chris Lattnerfb8ed0c2001-07-08 18:38:36 +000030#include <algorithm>
Chris Lattnerfc7bdac2003-12-19 09:08:34 +000031using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000032
Chris Lattner019f3642002-05-06 17:27:57 +000033namespace {
Chris Lattnerbf3a0992002-10-01 22:38:41 +000034 Statistic<> NumBlockRemoved("adce", "Number of basic blocks removed");
35 Statistic<> NumInstRemoved ("adce", "Number of instructions removed");
Chris Lattnercfa1adc2004-04-10 06:53:09 +000036 Statistic<> NumCallRemoved ("adce", "Number of calls and invokes removed");
Chris Lattner019f3642002-05-06 17:27:57 +000037
Chris Lattnerb28986f2001-06-30 06:39:11 +000038//===----------------------------------------------------------------------===//
39// ADCE Class
40//
Chris Lattnerc1496bda2002-05-07 22:11:39 +000041// This class does all of the work of Aggressive Dead Code Elimination.
Chris Lattnerb28986f2001-06-30 06:39:11 +000042// It's public interface consists of a constructor and a doADCE() method.
43//
Chris Lattner019f3642002-05-06 17:27:57 +000044class ADCE : public FunctionPass {
45 Function *Func; // The function that we are working on
Chris Lattnercfa1adc2004-04-10 06:53:09 +000046 AliasAnalysis *AA; // Current AliasAnalysis object
Chris Lattner7f74a562002-01-20 22:54:45 +000047 std::vector<Instruction*> WorkList; // Instructions that just became live
48 std::set<Instruction*> LiveSet; // The set of live instructions
Chris Lattnerb28986f2001-06-30 06:39:11 +000049
50 //===--------------------------------------------------------------------===//
51 // The public interface for this class
52 //
53public:
Chris Lattner559f0ee2002-05-22 21:32:16 +000054 // Execute the Aggressive Dead Code Elimination Algorithm
Chris Lattner019f3642002-05-06 17:27:57 +000055 //
Chris Lattner113f4f42002-06-25 16:13:24 +000056 virtual bool runOnFunction(Function &F) {
57 Func = &F;
Chris Lattnercfa1adc2004-04-10 06:53:09 +000058 AA = &getAnalysis<AliasAnalysis>();
Chris Lattner559f0ee2002-05-22 21:32:16 +000059 bool Changed = doADCE();
Chris Lattner019f3642002-05-06 17:27:57 +000060 assert(WorkList.empty());
61 LiveSet.clear();
Chris Lattner559f0ee2002-05-22 21:32:16 +000062 return Changed;
Chris Lattner019f3642002-05-06 17:27:57 +000063 }
64 // getAnalysisUsage - We require post dominance frontiers (aka Control
65 // Dependence Graph)
66 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerfc7bdac2003-12-19 09:08:34 +000067 // We require that all function nodes are unified, because otherwise code
68 // can be marked live that wouldn't necessarily be otherwise.
69 AU.addRequired<UnifyFunctionExitNodes>();
Chris Lattnercfa1adc2004-04-10 06:53:09 +000070 AU.addRequired<AliasAnalysis>();
Chris Lattnerf0ed55d2002-08-08 19:01:30 +000071 AU.addRequired<PostDominatorTree>();
72 AU.addRequired<PostDominanceFrontier>();
Chris Lattner019f3642002-05-06 17:27:57 +000073 }
Chris Lattnerb28986f2001-06-30 06:39:11 +000074
Chris Lattnerb28986f2001-06-30 06:39:11 +000075
76 //===--------------------------------------------------------------------===//
77 // The implementation of this class
78 //
79private:
Chris Lattnerc1496bda2002-05-07 22:11:39 +000080 // doADCE() - Run the Aggressive Dead Code Elimination algorithm, returning
Chris Lattner019f3642002-05-06 17:27:57 +000081 // true if the function was modified.
82 //
Chris Lattner559f0ee2002-05-22 21:32:16 +000083 bool doADCE();
84
85 void markBlockAlive(BasicBlock *BB);
Chris Lattner019f3642002-05-06 17:27:57 +000086
Chris Lattner33fca9762002-07-30 00:22:34 +000087
88 // dropReferencesOfDeadInstructionsInLiveBlock - Loop over all of the
89 // instructions in the specified basic block, dropping references on
90 // instructions that are dead according to LiveSet.
91 bool dropReferencesOfDeadInstructionsInLiveBlock(BasicBlock *BB);
92
Chris Lattneree967712003-06-24 23:02:45 +000093 TerminatorInst *convertToUnconditionalBranch(TerminatorInst *TI);
94
Chris Lattnerb28986f2001-06-30 06:39:11 +000095 inline void markInstructionLive(Instruction *I) {
96 if (LiveSet.count(I)) return;
Chris Lattner8d0a71a2003-05-22 22:00:07 +000097 DEBUG(std::cerr << "Insn Live: " << I);
Chris Lattnerb28986f2001-06-30 06:39:11 +000098 LiveSet.insert(I);
99 WorkList.push_back(I);
100 }
101
Chris Lattnerfb8ed0c2001-07-08 18:38:36 +0000102 inline void markTerminatorLive(const BasicBlock *BB) {
Chris Lattner21580522003-09-10 20:38:14 +0000103 DEBUG(std::cerr << "Terminator Live: " << BB->getTerminator());
104 markInstructionLive(const_cast<TerminatorInst*>(BB->getTerminator()));
Chris Lattnerfb8ed0c2001-07-08 18:38:36 +0000105 }
Chris Lattnerb28986f2001-06-30 06:39:11 +0000106};
107
Chris Lattnerc8b70922002-07-26 21:12:46 +0000108 RegisterOpt<ADCE> X("adce", "Aggressive Dead Code Elimination");
Chris Lattner019f3642002-05-06 17:27:57 +0000109} // End of anonymous namespace
110
Chris Lattnerfc7bdac2003-12-19 09:08:34 +0000111Pass *llvm::createAggressiveDCEPass() { return new ADCE(); }
Chris Lattner559f0ee2002-05-22 21:32:16 +0000112
Chris Lattner559f0ee2002-05-22 21:32:16 +0000113void ADCE::markBlockAlive(BasicBlock *BB) {
114 // Mark the basic block as being newly ALIVE... and mark all branches that
Misha Brukmanbe372b92003-08-21 22:14:26 +0000115 // this block is control dependent on as being alive also...
Chris Lattner559f0ee2002-05-22 21:32:16 +0000116 //
Chris Lattner64eea742002-07-26 18:40:14 +0000117 PostDominanceFrontier &CDG = getAnalysis<PostDominanceFrontier>();
Chris Lattner559f0ee2002-05-22 21:32:16 +0000118
Chris Lattner64eea742002-07-26 18:40:14 +0000119 PostDominanceFrontier::const_iterator It = CDG.find(BB);
Chris Lattner559f0ee2002-05-22 21:32:16 +0000120 if (It != CDG.end()) {
Misha Brukmanbe372b92003-08-21 22:14:26 +0000121 // Get the blocks that this node is control dependent on...
Chris Lattner64eea742002-07-26 18:40:14 +0000122 const PostDominanceFrontier::DomSetType &CDB = It->second;
Chris Lattner559f0ee2002-05-22 21:32:16 +0000123 for_each(CDB.begin(), CDB.end(), // Mark all their terminators as live
124 bind_obj(this, &ADCE::markTerminatorLive));
125 }
126
Chris Lattner83410552003-06-24 21:49:45 +0000127 // If this basic block is live, and it ends in an unconditional branch, then
128 // the branch is alive as well...
129 if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator()))
130 if (BI->isUnconditional())
131 markTerminatorLive(BB);
Chris Lattner019f3642002-05-06 17:27:57 +0000132}
Chris Lattnerb28986f2001-06-30 06:39:11 +0000133
Chris Lattner33fca9762002-07-30 00:22:34 +0000134// dropReferencesOfDeadInstructionsInLiveBlock - Loop over all of the
135// instructions in the specified basic block, dropping references on
136// instructions that are dead according to LiveSet.
137bool ADCE::dropReferencesOfDeadInstructionsInLiveBlock(BasicBlock *BB) {
138 bool Changed = false;
139 for (BasicBlock::iterator I = BB->begin(), E = --BB->end(); I != E; )
140 if (!LiveSet.count(I)) { // Is this instruction alive?
141 I->dropAllReferences(); // Nope, drop references...
Chris Lattner889f6202003-04-23 16:37:45 +0000142 if (PHINode *PN = dyn_cast<PHINode>(I)) {
Chris Lattner33fca9762002-07-30 00:22:34 +0000143 // We don't want to leave PHI nodes in the program that have
144 // #arguments != #predecessors, so we remove them now.
145 //
146 PN->replaceAllUsesWith(Constant::getNullValue(PN->getType()));
Chris Lattner6149ac82004-04-10 07:02:02 +0000147
148 } else {
149 if (isa<CallInst>(I))
150 ++NumCallRemoved;
151 else
152 ++NumInstRemoved;
Chris Lattner33fca9762002-07-30 00:22:34 +0000153
154 // Delete the instruction...
Chris Lattner6149ac82004-04-10 07:02:02 +0000155 BB->getInstList().erase(I++);
Chris Lattner33fca9762002-07-30 00:22:34 +0000156 Changed = true;
Chris Lattner33fca9762002-07-30 00:22:34 +0000157 }
158 } else {
159 ++I;
160 }
161 return Changed;
162}
163
Chris Lattnerb28986f2001-06-30 06:39:11 +0000164
Chris Lattneree967712003-06-24 23:02:45 +0000165/// convertToUnconditionalBranch - Transform this conditional terminator
166/// instruction into an unconditional branch because we don't care which of the
167/// successors it goes to. This eliminate a use of the condition as well.
168///
169TerminatorInst *ADCE::convertToUnconditionalBranch(TerminatorInst *TI) {
170 BranchInst *NB = new BranchInst(TI->getSuccessor(0), TI);
171 BasicBlock *BB = TI->getParent();
172
173 // Remove entries from PHI nodes to avoid confusing ourself later...
174 for (unsigned i = 1, e = TI->getNumSuccessors(); i != e; ++i)
175 TI->getSuccessor(i)->removePredecessor(BB);
176
177 // Delete the old branch itself...
178 BB->getInstList().erase(TI);
179 return NB;
180}
181
182
Chris Lattnerc1496bda2002-05-07 22:11:39 +0000183// doADCE() - Run the Aggressive Dead Code Elimination algorithm, returning
Chris Lattnerc8e66542002-04-27 06:56:12 +0000184// true if the function was modified.
Chris Lattnerb28986f2001-06-30 06:39:11 +0000185//
Chris Lattner559f0ee2002-05-22 21:32:16 +0000186bool ADCE::doADCE() {
187 bool MadeChanges = false;
Chris Lattneracfd27d2001-09-09 22:26:47 +0000188
Chris Lattnerc8e66542002-04-27 06:56:12 +0000189 // Iterate over all of the instructions in the function, eliminating trivially
Chris Lattneracfd27d2001-09-09 22:26:47 +0000190 // dead instructions, and marking instructions live that are known to be
191 // needed. Perform the walk in depth first order so that we avoid marking any
192 // instructions live in basic blocks that are unreachable. These blocks will
193 // be eliminated later, along with the instructions inside.
194 //
Chris Lattner019f3642002-05-06 17:27:57 +0000195 for (df_iterator<Function*> BBI = df_begin(Func), BBE = df_end(Func);
Chris Lattneracfd27d2001-09-09 22:26:47 +0000196 BBI != BBE; ++BBI) {
197 BasicBlock *BB = *BBI;
198 for (BasicBlock::iterator II = BB->begin(), EI = BB->end(); II != EI; ) {
Chris Lattnercfa1adc2004-04-10 06:53:09 +0000199 Instruction *I = II++;
200 if (CallInst *CI = dyn_cast<CallInst>(I)) {
201 Function *F = CI->getCalledFunction();
202 if (F && AA->onlyReadsMemory(F)) {
203 if (CI->use_empty()) {
204 BB->getInstList().erase(CI);
205 ++NumCallRemoved;
206 }
207 } else {
208 markInstructionLive(I);
209 }
210 } else if (InvokeInst *II = dyn_cast<InvokeInst>(I)) {
211 Function *F = II->getCalledFunction();
212 if (F && AA->onlyReadsMemory(F)) {
213 // The function cannot unwind. Convert it to a call with a branch
214 // after it to the normal destination.
215 std::vector<Value*> Args(II->op_begin()+1, II->op_end());
216 std::string Name = II->getName(); II->setName("");
217 Instruction *NewCall = new CallInst(F, Args, Name, II);
218 II->replaceAllUsesWith(NewCall);
219 new BranchInst(II->getNormalDest(), II);
220 BB->getInstList().erase(II);
221
222 if (NewCall->use_empty()) {
223 BB->getInstList().erase(NewCall);
224 ++NumCallRemoved;
225 }
226 } else {
227 markInstructionLive(I);
228 }
229 } else if (I->mayWriteToMemory() || isa<ReturnInst>(I) ||
230 isa<UnwindInst>(I)) {
231 markInstructionLive(I);
232 } else if (isInstructionTriviallyDead(I)) {
Chris Lattnerc1496bda2002-05-07 22:11:39 +0000233 // Remove the instruction from it's basic block...
Chris Lattnercfa1adc2004-04-10 06:53:09 +0000234 BB->getInstList().erase(I);
Chris Lattner559f0ee2002-05-22 21:32:16 +0000235 ++NumInstRemoved;
Chris Lattneracfd27d2001-09-09 22:26:47 +0000236 }
Chris Lattneracfd27d2001-09-09 22:26:47 +0000237 }
238 }
239
Chris Lattnerdc62f1e2003-06-16 12:10:45 +0000240 // Check to ensure we have an exit node for this CFG. If we don't, we won't
241 // have any post-dominance information, thus we cannot perform our
242 // transformations safely.
243 //
244 PostDominatorTree &DT = getAnalysis<PostDominatorTree>();
Chris Lattner5dac64f2003-09-20 14:39:18 +0000245 if (DT[&Func->getEntryBlock()] == 0) {
Chris Lattnerdc62f1e2003-06-16 12:10:45 +0000246 WorkList.clear();
247 return MadeChanges;
248 }
249
Chris Lattner841dd532003-11-16 21:39:27 +0000250 // Scan the function marking blocks without post-dominance information as
251 // live. Blocks without post-dominance information occur when there is an
252 // infinite loop in the program. Because the infinite loop could contain a
253 // function which unwinds, exits or has side-effects, we don't want to delete
254 // the infinite loop or those blocks leading up to it.
255 for (Function::iterator I = Func->begin(), E = Func->end(); I != E; ++I)
256 if (DT[I] == 0)
257 for (pred_iterator PI = pred_begin(I), E = pred_end(I); PI != E; ++PI)
258 markInstructionLive((*PI)->getTerminator());
259
260
261
Chris Lattner8d0a71a2003-05-22 22:00:07 +0000262 DEBUG(std::cerr << "Processing work list\n");
Chris Lattnerb28986f2001-06-30 06:39:11 +0000263
Chris Lattnerfb8ed0c2001-07-08 18:38:36 +0000264 // AliveBlocks - Set of basic blocks that we know have instructions that are
265 // alive in them...
266 //
Chris Lattner7f74a562002-01-20 22:54:45 +0000267 std::set<BasicBlock*> AliveBlocks;
Chris Lattnerfb8ed0c2001-07-08 18:38:36 +0000268
Chris Lattnerb28986f2001-06-30 06:39:11 +0000269 // Process the work list of instructions that just became live... if they
Misha Brukman7eb05a12003-08-18 14:43:39 +0000270 // became live, then that means that all of their operands are necessary as
Chris Lattnerb28986f2001-06-30 06:39:11 +0000271 // well... make them live as well.
272 //
273 while (!WorkList.empty()) {
Chris Lattnerfb8ed0c2001-07-08 18:38:36 +0000274 Instruction *I = WorkList.back(); // Get an instruction that became live...
Chris Lattnerb28986f2001-06-30 06:39:11 +0000275 WorkList.pop_back();
276
Chris Lattnerfb8ed0c2001-07-08 18:38:36 +0000277 BasicBlock *BB = I->getParent();
Chris Lattner559f0ee2002-05-22 21:32:16 +0000278 if (!AliveBlocks.count(BB)) { // Basic block not alive yet...
279 AliveBlocks.insert(BB); // Block is now ALIVE!
280 markBlockAlive(BB); // Make it so now!
Chris Lattnerfb8ed0c2001-07-08 18:38:36 +0000281 }
282
Chris Lattner559f0ee2002-05-22 21:32:16 +0000283 // PHI nodes are a special case, because the incoming values are actually
284 // defined in the predecessor nodes of this block, meaning that the PHI
285 // makes the predecessors alive.
286 //
287 if (PHINode *PN = dyn_cast<PHINode>(I))
288 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI)
289 if (!AliveBlocks.count(*PI)) {
290 AliveBlocks.insert(BB); // Block is now ALIVE!
291 markBlockAlive(*PI);
292 }
293
Chris Lattneracfd27d2001-09-09 22:26:47 +0000294 // Loop over all of the operands of the live instruction, making sure that
295 // they are known to be alive as well...
296 //
Chris Lattnerc1496bda2002-05-07 22:11:39 +0000297 for (unsigned op = 0, End = I->getNumOperands(); op != End; ++op)
Chris Lattner4b717c02001-10-01 16:18:37 +0000298 if (Instruction *Operand = dyn_cast<Instruction>(I->getOperand(op)))
Chris Lattneracfd27d2001-09-09 22:26:47 +0000299 markInstructionLive(Operand);
Chris Lattnerb28986f2001-06-30 06:39:11 +0000300 }
301
Chris Lattner8d0a71a2003-05-22 22:00:07 +0000302 DEBUG(
303 std::cerr << "Current Function: X = Live\n";
Chris Lattnerdc62f1e2003-06-16 12:10:45 +0000304 for (Function::iterator I = Func->begin(), E = Func->end(); I != E; ++I){
305 std::cerr << I->getName() << ":\t"
306 << (AliveBlocks.count(I) ? "LIVE\n" : "DEAD\n");
Chris Lattner113f4f42002-06-25 16:13:24 +0000307 for (BasicBlock::iterator BI = I->begin(), BE = I->end(); BI != BE; ++BI){
Chris Lattner8d0a71a2003-05-22 22:00:07 +0000308 if (LiveSet.count(BI)) std::cerr << "X ";
309 std::cerr << *BI;
Chris Lattner71cbd422002-05-22 17:17:27 +0000310 }
Chris Lattnerdc62f1e2003-06-16 12:10:45 +0000311 });
Chris Lattneracfd27d2001-09-09 22:26:47 +0000312
Chris Lattner559f0ee2002-05-22 21:32:16 +0000313 // Find the first postdominator of the entry node that is alive. Make it the
314 // new entry node...
Chris Lattnerb28986f2001-06-30 06:39:11 +0000315 //
Chris Lattner33fca9762002-07-30 00:22:34 +0000316 if (AliveBlocks.size() == Func->size()) { // No dead blocks?
Chris Lattneree967712003-06-24 23:02:45 +0000317 for (Function::iterator I = Func->begin(), E = Func->end(); I != E; ++I) {
Chris Lattner33fca9762002-07-30 00:22:34 +0000318 // Loop over all of the instructions in the function, telling dead
319 // instructions to drop their references. This is so that the next sweep
320 // over the program can safely delete dead instructions without other dead
Misha Brukman8b2bd4e2003-10-10 17:57:28 +0000321 // instructions still referring to them.
Chris Lattner33fca9762002-07-30 00:22:34 +0000322 //
323 dropReferencesOfDeadInstructionsInLiveBlock(I);
Chris Lattneree967712003-06-24 23:02:45 +0000324
325 // Check to make sure the terminator instruction is live. If it isn't,
326 // this means that the condition that it branches on (we know it is not an
327 // unconditional branch), is not needed to make the decision of where to
328 // go to, because all outgoing edges go to the same place. We must remove
329 // the use of the condition (because it's probably dead), so we convert
330 // the terminator to a conditional branch.
331 //
332 TerminatorInst *TI = I->getTerminator();
333 if (!LiveSet.count(TI))
334 convertToUnconditionalBranch(TI);
335 }
Chris Lattner33fca9762002-07-30 00:22:34 +0000336
337 } else { // If there are some blocks dead...
Chris Lattner313fd772002-08-14 21:35:02 +0000338 // If the entry node is dead, insert a new entry node to eliminate the entry
339 // node as a special case.
340 //
341 if (!AliveBlocks.count(&Func->front())) {
342 BasicBlock *NewEntry = new BasicBlock();
Chris Lattnera2960002003-11-21 16:52:05 +0000343 new BranchInst(&Func->front(), NewEntry);
Chris Lattner313fd772002-08-14 21:35:02 +0000344 Func->getBasicBlockList().push_front(NewEntry);
345 AliveBlocks.insert(NewEntry); // This block is always alive!
Chris Lattner83410552003-06-24 21:49:45 +0000346 LiveSet.insert(NewEntry->getTerminator()); // The branch is live
Chris Lattner313fd772002-08-14 21:35:02 +0000347 }
Chris Lattner559f0ee2002-05-22 21:32:16 +0000348
349 // Loop over all of the alive blocks in the function. If any successor
350 // blocks are not alive, we adjust the outgoing branches to branch to the
351 // first live postdominator of the live block, adjusting any PHI nodes in
352 // the block to reflect this.
353 //
354 for (Function::iterator I = Func->begin(), E = Func->end(); I != E; ++I)
Chris Lattner113f4f42002-06-25 16:13:24 +0000355 if (AliveBlocks.count(I)) {
356 BasicBlock *BB = I;
Chris Lattner559f0ee2002-05-22 21:32:16 +0000357 TerminatorInst *TI = BB->getTerminator();
358
Chris Lattner83410552003-06-24 21:49:45 +0000359 // If the terminator instruction is alive, but the block it is contained
360 // in IS alive, this means that this terminator is a conditional branch
361 // on a condition that doesn't matter. Make it an unconditional branch
362 // to ONE of the successors. This has the side effect of dropping a use
363 // of the conditional value, which may also be dead.
Chris Lattneree967712003-06-24 23:02:45 +0000364 if (!LiveSet.count(TI))
365 TI = convertToUnconditionalBranch(TI);
Chris Lattner83410552003-06-24 21:49:45 +0000366
Chris Lattneree420b72002-07-29 22:31:39 +0000367 // Loop over all of the successors, looking for ones that are not alive.
368 // We cannot save the number of successors in the terminator instruction
369 // here because we may remove them if we don't have a postdominator...
370 //
371 for (unsigned i = 0; i != TI->getNumSuccessors(); ++i)
Chris Lattner559f0ee2002-05-22 21:32:16 +0000372 if (!AliveBlocks.count(TI->getSuccessor(i))) {
373 // Scan up the postdominator tree, looking for the first
374 // postdominator that is alive, and the last postdominator that is
375 // dead...
376 //
Chris Lattner64eea742002-07-26 18:40:14 +0000377 PostDominatorTree::Node *LastNode = DT[TI->getSuccessor(i)];
Chris Lattneree420b72002-07-29 22:31:39 +0000378
379 // There is a special case here... if there IS no post-dominator for
380 // the block we have no owhere to point our branch to. Instead,
381 // convert it to a return. This can only happen if the code
382 // branched into an infinite loop. Note that this may not be
383 // desirable, because we _are_ altering the behavior of the code.
384 // This is a well known drawback of ADCE, so in the future if we
385 // choose to revisit the decision, this is where it should be.
Chris Lattner559f0ee2002-05-22 21:32:16 +0000386 //
Chris Lattneree420b72002-07-29 22:31:39 +0000387 if (LastNode == 0) { // No postdominator!
388 // Call RemoveSuccessor to transmogrify the terminator instruction
389 // to not contain the outgoing branch, or to create a new
Misha Brukman8b2bd4e2003-10-10 17:57:28 +0000390 // terminator if the form fundamentally changes (i.e.,
391 // unconditional branch to return). Note that this will change a
392 // branch into an infinite loop into a return instruction!
Chris Lattneree420b72002-07-29 22:31:39 +0000393 //
394 RemoveSuccessor(TI, i);
395
396 // RemoveSuccessor may replace TI... make sure we have a fresh
397 // pointer... and e variable.
398 //
399 TI = BB->getTerminator();
400
401 // Rescan this successor...
402 --i;
403 } else {
404 PostDominatorTree::Node *NextNode = LastNode->getIDom();
405
Chris Lattnerbb9d03b2003-09-11 16:26:13 +0000406 while (!AliveBlocks.count(NextNode->getBlock())) {
Chris Lattneree420b72002-07-29 22:31:39 +0000407 LastNode = NextNode;
408 NextNode = NextNode->getIDom();
409 }
410
411 // Get the basic blocks that we need...
Chris Lattnerbb9d03b2003-09-11 16:26:13 +0000412 BasicBlock *LastDead = LastNode->getBlock();
413 BasicBlock *NextAlive = NextNode->getBlock();
Chris Lattneree420b72002-07-29 22:31:39 +0000414
415 // Make the conditional branch now go to the next alive block...
416 TI->getSuccessor(i)->removePredecessor(BB);
417 TI->setSuccessor(i, NextAlive);
418
419 // If there are PHI nodes in NextAlive, we need to add entries to
420 // the PHI nodes for the new incoming edge. The incoming values
421 // should be identical to the incoming values for LastDead.
422 //
423 for (BasicBlock::iterator II = NextAlive->begin();
Chris Lattnerb68a34e2003-04-25 22:53:27 +0000424 PHINode *PN = dyn_cast<PHINode>(II); ++II)
425 if (LiveSet.count(PN)) { // Only modify live phi nodes
426 // Get the incoming value for LastDead...
427 int OldIdx = PN->getBasicBlockIndex(LastDead);
428 assert(OldIdx != -1 &&"LastDead is not a pred of NextAlive!");
429 Value *InVal = PN->getIncomingValue(OldIdx);
430
431 // Add an incoming value for BB now...
432 PN->addIncoming(InVal, BB);
433 }
Chris Lattner559f0ee2002-05-22 21:32:16 +0000434 }
435 }
Chris Lattnerbad1b4d2002-05-10 15:37:35 +0000436
Chris Lattner559f0ee2002-05-22 21:32:16 +0000437 // Now loop over all of the instructions in the basic block, telling
438 // dead instructions to drop their references. This is so that the next
439 // sweep over the program can safely delete dead instructions without
Misha Brukman8b2bd4e2003-10-10 17:57:28 +0000440 // other dead instructions still referring to them.
Chris Lattner559f0ee2002-05-22 21:32:16 +0000441 //
Chris Lattner33fca9762002-07-30 00:22:34 +0000442 dropReferencesOfDeadInstructionsInLiveBlock(BB);
Chris Lattner559f0ee2002-05-22 21:32:16 +0000443 }
Chris Lattneracfd27d2001-09-09 22:26:47 +0000444 }
445
Chris Lattner6fa16292003-01-23 02:12:18 +0000446 // We make changes if there are any dead blocks in the function...
447 if (unsigned NumDeadBlocks = Func->size() - AliveBlocks.size()) {
448 MadeChanges = true;
449 NumBlockRemoved += NumDeadBlocks;
450 }
451
452 // Loop over all of the basic blocks in the function, removing control flow
453 // edges to live blocks (also eliminating any entries in PHI functions in
454 // referenced blocks).
Chris Lattner559f0ee2002-05-22 21:32:16 +0000455 //
Chris Lattner6fa16292003-01-23 02:12:18 +0000456 for (Function::iterator BB = Func->begin(), E = Func->end(); BB != E; ++BB)
Chris Lattner194138c2002-05-28 21:38:16 +0000457 if (!AliveBlocks.count(BB)) {
Chris Lattner559f0ee2002-05-22 21:32:16 +0000458 // Remove all outgoing edges from this basic block and convert the
459 // terminator into a return instruction.
Chris Lattner8d0a71a2003-05-22 22:00:07 +0000460 std::vector<BasicBlock*> Succs(succ_begin(BB), succ_end(BB));
Chris Lattner559f0ee2002-05-22 21:32:16 +0000461
462 if (!Succs.empty()) {
463 // Loop over all of the successors, removing this block from PHI node
464 // entries that might be in the block...
465 while (!Succs.empty()) {
466 Succs.back()->removePredecessor(BB);
467 Succs.pop_back();
468 }
469
470 // Delete the old terminator instruction...
Chris Lattner4cc2cc52003-11-22 02:13:08 +0000471 const Type *TermTy = BB->getTerminator()->getType();
472 if (TermTy != Type::VoidTy)
473 BB->getTerminator()->replaceAllUsesWith(
474 Constant::getNullValue(TermTy));
Chris Lattner113f4f42002-06-25 16:13:24 +0000475 BB->getInstList().pop_back();
Chris Lattner559f0ee2002-05-22 21:32:16 +0000476 const Type *RetTy = Func->getReturnType();
Chris Lattner2af51722003-11-20 18:25:24 +0000477 new ReturnInst(RetTy != Type::VoidTy ?
478 Constant::getNullValue(RetTy) : 0, BB);
Chris Lattner559f0ee2002-05-22 21:32:16 +0000479 }
Chris Lattner559f0ee2002-05-22 21:32:16 +0000480 }
Chris Lattner6fa16292003-01-23 02:12:18 +0000481
482
483 // Loop over all of the basic blocks in the function, dropping references of
484 // the dead basic blocks. We must do this after the previous step to avoid
485 // dropping references to PHIs which still have entries...
486 //
487 for (Function::iterator BB = Func->begin(), E = Func->end(); BB != E; ++BB)
488 if (!AliveBlocks.count(BB))
489 BB->dropAllReferences();
Chris Lattnerbad1b4d2002-05-10 15:37:35 +0000490
Chris Lattner194138c2002-05-28 21:38:16 +0000491 // Now loop through all of the blocks and delete the dead ones. We can safely
492 // do this now because we know that there are no references to dead blocks
493 // (because they have dropped all of their references... we also remove dead
494 // instructions from alive blocks.
Chris Lattneracfd27d2001-09-09 22:26:47 +0000495 //
Chris Lattner559f0ee2002-05-22 21:32:16 +0000496 for (Function::iterator BI = Func->begin(); BI != Func->end(); )
Chris Lattner33fca9762002-07-30 00:22:34 +0000497 if (!AliveBlocks.count(BI)) { // Delete dead blocks...
Chris Lattner113f4f42002-06-25 16:13:24 +0000498 BI = Func->getBasicBlockList().erase(BI);
Chris Lattner33fca9762002-07-30 00:22:34 +0000499 } else { // Scan alive blocks...
Chris Lattner113f4f42002-06-25 16:13:24 +0000500 for (BasicBlock::iterator II = BI->begin(); II != --BI->end(); )
501 if (!LiveSet.count(II)) { // Is this instruction alive?
Chris Lattner194138c2002-05-28 21:38:16 +0000502 // Nope... remove the instruction from it's basic block...
Chris Lattner6149ac82004-04-10 07:02:02 +0000503 if (isa<CallInst>(II))
504 ++NumCallRemoved;
505 else
506 ++NumInstRemoved;
Chris Lattner113f4f42002-06-25 16:13:24 +0000507 II = BI->getInstList().erase(II);
Chris Lattner194138c2002-05-28 21:38:16 +0000508 MadeChanges = true;
509 } else {
510 ++II;
511 }
512
Chris Lattner559f0ee2002-05-22 21:32:16 +0000513 ++BI; // Increment iterator...
Chris Lattner194138c2002-05-28 21:38:16 +0000514 }
Chris Lattnerbad1b4d2002-05-10 15:37:35 +0000515
Chris Lattner559f0ee2002-05-22 21:32:16 +0000516 return MadeChanges;
Chris Lattnerb28986f2001-06-30 06:39:11 +0000517}