LLVM API Documentation

SimplifyCFGPass.cpp

Go to the documentation of this file.
00001 //===- SimplifyCFGPass.cpp - CFG Simplification Pass ----------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements dead code elimination and basic block merging, along
00011 // with a collection of other peephole control flow optimizations.  For example:
00012 //
00013 //   * Removes basic blocks with no predecessors.
00014 //   * Merges a basic block into its predecessor if there is only one and the
00015 //     predecessor only has one successor.
00016 //   * Eliminates PHI nodes for basic blocks with a single predecessor.
00017 //   * Eliminates a basic block that only contains an unconditional branch.
00018 //   * Changes invoke instructions to nounwind functions to be calls.
00019 //   * Change things like "if (x) if (y)" into "if (x&y)".
00020 //   * etc..
00021 //
00022 //===----------------------------------------------------------------------===//
00023 
00024 #define DEBUG_TYPE "simplifycfg"
00025 #include "llvm/Transforms/Scalar.h"
00026 #include "llvm/Transforms/Utils/Local.h"
00027 #include "llvm/Constants.h"
00028 #include "llvm/Instructions.h"
00029 #include "llvm/Module.h"
00030 #include "llvm/Attributes.h"
00031 #include "llvm/Support/CFG.h"
00032 #include "llvm/Support/Compiler.h"
00033 #include "llvm/Pass.h"
00034 #include "llvm/ADT/SmallVector.h"
00035 #include "llvm/ADT/SmallPtrSet.h"
00036 #include "llvm/ADT/Statistic.h"
00037 using namespace llvm;
00038 
00039 STATISTIC(NumSimpl, "Number of blocks simplified");
00040 
00041 namespace {
00042   struct VISIBILITY_HIDDEN CFGSimplifyPass : public FunctionPass {
00043     static char ID; // Pass identification, replacement for typeid
00044     CFGSimplifyPass() : FunctionPass(&ID) {}
00045 
00046     virtual bool runOnFunction(Function &F);
00047   };
00048 }
00049 
00050 char CFGSimplifyPass::ID = 0;
00051 static RegisterPass<CFGSimplifyPass> X("simplifycfg", "Simplify the CFG");
00052 
00053 // Public interface to the CFGSimplification pass
00054 FunctionPass *llvm::createCFGSimplificationPass() {
00055   return new CFGSimplifyPass();
00056 }
00057 
00058 /// ChangeToUnreachable - Insert an unreachable instruction before the specified
00059 /// instruction, making it and the rest of the code in the block dead.
00060 static void ChangeToUnreachable(Instruction *I) {
00061   BasicBlock *BB = I->getParent();
00062   // Loop over all of the successors, removing BB's entry from any PHI
00063   // nodes.
00064   for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI)
00065     (*SI)->removePredecessor(BB);
00066   
00067   new UnreachableInst(I);
00068   
00069   // All instructions after this are dead.
00070   BasicBlock::iterator BBI = I, BBE = BB->end();
00071   while (BBI != BBE) {
00072     if (!BBI->use_empty())
00073       BBI->replaceAllUsesWith(UndefValue::get(BBI->getType()));
00074     BB->getInstList().erase(BBI++);
00075   }
00076 }
00077 
00078 /// ChangeToCall - Convert the specified invoke into a normal call.
00079 static void ChangeToCall(InvokeInst *II) {
00080   BasicBlock *BB = II->getParent();
00081   SmallVector<Value*, 8> Args(II->op_begin()+3, II->op_end());
00082   CallInst *NewCall = CallInst::Create(II->getCalledValue(), Args.begin(),
00083                                        Args.end(), "", II);
00084   NewCall->takeName(II);
00085   NewCall->setCallingConv(II->getCallingConv());
00086   NewCall->setAttributes(II->getAttributes());
00087   II->replaceAllUsesWith(NewCall);
00088 
00089   // Follow the call by a branch to the normal destination.
00090   BranchInst::Create(II->getNormalDest(), II);
00091 
00092   // Update PHI nodes in the unwind destination
00093   II->getUnwindDest()->removePredecessor(BB);
00094   BB->getInstList().erase(II);
00095 }
00096 
00097 static bool MarkAliveBlocks(BasicBlock *BB,
00098                             SmallPtrSet<BasicBlock*, 128> &Reachable) {
00099   
00100   SmallVector<BasicBlock*, 128> Worklist;
00101   Worklist.push_back(BB);
00102   bool Changed = false;
00103   while (!Worklist.empty()) {
00104     BB = Worklist.back();
00105     Worklist.pop_back();
00106     
00107     if (!Reachable.insert(BB))
00108       continue;
00109 
00110     // Do a quick scan of the basic block, turning any obviously unreachable
00111     // instructions into LLVM unreachable insts.  The instruction combining pass
00112     // canonicalizes unreachable insts into stores to null or undef.
00113     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E;++BBI){
00114       if (CallInst *CI = dyn_cast<CallInst>(BBI)) {
00115         if (CI->doesNotReturn()) {
00116           // If we found a call to a no-return function, insert an unreachable
00117           // instruction after it.  Make sure there isn't *already* one there
00118           // though.
00119           ++BBI;
00120           if (!isa<UnreachableInst>(BBI)) {
00121             ChangeToUnreachable(BBI);
00122             Changed = true;
00123           }
00124           break;
00125         }
00126       }
00127       
00128       if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
00129         if (isa<ConstantPointerNull>(SI->getOperand(1)) ||
00130             isa<UndefValue>(SI->getOperand(1))) {
00131           ChangeToUnreachable(SI);
00132           Changed = true;
00133           break;
00134         }
00135     }
00136 
00137     // Turn invokes that call 'nounwind' functions into ordinary calls.
00138     if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator()))
00139       if (II->doesNotThrow()) {
00140         ChangeToCall(II);
00141         Changed = true;
00142       }
00143 
00144     Changed |= ConstantFoldTerminator(BB);
00145     for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI)
00146       Worklist.push_back(*SI);
00147   }
00148   return Changed;
00149 }
00150 
00151 /// RemoveUnreachableBlocksFromFn - Remove blocks that are not reachable, even 
00152 /// if they are in a dead cycle.  Return true if a change was made, false 
00153 /// otherwise.
00154 static bool RemoveUnreachableBlocksFromFn(Function &F) {
00155   SmallPtrSet<BasicBlock*, 128> Reachable;
00156   bool Changed = MarkAliveBlocks(F.begin(), Reachable);
00157   
00158   // If there are unreachable blocks in the CFG...
00159   if (Reachable.size() == F.size())
00160     return Changed;
00161   
00162   assert(Reachable.size() < F.size());
00163   NumSimpl += F.size()-Reachable.size();
00164   
00165   // Loop over all of the basic blocks that are not reachable, dropping all of
00166   // their internal references...
00167   for (Function::iterator BB = ++F.begin(), E = F.end(); BB != E; ++BB) {
00168     if (Reachable.count(BB))
00169       continue;
00170     
00171     for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI)
00172       if (Reachable.count(*SI))
00173         (*SI)->removePredecessor(BB);
00174     BB->dropAllReferences();
00175   }
00176   
00177   for (Function::iterator I = ++F.begin(); I != F.end();)
00178     if (!Reachable.count(I))
00179       I = F.getBasicBlockList().erase(I);
00180     else
00181       ++I;
00182   
00183   return true;
00184 }
00185 
00186 /// IterativeSimplifyCFG - Call SimplifyCFG on all the blocks in the function,
00187 /// iterating until no more changes are made.
00188 static bool IterativeSimplifyCFG(Function &F) {
00189   bool Changed = false;
00190   bool LocalChange = true;
00191   while (LocalChange) {
00192     LocalChange = false;
00193     
00194     // Loop over all of the basic blocks (except the first one) and remove them
00195     // if they are unneeded...
00196     //
00197     for (Function::iterator BBIt = ++F.begin(); BBIt != F.end(); ) {
00198       if (SimplifyCFG(BBIt++)) {
00199         LocalChange = true;
00200         ++NumSimpl;
00201       }
00202     }
00203     Changed |= LocalChange;
00204   }
00205   return Changed;
00206 }
00207 
00208 // It is possible that we may require multiple passes over the code to fully
00209 // simplify the CFG.
00210 //
00211 bool CFGSimplifyPass::runOnFunction(Function &F) {
00212   bool EverChanged = RemoveUnreachableBlocksFromFn(F);
00213   EverChanged |= IterativeSimplifyCFG(F);
00214   
00215   // If neither pass changed anything, we're done.
00216   if (!EverChanged) return false;
00217 
00218   // IterativeSimplifyCFG can (rarely) make some loops dead.  If this happens,
00219   // RemoveUnreachableBlocksFromFn is needed to nuke them, which means we should
00220   // iterate between the two optimizations.  We structure the code like this to
00221   // avoid reruning IterativeSimplifyCFG if the second pass of 
00222   // RemoveUnreachableBlocksFromFn doesn't do anything.
00223   if (!RemoveUnreachableBlocksFromFn(F))
00224     return true;
00225   
00226   do {
00227     EverChanged = IterativeSimplifyCFG(F);
00228     EverChanged |= RemoveUnreachableBlocksFromFn(F);
00229   } while (EverChanged);
00230   
00231   return true;
00232 }



This web site is hosted by the Computer Science Department at the University of Illinois at Urbana-Champaign.