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