1 //===- LowerInvoke.cpp - Eliminate Invoke & Unwind instructions -----------===//
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().
8 //===----------------------------------------------------------------------===//
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"
20 Statistic<> NumLowered("lowerinvoke", "Number of invoke & unwinds replaced");
22 class LowerInvoke : public FunctionPass {
25 bool doInitialization(Module &M);
26 bool runOnFunction(Function &F);
29 RegisterOpt<LowerInvoke>
30 X("lowerinvoke", "Lower invoke and unwind, for unwindless code generators");
33 FunctionPass *createLowerInvokePass() { return new LowerInvoke(); }
35 // doInitialization - Make sure that there is a prototype for abort in the
37 bool LowerInvoke::doInitialization(Module &M) {
38 AbortFn = M.getOrInsertFunction("abort", Type::VoidTy, 0);
42 bool LowerInvoke::runOnFunction(Function &F) {
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);
53 // Insert an unconditional branch to the normal destination
54 new BranchInst(II->getNormalDest(), II);
56 // Remove the invoke instruction now.
57 I->getInstList().erase(II);
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);
64 // Insert a return instruction.
65 new ReturnInst(F.getReturnType() == Type::VoidTy ? 0 :
66 Constant::getNullValue(F.getReturnType()), UI);
68 // Remove the unwind instruction now.
69 I->getInstList().erase(UI);
71 ++NumLowered; Changed = true;