Home | History | Annotate | Download | only in IPO
      1 //===- PruneEH.cpp - Pass which deletes unused exception handlers ---------===//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 //
     10 // This file implements a simple interprocedural pass which walks the
     11 // call-graph, turning invoke instructions into calls, iff the callee cannot
     12 // throw an exception, and marking functions 'nounwind' if they cannot throw.
     13 // It implements this as a bottom-up traversal of the call-graph.
     14 //
     15 //===----------------------------------------------------------------------===//
     16 
     17 #include "llvm/Transforms/IPO.h"
     18 #include "llvm/ADT/SmallPtrSet.h"
     19 #include "llvm/ADT/Statistic.h"
     20 #include "llvm/Support/raw_ostream.h"
     21 #include "llvm/Analysis/CallGraph.h"
     22 #include "llvm/Analysis/CallGraphSCCPass.h"
     23 #include "llvm/Analysis/EHPersonalities.h"
     24 #include "llvm/IR/CFG.h"
     25 #include "llvm/IR/Constants.h"
     26 #include "llvm/IR/Function.h"
     27 #include "llvm/IR/InlineAsm.h"
     28 #include "llvm/IR/Instructions.h"
     29 #include "llvm/IR/IntrinsicInst.h"
     30 #include "llvm/IR/LLVMContext.h"
     31 #include "llvm/Transforms/Utils/Local.h"
     32 #include <algorithm>
     33 using namespace llvm;
     34 
     35 #define DEBUG_TYPE "prune-eh"
     36 
     37 STATISTIC(NumRemoved, "Number of invokes removed");
     38 STATISTIC(NumUnreach, "Number of noreturn calls optimized");
     39 
     40 namespace {
     41   struct PruneEH : public CallGraphSCCPass {
     42     static char ID; // Pass identification, replacement for typeid
     43     PruneEH() : CallGraphSCCPass(ID) {
     44       initializePruneEHPass(*PassRegistry::getPassRegistry());
     45     }
     46 
     47     // runOnSCC - Analyze the SCC, performing the transformation if possible.
     48     bool runOnSCC(CallGraphSCC &SCC) override;
     49 
     50   };
     51 }
     52 static bool SimplifyFunction(Function *F, CallGraph &CG);
     53 static void DeleteBasicBlock(BasicBlock *BB, CallGraph &CG);
     54 
     55 char PruneEH::ID = 0;
     56 INITIALIZE_PASS_BEGIN(PruneEH, "prune-eh",
     57                 "Remove unused exception handling info", false, false)
     58 INITIALIZE_PASS_DEPENDENCY(CallGraphWrapperPass)
     59 INITIALIZE_PASS_END(PruneEH, "prune-eh",
     60                 "Remove unused exception handling info", false, false)
     61 
     62 Pass *llvm::createPruneEHPass() { return new PruneEH(); }
     63 
     64 static bool runImpl(CallGraphSCC &SCC, CallGraph &CG) {
     65   SmallPtrSet<CallGraphNode *, 8> SCCNodes;
     66   bool MadeChange = false;
     67 
     68   // Fill SCCNodes with the elements of the SCC.  Used for quickly
     69   // looking up whether a given CallGraphNode is in this SCC.
     70   for (CallGraphNode *I : SCC)
     71     SCCNodes.insert(I);
     72 
     73   // First pass, scan all of the functions in the SCC, simplifying them
     74   // according to what we know.
     75   for (CallGraphNode *I : SCC)
     76     if (Function *F = I->getFunction())
     77       MadeChange |= SimplifyFunction(F, CG);
     78 
     79   // Next, check to see if any callees might throw or if there are any external
     80   // functions in this SCC: if so, we cannot prune any functions in this SCC.
     81   // Definitions that are weak and not declared non-throwing might be
     82   // overridden at linktime with something that throws, so assume that.
     83   // If this SCC includes the unwind instruction, we KNOW it throws, so
     84   // obviously the SCC might throw.
     85   //
     86   bool SCCMightUnwind = false, SCCMightReturn = false;
     87   for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end();
     88        (!SCCMightUnwind || !SCCMightReturn) && I != E; ++I) {
     89     Function *F = (*I)->getFunction();
     90     if (!F) {
     91       SCCMightUnwind = true;
     92       SCCMightReturn = true;
     93     } else if (F->isDeclaration() || F->isInterposable()) {
     94       // Note: isInterposable (as opposed to hasExactDefinition) is fine above,
     95       // since we're not inferring new attributes here, but only using existing,
     96       // assumed to be correct, function attributes.
     97       SCCMightUnwind |= !F->doesNotThrow();
     98       SCCMightReturn |= !F->doesNotReturn();
     99     } else {
    100       bool CheckUnwind = !SCCMightUnwind && !F->doesNotThrow();
    101       bool CheckReturn = !SCCMightReturn && !F->doesNotReturn();
    102       // Determine if we should scan for InlineAsm in a naked function as it
    103       // is the only way to return without a ReturnInst.  Only do this for
    104       // no-inline functions as functions which may be inlined cannot
    105       // meaningfully return via assembly.
    106       bool CheckReturnViaAsm = CheckReturn &&
    107                                F->hasFnAttribute(Attribute::Naked) &&
    108                                F->hasFnAttribute(Attribute::NoInline);
    109 
    110       if (!CheckUnwind && !CheckReturn)
    111         continue;
    112 
    113       for (const BasicBlock &BB : *F) {
    114         const TerminatorInst *TI = BB.getTerminator();
    115         if (CheckUnwind && TI->mayThrow()) {
    116           SCCMightUnwind = true;
    117         } else if (CheckReturn && isa<ReturnInst>(TI)) {
    118           SCCMightReturn = true;
    119         }
    120 
    121         for (const Instruction &I : BB) {
    122           if ((!CheckUnwind || SCCMightUnwind) &&
    123               (!CheckReturnViaAsm || SCCMightReturn))
    124             break;
    125 
    126           // Check to see if this function performs an unwind or calls an
    127           // unwinding function.
    128           if (CheckUnwind && !SCCMightUnwind && I.mayThrow()) {
    129             bool InstMightUnwind = true;
    130             if (const auto *CI = dyn_cast<CallInst>(&I)) {
    131               if (Function *Callee = CI->getCalledFunction()) {
    132                 CallGraphNode *CalleeNode = CG[Callee];
    133                 // If the callee is outside our current SCC then we may throw
    134                 // because it might.  If it is inside, do nothing.
    135                 if (SCCNodes.count(CalleeNode) > 0)
    136                   InstMightUnwind = false;
    137               }
    138             }
    139             SCCMightUnwind |= InstMightUnwind;
    140           }
    141           if (CheckReturnViaAsm && !SCCMightReturn)
    142             if (auto ICS = ImmutableCallSite(&I))
    143               if (const auto *IA = dyn_cast<InlineAsm>(ICS.getCalledValue()))
    144                 if (IA->hasSideEffects())
    145                   SCCMightReturn = true;
    146         }
    147 
    148         if (SCCMightUnwind && SCCMightReturn)
    149           break;
    150       }
    151     }
    152   }
    153 
    154   // If the SCC doesn't unwind or doesn't throw, note this fact.
    155   if (!SCCMightUnwind || !SCCMightReturn)
    156     for (CallGraphNode *I : SCC) {
    157       Function *F = I->getFunction();
    158 
    159       if (!SCCMightUnwind && !F->hasFnAttribute(Attribute::NoUnwind)) {
    160         F->addFnAttr(Attribute::NoUnwind);
    161         MadeChange = true;
    162       }
    163 
    164       if (!SCCMightReturn && !F->hasFnAttribute(Attribute::NoReturn)) {
    165         F->addFnAttr(Attribute::NoReturn);
    166         MadeChange = true;
    167       }
    168     }
    169 
    170   for (CallGraphNode *I : SCC) {
    171     // Convert any invoke instructions to non-throwing functions in this node
    172     // into call instructions with a branch.  This makes the exception blocks
    173     // dead.
    174     if (Function *F = I->getFunction())
    175       MadeChange |= SimplifyFunction(F, CG);
    176   }
    177 
    178   return MadeChange;
    179 }
    180 
    181 
    182 bool PruneEH::runOnSCC(CallGraphSCC &SCC) {
    183   if (skipSCC(SCC))
    184     return false;
    185   CallGraph &CG = getAnalysis<CallGraphWrapperPass>().getCallGraph();
    186   return runImpl(SCC, CG);
    187 }
    188 
    189 
    190 // SimplifyFunction - Given information about callees, simplify the specified
    191 // function if we have invokes to non-unwinding functions or code after calls to
    192 // no-return functions.
    193 static bool SimplifyFunction(Function *F, CallGraph &CG) {
    194   bool MadeChange = false;
    195   for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
    196     if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator()))
    197       if (II->doesNotThrow() && canSimplifyInvokeNoUnwind(F)) {
    198         BasicBlock *UnwindBlock = II->getUnwindDest();
    199         removeUnwindEdge(&*BB);
    200 
    201         // If the unwind block is now dead, nuke it.
    202         if (pred_empty(UnwindBlock))
    203           DeleteBasicBlock(UnwindBlock, CG);  // Delete the new BB.
    204 
    205         ++NumRemoved;
    206         MadeChange = true;
    207       }
    208 
    209     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
    210       if (CallInst *CI = dyn_cast<CallInst>(I++))
    211         if (CI->doesNotReturn() && !isa<UnreachableInst>(I)) {
    212           // This call calls a function that cannot return.  Insert an
    213           // unreachable instruction after it and simplify the code.  Do this
    214           // by splitting the BB, adding the unreachable, then deleting the
    215           // new BB.
    216           BasicBlock *New = BB->splitBasicBlock(I);
    217 
    218           // Remove the uncond branch and add an unreachable.
    219           BB->getInstList().pop_back();
    220           new UnreachableInst(BB->getContext(), &*BB);
    221 
    222           DeleteBasicBlock(New, CG);  // Delete the new BB.
    223           MadeChange = true;
    224           ++NumUnreach;
    225           break;
    226         }
    227   }
    228 
    229   return MadeChange;
    230 }
    231 
    232 /// DeleteBasicBlock - remove the specified basic block from the program,
    233 /// updating the callgraph to reflect any now-obsolete edges due to calls that
    234 /// exist in the BB.
    235 static void DeleteBasicBlock(BasicBlock *BB, CallGraph &CG) {
    236   assert(pred_empty(BB) && "BB is not dead!");
    237 
    238   Instruction *TokenInst = nullptr;
    239 
    240   CallGraphNode *CGN = CG[BB->getParent()];
    241   for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; ) {
    242     --I;
    243 
    244     if (I->getType()->isTokenTy()) {
    245       TokenInst = &*I;
    246       break;
    247     }
    248 
    249     if (auto CS = CallSite (&*I)) {
    250       const Function *Callee = CS.getCalledFunction();
    251       if (!Callee || !Intrinsic::isLeaf(Callee->getIntrinsicID()))
    252         CGN->removeCallEdgeFor(CS);
    253       else if (!Callee->isIntrinsic())
    254         CGN->removeCallEdgeFor(CS);
    255     }
    256 
    257     if (!I->use_empty())
    258       I->replaceAllUsesWith(UndefValue::get(I->getType()));
    259   }
    260 
    261   if (TokenInst) {
    262     if (!isa<TerminatorInst>(TokenInst))
    263       changeToUnreachable(TokenInst->getNextNode(), /*UseLLVMTrap=*/false);
    264   } else {
    265     // Get the list of successors of this block.
    266     std::vector<BasicBlock *> Succs(succ_begin(BB), succ_end(BB));
    267 
    268     for (unsigned i = 0, e = Succs.size(); i != e; ++i)
    269       Succs[i]->removePredecessor(BB);
    270 
    271     BB->eraseFromParent();
    272   }
    273 }
    274