1 //===- ADCE.cpp - Code to perform aggressive dead code elimination --------===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
10 // This file implements "aggressive" dead code elimination. ADCE is DCe where
11 // values are assumed to be dead until proven otherwise. This is similar to
12 // SCCP, except applied to the liveness of values.
14 //===----------------------------------------------------------------------===//
16 #include "llvm/Transforms/Scalar.h"
17 #include "llvm/Type.h"
18 #include "llvm/Analysis/PostDominators.h"
19 #include "llvm/iTerminators.h"
20 #include "llvm/iPHINode.h"
21 #include "llvm/Constant.h"
22 #include "llvm/Support/CFG.h"
23 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
24 #include "llvm/Transforms/Utils/Local.h"
25 #include "llvm/Transforms/Utils/UnifyFunctionExitNodes.h"
26 #include "Support/Debug.h"
27 #include "Support/DepthFirstIterator.h"
28 #include "Support/Statistic.h"
29 #include "Support/STLExtras.h"
34 Statistic<> NumBlockRemoved("adce", "Number of basic blocks removed");
35 Statistic<> NumInstRemoved ("adce", "Number of instructions removed");
37 //===----------------------------------------------------------------------===//
40 // This class does all of the work of Aggressive Dead Code Elimination.
41 // It's public interface consists of a constructor and a doADCE() method.
43 class ADCE : public FunctionPass {
44 Function *Func; // The function that we are working on
45 std::vector<Instruction*> WorkList; // Instructions that just became live
46 std::set<Instruction*> LiveSet; // The set of live instructions
48 //===--------------------------------------------------------------------===//
49 // The public interface for this class
52 // Execute the Aggressive Dead Code Elimination Algorithm
54 virtual bool runOnFunction(Function &F) {
56 bool Changed = doADCE();
57 assert(WorkList.empty());
61 // getAnalysisUsage - We require post dominance frontiers (aka Control
63 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
64 // We require that all function nodes are unified, because otherwise code
65 // can be marked live that wouldn't necessarily be otherwise.
66 AU.addRequired<UnifyFunctionExitNodes>();
67 AU.addRequired<PostDominatorTree>();
68 AU.addRequired<PostDominanceFrontier>();
72 //===--------------------------------------------------------------------===//
73 // The implementation of this class
76 // doADCE() - Run the Aggressive Dead Code Elimination algorithm, returning
77 // true if the function was modified.
81 void markBlockAlive(BasicBlock *BB);
84 // dropReferencesOfDeadInstructionsInLiveBlock - Loop over all of the
85 // instructions in the specified basic block, dropping references on
86 // instructions that are dead according to LiveSet.
87 bool dropReferencesOfDeadInstructionsInLiveBlock(BasicBlock *BB);
89 TerminatorInst *convertToUnconditionalBranch(TerminatorInst *TI);
91 inline void markInstructionLive(Instruction *I) {
92 if (LiveSet.count(I)) return;
93 DEBUG(std::cerr << "Insn Live: " << I);
95 WorkList.push_back(I);
98 inline void markTerminatorLive(const BasicBlock *BB) {
99 DEBUG(std::cerr << "Terminator Live: " << BB->getTerminator());
100 markInstructionLive(const_cast<TerminatorInst*>(BB->getTerminator()));
104 RegisterOpt<ADCE> X("adce", "Aggressive Dead Code Elimination");
105 } // End of anonymous namespace
107 Pass *llvm::createAggressiveDCEPass() { return new ADCE(); }
109 void ADCE::markBlockAlive(BasicBlock *BB) {
110 // Mark the basic block as being newly ALIVE... and mark all branches that
111 // this block is control dependent on as being alive also...
113 PostDominanceFrontier &CDG = getAnalysis<PostDominanceFrontier>();
115 PostDominanceFrontier::const_iterator It = CDG.find(BB);
116 if (It != CDG.end()) {
117 // Get the blocks that this node is control dependent on...
118 const PostDominanceFrontier::DomSetType &CDB = It->second;
119 for_each(CDB.begin(), CDB.end(), // Mark all their terminators as live
120 bind_obj(this, &ADCE::markTerminatorLive));
123 // If this basic block is live, and it ends in an unconditional branch, then
124 // the branch is alive as well...
125 if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator()))
126 if (BI->isUnconditional())
127 markTerminatorLive(BB);
130 // dropReferencesOfDeadInstructionsInLiveBlock - Loop over all of the
131 // instructions in the specified basic block, dropping references on
132 // instructions that are dead according to LiveSet.
133 bool ADCE::dropReferencesOfDeadInstructionsInLiveBlock(BasicBlock *BB) {
134 bool Changed = false;
135 for (BasicBlock::iterator I = BB->begin(), E = --BB->end(); I != E; )
136 if (!LiveSet.count(I)) { // Is this instruction alive?
137 I->dropAllReferences(); // Nope, drop references...
138 if (PHINode *PN = dyn_cast<PHINode>(I)) {
139 // We don't want to leave PHI nodes in the program that have
140 // #arguments != #predecessors, so we remove them now.
142 PN->replaceAllUsesWith(Constant::getNullValue(PN->getType()));
144 // Delete the instruction...
145 I = BB->getInstList().erase(I);
157 /// convertToUnconditionalBranch - Transform this conditional terminator
158 /// instruction into an unconditional branch because we don't care which of the
159 /// successors it goes to. This eliminate a use of the condition as well.
161 TerminatorInst *ADCE::convertToUnconditionalBranch(TerminatorInst *TI) {
162 BranchInst *NB = new BranchInst(TI->getSuccessor(0), TI);
163 BasicBlock *BB = TI->getParent();
165 // Remove entries from PHI nodes to avoid confusing ourself later...
166 for (unsigned i = 1, e = TI->getNumSuccessors(); i != e; ++i)
167 TI->getSuccessor(i)->removePredecessor(BB);
169 // Delete the old branch itself...
170 BB->getInstList().erase(TI);
175 // doADCE() - Run the Aggressive Dead Code Elimination algorithm, returning
176 // true if the function was modified.
178 bool ADCE::doADCE() {
179 bool MadeChanges = false;
181 // Iterate over all of the instructions in the function, eliminating trivially
182 // dead instructions, and marking instructions live that are known to be
183 // needed. Perform the walk in depth first order so that we avoid marking any
184 // instructions live in basic blocks that are unreachable. These blocks will
185 // be eliminated later, along with the instructions inside.
187 for (df_iterator<Function*> BBI = df_begin(Func), BBE = df_end(Func);
189 BasicBlock *BB = *BBI;
190 for (BasicBlock::iterator II = BB->begin(), EI = BB->end(); II != EI; ) {
191 if (II->mayWriteToMemory() || isa<ReturnInst>(II) || isa<UnwindInst>(II)){
192 markInstructionLive(II);
193 ++II; // Increment the inst iterator if the inst wasn't deleted
194 } else if (isInstructionTriviallyDead(II)) {
195 // Remove the instruction from it's basic block...
196 II = BB->getInstList().erase(II);
200 ++II; // Increment the inst iterator if the inst wasn't deleted
205 // Check to ensure we have an exit node for this CFG. If we don't, we won't
206 // have any post-dominance information, thus we cannot perform our
207 // transformations safely.
209 PostDominatorTree &DT = getAnalysis<PostDominatorTree>();
210 if (DT[&Func->getEntryBlock()] == 0) {
215 // Scan the function marking blocks without post-dominance information as
216 // live. Blocks without post-dominance information occur when there is an
217 // infinite loop in the program. Because the infinite loop could contain a
218 // function which unwinds, exits or has side-effects, we don't want to delete
219 // the infinite loop or those blocks leading up to it.
220 for (Function::iterator I = Func->begin(), E = Func->end(); I != E; ++I)
222 for (pred_iterator PI = pred_begin(I), E = pred_end(I); PI != E; ++PI)
223 markInstructionLive((*PI)->getTerminator());
227 DEBUG(std::cerr << "Processing work list\n");
229 // AliveBlocks - Set of basic blocks that we know have instructions that are
232 std::set<BasicBlock*> AliveBlocks;
234 // Process the work list of instructions that just became live... if they
235 // became live, then that means that all of their operands are necessary as
236 // well... make them live as well.
238 while (!WorkList.empty()) {
239 Instruction *I = WorkList.back(); // Get an instruction that became live...
242 BasicBlock *BB = I->getParent();
243 if (!AliveBlocks.count(BB)) { // Basic block not alive yet...
244 AliveBlocks.insert(BB); // Block is now ALIVE!
245 markBlockAlive(BB); // Make it so now!
248 // PHI nodes are a special case, because the incoming values are actually
249 // defined in the predecessor nodes of this block, meaning that the PHI
250 // makes the predecessors alive.
252 if (PHINode *PN = dyn_cast<PHINode>(I))
253 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI)
254 if (!AliveBlocks.count(*PI)) {
255 AliveBlocks.insert(BB); // Block is now ALIVE!
259 // Loop over all of the operands of the live instruction, making sure that
260 // they are known to be alive as well...
262 for (unsigned op = 0, End = I->getNumOperands(); op != End; ++op)
263 if (Instruction *Operand = dyn_cast<Instruction>(I->getOperand(op)))
264 markInstructionLive(Operand);
268 std::cerr << "Current Function: X = Live\n";
269 for (Function::iterator I = Func->begin(), E = Func->end(); I != E; ++I){
270 std::cerr << I->getName() << ":\t"
271 << (AliveBlocks.count(I) ? "LIVE\n" : "DEAD\n");
272 for (BasicBlock::iterator BI = I->begin(), BE = I->end(); BI != BE; ++BI){
273 if (LiveSet.count(BI)) std::cerr << "X ";
278 // Find the first postdominator of the entry node that is alive. Make it the
281 if (AliveBlocks.size() == Func->size()) { // No dead blocks?
282 for (Function::iterator I = Func->begin(), E = Func->end(); I != E; ++I) {
283 // Loop over all of the instructions in the function, telling dead
284 // instructions to drop their references. This is so that the next sweep
285 // over the program can safely delete dead instructions without other dead
286 // instructions still referring to them.
288 dropReferencesOfDeadInstructionsInLiveBlock(I);
290 // Check to make sure the terminator instruction is live. If it isn't,
291 // this means that the condition that it branches on (we know it is not an
292 // unconditional branch), is not needed to make the decision of where to
293 // go to, because all outgoing edges go to the same place. We must remove
294 // the use of the condition (because it's probably dead), so we convert
295 // the terminator to a conditional branch.
297 TerminatorInst *TI = I->getTerminator();
298 if (!LiveSet.count(TI))
299 convertToUnconditionalBranch(TI);
302 } else { // If there are some blocks dead...
303 // If the entry node is dead, insert a new entry node to eliminate the entry
304 // node as a special case.
306 if (!AliveBlocks.count(&Func->front())) {
307 BasicBlock *NewEntry = new BasicBlock();
308 new BranchInst(&Func->front(), NewEntry);
309 Func->getBasicBlockList().push_front(NewEntry);
310 AliveBlocks.insert(NewEntry); // This block is always alive!
311 LiveSet.insert(NewEntry->getTerminator()); // The branch is live
314 // Loop over all of the alive blocks in the function. If any successor
315 // blocks are not alive, we adjust the outgoing branches to branch to the
316 // first live postdominator of the live block, adjusting any PHI nodes in
317 // the block to reflect this.
319 for (Function::iterator I = Func->begin(), E = Func->end(); I != E; ++I)
320 if (AliveBlocks.count(I)) {
322 TerminatorInst *TI = BB->getTerminator();
324 // If the terminator instruction is alive, but the block it is contained
325 // in IS alive, this means that this terminator is a conditional branch
326 // on a condition that doesn't matter. Make it an unconditional branch
327 // to ONE of the successors. This has the side effect of dropping a use
328 // of the conditional value, which may also be dead.
329 if (!LiveSet.count(TI))
330 TI = convertToUnconditionalBranch(TI);
332 // Loop over all of the successors, looking for ones that are not alive.
333 // We cannot save the number of successors in the terminator instruction
334 // here because we may remove them if we don't have a postdominator...
336 for (unsigned i = 0; i != TI->getNumSuccessors(); ++i)
337 if (!AliveBlocks.count(TI->getSuccessor(i))) {
338 // Scan up the postdominator tree, looking for the first
339 // postdominator that is alive, and the last postdominator that is
342 PostDominatorTree::Node *LastNode = DT[TI->getSuccessor(i)];
344 // There is a special case here... if there IS no post-dominator for
345 // the block we have no owhere to point our branch to. Instead,
346 // convert it to a return. This can only happen if the code
347 // branched into an infinite loop. Note that this may not be
348 // desirable, because we _are_ altering the behavior of the code.
349 // This is a well known drawback of ADCE, so in the future if we
350 // choose to revisit the decision, this is where it should be.
352 if (LastNode == 0) { // No postdominator!
353 // Call RemoveSuccessor to transmogrify the terminator instruction
354 // to not contain the outgoing branch, or to create a new
355 // terminator if the form fundamentally changes (i.e.,
356 // unconditional branch to return). Note that this will change a
357 // branch into an infinite loop into a return instruction!
359 RemoveSuccessor(TI, i);
361 // RemoveSuccessor may replace TI... make sure we have a fresh
362 // pointer... and e variable.
364 TI = BB->getTerminator();
366 // Rescan this successor...
369 PostDominatorTree::Node *NextNode = LastNode->getIDom();
371 while (!AliveBlocks.count(NextNode->getBlock())) {
373 NextNode = NextNode->getIDom();
376 // Get the basic blocks that we need...
377 BasicBlock *LastDead = LastNode->getBlock();
378 BasicBlock *NextAlive = NextNode->getBlock();
380 // Make the conditional branch now go to the next alive block...
381 TI->getSuccessor(i)->removePredecessor(BB);
382 TI->setSuccessor(i, NextAlive);
384 // If there are PHI nodes in NextAlive, we need to add entries to
385 // the PHI nodes for the new incoming edge. The incoming values
386 // should be identical to the incoming values for LastDead.
388 for (BasicBlock::iterator II = NextAlive->begin();
389 PHINode *PN = dyn_cast<PHINode>(II); ++II)
390 if (LiveSet.count(PN)) { // Only modify live phi nodes
391 // Get the incoming value for LastDead...
392 int OldIdx = PN->getBasicBlockIndex(LastDead);
393 assert(OldIdx != -1 &&"LastDead is not a pred of NextAlive!");
394 Value *InVal = PN->getIncomingValue(OldIdx);
396 // Add an incoming value for BB now...
397 PN->addIncoming(InVal, BB);
402 // Now loop over all of the instructions in the basic block, telling
403 // dead instructions to drop their references. This is so that the next
404 // sweep over the program can safely delete dead instructions without
405 // other dead instructions still referring to them.
407 dropReferencesOfDeadInstructionsInLiveBlock(BB);
411 // We make changes if there are any dead blocks in the function...
412 if (unsigned NumDeadBlocks = Func->size() - AliveBlocks.size()) {
414 NumBlockRemoved += NumDeadBlocks;
417 // Loop over all of the basic blocks in the function, removing control flow
418 // edges to live blocks (also eliminating any entries in PHI functions in
419 // referenced blocks).
421 for (Function::iterator BB = Func->begin(), E = Func->end(); BB != E; ++BB)
422 if (!AliveBlocks.count(BB)) {
423 // Remove all outgoing edges from this basic block and convert the
424 // terminator into a return instruction.
425 std::vector<BasicBlock*> Succs(succ_begin(BB), succ_end(BB));
427 if (!Succs.empty()) {
428 // Loop over all of the successors, removing this block from PHI node
429 // entries that might be in the block...
430 while (!Succs.empty()) {
431 Succs.back()->removePredecessor(BB);
435 // Delete the old terminator instruction...
436 const Type *TermTy = BB->getTerminator()->getType();
437 if (TermTy != Type::VoidTy)
438 BB->getTerminator()->replaceAllUsesWith(
439 Constant::getNullValue(TermTy));
440 BB->getInstList().pop_back();
441 const Type *RetTy = Func->getReturnType();
442 new ReturnInst(RetTy != Type::VoidTy ?
443 Constant::getNullValue(RetTy) : 0, BB);
448 // Loop over all of the basic blocks in the function, dropping references of
449 // the dead basic blocks. We must do this after the previous step to avoid
450 // dropping references to PHIs which still have entries...
452 for (Function::iterator BB = Func->begin(), E = Func->end(); BB != E; ++BB)
453 if (!AliveBlocks.count(BB))
454 BB->dropAllReferences();
456 // Now loop through all of the blocks and delete the dead ones. We can safely
457 // do this now because we know that there are no references to dead blocks
458 // (because they have dropped all of their references... we also remove dead
459 // instructions from alive blocks.
461 for (Function::iterator BI = Func->begin(); BI != Func->end(); )
462 if (!AliveBlocks.count(BI)) { // Delete dead blocks...
463 BI = Func->getBasicBlockList().erase(BI);
464 } else { // Scan alive blocks...
465 for (BasicBlock::iterator II = BI->begin(); II != --BI->end(); )
466 if (!LiveSet.count(II)) { // Is this instruction alive?
467 // Nope... remove the instruction from it's basic block...
468 II = BI->getInstList().erase(II);
475 ++BI; // Increment iterator...