Eliminate use of ctors that take vectors.
[oota-llvm.git] / lib / Transforms / IPO / PruneEH.cpp
1 //===- PruneEH.cpp - Pass which deletes unused exception handlers ---------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
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.
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.  It implements this as a bottom-up traversal of the
13 // call-graph.
14 //
15 //===----------------------------------------------------------------------===//
16
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"
29 #include <set>
30 #include <algorithm>
31 using namespace llvm;
32
33 STATISTIC(NumRemoved, "Number of invokes removed");
34 STATISTIC(NumUnreach, "Number of noreturn calls optimized");
35
36 namespace {
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;
41
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;
45
46     // runOnSCC - Analyze the SCC, performing the transformation if possible.
47     bool runOnSCC(const std::vector<CallGraphNode *> &SCC);
48
49     bool SimplifyFunction(Function *F);
50     void DeleteBasicBlock(BasicBlock *BB);
51   };
52   RegisterPass<PruneEH> X("prune-eh", "Remove unused exception handling info");
53 }
54
55 Pass *llvm::createPruneEHPass() { return new PruneEH(); }
56
57
58 bool PruneEH::runOnSCC(const std::vector<CallGraphNode *> &SCC) {
59   CallGraph &CG = getAnalysis<CallGraph>();
60   bool MadeChange = false;
61
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);
67
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.
72   //
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;
80     } else {
81       if (F->isDeclaration())
82         SCCMightReturn = true;
83
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;
91         }
92
93         // Invoke instructions don't allow unwinding to continue, so we are
94         // only interested in call instructions.
95         if (!SCCMightUnwind)
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;
105                   break;
106                 }
107               } else {
108                 // Indirect call, it might throw.
109                 SCCMightUnwind = true;
110                 break;
111               }
112             }
113         if (SCCMightUnwind && SCCMightReturn) break;
114       }
115     }
116   }
117
118   // If the SCC doesn't unwind or doesn't throw, note this fact.
119   if (!SCCMightUnwind)
120     for (unsigned i = 0, e = SCC.size(); i != e; ++i)
121       DoesNotUnwind.insert(SCC[i]);
122   if (!SCCMightReturn)
123     for (unsigned i = 0, e = SCC.size(); i != e; ++i)
124       DoesNotReturn.insert(SCC[i]);
125
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
129     // dead.
130     if (Function *F = SCC[i]->getFunction())
131       MadeChange |= SimplifyFunction(F);
132   }
133
134   return MadeChange;
135 }
136
137
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);
152           Call->takeName(II);
153           Call->setCallingConv(II->getCallingConv());
154
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());
160
161           // Insert a branch to the normal destination right before the
162           // invoke.
163           new BranchInst(II->getNormalDest(), II);
164
165           // Finally, delete the invoke instruction!
166           BB->getInstList().pop_back();
167
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.
171
172           ++NumRemoved;
173           MadeChange = true;
174         }
175
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
183             // new BB.
184             BasicBlock *New = BB->splitBasicBlock(I);
185
186             // Remove the uncond branch and add an unreachable.
187             BB->getInstList().pop_back();
188             new UnreachableInst(BB);
189
190             DeleteBasicBlock(New);  // Delete the new BB.
191             MadeChange = true;
192             ++NumUnreach;
193             break;
194           }
195
196   }
197   return MadeChange;
198 }
199
200 /// DeleteBasicBlock - remove the specified basic block from the program,
201 /// updating the callgraph to reflect any now-obsolete edges due to calls that
202 /// exist in the BB.
203 void PruneEH::DeleteBasicBlock(BasicBlock *BB) {
204   assert(pred_begin(BB) == pred_end(BB) && "BB is not dead!");
205   CallGraph &CG = getAnalysis<CallGraph>();
206
207   CallGraphNode *CGN = CG[BB->getParent()];
208   for (BasicBlock::iterator I = BB->end(), E = BB->begin(); I != E; ) {
209     --I;
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]);
216     }
217     if (!I->use_empty())
218       I->replaceAllUsesWith(UndefValue::get(I->getType()));
219   }
220
221   // Get the list of successors of this block.
222   std::vector<BasicBlock*> Succs(succ_begin(BB), succ_end(BB));
223
224   for (unsigned i = 0, e = Succs.size(); i != e; ++i)
225     Succs[i]->removePredecessor(BB);
226
227   BB->eraseFromParent();
228 }