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 static const int ID; // Pass identifcation, replacement for typeid
39 PruneEH() : CallGraphSCCPass((intptr_t)&ID) {}
41 /// DoesNotUnwind - This set contains all of the functions which we have
42 /// determined cannot unwind.
43 std::set<CallGraphNode*> DoesNotUnwind;
45 /// DoesNotReturn - This set contains all of the functions which we have
46 /// determined cannot return normally (but might unwind).
47 std::set<CallGraphNode*> DoesNotReturn;
49 // runOnSCC - Analyze the SCC, performing the transformation if possible.
50 bool runOnSCC(const std::vector<CallGraphNode *> &SCC);
52 bool SimplifyFunction(Function *F);
53 void DeleteBasicBlock(BasicBlock *BB);
56 const int PruneEH::ID = 0;
57 RegisterPass<PruneEH> X("prune-eh", "Remove unused exception handling info");
60 Pass *llvm::createPruneEHPass() { return new PruneEH(); }
63 bool PruneEH::runOnSCC(const std::vector<CallGraphNode *> &SCC) {
64 CallGraph &CG = getAnalysis<CallGraph>();
65 bool MadeChange = false;
67 // First pass, scan all of the functions in the SCC, simplifying them
68 // according to what we know.
69 for (unsigned i = 0, e = SCC.size(); i != e; ++i)
70 if (Function *F = SCC[i]->getFunction())
71 MadeChange |= SimplifyFunction(F);
73 // Next, check to see if any callees might throw or if there are any external
74 // functions in this SCC: if so, we cannot prune any functions in this SCC.
75 // If this SCC includes the unwind instruction, we KNOW it throws, so
76 // obviously the SCC might throw.
78 bool SCCMightUnwind = false, SCCMightReturn = false;
79 for (unsigned i = 0, e = SCC.size();
80 (!SCCMightUnwind || !SCCMightReturn) && i != e; ++i) {
81 Function *F = SCC[i]->getFunction();
82 if (F == 0 || (F->isDeclaration() && !F->getIntrinsicID())) {
83 SCCMightUnwind = true;
84 SCCMightReturn = true;
86 if (F->isDeclaration())
87 SCCMightReturn = true;
89 // Check to see if this function performs an unwind or calls an
90 // unwinding function.
91 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
92 if (isa<UnwindInst>(BB->getTerminator())) { // Uses unwind!
93 SCCMightUnwind = true;
94 } else if (isa<ReturnInst>(BB->getTerminator())) {
95 SCCMightReturn = true;
98 // Invoke instructions don't allow unwinding to continue, so we are
99 // only interested in call instructions.
101 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
102 if (CallInst *CI = dyn_cast<CallInst>(I)) {
103 if (Function *Callee = CI->getCalledFunction()) {
104 CallGraphNode *CalleeNode = CG[Callee];
105 // If the callee is outside our current SCC, or if it is not
106 // known to throw, then we might throw also.
107 if (std::find(SCC.begin(), SCC.end(), CalleeNode) == SCC.end()&&
108 !DoesNotUnwind.count(CalleeNode)) {
109 SCCMightUnwind = true;
113 // Indirect call, it might throw.
114 SCCMightUnwind = true;
118 if (SCCMightUnwind && SCCMightReturn) break;
123 // If the SCC doesn't unwind or doesn't throw, note this fact.
125 for (unsigned i = 0, e = SCC.size(); i != e; ++i)
126 DoesNotUnwind.insert(SCC[i]);
128 for (unsigned i = 0, e = SCC.size(); i != e; ++i)
129 DoesNotReturn.insert(SCC[i]);
131 for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
132 // Convert any invoke instructions to non-throwing functions in this node
133 // into call instructions with a branch. This makes the exception blocks
135 if (Function *F = SCC[i]->getFunction())
136 MadeChange |= SimplifyFunction(F);
143 // SimplifyFunction - Given information about callees, simplify the specified
144 // function if we have invokes to non-unwinding functions or code after calls to
145 // no-return functions.
146 bool PruneEH::SimplifyFunction(Function *F) {
147 CallGraph &CG = getAnalysis<CallGraph>();
148 bool MadeChange = false;
149 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
150 if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator()))
151 if (Function *F = II->getCalledFunction())
152 if (DoesNotUnwind.count(CG[F])) {
153 SmallVector<Value*, 8> Args(II->op_begin()+3, II->op_end());
154 // Insert a call instruction before the invoke.
155 CallInst *Call = new CallInst(II->getCalledValue(),
156 &Args[0], Args.size(), "", II);
158 Call->setCallingConv(II->getCallingConv());
160 // Anything that used the value produced by the invoke instruction
161 // now uses the value produced by the call instruction.
162 II->replaceAllUsesWith(Call);
163 BasicBlock *UnwindBlock = II->getUnwindDest();
164 UnwindBlock->removePredecessor(II->getParent());
166 // Insert a branch to the normal destination right before the
168 new BranchInst(II->getNormalDest(), II);
170 // Finally, delete the invoke instruction!
171 BB->getInstList().pop_back();
173 // If the unwind block is now dead, nuke it.
174 if (pred_begin(UnwindBlock) == pred_end(UnwindBlock))
175 DeleteBasicBlock(UnwindBlock); // Delete the new BB.
181 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
182 if (CallInst *CI = dyn_cast<CallInst>(I++))
183 if (Function *Callee = CI->getCalledFunction())
184 if (DoesNotReturn.count(CG[Callee]) && !isa<UnreachableInst>(I)) {
185 // This call calls a function that cannot return. Insert an
186 // unreachable instruction after it and simplify the code. Do this
187 // by splitting the BB, adding the unreachable, then deleting the
189 BasicBlock *New = BB->splitBasicBlock(I);
191 // Remove the uncond branch and add an unreachable.
192 BB->getInstList().pop_back();
193 new UnreachableInst(BB);
195 DeleteBasicBlock(New); // Delete the new BB.
205 /// DeleteBasicBlock - remove the specified basic block from the program,
206 /// updating the callgraph to reflect any now-obsolete edges due to calls that
208 void PruneEH::DeleteBasicBlock(BasicBlock *BB) {
209 assert(pred_begin(BB) == pred_end(BB) && "BB is not dead!");
210 CallGraph &CG = getAnalysis<CallGraph>();
212 CallGraphNode *CGN = CG[BB->getParent()];
213 for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; ) {
215 if (CallInst *CI = dyn_cast<CallInst>(I)) {
216 if (Function *Callee = CI->getCalledFunction())
217 CGN->removeCallEdgeTo(CG[Callee]);
218 } else if (InvokeInst *II = dyn_cast<InvokeInst>(I)) {
219 if (Function *Callee = II->getCalledFunction())
220 CGN->removeCallEdgeTo(CG[Callee]);
223 I->replaceAllUsesWith(UndefValue::get(I->getType()));
226 // Get the list of successors of this block.
227 std::vector<BasicBlock*> Succs(succ_begin(BB), succ_end(BB));
229 for (unsigned i = 0, e = Succs.size(); i != e; ++i)
230 Succs[i]->removePredecessor(BB);
232 BB->eraseFromParent();