simplify name juggling through the use of Value::takeName.
[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/Statistic.h"
26 #include "llvm/Support/CFG.h"
27 #include "llvm/Support/Compiler.h"
28 #include <set>
29 #include <algorithm>
30 using namespace llvm;
31
32 STATISTIC(NumRemoved, "Number of invokes removed");
33 STATISTIC(NumUnreach, "Number of noreturn calls optimized");
34
35 namespace {
36   struct VISIBILITY_HIDDEN PruneEH : public CallGraphSCCPass {
37     /// DoesNotUnwind - This set contains all of the functions which we have
38     /// determined cannot unwind.
39     std::set<CallGraphNode*> DoesNotUnwind;
40
41     /// DoesNotReturn - This set contains all of the functions which we have
42     /// determined cannot return normally (but might unwind).
43     std::set<CallGraphNode*> DoesNotReturn;
44
45     // runOnSCC - Analyze the SCC, performing the transformation if possible.
46     bool runOnSCC(const std::vector<CallGraphNode *> &SCC);
47
48     bool SimplifyFunction(Function *F);
49     void DeleteBasicBlock(BasicBlock *BB);
50   };
51   RegisterPass<PruneEH> X("prune-eh", "Remove unused exception handling info");
52 }
53
54 Pass *llvm::createPruneEHPass() { return new PruneEH(); }
55
56
57 bool PruneEH::runOnSCC(const std::vector<CallGraphNode *> &SCC) {
58   CallGraph &CG = getAnalysis<CallGraph>();
59   bool MadeChange = false;
60
61   // First pass, scan all of the functions in the SCC, simplifying them
62   // according to what we know.
63   for (unsigned i = 0, e = SCC.size(); i != e; ++i)
64     if (Function *F = SCC[i]->getFunction())
65       MadeChange |= SimplifyFunction(F);
66
67   // Next, check to see if any callees might throw or if there are any external
68   // functions in this SCC: if so, we cannot prune any functions in this SCC.
69   // If this SCC includes the unwind instruction, we KNOW it throws, so
70   // obviously the SCC might throw.
71   //
72   bool SCCMightUnwind = false, SCCMightReturn = false;
73   for (unsigned i = 0, e = SCC.size();
74        (!SCCMightUnwind || !SCCMightReturn) && i != e; ++i) {
75     Function *F = SCC[i]->getFunction();
76     if (F == 0 || (F->isDeclaration() && !F->getIntrinsicID())) {
77       SCCMightUnwind = true;
78       SCCMightReturn = true;
79     } else {
80       if (F->isDeclaration())
81         SCCMightReturn = true;
82
83       // Check to see if this function performs an unwind or calls an
84       // unwinding function.
85       for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
86         if (isa<UnwindInst>(BB->getTerminator())) {  // Uses unwind!
87           SCCMightUnwind = true;
88         } else if (isa<ReturnInst>(BB->getTerminator())) {
89           SCCMightReturn = true;
90         }
91
92         // Invoke instructions don't allow unwinding to continue, so we are
93         // only interested in call instructions.
94         if (!SCCMightUnwind)
95           for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
96             if (CallInst *CI = dyn_cast<CallInst>(I)) {
97               if (Function *Callee = CI->getCalledFunction()) {
98                 CallGraphNode *CalleeNode = CG[Callee];
99                 // If the callee is outside our current SCC, or if it is not
100                 // known to throw, then we might throw also.
101                 if (std::find(SCC.begin(), SCC.end(), CalleeNode) == SCC.end()&&
102                     !DoesNotUnwind.count(CalleeNode)) {
103                   SCCMightUnwind = true;
104                   break;
105                 }
106               } else {
107                 // Indirect call, it might throw.
108                 SCCMightUnwind = true;
109                 break;
110               }
111             }
112         if (SCCMightUnwind && SCCMightReturn) break;
113       }
114     }
115   }
116
117   // If the SCC doesn't unwind or doesn't throw, note this fact.
118   if (!SCCMightUnwind)
119     for (unsigned i = 0, e = SCC.size(); i != e; ++i)
120       DoesNotUnwind.insert(SCC[i]);
121   if (!SCCMightReturn)
122     for (unsigned i = 0, e = SCC.size(); i != e; ++i)
123       DoesNotReturn.insert(SCC[i]);
124
125   for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
126     // Convert any invoke instructions to non-throwing functions in this node
127     // into call instructions with a branch.  This makes the exception blocks
128     // dead.
129     if (Function *F = SCC[i]->getFunction())
130       MadeChange |= SimplifyFunction(F);
131   }
132
133   return MadeChange;
134 }
135
136
137 // SimplifyFunction - Given information about callees, simplify the specified
138 // function if we have invokes to non-unwinding functions or code after calls to
139 // no-return functions.
140 bool PruneEH::SimplifyFunction(Function *F) {
141   CallGraph &CG = getAnalysis<CallGraph>();
142   bool MadeChange = false;
143   for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
144     if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator()))
145       if (Function *F = II->getCalledFunction())
146         if (DoesNotUnwind.count(CG[F])) {
147           // Insert a call instruction before the invoke.
148           CallInst *Call = new CallInst(II->getCalledValue(),
149                                         std::vector<Value*>(II->op_begin()+3,
150                                                             II->op_end()),
151                                         "", 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 }