LLVM API Documentation
00001 //===- ADCE.cpp - Code to perform aggressive dead code elimination --------===// 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file was developed by the LLVM research group and is distributed under 00006 // the University of Illinois Open Source License. See LICENSE.TXT for details. 00007 // 00008 //===----------------------------------------------------------------------===// 00009 // 00010 // This file implements "aggressive" dead code elimination. ADCE is DCe where 00011 // values are assumed to be dead until proven otherwise. This is similar to 00012 // SCCP, except applied to the liveness of values. 00013 // 00014 //===----------------------------------------------------------------------===// 00015 00016 #include "llvm/Transforms/Scalar.h" 00017 #include "llvm/Constant.h" 00018 #include "llvm/Instructions.h" 00019 #include "llvm/Type.h" 00020 #include "llvm/Analysis/AliasAnalysis.h" 00021 #include "llvm/Analysis/PostDominators.h" 00022 #include "llvm/Support/CFG.h" 00023 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 00024 #include "llvm/Transforms/Utils/Local.h" 00025 #include "llvm/Transforms/Utils/UnifyFunctionExitNodes.h" 00026 #include "llvm/Support/Debug.h" 00027 #include "llvm/ADT/DepthFirstIterator.h" 00028 #include "llvm/ADT/Statistic.h" 00029 #include "llvm/ADT/STLExtras.h" 00030 #include <algorithm> 00031 using namespace llvm; 00032 00033 namespace { 00034 Statistic<> NumBlockRemoved("adce", "Number of basic blocks removed"); 00035 Statistic<> NumInstRemoved ("adce", "Number of instructions removed"); 00036 Statistic<> NumCallRemoved ("adce", "Number of calls and invokes removed"); 00037 00038 //===----------------------------------------------------------------------===// 00039 // ADCE Class 00040 // 00041 // This class does all of the work of Aggressive Dead Code Elimination. 00042 // It's public interface consists of a constructor and a doADCE() method. 00043 // 00044 class ADCE : public FunctionPass { 00045 Function *Func; // The function that we are working on 00046 std::vector<Instruction*> WorkList; // Instructions that just became live 00047 std::set<Instruction*> LiveSet; // The set of live instructions 00048 00049 //===--------------------------------------------------------------------===// 00050 // The public interface for this class 00051 // 00052 public: 00053 // Execute the Aggressive Dead Code Elimination Algorithm 00054 // 00055 virtual bool runOnFunction(Function &F) { 00056 Func = &F; 00057 bool Changed = doADCE(); 00058 assert(WorkList.empty()); 00059 LiveSet.clear(); 00060 return Changed; 00061 } 00062 // getAnalysisUsage - We require post dominance frontiers (aka Control 00063 // Dependence Graph) 00064 virtual void getAnalysisUsage(AnalysisUsage &AU) const { 00065 // We require that all function nodes are unified, because otherwise code 00066 // can be marked live that wouldn't necessarily be otherwise. 00067 AU.addRequired<UnifyFunctionExitNodes>(); 00068 AU.addRequired<AliasAnalysis>(); 00069 AU.addRequired<PostDominatorTree>(); 00070 AU.addRequired<PostDominanceFrontier>(); 00071 } 00072 00073 00074 //===--------------------------------------------------------------------===// 00075 // The implementation of this class 00076 // 00077 private: 00078 // doADCE() - Run the Aggressive Dead Code Elimination algorithm, returning 00079 // true if the function was modified. 00080 // 00081 bool doADCE(); 00082 00083 void markBlockAlive(BasicBlock *BB); 00084 00085 00086 // dropReferencesOfDeadInstructionsInLiveBlock - Loop over all of the 00087 // instructions in the specified basic block, dropping references on 00088 // instructions that are dead according to LiveSet. 00089 bool dropReferencesOfDeadInstructionsInLiveBlock(BasicBlock *BB); 00090 00091 TerminatorInst *convertToUnconditionalBranch(TerminatorInst *TI); 00092 00093 inline void markInstructionLive(Instruction *I) { 00094 if (LiveSet.count(I)) return; 00095 DEBUG(std::cerr << "Insn Live: " << *I); 00096 LiveSet.insert(I); 00097 WorkList.push_back(I); 00098 } 00099 00100 inline void markTerminatorLive(const BasicBlock *BB) { 00101 DEBUG(std::cerr << "Terminator Live: " << *BB->getTerminator()); 00102 markInstructionLive(const_cast<TerminatorInst*>(BB->getTerminator())); 00103 } 00104 }; 00105 00106 RegisterOpt<ADCE> X("adce", "Aggressive Dead Code Elimination"); 00107 } // End of anonymous namespace 00108 00109 FunctionPass *llvm::createAggressiveDCEPass() { return new ADCE(); } 00110 00111 void ADCE::markBlockAlive(BasicBlock *BB) { 00112 // Mark the basic block as being newly ALIVE... and mark all branches that 00113 // this block is control dependent on as being alive also... 00114 // 00115 PostDominanceFrontier &CDG = getAnalysis<PostDominanceFrontier>(); 00116 00117 PostDominanceFrontier::const_iterator It = CDG.find(BB); 00118 if (It != CDG.end()) { 00119 // Get the blocks that this node is control dependent on... 00120 const PostDominanceFrontier::DomSetType &CDB = It->second; 00121 for_each(CDB.begin(), CDB.end(), // Mark all their terminators as live 00122 bind_obj(this, &ADCE::markTerminatorLive)); 00123 } 00124 00125 // If this basic block is live, and it ends in an unconditional branch, then 00126 // the branch is alive as well... 00127 if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) 00128 if (BI->isUnconditional()) 00129 markTerminatorLive(BB); 00130 } 00131 00132 // dropReferencesOfDeadInstructionsInLiveBlock - Loop over all of the 00133 // instructions in the specified basic block, dropping references on 00134 // instructions that are dead according to LiveSet. 00135 bool ADCE::dropReferencesOfDeadInstructionsInLiveBlock(BasicBlock *BB) { 00136 bool Changed = false; 00137 for (BasicBlock::iterator I = BB->begin(), E = --BB->end(); I != E; ) 00138 if (!LiveSet.count(I)) { // Is this instruction alive? 00139 I->dropAllReferences(); // Nope, drop references... 00140 if (PHINode *PN = dyn_cast<PHINode>(I)) { 00141 // We don't want to leave PHI nodes in the program that have 00142 // #arguments != #predecessors, so we remove them now. 00143 // 00144 PN->replaceAllUsesWith(Constant::getNullValue(PN->getType())); 00145 00146 // Delete the instruction... 00147 ++I; 00148 BB->getInstList().erase(PN); 00149 Changed = true; 00150 ++NumInstRemoved; 00151 } else { 00152 ++I; 00153 } 00154 } else { 00155 ++I; 00156 } 00157 return Changed; 00158 } 00159 00160 00161 /// convertToUnconditionalBranch - Transform this conditional terminator 00162 /// instruction into an unconditional branch because we don't care which of the 00163 /// successors it goes to. This eliminate a use of the condition as well. 00164 /// 00165 TerminatorInst *ADCE::convertToUnconditionalBranch(TerminatorInst *TI) { 00166 BranchInst *NB = new BranchInst(TI->getSuccessor(0), TI); 00167 BasicBlock *BB = TI->getParent(); 00168 00169 // Remove entries from PHI nodes to avoid confusing ourself later... 00170 for (unsigned i = 1, e = TI->getNumSuccessors(); i != e; ++i) 00171 TI->getSuccessor(i)->removePredecessor(BB); 00172 00173 // Delete the old branch itself... 00174 BB->getInstList().erase(TI); 00175 return NB; 00176 } 00177 00178 00179 // doADCE() - Run the Aggressive Dead Code Elimination algorithm, returning 00180 // true if the function was modified. 00181 // 00182 bool ADCE::doADCE() { 00183 bool MadeChanges = false; 00184 00185 AliasAnalysis &AA = getAnalysis<AliasAnalysis>(); 00186 00187 00188 // Iterate over all invokes in the function, turning invokes into calls if 00189 // they cannot throw. 00190 for (Function::iterator BB = Func->begin(), E = Func->end(); BB != E; ++BB) 00191 if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator())) 00192 if (Function *F = II->getCalledFunction()) 00193 if (AA.onlyReadsMemory(F)) { 00194 // The function cannot unwind. Convert it to a call with a branch 00195 // after it to the normal destination. 00196 std::vector<Value*> Args(II->op_begin()+3, II->op_end()); 00197 std::string Name = II->getName(); II->setName(""); 00198 Instruction *NewCall = new CallInst(F, Args, Name, II); 00199 II->replaceAllUsesWith(NewCall); 00200 new BranchInst(II->getNormalDest(), II); 00201 00202 // Update PHI nodes in the unwind destination 00203 II->getUnwindDest()->removePredecessor(BB); 00204 BB->getInstList().erase(II); 00205 00206 if (NewCall->use_empty()) { 00207 BB->getInstList().erase(NewCall); 00208 ++NumCallRemoved; 00209 } 00210 } 00211 00212 // Iterate over all of the instructions in the function, eliminating trivially 00213 // dead instructions, and marking instructions live that are known to be 00214 // needed. Perform the walk in depth first order so that we avoid marking any 00215 // instructions live in basic blocks that are unreachable. These blocks will 00216 // be eliminated later, along with the instructions inside. 00217 // 00218 std::set<BasicBlock*> ReachableBBs; 00219 for (df_ext_iterator<BasicBlock*> 00220 BBI = df_ext_begin(&Func->front(), ReachableBBs), 00221 BBE = df_ext_end(&Func->front(), ReachableBBs); BBI != BBE; ++BBI) { 00222 BasicBlock *BB = *BBI; 00223 for (BasicBlock::iterator II = BB->begin(), EI = BB->end(); II != EI; ) { 00224 Instruction *I = II++; 00225 if (CallInst *CI = dyn_cast<CallInst>(I)) { 00226 Function *F = CI->getCalledFunction(); 00227 if (F && AA.onlyReadsMemory(F)) { 00228 if (CI->use_empty()) { 00229 BB->getInstList().erase(CI); 00230 ++NumCallRemoved; 00231 } 00232 } else { 00233 markInstructionLive(I); 00234 } 00235 } else if (I->mayWriteToMemory() || isa<ReturnInst>(I) || 00236 isa<UnwindInst>(I) || isa<UnreachableInst>(I)) { 00237 // FIXME: Unreachable instructions should not be marked intrinsically 00238 // live here. 00239 markInstructionLive(I); 00240 } else if (isInstructionTriviallyDead(I)) { 00241 // Remove the instruction from it's basic block... 00242 BB->getInstList().erase(I); 00243 ++NumInstRemoved; 00244 } 00245 } 00246 } 00247 00248 // Check to ensure we have an exit node for this CFG. If we don't, we won't 00249 // have any post-dominance information, thus we cannot perform our 00250 // transformations safely. 00251 // 00252 PostDominatorTree &DT = getAnalysis<PostDominatorTree>(); 00253 if (DT[&Func->getEntryBlock()] == 0) { 00254 WorkList.clear(); 00255 return MadeChanges; 00256 } 00257 00258 // Scan the function marking blocks without post-dominance information as 00259 // live. Blocks without post-dominance information occur when there is an 00260 // infinite loop in the program. Because the infinite loop could contain a 00261 // function which unwinds, exits or has side-effects, we don't want to delete 00262 // the infinite loop or those blocks leading up to it. 00263 for (Function::iterator I = Func->begin(), E = Func->end(); I != E; ++I) 00264 if (DT[I] == 0) 00265 for (pred_iterator PI = pred_begin(I), E = pred_end(I); PI != E; ++PI) 00266 markInstructionLive((*PI)->getTerminator()); 00267 00268 00269 00270 DEBUG(std::cerr << "Processing work list\n"); 00271 00272 // AliveBlocks - Set of basic blocks that we know have instructions that are 00273 // alive in them... 00274 // 00275 std::set<BasicBlock*> AliveBlocks; 00276 00277 // Process the work list of instructions that just became live... if they 00278 // became live, then that means that all of their operands are necessary as 00279 // well... make them live as well. 00280 // 00281 while (!WorkList.empty()) { 00282 Instruction *I = WorkList.back(); // Get an instruction that became live... 00283 WorkList.pop_back(); 00284 00285 BasicBlock *BB = I->getParent(); 00286 if (!ReachableBBs.count(BB)) continue; 00287 if (!AliveBlocks.count(BB)) { // Basic block not alive yet... 00288 AliveBlocks.insert(BB); // Block is now ALIVE! 00289 markBlockAlive(BB); // Make it so now! 00290 } 00291 00292 // PHI nodes are a special case, because the incoming values are actually 00293 // defined in the predecessor nodes of this block, meaning that the PHI 00294 // makes the predecessors alive. 00295 // 00296 if (PHINode *PN = dyn_cast<PHINode>(I)) 00297 for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) 00298 if (!AliveBlocks.count(*PI)) { 00299 AliveBlocks.insert(BB); // Block is now ALIVE! 00300 markBlockAlive(*PI); 00301 } 00302 00303 // Loop over all of the operands of the live instruction, making sure that 00304 // they are known to be alive as well... 00305 // 00306 for (unsigned op = 0, End = I->getNumOperands(); op != End; ++op) 00307 if (Instruction *Operand = dyn_cast<Instruction>(I->getOperand(op))) 00308 markInstructionLive(Operand); 00309 } 00310 00311 DEBUG( 00312 std::cerr << "Current Function: X = Live\n"; 00313 for (Function::iterator I = Func->begin(), E = Func->end(); I != E; ++I){ 00314 std::cerr << I->getName() << ":\t" 00315 << (AliveBlocks.count(I) ? "LIVE\n" : "DEAD\n"); 00316 for (BasicBlock::iterator BI = I->begin(), BE = I->end(); BI != BE; ++BI){ 00317 if (LiveSet.count(BI)) std::cerr << "X "; 00318 std::cerr << *BI; 00319 } 00320 }); 00321 00322 // Find the first postdominator of the entry node that is alive. Make it the 00323 // new entry node... 00324 // 00325 if (AliveBlocks.size() == Func->size()) { // No dead blocks? 00326 for (Function::iterator I = Func->begin(), E = Func->end(); I != E; ++I) { 00327 // Loop over all of the instructions in the function, telling dead 00328 // instructions to drop their references. This is so that the next sweep 00329 // over the program can safely delete dead instructions without other dead 00330 // instructions still referring to them. 00331 // 00332 dropReferencesOfDeadInstructionsInLiveBlock(I); 00333 00334 // Check to make sure the terminator instruction is live. If it isn't, 00335 // this means that the condition that it branches on (we know it is not an 00336 // unconditional branch), is not needed to make the decision of where to 00337 // go to, because all outgoing edges go to the same place. We must remove 00338 // the use of the condition (because it's probably dead), so we convert 00339 // the terminator to a conditional branch. 00340 // 00341 TerminatorInst *TI = I->getTerminator(); 00342 if (!LiveSet.count(TI)) 00343 convertToUnconditionalBranch(TI); 00344 } 00345 00346 } else { // If there are some blocks dead... 00347 // If the entry node is dead, insert a new entry node to eliminate the entry 00348 // node as a special case. 00349 // 00350 if (!AliveBlocks.count(&Func->front())) { 00351 BasicBlock *NewEntry = new BasicBlock(); 00352 new BranchInst(&Func->front(), NewEntry); 00353 Func->getBasicBlockList().push_front(NewEntry); 00354 AliveBlocks.insert(NewEntry); // This block is always alive! 00355 LiveSet.insert(NewEntry->getTerminator()); // The branch is live 00356 } 00357 00358 // Loop over all of the alive blocks in the function. If any successor 00359 // blocks are not alive, we adjust the outgoing branches to branch to the 00360 // first live postdominator of the live block, adjusting any PHI nodes in 00361 // the block to reflect this. 00362 // 00363 for (Function::iterator I = Func->begin(), E = Func->end(); I != E; ++I) 00364 if (AliveBlocks.count(I)) { 00365 BasicBlock *BB = I; 00366 TerminatorInst *TI = BB->getTerminator(); 00367 00368 // If the terminator instruction is alive, but the block it is contained 00369 // in IS alive, this means that this terminator is a conditional branch 00370 // on a condition that doesn't matter. Make it an unconditional branch 00371 // to ONE of the successors. This has the side effect of dropping a use 00372 // of the conditional value, which may also be dead. 00373 if (!LiveSet.count(TI)) 00374 TI = convertToUnconditionalBranch(TI); 00375 00376 // Loop over all of the successors, looking for ones that are not alive. 00377 // We cannot save the number of successors in the terminator instruction 00378 // here because we may remove them if we don't have a postdominator... 00379 // 00380 for (unsigned i = 0; i != TI->getNumSuccessors(); ++i) 00381 if (!AliveBlocks.count(TI->getSuccessor(i))) { 00382 // Scan up the postdominator tree, looking for the first 00383 // postdominator that is alive, and the last postdominator that is 00384 // dead... 00385 // 00386 PostDominatorTree::Node *LastNode = DT[TI->getSuccessor(i)]; 00387 00388 // There is a special case here... if there IS no post-dominator for 00389 // the block we have no owhere to point our branch to. Instead, 00390 // convert it to a return. This can only happen if the code 00391 // branched into an infinite loop. Note that this may not be 00392 // desirable, because we _are_ altering the behavior of the code. 00393 // This is a well known drawback of ADCE, so in the future if we 00394 // choose to revisit the decision, this is where it should be. 00395 // 00396 if (LastNode == 0) { // No postdominator! 00397 // Call RemoveSuccessor to transmogrify the terminator instruction 00398 // to not contain the outgoing branch, or to create a new 00399 // terminator if the form fundamentally changes (i.e., 00400 // unconditional branch to return). Note that this will change a 00401 // branch into an infinite loop into a return instruction! 00402 // 00403 RemoveSuccessor(TI, i); 00404 00405 // RemoveSuccessor may replace TI... make sure we have a fresh 00406 // pointer... and e variable. 00407 // 00408 TI = BB->getTerminator(); 00409 00410 // Rescan this successor... 00411 --i; 00412 } else { 00413 PostDominatorTree::Node *NextNode = LastNode->getIDom(); 00414 00415 while (!AliveBlocks.count(NextNode->getBlock())) { 00416 LastNode = NextNode; 00417 NextNode = NextNode->getIDom(); 00418 } 00419 00420 // Get the basic blocks that we need... 00421 BasicBlock *LastDead = LastNode->getBlock(); 00422 BasicBlock *NextAlive = NextNode->getBlock(); 00423 00424 // Make the conditional branch now go to the next alive block... 00425 TI->getSuccessor(i)->removePredecessor(BB); 00426 TI->setSuccessor(i, NextAlive); 00427 00428 // If there are PHI nodes in NextAlive, we need to add entries to 00429 // the PHI nodes for the new incoming edge. The incoming values 00430 // should be identical to the incoming values for LastDead. 00431 // 00432 for (BasicBlock::iterator II = NextAlive->begin(); 00433 isa<PHINode>(II); ++II) { 00434 PHINode *PN = cast<PHINode>(II); 00435 if (LiveSet.count(PN)) { // Only modify live phi nodes 00436 // Get the incoming value for LastDead... 00437 int OldIdx = PN->getBasicBlockIndex(LastDead); 00438 assert(OldIdx != -1 &&"LastDead is not a pred of NextAlive!"); 00439 Value *InVal = PN->getIncomingValue(OldIdx); 00440 00441 // Add an incoming value for BB now... 00442 PN->addIncoming(InVal, BB); 00443 } 00444 } 00445 } 00446 } 00447 00448 // Now loop over all of the instructions in the basic block, telling 00449 // dead instructions to drop their references. This is so that the next 00450 // sweep over the program can safely delete dead instructions without 00451 // other dead instructions still referring to them. 00452 // 00453 dropReferencesOfDeadInstructionsInLiveBlock(BB); 00454 } 00455 } 00456 00457 // We make changes if there are any dead blocks in the function... 00458 if (unsigned NumDeadBlocks = Func->size() - AliveBlocks.size()) { 00459 MadeChanges = true; 00460 NumBlockRemoved += NumDeadBlocks; 00461 } 00462 00463 // Loop over all of the basic blocks in the function, removing control flow 00464 // edges to live blocks (also eliminating any entries in PHI functions in 00465 // referenced blocks). 00466 // 00467 for (Function::iterator BB = Func->begin(), E = Func->end(); BB != E; ++BB) 00468 if (!AliveBlocks.count(BB)) { 00469 // Remove all outgoing edges from this basic block and convert the 00470 // terminator into a return instruction. 00471 std::vector<BasicBlock*> Succs(succ_begin(BB), succ_end(BB)); 00472 00473 if (!Succs.empty()) { 00474 // Loop over all of the successors, removing this block from PHI node 00475 // entries that might be in the block... 00476 while (!Succs.empty()) { 00477 Succs.back()->removePredecessor(BB); 00478 Succs.pop_back(); 00479 } 00480 00481 // Delete the old terminator instruction... 00482 const Type *TermTy = BB->getTerminator()->getType(); 00483 if (TermTy != Type::VoidTy) 00484 BB->getTerminator()->replaceAllUsesWith( 00485 Constant::getNullValue(TermTy)); 00486 BB->getInstList().pop_back(); 00487 const Type *RetTy = Func->getReturnType(); 00488 new ReturnInst(RetTy != Type::VoidTy ? 00489 Constant::getNullValue(RetTy) : 0, BB); 00490 } 00491 } 00492 00493 00494 // Loop over all of the basic blocks in the function, dropping references of 00495 // the dead basic blocks. We must do this after the previous step to avoid 00496 // dropping references to PHIs which still have entries... 00497 // 00498 for (Function::iterator BB = Func->begin(), E = Func->end(); BB != E; ++BB) 00499 if (!AliveBlocks.count(BB)) 00500 BB->dropAllReferences(); 00501 00502 // Now loop through all of the blocks and delete the dead ones. We can safely 00503 // do this now because we know that there are no references to dead blocks 00504 // (because they have dropped all of their references... we also remove dead 00505 // instructions from alive blocks. 00506 // 00507 for (Function::iterator BI = Func->begin(); BI != Func->end(); ) 00508 if (!AliveBlocks.count(BI)) { // Delete dead blocks... 00509 BI = Func->getBasicBlockList().erase(BI); 00510 } else { // Scan alive blocks... 00511 for (BasicBlock::iterator II = BI->begin(); II != --BI->end(); ) 00512 if (!LiveSet.count(II)) { // Is this instruction alive? 00513 // Nope... remove the instruction from it's basic block... 00514 if (isa<CallInst>(II)) 00515 ++NumCallRemoved; 00516 else 00517 ++NumInstRemoved; 00518 II = BI->getInstList().erase(II); 00519 MadeChanges = true; 00520 } else { 00521 ++II; 00522 } 00523 00524 ++BI; // Increment iterator... 00525 } 00526 00527 return MadeChanges; 00528 }