blob: a22cdce641b40e620123dc226124003b2f930cde [file] [log] [blame]
Chris Lattnerea54ab92002-05-07 22:11:39 +00001//===- ADCE.cpp - Code to perform aggressive dead code elimination --------===//
Chris Lattner02e90d52001-06-30 06:39:11 +00002//
Chris Lattnerea54ab92002-05-07 22:11:39 +00003// This file implements "aggressive" dead code elimination. ADCE is DCe where
Chris Lattner02e90d52001-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 Lattner022103b2002-05-07 20:03:00 +00009#include "llvm/Transforms/Scalar.h"
Chris Lattnerea54ab92002-05-07 22:11:39 +000010#include "llvm/Transforms/Utils/Local.h"
Chris Lattner011de072002-07-29 22:31:39 +000011#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattner02e90d52001-06-30 06:39:11 +000012#include "llvm/Type.h"
Chris Lattnera69fd902002-08-21 23:43:50 +000013#include "llvm/Analysis/PostDominators.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 Lattnerd9036a12002-05-22 21:32:16 +000016#include "llvm/Constant.h"
Chris Lattner221d6882002-02-12 21:07:25 +000017#include "llvm/Support/CFG.h"
Chris Lattner6806f562003-08-01 22:15:03 +000018#include "Support/Debug.h"
Chris Lattnercee8f9a2001-11-27 00:03:19 +000019#include "Support/DepthFirstIterator.h"
Chris Lattnera92f6962002-10-01 22:38:41 +000020#include "Support/Statistic.h"
Chris Lattner6806f562003-08-01 22:15:03 +000021#include "Support/STLExtras.h"
Chris Lattner72f1e992001-07-08 18:38:36 +000022#include <algorithm>
Chris Lattner02e90d52001-06-30 06:39:11 +000023
Chris Lattnerdfe81ab2002-05-06 17:27:57 +000024namespace {
Chris Lattnera92f6962002-10-01 22:38:41 +000025 Statistic<> NumBlockRemoved("adce", "Number of basic blocks removed");
26 Statistic<> NumInstRemoved ("adce", "Number of instructions removed");
Chris Lattnerdfe81ab2002-05-06 17:27:57 +000027
Chris Lattner02e90d52001-06-30 06:39:11 +000028//===----------------------------------------------------------------------===//
29// ADCE Class
30//
Chris Lattnerea54ab92002-05-07 22:11:39 +000031// This class does all of the work of Aggressive Dead Code Elimination.
Chris Lattner02e90d52001-06-30 06:39:11 +000032// It's public interface consists of a constructor and a doADCE() method.
33//
Chris Lattnerdfe81ab2002-05-06 17:27:57 +000034class ADCE : public FunctionPass {
35 Function *Func; // The function that we are working on
Chris Lattner697954c2002-01-20 22:54:45 +000036 std::vector<Instruction*> WorkList; // Instructions that just became live
37 std::set<Instruction*> LiveSet; // The set of live instructions
Chris Lattner02e90d52001-06-30 06:39:11 +000038
39 //===--------------------------------------------------------------------===//
40 // The public interface for this class
41 //
42public:
Chris Lattnerd9036a12002-05-22 21:32:16 +000043 // Execute the Aggressive Dead Code Elimination Algorithm
Chris Lattnerdfe81ab2002-05-06 17:27:57 +000044 //
Chris Lattner7e708292002-06-25 16:13:24 +000045 virtual bool runOnFunction(Function &F) {
46 Func = &F;
Chris Lattnerd9036a12002-05-22 21:32:16 +000047 bool Changed = doADCE();
Chris Lattnerdfe81ab2002-05-06 17:27:57 +000048 assert(WorkList.empty());
49 LiveSet.clear();
Chris Lattnerd9036a12002-05-22 21:32:16 +000050 return Changed;
Chris Lattnerdfe81ab2002-05-06 17:27:57 +000051 }
52 // getAnalysisUsage - We require post dominance frontiers (aka Control
53 // Dependence Graph)
54 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner5f0eb8d2002-08-08 19:01:30 +000055 AU.addRequired<PostDominatorTree>();
56 AU.addRequired<PostDominanceFrontier>();
Chris Lattnerdfe81ab2002-05-06 17:27:57 +000057 }
Chris Lattner02e90d52001-06-30 06:39:11 +000058
Chris Lattner02e90d52001-06-30 06:39:11 +000059
60 //===--------------------------------------------------------------------===//
61 // The implementation of this class
62 //
63private:
Chris Lattnerea54ab92002-05-07 22:11:39 +000064 // doADCE() - Run the Aggressive Dead Code Elimination algorithm, returning
Chris Lattnerdfe81ab2002-05-06 17:27:57 +000065 // true if the function was modified.
66 //
Chris Lattnerd9036a12002-05-22 21:32:16 +000067 bool doADCE();
68
69 void markBlockAlive(BasicBlock *BB);
Chris Lattnerdfe81ab2002-05-06 17:27:57 +000070
Chris Lattner446698b2002-07-30 00:22:34 +000071
72 // dropReferencesOfDeadInstructionsInLiveBlock - Loop over all of the
73 // instructions in the specified basic block, dropping references on
74 // instructions that are dead according to LiveSet.
75 bool dropReferencesOfDeadInstructionsInLiveBlock(BasicBlock *BB);
76
Chris Lattner837e42c2003-06-24 23:02:45 +000077 TerminatorInst *convertToUnconditionalBranch(TerminatorInst *TI);
78
Chris Lattner02e90d52001-06-30 06:39:11 +000079 inline void markInstructionLive(Instruction *I) {
80 if (LiveSet.count(I)) return;
Chris Lattnerde579f12003-05-22 22:00:07 +000081 DEBUG(std::cerr << "Insn Live: " << I);
Chris Lattner02e90d52001-06-30 06:39:11 +000082 LiveSet.insert(I);
83 WorkList.push_back(I);
84 }
85
Chris Lattner72f1e992001-07-08 18:38:36 +000086 inline void markTerminatorLive(const BasicBlock *BB) {
Chris Lattnerde579f12003-05-22 22:00:07 +000087 DEBUG(std::cerr << "Terminat Live: " << BB->getTerminator());
Chris Lattnerb8259dd2001-09-09 22:26:47 +000088 markInstructionLive((Instruction*)BB->getTerminator());
Chris Lattner72f1e992001-07-08 18:38:36 +000089 }
Chris Lattner02e90d52001-06-30 06:39:11 +000090};
91
Chris Lattnera6275cc2002-07-26 21:12:46 +000092 RegisterOpt<ADCE> X("adce", "Aggressive Dead Code Elimination");
Chris Lattnerdfe81ab2002-05-06 17:27:57 +000093} // End of anonymous namespace
94
Chris Lattnerd9036a12002-05-22 21:32:16 +000095Pass *createAggressiveDCEPass() { return new ADCE(); }
96
Chris Lattnerd9036a12002-05-22 21:32:16 +000097void ADCE::markBlockAlive(BasicBlock *BB) {
98 // Mark the basic block as being newly ALIVE... and mark all branches that
99 // this block is control dependant on as being alive also...
100 //
Chris Lattnerce6ef112002-07-26 18:40:14 +0000101 PostDominanceFrontier &CDG = getAnalysis<PostDominanceFrontier>();
Chris Lattnerd9036a12002-05-22 21:32:16 +0000102
Chris Lattnerce6ef112002-07-26 18:40:14 +0000103 PostDominanceFrontier::const_iterator It = CDG.find(BB);
Chris Lattnerd9036a12002-05-22 21:32:16 +0000104 if (It != CDG.end()) {
105 // Get the blocks that this node is control dependant on...
Chris Lattnerce6ef112002-07-26 18:40:14 +0000106 const PostDominanceFrontier::DomSetType &CDB = It->second;
Chris Lattnerd9036a12002-05-22 21:32:16 +0000107 for_each(CDB.begin(), CDB.end(), // Mark all their terminators as live
108 bind_obj(this, &ADCE::markTerminatorLive));
109 }
110
Chris Lattner99c91e02003-06-24 21:49:45 +0000111 // If this basic block is live, and it ends in an unconditional branch, then
112 // the branch is alive as well...
113 if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator()))
114 if (BI->isUnconditional())
115 markTerminatorLive(BB);
Chris Lattnerdfe81ab2002-05-06 17:27:57 +0000116}
Chris Lattner02e90d52001-06-30 06:39:11 +0000117
Chris Lattner446698b2002-07-30 00:22:34 +0000118// dropReferencesOfDeadInstructionsInLiveBlock - Loop over all of the
119// instructions in the specified basic block, dropping references on
120// instructions that are dead according to LiveSet.
121bool ADCE::dropReferencesOfDeadInstructionsInLiveBlock(BasicBlock *BB) {
122 bool Changed = false;
123 for (BasicBlock::iterator I = BB->begin(), E = --BB->end(); I != E; )
124 if (!LiveSet.count(I)) { // Is this instruction alive?
125 I->dropAllReferences(); // Nope, drop references...
Chris Lattnere408e252003-04-23 16:37:45 +0000126 if (PHINode *PN = dyn_cast<PHINode>(I)) {
Chris Lattner446698b2002-07-30 00:22:34 +0000127 // We don't want to leave PHI nodes in the program that have
128 // #arguments != #predecessors, so we remove them now.
129 //
130 PN->replaceAllUsesWith(Constant::getNullValue(PN->getType()));
131
132 // Delete the instruction...
133 I = BB->getInstList().erase(I);
134 Changed = true;
135 } else {
136 ++I;
137 }
138 } else {
139 ++I;
140 }
141 return Changed;
142}
143
Chris Lattner02e90d52001-06-30 06:39:11 +0000144
Chris Lattner837e42c2003-06-24 23:02:45 +0000145/// convertToUnconditionalBranch - Transform this conditional terminator
146/// instruction into an unconditional branch because we don't care which of the
147/// successors it goes to. This eliminate a use of the condition as well.
148///
149TerminatorInst *ADCE::convertToUnconditionalBranch(TerminatorInst *TI) {
150 BranchInst *NB = new BranchInst(TI->getSuccessor(0), TI);
151 BasicBlock *BB = TI->getParent();
152
153 // Remove entries from PHI nodes to avoid confusing ourself later...
154 for (unsigned i = 1, e = TI->getNumSuccessors(); i != e; ++i)
155 TI->getSuccessor(i)->removePredecessor(BB);
156
157 // Delete the old branch itself...
158 BB->getInstList().erase(TI);
159 return NB;
160}
161
162
Chris Lattnerea54ab92002-05-07 22:11:39 +0000163// doADCE() - Run the Aggressive Dead Code Elimination algorithm, returning
Chris Lattnerf57b8452002-04-27 06:56:12 +0000164// true if the function was modified.
Chris Lattner02e90d52001-06-30 06:39:11 +0000165//
Chris Lattnerd9036a12002-05-22 21:32:16 +0000166bool ADCE::doADCE() {
167 bool MadeChanges = false;
Chris Lattnerb8259dd2001-09-09 22:26:47 +0000168
Chris Lattnerf57b8452002-04-27 06:56:12 +0000169 // Iterate over all of the instructions in the function, eliminating trivially
Chris Lattnerb8259dd2001-09-09 22:26:47 +0000170 // dead instructions, and marking instructions live that are known to be
171 // needed. Perform the walk in depth first order so that we avoid marking any
172 // instructions live in basic blocks that are unreachable. These blocks will
173 // be eliminated later, along with the instructions inside.
174 //
Chris Lattnerdfe81ab2002-05-06 17:27:57 +0000175 for (df_iterator<Function*> BBI = df_begin(Func), BBE = df_end(Func);
Chris Lattnerb8259dd2001-09-09 22:26:47 +0000176 BBI != BBE; ++BBI) {
177 BasicBlock *BB = *BBI;
178 for (BasicBlock::iterator II = BB->begin(), EI = BB->end(); II != EI; ) {
Chris Lattnerf0a93ed2003-02-24 20:48:32 +0000179 if (II->mayWriteToMemory() || II->getOpcode() == Instruction::Ret) {
Chris Lattner7e708292002-06-25 16:13:24 +0000180 markInstructionLive(II);
Chris Lattnerea54ab92002-05-07 22:11:39 +0000181 ++II; // Increment the inst iterator if the inst wasn't deleted
Chris Lattner7e708292002-06-25 16:13:24 +0000182 } else if (isInstructionTriviallyDead(II)) {
Chris Lattnerea54ab92002-05-07 22:11:39 +0000183 // Remove the instruction from it's basic block...
Chris Lattner7e708292002-06-25 16:13:24 +0000184 II = BB->getInstList().erase(II);
Chris Lattnerd9036a12002-05-22 21:32:16 +0000185 ++NumInstRemoved;
Chris Lattnerea54ab92002-05-07 22:11:39 +0000186 MadeChanges = true;
Chris Lattnerb8259dd2001-09-09 22:26:47 +0000187 } else {
Chris Lattnerea54ab92002-05-07 22:11:39 +0000188 ++II; // Increment the inst iterator if the inst wasn't deleted
Chris Lattnerb8259dd2001-09-09 22:26:47 +0000189 }
Chris Lattnerb8259dd2001-09-09 22:26:47 +0000190 }
191 }
192
Chris Lattner34e353e2003-06-16 12:10:45 +0000193 // Check to ensure we have an exit node for this CFG. If we don't, we won't
194 // have any post-dominance information, thus we cannot perform our
195 // transformations safely.
196 //
197 PostDominatorTree &DT = getAnalysis<PostDominatorTree>();
198 if (DT[&Func->getEntryNode()] == 0) {
199 WorkList.clear();
200 return MadeChanges;
201 }
202
Chris Lattnerde579f12003-05-22 22:00:07 +0000203 DEBUG(std::cerr << "Processing work list\n");
Chris Lattner02e90d52001-06-30 06:39:11 +0000204
Chris Lattner72f1e992001-07-08 18:38:36 +0000205 // AliveBlocks - Set of basic blocks that we know have instructions that are
206 // alive in them...
207 //
Chris Lattner697954c2002-01-20 22:54:45 +0000208 std::set<BasicBlock*> AliveBlocks;
Chris Lattner72f1e992001-07-08 18:38:36 +0000209
Chris Lattner02e90d52001-06-30 06:39:11 +0000210 // Process the work list of instructions that just became live... if they
Misha Brukman5560c9d2003-08-18 14:43:39 +0000211 // became live, then that means that all of their operands are necessary as
Chris Lattner02e90d52001-06-30 06:39:11 +0000212 // well... make them live as well.
213 //
214 while (!WorkList.empty()) {
Chris Lattner72f1e992001-07-08 18:38:36 +0000215 Instruction *I = WorkList.back(); // Get an instruction that became live...
Chris Lattner02e90d52001-06-30 06:39:11 +0000216 WorkList.pop_back();
217
Chris Lattner72f1e992001-07-08 18:38:36 +0000218 BasicBlock *BB = I->getParent();
Chris Lattnerd9036a12002-05-22 21:32:16 +0000219 if (!AliveBlocks.count(BB)) { // Basic block not alive yet...
220 AliveBlocks.insert(BB); // Block is now ALIVE!
221 markBlockAlive(BB); // Make it so now!
Chris Lattner72f1e992001-07-08 18:38:36 +0000222 }
223
Chris Lattnerd9036a12002-05-22 21:32:16 +0000224 // PHI nodes are a special case, because the incoming values are actually
225 // defined in the predecessor nodes of this block, meaning that the PHI
226 // makes the predecessors alive.
227 //
228 if (PHINode *PN = dyn_cast<PHINode>(I))
229 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI)
230 if (!AliveBlocks.count(*PI)) {
231 AliveBlocks.insert(BB); // Block is now ALIVE!
232 markBlockAlive(*PI);
233 }
234
Chris Lattnerb8259dd2001-09-09 22:26:47 +0000235 // Loop over all of the operands of the live instruction, making sure that
236 // they are known to be alive as well...
237 //
Chris Lattnerea54ab92002-05-07 22:11:39 +0000238 for (unsigned op = 0, End = I->getNumOperands(); op != End; ++op)
Chris Lattner9636a912001-10-01 16:18:37 +0000239 if (Instruction *Operand = dyn_cast<Instruction>(I->getOperand(op)))
Chris Lattnerb8259dd2001-09-09 22:26:47 +0000240 markInstructionLive(Operand);
Chris Lattner02e90d52001-06-30 06:39:11 +0000241 }
242
Chris Lattnerde579f12003-05-22 22:00:07 +0000243 DEBUG(
244 std::cerr << "Current Function: X = Live\n";
Chris Lattner34e353e2003-06-16 12:10:45 +0000245 for (Function::iterator I = Func->begin(), E = Func->end(); I != E; ++I){
246 std::cerr << I->getName() << ":\t"
247 << (AliveBlocks.count(I) ? "LIVE\n" : "DEAD\n");
Chris Lattner7e708292002-06-25 16:13:24 +0000248 for (BasicBlock::iterator BI = I->begin(), BE = I->end(); BI != BE; ++BI){
Chris Lattnerde579f12003-05-22 22:00:07 +0000249 if (LiveSet.count(BI)) std::cerr << "X ";
250 std::cerr << *BI;
Chris Lattnerf016ea42002-05-22 17:17:27 +0000251 }
Chris Lattner34e353e2003-06-16 12:10:45 +0000252 });
Chris Lattnerb8259dd2001-09-09 22:26:47 +0000253
Chris Lattnerd9036a12002-05-22 21:32:16 +0000254 // Find the first postdominator of the entry node that is alive. Make it the
255 // new entry node...
Chris Lattner02e90d52001-06-30 06:39:11 +0000256 //
Chris Lattner446698b2002-07-30 00:22:34 +0000257 if (AliveBlocks.size() == Func->size()) { // No dead blocks?
Chris Lattner837e42c2003-06-24 23:02:45 +0000258 for (Function::iterator I = Func->begin(), E = Func->end(); I != E; ++I) {
Chris Lattner446698b2002-07-30 00:22:34 +0000259 // Loop over all of the instructions in the function, telling dead
260 // instructions to drop their references. This is so that the next sweep
261 // over the program can safely delete dead instructions without other dead
262 // instructions still refering to them.
263 //
264 dropReferencesOfDeadInstructionsInLiveBlock(I);
Chris Lattner837e42c2003-06-24 23:02:45 +0000265
266 // Check to make sure the terminator instruction is live. If it isn't,
267 // this means that the condition that it branches on (we know it is not an
268 // unconditional branch), is not needed to make the decision of where to
269 // go to, because all outgoing edges go to the same place. We must remove
270 // the use of the condition (because it's probably dead), so we convert
271 // the terminator to a conditional branch.
272 //
273 TerminatorInst *TI = I->getTerminator();
274 if (!LiveSet.count(TI))
275 convertToUnconditionalBranch(TI);
276 }
Chris Lattner446698b2002-07-30 00:22:34 +0000277
278 } else { // If there are some blocks dead...
Chris Lattnerdb6e4d62002-08-14 21:35:02 +0000279 // If the entry node is dead, insert a new entry node to eliminate the entry
280 // node as a special case.
281 //
282 if (!AliveBlocks.count(&Func->front())) {
283 BasicBlock *NewEntry = new BasicBlock();
Chris Lattner9e6161c2002-09-10 23:46:10 +0000284 NewEntry->getInstList().push_back(new BranchInst(&Func->front()));
Chris Lattnerdb6e4d62002-08-14 21:35:02 +0000285 Func->getBasicBlockList().push_front(NewEntry);
286 AliveBlocks.insert(NewEntry); // This block is always alive!
Chris Lattner99c91e02003-06-24 21:49:45 +0000287 LiveSet.insert(NewEntry->getTerminator()); // The branch is live
Chris Lattnerdb6e4d62002-08-14 21:35:02 +0000288 }
Chris Lattnerd9036a12002-05-22 21:32:16 +0000289
290 // Loop over all of the alive blocks in the function. If any successor
291 // blocks are not alive, we adjust the outgoing branches to branch to the
292 // first live postdominator of the live block, adjusting any PHI nodes in
293 // the block to reflect this.
294 //
295 for (Function::iterator I = Func->begin(), E = Func->end(); I != E; ++I)
Chris Lattner7e708292002-06-25 16:13:24 +0000296 if (AliveBlocks.count(I)) {
297 BasicBlock *BB = I;
Chris Lattnerd9036a12002-05-22 21:32:16 +0000298 TerminatorInst *TI = BB->getTerminator();
299
Chris Lattner99c91e02003-06-24 21:49:45 +0000300 // If the terminator instruction is alive, but the block it is contained
301 // in IS alive, this means that this terminator is a conditional branch
302 // on a condition that doesn't matter. Make it an unconditional branch
303 // to ONE of the successors. This has the side effect of dropping a use
304 // of the conditional value, which may also be dead.
Chris Lattner837e42c2003-06-24 23:02:45 +0000305 if (!LiveSet.count(TI))
306 TI = convertToUnconditionalBranch(TI);
Chris Lattner99c91e02003-06-24 21:49:45 +0000307
Chris Lattner011de072002-07-29 22:31:39 +0000308 // Loop over all of the successors, looking for ones that are not alive.
309 // We cannot save the number of successors in the terminator instruction
310 // here because we may remove them if we don't have a postdominator...
311 //
312 for (unsigned i = 0; i != TI->getNumSuccessors(); ++i)
Chris Lattnerd9036a12002-05-22 21:32:16 +0000313 if (!AliveBlocks.count(TI->getSuccessor(i))) {
314 // Scan up the postdominator tree, looking for the first
315 // postdominator that is alive, and the last postdominator that is
316 // dead...
317 //
Chris Lattnerce6ef112002-07-26 18:40:14 +0000318 PostDominatorTree::Node *LastNode = DT[TI->getSuccessor(i)];
Chris Lattner011de072002-07-29 22:31:39 +0000319
320 // There is a special case here... if there IS no post-dominator for
321 // the block we have no owhere to point our branch to. Instead,
322 // convert it to a return. This can only happen if the code
323 // branched into an infinite loop. Note that this may not be
324 // desirable, because we _are_ altering the behavior of the code.
325 // This is a well known drawback of ADCE, so in the future if we
326 // choose to revisit the decision, this is where it should be.
Chris Lattnerd9036a12002-05-22 21:32:16 +0000327 //
Chris Lattner011de072002-07-29 22:31:39 +0000328 if (LastNode == 0) { // No postdominator!
329 // Call RemoveSuccessor to transmogrify the terminator instruction
330 // to not contain the outgoing branch, or to create a new
331 // terminator if the form fundementally changes (ie unconditional
332 // branch to return). Note that this will change a branch into an
333 // infinite loop into a return instruction!
334 //
335 RemoveSuccessor(TI, i);
336
337 // RemoveSuccessor may replace TI... make sure we have a fresh
338 // pointer... and e variable.
339 //
340 TI = BB->getTerminator();
341
342 // Rescan this successor...
343 --i;
344 } else {
345 PostDominatorTree::Node *NextNode = LastNode->getIDom();
346
347 while (!AliveBlocks.count(NextNode->getNode())) {
348 LastNode = NextNode;
349 NextNode = NextNode->getIDom();
350 }
351
352 // Get the basic blocks that we need...
353 BasicBlock *LastDead = LastNode->getNode();
354 BasicBlock *NextAlive = NextNode->getNode();
355
356 // Make the conditional branch now go to the next alive block...
357 TI->getSuccessor(i)->removePredecessor(BB);
358 TI->setSuccessor(i, NextAlive);
359
360 // If there are PHI nodes in NextAlive, we need to add entries to
361 // the PHI nodes for the new incoming edge. The incoming values
362 // should be identical to the incoming values for LastDead.
363 //
364 for (BasicBlock::iterator II = NextAlive->begin();
Chris Lattner619f8252003-04-25 22:53:27 +0000365 PHINode *PN = dyn_cast<PHINode>(II); ++II)
366 if (LiveSet.count(PN)) { // Only modify live phi nodes
367 // Get the incoming value for LastDead...
368 int OldIdx = PN->getBasicBlockIndex(LastDead);
369 assert(OldIdx != -1 &&"LastDead is not a pred of NextAlive!");
370 Value *InVal = PN->getIncomingValue(OldIdx);
371
372 // Add an incoming value for BB now...
373 PN->addIncoming(InVal, BB);
374 }
Chris Lattnerd9036a12002-05-22 21:32:16 +0000375 }
376 }
Chris Lattner55547272002-05-10 15:37:35 +0000377
Chris Lattnerd9036a12002-05-22 21:32:16 +0000378 // Now loop over all of the instructions in the basic block, telling
379 // dead instructions to drop their references. This is so that the next
380 // sweep over the program can safely delete dead instructions without
381 // other dead instructions still refering to them.
382 //
Chris Lattner446698b2002-07-30 00:22:34 +0000383 dropReferencesOfDeadInstructionsInLiveBlock(BB);
Chris Lattnerd9036a12002-05-22 21:32:16 +0000384 }
Chris Lattnerb8259dd2001-09-09 22:26:47 +0000385 }
386
Chris Lattnerd7f268d2003-01-23 02:12:18 +0000387 // We make changes if there are any dead blocks in the function...
388 if (unsigned NumDeadBlocks = Func->size() - AliveBlocks.size()) {
389 MadeChanges = true;
390 NumBlockRemoved += NumDeadBlocks;
391 }
392
393 // Loop over all of the basic blocks in the function, removing control flow
394 // edges to live blocks (also eliminating any entries in PHI functions in
395 // referenced blocks).
Chris Lattnerd9036a12002-05-22 21:32:16 +0000396 //
Chris Lattnerd7f268d2003-01-23 02:12:18 +0000397 for (Function::iterator BB = Func->begin(), E = Func->end(); BB != E; ++BB)
Chris Lattner84369b32002-05-28 21:38:16 +0000398 if (!AliveBlocks.count(BB)) {
Chris Lattnerd9036a12002-05-22 21:32:16 +0000399 // Remove all outgoing edges from this basic block and convert the
400 // terminator into a return instruction.
Chris Lattnerde579f12003-05-22 22:00:07 +0000401 std::vector<BasicBlock*> Succs(succ_begin(BB), succ_end(BB));
Chris Lattnerd9036a12002-05-22 21:32:16 +0000402
403 if (!Succs.empty()) {
404 // Loop over all of the successors, removing this block from PHI node
405 // entries that might be in the block...
406 while (!Succs.empty()) {
407 Succs.back()->removePredecessor(BB);
408 Succs.pop_back();
409 }
410
411 // Delete the old terminator instruction...
Chris Lattner7e708292002-06-25 16:13:24 +0000412 BB->getInstList().pop_back();
Chris Lattnerd9036a12002-05-22 21:32:16 +0000413 const Type *RetTy = Func->getReturnType();
Chris Lattner9e6161c2002-09-10 23:46:10 +0000414 BB->getInstList().push_back(new ReturnInst(RetTy != Type::VoidTy ?
415 Constant::getNullValue(RetTy) : 0));
Chris Lattnerd9036a12002-05-22 21:32:16 +0000416 }
Chris Lattnerd9036a12002-05-22 21:32:16 +0000417 }
Chris Lattnerd7f268d2003-01-23 02:12:18 +0000418
419
420 // Loop over all of the basic blocks in the function, dropping references of
421 // the dead basic blocks. We must do this after the previous step to avoid
422 // dropping references to PHIs which still have entries...
423 //
424 for (Function::iterator BB = Func->begin(), E = Func->end(); BB != E; ++BB)
425 if (!AliveBlocks.count(BB))
426 BB->dropAllReferences();
Chris Lattner55547272002-05-10 15:37:35 +0000427
Chris Lattner84369b32002-05-28 21:38:16 +0000428 // Now loop through all of the blocks and delete the dead ones. We can safely
429 // do this now because we know that there are no references to dead blocks
430 // (because they have dropped all of their references... we also remove dead
431 // instructions from alive blocks.
Chris Lattnerb8259dd2001-09-09 22:26:47 +0000432 //
Chris Lattnerd9036a12002-05-22 21:32:16 +0000433 for (Function::iterator BI = Func->begin(); BI != Func->end(); )
Chris Lattner446698b2002-07-30 00:22:34 +0000434 if (!AliveBlocks.count(BI)) { // Delete dead blocks...
Chris Lattner7e708292002-06-25 16:13:24 +0000435 BI = Func->getBasicBlockList().erase(BI);
Chris Lattner446698b2002-07-30 00:22:34 +0000436 } else { // Scan alive blocks...
Chris Lattner7e708292002-06-25 16:13:24 +0000437 for (BasicBlock::iterator II = BI->begin(); II != --BI->end(); )
438 if (!LiveSet.count(II)) { // Is this instruction alive?
Chris Lattner84369b32002-05-28 21:38:16 +0000439 // Nope... remove the instruction from it's basic block...
Chris Lattner7e708292002-06-25 16:13:24 +0000440 II = BI->getInstList().erase(II);
Chris Lattner84369b32002-05-28 21:38:16 +0000441 ++NumInstRemoved;
442 MadeChanges = true;
443 } else {
444 ++II;
445 }
446
Chris Lattnerd9036a12002-05-22 21:32:16 +0000447 ++BI; // Increment iterator...
Chris Lattner84369b32002-05-28 21:38:16 +0000448 }
Chris Lattner55547272002-05-10 15:37:35 +0000449
Chris Lattnerd9036a12002-05-22 21:32:16 +0000450 return MadeChanges;
Chris Lattner02e90d52001-06-30 06:39:11 +0000451}