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     bool SimplifyFunction(Function *F);
51     void DeleteBasicBlock(BasicBlock *BB);
52   };
53 }
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 
65 bool PruneEH::runOnSCC(CallGraphSCC &SCC) {
66   if (skipSCC(SCC))
67     return false;
68 
69   SmallPtrSet<CallGraphNode *, 8> SCCNodes;
70   CallGraph &CG = getAnalysis<CallGraphWrapperPass>().getCallGraph();
71   bool MadeChange = false;
72 
73   // Fill SCCNodes with the elements of the SCC.  Used for quickly
74   // looking up whether a given CallGraphNode is in this SCC.
75   for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I)
76     SCCNodes.insert(*I);
77 
78   // First pass, scan all of the functions in the SCC, simplifying them
79   // according to what we know.
80   for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I)
81     if (Function *F = (*I)->getFunction())
82       MadeChange |= SimplifyFunction(F);
83 
84   // Next, check to see if any callees might throw or if there are any external
85   // functions in this SCC: if so, we cannot prune any functions in this SCC.
86   // Definitions that are weak and not declared non-throwing might be
87   // overridden at linktime with something that throws, so assume that.
88   // If this SCC includes the unwind instruction, we KNOW it throws, so
89   // obviously the SCC might throw.
90   //
91   bool SCCMightUnwind = false, SCCMightReturn = false;
92   for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end();
93        (!SCCMightUnwind || !SCCMightReturn) && I != E; ++I) {
94     Function *F = (*I)->getFunction();
95     if (!F) {
96       SCCMightUnwind = true;
97       SCCMightReturn = true;
98     } else if (F->isDeclaration() || F->isInterposable()) {
99       // Note: isInterposable (as opposed to hasExactDefinition) is fine above,
100       // since we're not inferring new attributes here, but only using existing,
101       // assumed to be correct, function attributes.
102       SCCMightUnwind |= !F->doesNotThrow();
103       SCCMightReturn |= !F->doesNotReturn();
104     } else {
105       bool CheckUnwind = !SCCMightUnwind && !F->doesNotThrow();
106       bool CheckReturn = !SCCMightReturn && !F->doesNotReturn();
107       // Determine if we should scan for InlineAsm in a naked function as it
108       // is the only way to return without a ReturnInst.  Only do this for
109       // no-inline functions as functions which may be inlined cannot
110       // meaningfully return via assembly.
111       bool CheckReturnViaAsm = CheckReturn &&
112                                F->hasFnAttribute(Attribute::Naked) &&
113                                F->hasFnAttribute(Attribute::NoInline);
114 
115       if (!CheckUnwind && !CheckReturn)
116         continue;
117 
118       for (const BasicBlock &BB : *F) {
119         const TerminatorInst *TI = BB.getTerminator();
120         if (CheckUnwind && TI->mayThrow()) {
121           SCCMightUnwind = true;
122         } else if (CheckReturn && isa<ReturnInst>(TI)) {
123           SCCMightReturn = true;
124         }
125 
126         for (const Instruction &I : BB) {
127           if ((!CheckUnwind || SCCMightUnwind) &&
128               (!CheckReturnViaAsm || SCCMightReturn))
129             break;
130 
131           // Check to see if this function performs an unwind or calls an
132           // unwinding function.
133           if (CheckUnwind && !SCCMightUnwind && I.mayThrow()) {
134             bool InstMightUnwind = true;
135             if (const auto *CI = dyn_cast<CallInst>(&I)) {
136               if (Function *Callee = CI->getCalledFunction()) {
137                 CallGraphNode *CalleeNode = CG[Callee];
138                 // If the callee is outside our current SCC then we may throw
139                 // because it might.  If it is inside, do nothing.
140                 if (SCCNodes.count(CalleeNode) > 0)
141                   InstMightUnwind = false;
142               }
143             }
144             SCCMightUnwind |= InstMightUnwind;
145           }
146           if (CheckReturnViaAsm && !SCCMightReturn)
147             if (auto ICS = ImmutableCallSite(&I))
148               if (const auto *IA = dyn_cast<InlineAsm>(ICS.getCalledValue()))
149                 if (IA->hasSideEffects())
150                   SCCMightReturn = true;
151         }
152 
153         if (SCCMightUnwind && SCCMightReturn)
154           break;
155       }
156     }
157   }
158 
159   // If the SCC doesn't unwind or doesn't throw, note this fact.
160   if (!SCCMightUnwind || !SCCMightReturn)
161     for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
162       Function *F = (*I)->getFunction();
163 
164       if (!SCCMightUnwind && !F->hasFnAttribute(Attribute::NoUnwind)) {
165         F->addFnAttr(Attribute::NoUnwind);
166         MadeChange = true;
167       }
168 
169       if (!SCCMightReturn && !F->hasFnAttribute(Attribute::NoReturn)) {
170         F->addFnAttr(Attribute::NoReturn);
171         MadeChange = true;
172       }
173     }
174 
175   for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
176     // Convert any invoke instructions to non-throwing functions in this node
177     // into call instructions with a branch.  This makes the exception blocks
178     // dead.
179     if (Function *F = (*I)->getFunction())
180       MadeChange |= SimplifyFunction(F);
181   }
182 
183   return MadeChange;
184 }
185 
186 
187 // SimplifyFunction - Given information about callees, simplify the specified
188 // function if we have invokes to non-unwinding functions or code after calls to
189 // no-return functions.
190 bool PruneEH::SimplifyFunction(Function *F) {
191   bool MadeChange = false;
192   for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
193     if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator()))
194       if (II->doesNotThrow() && canSimplifyInvokeNoUnwind(F)) {
195         BasicBlock *UnwindBlock = II->getUnwindDest();
196         removeUnwindEdge(&*BB);
197 
198         // If the unwind block is now dead, nuke it.
199         if (pred_empty(UnwindBlock))
200           DeleteBasicBlock(UnwindBlock);  // Delete the new BB.
201 
202         ++NumRemoved;
203         MadeChange = true;
204       }
205 
206     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
207       if (CallInst *CI = dyn_cast<CallInst>(I++))
208         if (CI->doesNotReturn() && !isa<UnreachableInst>(I)) {
209           // This call calls a function that cannot return.  Insert an
210           // unreachable instruction after it and simplify the code.  Do this
211           // by splitting the BB, adding the unreachable, then deleting the
212           // new BB.
213           BasicBlock *New = BB->splitBasicBlock(I);
214 
215           // Remove the uncond branch and add an unreachable.
216           BB->getInstList().pop_back();
217           new UnreachableInst(BB->getContext(), &*BB);
218 
219           DeleteBasicBlock(New);  // Delete the new BB.
220           MadeChange = true;
221           ++NumUnreach;
222           break;
223         }
224   }
225 
226   return MadeChange;
227 }
228 
229 /// DeleteBasicBlock - remove the specified basic block from the program,
230 /// updating the callgraph to reflect any now-obsolete edges due to calls that
231 /// exist in the BB.
232 void PruneEH::DeleteBasicBlock(BasicBlock *BB) {
233   assert(pred_empty(BB) && "BB is not dead!");
234   CallGraph &CG = getAnalysis<CallGraphWrapperPass>().getCallGraph();
235 
236   Instruction *TokenInst = nullptr;
237 
238   CallGraphNode *CGN = CG[BB->getParent()];
239   for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; ) {
240     --I;
241 
242     if (I->getType()->isTokenTy()) {
243       TokenInst = &*I;
244       break;
245     }
246 
247     if (auto CS = CallSite (&*I)) {
248       const Function *Callee = CS.getCalledFunction();
249       if (!Callee || !Intrinsic::isLeaf(Callee->getIntrinsicID()))
250         CGN->removeCallEdgeFor(CS);
251       else if (!Callee->isIntrinsic())
252         CGN->removeCallEdgeFor(CS);
253     }
254 
255     if (!I->use_empty())
256       I->replaceAllUsesWith(UndefValue::get(I->getType()));
257   }
258 
259   if (TokenInst) {
260     if (!isa<TerminatorInst>(TokenInst))
261       changeToUnreachable(TokenInst->getNextNode(), /*UseLLVMTrap=*/false);
262   } else {
263     // Get the list of successors of this block.
264     std::vector<BasicBlock *> Succs(succ_begin(BB), succ_end(BB));
265 
266     for (unsigned i = 0, e = Succs.size(); i != e; ++i)
267       Succs[i]->removePredecessor(BB);
268 
269     BB->eraseFromParent();
270   }
271 }
272