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