File is renamed to LoopSimplify.cpp
[oota-llvm.git] / lib / Transforms / Utils / LowerInvoke.cpp
1 //===- LowerInvoke.cpp - Eliminate Invoke & Unwind instructions -----------===//
2 //
3 // This transformation is designed for use by code generators which do not yet
4 // support stack unwinding.  This pass gives them the ability to execute any
5 // program which does not throw an exception, by turning 'invoke' instructions
6 // into calls and by turning 'unwind' instructions into calls to abort().
7 //
8 //===----------------------------------------------------------------------===//
9
10 #include "llvm/Transforms/Scalar.h"
11 #include "llvm/Pass.h"
12 #include "llvm/iTerminators.h"
13 #include "llvm/iOther.h"
14 #include "llvm/Module.h"
15 #include "llvm/Type.h"
16 #include "llvm/Constant.h"
17 #include "Support/Statistic.h"
18
19 namespace {
20   Statistic<> NumLowered("lowerinvoke", "Number of invoke & unwinds replaced");
21
22   class LowerInvoke : public FunctionPass {
23     Function *AbortFn;
24   public:
25     bool doInitialization(Module &M);
26     bool runOnFunction(Function &F);
27   };
28
29   RegisterOpt<LowerInvoke>
30   X("lowerinvoke", "Lower invoke and unwind, for unwindless code generators");
31 }
32
33 FunctionPass *createLowerInvokePass() { return new LowerInvoke(); }
34
35 // doInitialization - Make sure that there is a prototype for abort in the
36 // current module.
37 bool LowerInvoke::doInitialization(Module &M) {
38   AbortFn = M.getOrInsertFunction("abort", Type::VoidTy, 0);
39   return true;
40 }
41
42 bool LowerInvoke::runOnFunction(Function &F) {
43   bool Changed = false;
44   for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
45     if (InvokeInst *II = dyn_cast<InvokeInst>(I->getTerminator())) {
46       // Insert a normal call instruction...
47       std::string Name = II->getName(); II->setName("");
48       Value *NewCall = new CallInst(II->getCalledValue(),
49                                     std::vector<Value*>(II->op_begin()+3,
50                                                         II->op_end()), Name,II);
51       II->replaceAllUsesWith(NewCall);
52       
53       // Insert an unconditional branch to the normal destination
54       new BranchInst(II->getNormalDest(), II);
55
56       // Remove the invoke instruction now.
57       I->getInstList().erase(II);
58
59       ++NumLowered; Changed = true;
60     } else if (UnwindInst *UI = dyn_cast<UnwindInst>(I->getTerminator())) {
61       // Insert a call to abort()
62       new CallInst(AbortFn, std::vector<Value*>(), "", UI);
63
64       // Insert a return instruction.
65       new ReturnInst(F.getReturnType() == Type::VoidTy ? 0 :
66                             Constant::getNullValue(F.getReturnType()), UI);
67
68       // Remove the unwind instruction now.
69       I->getInstList().erase(UI);
70
71       ++NumLowered; Changed = true;
72     }
73   return Changed;
74 }