1 //===- PruneEH.cpp - Pass which deletes unused exception handlers ---------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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. It implements this as a bottom-up traversal of the
15 //===----------------------------------------------------------------------===//
17 #define DEBUG_TYPE "prune-eh"
18 #include "llvm/Transforms/IPO.h"
19 #include "llvm/CallGraphSCCPass.h"
20 #include "llvm/Constants.h"
21 #include "llvm/Function.h"
22 #include "llvm/Intrinsics.h"
23 #include "llvm/Instructions.h"
24 #include "llvm/Analysis/CallGraph.h"
25 #include "llvm/ADT/SmallVector.h"
26 #include "llvm/ADT/Statistic.h"
27 #include "llvm/Support/CFG.h"
28 #include "llvm/Support/Compiler.h"
33 STATISTIC(NumRemoved, "Number of invokes removed");
34 STATISTIC(NumUnreach, "Number of noreturn calls optimized");
37 struct VISIBILITY_HIDDEN PruneEH : public CallGraphSCCPass {
38 /// DoesNotUnwind - This set contains all of the functions which we have
39 /// determined cannot unwind.
40 std::set<CallGraphNode*> DoesNotUnwind;
42 /// DoesNotReturn - This set contains all of the functions which we have
43 /// determined cannot return normally (but might unwind).
44 std::set<CallGraphNode*> DoesNotReturn;
46 // runOnSCC - Analyze the SCC, performing the transformation if possible.
47 bool runOnSCC(const std::vector<CallGraphNode *> &SCC);
49 bool SimplifyFunction(Function *F);
50 void DeleteBasicBlock(BasicBlock *BB);
52 RegisterPass<PruneEH> X("prune-eh", "Remove unused exception handling info");
55 Pass *llvm::createPruneEHPass() { return new PruneEH(); }
58 bool PruneEH::runOnSCC(const std::vector<CallGraphNode *> &SCC) {
59 CallGraph &CG = getAnalysis<CallGraph>();
60 bool MadeChange = false;
62 // First pass, scan all of the functions in the SCC, simplifying them
63 // according to what we know.
64 for (unsigned i = 0, e = SCC.size(); i != e; ++i)
65 if (Function *F = SCC[i]->getFunction())
66 MadeChange |= SimplifyFunction(F);
68 // Next, check to see if any callees might throw or if there are any external
69 // functions in this SCC: if so, we cannot prune any functions in this SCC.
70 // If this SCC includes the unwind instruction, we KNOW it throws, so
71 // obviously the SCC might throw.
73 bool SCCMightUnwind = false, SCCMightReturn = false;
74 for (unsigned i = 0, e = SCC.size();
75 (!SCCMightUnwind || !SCCMightReturn) && i != e; ++i) {
76 Function *F = SCC[i]->getFunction();
77 if (F == 0 || (F->isDeclaration() && !F->getIntrinsicID())) {
78 SCCMightUnwind = true;
79 SCCMightReturn = true;
81 if (F->isDeclaration())
82 SCCMightReturn = true;
84 // Check to see if this function performs an unwind or calls an
85 // unwinding function.
86 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
87 if (isa<UnwindInst>(BB->getTerminator())) { // Uses unwind!
88 SCCMightUnwind = true;
89 } else if (isa<ReturnInst>(BB->getTerminator())) {
90 SCCMightReturn = true;
93 // Invoke instructions don't allow unwinding to continue, so we are
94 // only interested in call instructions.
96 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
97 if (CallInst *CI = dyn_cast<CallInst>(I)) {
98 if (Function *Callee = CI->getCalledFunction()) {
99 CallGraphNode *CalleeNode = CG[Callee];
100 // If the callee is outside our current SCC, or if it is not
101 // known to throw, then we might throw also.
102 if (std::find(SCC.begin(), SCC.end(), CalleeNode) == SCC.end()&&
103 !DoesNotUnwind.count(CalleeNode)) {
104 SCCMightUnwind = true;
108 // Indirect call, it might throw.
109 SCCMightUnwind = true;
113 if (SCCMightUnwind && SCCMightReturn) break;
118 // If the SCC doesn't unwind or doesn't throw, note this fact.
120 for (unsigned i = 0, e = SCC.size(); i != e; ++i)
121 DoesNotUnwind.insert(SCC[i]);
123 for (unsigned i = 0, e = SCC.size(); i != e; ++i)
124 DoesNotReturn.insert(SCC[i]);
126 for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
127 // Convert any invoke instructions to non-throwing functions in this node
128 // into call instructions with a branch. This makes the exception blocks
130 if (Function *F = SCC[i]->getFunction())
131 MadeChange |= SimplifyFunction(F);
138 // SimplifyFunction - Given information about callees, simplify the specified
139 // function if we have invokes to non-unwinding functions or code after calls to
140 // no-return functions.
141 bool PruneEH::SimplifyFunction(Function *F) {
142 CallGraph &CG = getAnalysis<CallGraph>();
143 bool MadeChange = false;
144 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
145 if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator()))
146 if (Function *F = II->getCalledFunction())
147 if (DoesNotUnwind.count(CG[F])) {
148 SmallVector<Value*, 8> Args(II->op_begin()+3, II->op_end());
149 // Insert a call instruction before the invoke.
150 CallInst *Call = new CallInst(II->getCalledValue(),
151 &Args[0], Args.size(), "", II);
153 Call->setCallingConv(II->getCallingConv());
155 // Anything that used the value produced by the invoke instruction
156 // now uses the value produced by the call instruction.
157 II->replaceAllUsesWith(Call);
158 BasicBlock *UnwindBlock = II->getUnwindDest();
159 UnwindBlock->removePredecessor(II->getParent());
161 // Insert a branch to the normal destination right before the
163 new BranchInst(II->getNormalDest(), II);
165 // Finally, delete the invoke instruction!
166 BB->getInstList().pop_back();
168 // If the unwind block is now dead, nuke it.
169 if (pred_begin(UnwindBlock) == pred_end(UnwindBlock))
170 DeleteBasicBlock(UnwindBlock); // Delete the new BB.
176 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
177 if (CallInst *CI = dyn_cast<CallInst>(I++))
178 if (Function *Callee = CI->getCalledFunction())
179 if (DoesNotReturn.count(CG[Callee]) && !isa<UnreachableInst>(I)) {
180 // This call calls a function that cannot return. Insert an
181 // unreachable instruction after it and simplify the code. Do this
182 // by splitting the BB, adding the unreachable, then deleting the
184 BasicBlock *New = BB->splitBasicBlock(I);
186 // Remove the uncond branch and add an unreachable.
187 BB->getInstList().pop_back();
188 new UnreachableInst(BB);
190 DeleteBasicBlock(New); // Delete the new BB.
200 /// DeleteBasicBlock - remove the specified basic block from the program,
201 /// updating the callgraph to reflect any now-obsolete edges due to calls that
203 void PruneEH::DeleteBasicBlock(BasicBlock *BB) {
204 assert(pred_begin(BB) == pred_end(BB) && "BB is not dead!");
205 CallGraph &CG = getAnalysis<CallGraph>();
207 CallGraphNode *CGN = CG[BB->getParent()];
208 for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; ) {
210 if (CallInst *CI = dyn_cast<CallInst>(I)) {
211 if (Function *Callee = CI->getCalledFunction())
212 CGN->removeCallEdgeTo(CG[Callee]);
213 } else if (InvokeInst *II = dyn_cast<InvokeInst>(I)) {
214 if (Function *Callee = II->getCalledFunction())
215 CGN->removeCallEdgeTo(CG[Callee]);
218 I->replaceAllUsesWith(UndefValue::get(I->getType()));
221 // Get the list of successors of this block.
222 std::vector<BasicBlock*> Succs(succ_begin(BB), succ_end(BB));
224 for (unsigned i = 0, e = Succs.size(); i != e; ++i)
225 Succs[i]->removePredecessor(BB);
227 BB->eraseFromParent();