SjLjEHPrepare.cpp revision 198892
1198090Srdivacky//===- SjLjEHPass.cpp - Eliminate Invoke & Unwind instructions -----------===//
2198090Srdivacky//
3198090Srdivacky//                     The LLVM Compiler Infrastructure
4198090Srdivacky//
5198090Srdivacky// This file is distributed under the University of Illinois Open Source
6198090Srdivacky// License. See LICENSE.TXT for details.
7198090Srdivacky//
8198090Srdivacky//===----------------------------------------------------------------------===//
9198090Srdivacky//
10198090Srdivacky// This transformation is designed for use by code generators which use SjLj
11198090Srdivacky// based exception handling.
12198090Srdivacky//
13198090Srdivacky//===----------------------------------------------------------------------===//
14198090Srdivacky
15198090Srdivacky#define DEBUG_TYPE "sjljehprepare"
16198090Srdivacky#include "llvm/Transforms/Scalar.h"
17198090Srdivacky#include "llvm/Constants.h"
18198090Srdivacky#include "llvm/DerivedTypes.h"
19198090Srdivacky#include "llvm/Instructions.h"
20198090Srdivacky#include "llvm/Intrinsics.h"
21198090Srdivacky#include "llvm/LLVMContext.h"
22198090Srdivacky#include "llvm/Module.h"
23198090Srdivacky#include "llvm/Pass.h"
24198090Srdivacky#include "llvm/CodeGen/Passes.h"
25198090Srdivacky#include "llvm/Transforms/Utils/BasicBlockUtils.h"
26198090Srdivacky#include "llvm/Transforms/Utils/Local.h"
27198090Srdivacky#include "llvm/ADT/Statistic.h"
28198090Srdivacky#include "llvm/ADT/SmallVector.h"
29198090Srdivacky#include "llvm/Support/CommandLine.h"
30198090Srdivacky#include "llvm/Support/Debug.h"
31198090Srdivacky#include "llvm/Support/raw_ostream.h"
32198090Srdivacky#include "llvm/Target/TargetLowering.h"
33198090Srdivackyusing namespace llvm;
34198090Srdivacky
35198090SrdivackySTATISTIC(NumInvokes, "Number of invokes replaced");
36198090SrdivackySTATISTIC(NumUnwinds, "Number of unwinds replaced");
37198090SrdivackySTATISTIC(NumSpilled, "Number of registers live across unwind edges");
38198090Srdivacky
39198090Srdivackynamespace {
40198892Srdivacky  class SjLjEHPass : public FunctionPass {
41198090Srdivacky
42198090Srdivacky    const TargetLowering *TLI;
43198090Srdivacky
44198090Srdivacky    const Type *FunctionContextTy;
45198090Srdivacky    Constant *RegisterFn;
46198090Srdivacky    Constant *UnregisterFn;
47198090Srdivacky    Constant *ResumeFn;
48198090Srdivacky    Constant *BuiltinSetjmpFn;
49198090Srdivacky    Constant *FrameAddrFn;
50198090Srdivacky    Constant *LSDAAddrFn;
51198090Srdivacky    Value *PersonalityFn;
52198090Srdivacky    Constant *SelectorFn;
53198090Srdivacky    Constant *ExceptionFn;
54198090Srdivacky
55198090Srdivacky    Value *CallSite;
56198090Srdivacky  public:
57198090Srdivacky    static char ID; // Pass identification, replacement for typeid
58198090Srdivacky    explicit SjLjEHPass(const TargetLowering *tli = NULL)
59198090Srdivacky      : FunctionPass(&ID), TLI(tli) { }
60198090Srdivacky    bool doInitialization(Module &M);
61198090Srdivacky    bool runOnFunction(Function &F);
62198090Srdivacky
63198090Srdivacky    virtual void getAnalysisUsage(AnalysisUsage &AU) const { }
64198090Srdivacky    const char *getPassName() const {
65198090Srdivacky      return "SJLJ Exception Handling preparation";
66198090Srdivacky    }
67198090Srdivacky
68198090Srdivacky  private:
69198090Srdivacky    void markInvokeCallSite(InvokeInst *II, unsigned InvokeNo,
70198090Srdivacky                            Value *CallSite,
71198090Srdivacky                            SwitchInst *CatchSwitch);
72198090Srdivacky    void splitLiveRangesLiveAcrossInvokes(SmallVector<InvokeInst*,16> &Invokes);
73198090Srdivacky    bool insertSjLjEHSupport(Function &F);
74198090Srdivacky  };
75198090Srdivacky} // end anonymous namespace
76198090Srdivacky
77198090Srdivackychar SjLjEHPass::ID = 0;
78198090Srdivacky
79198090Srdivacky// Public Interface To the SjLjEHPass pass.
80198090SrdivackyFunctionPass *llvm::createSjLjEHPass(const TargetLowering *TLI) {
81198090Srdivacky  return new SjLjEHPass(TLI);
82198090Srdivacky}
83198090Srdivacky// doInitialization - Set up decalarations and types needed to process
84198090Srdivacky// exceptions.
85198090Srdivackybool SjLjEHPass::doInitialization(Module &M) {
86198090Srdivacky  // Build the function context structure.
87198090Srdivacky  // builtin_setjmp uses a five word jbuf
88198090Srdivacky  const Type *VoidPtrTy =
89198090Srdivacky          Type::getInt8PtrTy(M.getContext());
90198090Srdivacky  const Type *Int32Ty = Type::getInt32Ty(M.getContext());
91198090Srdivacky  FunctionContextTy =
92198090Srdivacky    StructType::get(M.getContext(),
93198090Srdivacky                    VoidPtrTy,                        // __prev
94198090Srdivacky                    Int32Ty,                          // call_site
95198090Srdivacky                    ArrayType::get(Int32Ty, 4),       // __data
96198090Srdivacky                    VoidPtrTy,                        // __personality
97198090Srdivacky                    VoidPtrTy,                        // __lsda
98198090Srdivacky                    ArrayType::get(VoidPtrTy, 5),     // __jbuf
99198090Srdivacky                    NULL);
100198090Srdivacky  RegisterFn = M.getOrInsertFunction("_Unwind_SjLj_Register",
101198090Srdivacky                                     Type::getVoidTy(M.getContext()),
102198090Srdivacky                                     PointerType::getUnqual(FunctionContextTy),
103198090Srdivacky                                     (Type *)0);
104198090Srdivacky  UnregisterFn =
105198090Srdivacky    M.getOrInsertFunction("_Unwind_SjLj_Unregister",
106198090Srdivacky                          Type::getVoidTy(M.getContext()),
107198090Srdivacky                          PointerType::getUnqual(FunctionContextTy),
108198090Srdivacky                          (Type *)0);
109198090Srdivacky  ResumeFn =
110198090Srdivacky    M.getOrInsertFunction("_Unwind_SjLj_Resume",
111198090Srdivacky                          Type::getVoidTy(M.getContext()),
112198090Srdivacky                          VoidPtrTy,
113198090Srdivacky                          (Type *)0);
114198090Srdivacky  FrameAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::frameaddress);
115198090Srdivacky  BuiltinSetjmpFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_setjmp);
116198090Srdivacky  LSDAAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_lsda);
117198090Srdivacky  SelectorFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_selector);
118198090Srdivacky  ExceptionFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_exception);
119198090Srdivacky  PersonalityFn = 0;
120198090Srdivacky
121198090Srdivacky  return true;
122198090Srdivacky}
123198090Srdivacky
124198090Srdivacky/// markInvokeCallSite - Insert code to mark the call_site for this invoke
125198090Srdivackyvoid SjLjEHPass::markInvokeCallSite(InvokeInst *II, unsigned InvokeNo,
126198090Srdivacky                                    Value *CallSite,
127198090Srdivacky                                    SwitchInst *CatchSwitch) {
128198090Srdivacky  ConstantInt *CallSiteNoC= ConstantInt::get(Type::getInt32Ty(II->getContext()),
129198090Srdivacky                                            InvokeNo);
130198090Srdivacky  // The runtime comes back to the dispatcher with the call_site - 1 in
131198090Srdivacky  // the context. Odd, but there it is.
132198090Srdivacky  ConstantInt *SwitchValC = ConstantInt::get(Type::getInt32Ty(II->getContext()),
133198090Srdivacky                                            InvokeNo - 1);
134198090Srdivacky
135198090Srdivacky  // If the unwind edge has phi nodes, split the edge.
136198090Srdivacky  if (isa<PHINode>(II->getUnwindDest()->begin())) {
137198090Srdivacky    SplitCriticalEdge(II, 1, this);
138198090Srdivacky
139198090Srdivacky    // If there are any phi nodes left, they must have a single predecessor.
140198090Srdivacky    while (PHINode *PN = dyn_cast<PHINode>(II->getUnwindDest()->begin())) {
141198090Srdivacky      PN->replaceAllUsesWith(PN->getIncomingValue(0));
142198090Srdivacky      PN->eraseFromParent();
143198090Srdivacky    }
144198090Srdivacky  }
145198090Srdivacky
146198090Srdivacky  // Insert a store of the invoke num before the invoke and store zero into the
147198090Srdivacky  // location afterward.
148198090Srdivacky  new StoreInst(CallSiteNoC, CallSite, true, II);  // volatile
149198090Srdivacky
150198090Srdivacky  // Add a switch case to our unwind block.
151198090Srdivacky  CatchSwitch->addCase(SwitchValC, II->getUnwindDest());
152198090Srdivacky  // We still want this to look like an invoke so we emit the LSDA properly
153198090Srdivacky  // FIXME: ??? Or will this cause strangeness with mis-matched IDs like
154198090Srdivacky  //  when it was in the front end?
155198090Srdivacky}
156198090Srdivacky
157198090Srdivacky/// MarkBlocksLiveIn - Insert BB and all of its predescessors into LiveBBs until
158198090Srdivacky/// we reach blocks we've already seen.
159198090Srdivackystatic void MarkBlocksLiveIn(BasicBlock *BB, std::set<BasicBlock*> &LiveBBs) {
160198090Srdivacky  if (!LiveBBs.insert(BB).second) return; // already been here.
161198090Srdivacky
162198090Srdivacky  for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
163198090Srdivacky    MarkBlocksLiveIn(*PI, LiveBBs);
164198090Srdivacky}
165198090Srdivacky
166198090Srdivacky/// splitLiveRangesAcrossInvokes - Each value that is live across an unwind edge
167198090Srdivacky/// we spill into a stack location, guaranteeing that there is nothing live
168198090Srdivacky/// across the unwind edge.  This process also splits all critical edges
169198090Srdivacky/// coming out of invoke's.
170198090Srdivackyvoid SjLjEHPass::
171198090SrdivackysplitLiveRangesLiveAcrossInvokes(SmallVector<InvokeInst*,16> &Invokes) {
172198090Srdivacky  // First step, split all critical edges from invoke instructions.
173198090Srdivacky  for (unsigned i = 0, e = Invokes.size(); i != e; ++i) {
174198090Srdivacky    InvokeInst *II = Invokes[i];
175198090Srdivacky    SplitCriticalEdge(II, 0, this);
176198090Srdivacky    SplitCriticalEdge(II, 1, this);
177198090Srdivacky    assert(!isa<PHINode>(II->getNormalDest()) &&
178198090Srdivacky           !isa<PHINode>(II->getUnwindDest()) &&
179198090Srdivacky           "critical edge splitting left single entry phi nodes?");
180198090Srdivacky  }
181198090Srdivacky
182198090Srdivacky  Function *F = Invokes.back()->getParent()->getParent();
183198090Srdivacky
184198090Srdivacky  // To avoid having to handle incoming arguments specially, we lower each arg
185198090Srdivacky  // to a copy instruction in the entry block.  This ensures that the argument
186198090Srdivacky  // value itself cannot be live across the entry block.
187198090Srdivacky  BasicBlock::iterator AfterAllocaInsertPt = F->begin()->begin();
188198090Srdivacky  while (isa<AllocaInst>(AfterAllocaInsertPt) &&
189198090Srdivacky        isa<ConstantInt>(cast<AllocaInst>(AfterAllocaInsertPt)->getArraySize()))
190198090Srdivacky    ++AfterAllocaInsertPt;
191198090Srdivacky  for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
192198090Srdivacky       AI != E; ++AI) {
193198090Srdivacky    // This is always a no-op cast because we're casting AI to AI->getType() so
194198090Srdivacky    // src and destination types are identical. BitCast is the only possibility.
195198090Srdivacky    CastInst *NC = new BitCastInst(
196198090Srdivacky      AI, AI->getType(), AI->getName()+".tmp", AfterAllocaInsertPt);
197198090Srdivacky    AI->replaceAllUsesWith(NC);
198198090Srdivacky    // Normally its is forbidden to replace a CastInst's operand because it
199198090Srdivacky    // could cause the opcode to reflect an illegal conversion. However, we're
200198090Srdivacky    // replacing it here with the same value it was constructed with to simply
201198090Srdivacky    // make NC its user.
202198090Srdivacky    NC->setOperand(0, AI);
203198090Srdivacky  }
204198090Srdivacky
205198090Srdivacky  // Finally, scan the code looking for instructions with bad live ranges.
206198090Srdivacky  for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
207198090Srdivacky    for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; ++II) {
208198090Srdivacky      // Ignore obvious cases we don't have to handle.  In particular, most
209198090Srdivacky      // instructions either have no uses or only have a single use inside the
210198090Srdivacky      // current block.  Ignore them quickly.
211198090Srdivacky      Instruction *Inst = II;
212198090Srdivacky      if (Inst->use_empty()) continue;
213198090Srdivacky      if (Inst->hasOneUse() &&
214198090Srdivacky          cast<Instruction>(Inst->use_back())->getParent() == BB &&
215198090Srdivacky          !isa<PHINode>(Inst->use_back())) continue;
216198090Srdivacky
217198090Srdivacky      // If this is an alloca in the entry block, it's not a real register
218198090Srdivacky      // value.
219198090Srdivacky      if (AllocaInst *AI = dyn_cast<AllocaInst>(Inst))
220198090Srdivacky        if (isa<ConstantInt>(AI->getArraySize()) && BB == F->begin())
221198090Srdivacky          continue;
222198090Srdivacky
223198090Srdivacky      // Avoid iterator invalidation by copying users to a temporary vector.
224198090Srdivacky      SmallVector<Instruction*,16> Users;
225198090Srdivacky      for (Value::use_iterator UI = Inst->use_begin(), E = Inst->use_end();
226198090Srdivacky           UI != E; ++UI) {
227198090Srdivacky        Instruction *User = cast<Instruction>(*UI);
228198090Srdivacky        if (User->getParent() != BB || isa<PHINode>(User))
229198090Srdivacky          Users.push_back(User);
230198090Srdivacky      }
231198090Srdivacky
232198090Srdivacky      // Find all of the blocks that this value is live in.
233198090Srdivacky      std::set<BasicBlock*> LiveBBs;
234198090Srdivacky      LiveBBs.insert(Inst->getParent());
235198090Srdivacky      while (!Users.empty()) {
236198090Srdivacky        Instruction *U = Users.back();
237198090Srdivacky        Users.pop_back();
238198090Srdivacky
239198090Srdivacky        if (!isa<PHINode>(U)) {
240198090Srdivacky          MarkBlocksLiveIn(U->getParent(), LiveBBs);
241198090Srdivacky        } else {
242198090Srdivacky          // Uses for a PHI node occur in their predecessor block.
243198090Srdivacky          PHINode *PN = cast<PHINode>(U);
244198090Srdivacky          for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
245198090Srdivacky            if (PN->getIncomingValue(i) == Inst)
246198090Srdivacky              MarkBlocksLiveIn(PN->getIncomingBlock(i), LiveBBs);
247198090Srdivacky        }
248198090Srdivacky      }
249198090Srdivacky
250198090Srdivacky      // Now that we know all of the blocks that this thing is live in, see if
251198090Srdivacky      // it includes any of the unwind locations.
252198090Srdivacky      bool NeedsSpill = false;
253198090Srdivacky      for (unsigned i = 0, e = Invokes.size(); i != e; ++i) {
254198090Srdivacky        BasicBlock *UnwindBlock = Invokes[i]->getUnwindDest();
255198090Srdivacky        if (UnwindBlock != BB && LiveBBs.count(UnwindBlock)) {
256198090Srdivacky          NeedsSpill = true;
257198090Srdivacky        }
258198090Srdivacky      }
259198090Srdivacky
260198090Srdivacky      // If we decided we need a spill, do it.
261198090Srdivacky      if (NeedsSpill) {
262198090Srdivacky        ++NumSpilled;
263198090Srdivacky        DemoteRegToStack(*Inst, true);
264198090Srdivacky      }
265198090Srdivacky    }
266198090Srdivacky}
267198090Srdivacky
268198090Srdivackybool SjLjEHPass::insertSjLjEHSupport(Function &F) {
269198090Srdivacky  SmallVector<ReturnInst*,16> Returns;
270198090Srdivacky  SmallVector<UnwindInst*,16> Unwinds;
271198090Srdivacky  SmallVector<InvokeInst*,16> Invokes;
272198090Srdivacky
273198090Srdivacky  // Look through the terminators of the basic blocks to find invokes, returns
274198090Srdivacky  // and unwinds
275198090Srdivacky  for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
276198090Srdivacky    if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
277198090Srdivacky      // Remember all return instructions in case we insert an invoke into this
278198090Srdivacky      // function.
279198090Srdivacky      Returns.push_back(RI);
280198090Srdivacky    } else if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
281198090Srdivacky      Invokes.push_back(II);
282198090Srdivacky    } else if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator())) {
283198090Srdivacky      Unwinds.push_back(UI);
284198090Srdivacky    }
285198090Srdivacky  // If we don't have any invokes or unwinds, there's nothing to do.
286198090Srdivacky  if (Unwinds.empty() && Invokes.empty()) return false;
287198090Srdivacky
288198090Srdivacky  // Find the eh.selector.*  and eh.exception calls. We'll use the first
289198090Srdivacky  // eh.selector to determine the right personality function to use. For
290198090Srdivacky  // SJLJ, we always use the same personality for the whole function,
291198090Srdivacky  // not on a per-selector basis.
292198090Srdivacky  // FIXME: That's a bit ugly. Better way?
293198090Srdivacky  SmallVector<CallInst*,16> EH_Selectors;
294198090Srdivacky  SmallVector<CallInst*,16> EH_Exceptions;
295198090Srdivacky  for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
296198090Srdivacky    for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
297198090Srdivacky      if (CallInst *CI = dyn_cast<CallInst>(I)) {
298198090Srdivacky        if (CI->getCalledFunction() == SelectorFn) {
299198090Srdivacky          if (!PersonalityFn) PersonalityFn = CI->getOperand(2);
300198090Srdivacky          EH_Selectors.push_back(CI);
301198090Srdivacky        } else if (CI->getCalledFunction() == ExceptionFn) {
302198090Srdivacky          EH_Exceptions.push_back(CI);
303198090Srdivacky        }
304198090Srdivacky      }
305198090Srdivacky    }
306198090Srdivacky  }
307198090Srdivacky  // If we don't have any eh.selector calls, we can't determine the personality
308198090Srdivacky  // function. Without a personality function, we can't process exceptions.
309198090Srdivacky  if (!PersonalityFn) return false;
310198090Srdivacky
311198090Srdivacky  NumInvokes += Invokes.size();
312198090Srdivacky  NumUnwinds += Unwinds.size();
313198090Srdivacky
314198090Srdivacky  if (!Invokes.empty()) {
315198090Srdivacky    // We have invokes, so we need to add register/unregister calls to get
316198090Srdivacky    // this function onto the global unwind stack.
317198090Srdivacky    //
318198090Srdivacky    // First thing we need to do is scan the whole function for values that are
319198090Srdivacky    // live across unwind edges.  Each value that is live across an unwind edge
320198090Srdivacky    // we spill into a stack location, guaranteeing that there is nothing live
321198090Srdivacky    // across the unwind edge.  This process also splits all critical edges
322198090Srdivacky    // coming out of invoke's.
323198090Srdivacky    splitLiveRangesLiveAcrossInvokes(Invokes);
324198090Srdivacky
325198090Srdivacky    BasicBlock *EntryBB = F.begin();
326198090Srdivacky    // Create an alloca for the incoming jump buffer ptr and the new jump buffer
327198090Srdivacky    // that needs to be restored on all exits from the function.  This is an
328198090Srdivacky    // alloca because the value needs to be added to the global context list.
329198090Srdivacky    unsigned Align = 4; // FIXME: Should be a TLI check?
330198090Srdivacky    AllocaInst *FunctionContext =
331198090Srdivacky      new AllocaInst(FunctionContextTy, 0, Align,
332198090Srdivacky                     "fcn_context", F.begin()->begin());
333198090Srdivacky
334198090Srdivacky    Value *Idxs[2];
335198090Srdivacky    const Type *Int32Ty = Type::getInt32Ty(F.getContext());
336198090Srdivacky    Value *Zero = ConstantInt::get(Int32Ty, 0);
337198090Srdivacky    // We need to also keep around a reference to the call_site field
338198090Srdivacky    Idxs[0] = Zero;
339198090Srdivacky    Idxs[1] = ConstantInt::get(Int32Ty, 1);
340198090Srdivacky    CallSite = GetElementPtrInst::Create(FunctionContext, Idxs, Idxs+2,
341198090Srdivacky                                         "call_site",
342198090Srdivacky                                         EntryBB->getTerminator());
343198090Srdivacky
344198090Srdivacky    // The exception selector comes back in context->data[1]
345198090Srdivacky    Idxs[1] = ConstantInt::get(Int32Ty, 2);
346198090Srdivacky    Value *FCData = GetElementPtrInst::Create(FunctionContext, Idxs, Idxs+2,
347198090Srdivacky                                              "fc_data",
348198090Srdivacky                                              EntryBB->getTerminator());
349198090Srdivacky    Idxs[1] = ConstantInt::get(Int32Ty, 1);
350198090Srdivacky    Value *SelectorAddr = GetElementPtrInst::Create(FCData, Idxs, Idxs+2,
351198090Srdivacky                                                    "exc_selector_gep",
352198090Srdivacky                                                    EntryBB->getTerminator());
353198090Srdivacky    // The exception value comes back in context->data[0]
354198090Srdivacky    Idxs[1] = Zero;
355198090Srdivacky    Value *ExceptionAddr = GetElementPtrInst::Create(FCData, Idxs, Idxs+2,
356198090Srdivacky                                                     "exception_gep",
357198090Srdivacky                                                     EntryBB->getTerminator());
358198090Srdivacky
359198090Srdivacky    // The result of the eh.selector call will be replaced with a
360198090Srdivacky    // a reference to the selector value returned in the function
361198090Srdivacky    // context. We leave the selector itself so the EH analysis later
362198090Srdivacky    // can use it.
363198090Srdivacky    for (int i = 0, e = EH_Selectors.size(); i < e; ++i) {
364198090Srdivacky      CallInst *I = EH_Selectors[i];
365198090Srdivacky      Value *SelectorVal = new LoadInst(SelectorAddr, "select_val", true, I);
366198090Srdivacky      I->replaceAllUsesWith(SelectorVal);
367198090Srdivacky    }
368198090Srdivacky    // eh.exception calls are replaced with references to the proper
369198090Srdivacky    // location in the context. Unlike eh.selector, the eh.exception
370198090Srdivacky    // calls are removed entirely.
371198090Srdivacky    for (int i = 0, e = EH_Exceptions.size(); i < e; ++i) {
372198090Srdivacky      CallInst *I = EH_Exceptions[i];
373198090Srdivacky      // Possible for there to be duplicates, so check to make sure
374198090Srdivacky      // the instruction hasn't already been removed.
375198090Srdivacky      if (!I->getParent()) continue;
376198090Srdivacky      Value *Val = new LoadInst(ExceptionAddr, "exception", true, I);
377198090Srdivacky      const Type *Ty = Type::getInt8PtrTy(F.getContext());
378198090Srdivacky      Val = CastInst::Create(Instruction::IntToPtr, Val, Ty, "", I);
379198090Srdivacky
380198090Srdivacky      I->replaceAllUsesWith(Val);
381198090Srdivacky      I->eraseFromParent();
382198090Srdivacky    }
383198090Srdivacky
384198090Srdivacky
385198090Srdivacky
386198090Srdivacky
387198090Srdivacky    // The entry block changes to have the eh.sjlj.setjmp, with a conditional
388198090Srdivacky    // branch to a dispatch block for non-zero returns. If we return normally,
389198090Srdivacky    // we're not handling an exception and just register the function context
390198090Srdivacky    // and continue.
391198090Srdivacky
392198090Srdivacky    // Create the dispatch block.  The dispatch block is basically a big switch
393198090Srdivacky    // statement that goes to all of the invoke landing pads.
394198090Srdivacky    BasicBlock *DispatchBlock =
395198090Srdivacky            BasicBlock::Create(F.getContext(), "eh.sjlj.setjmp.catch", &F);
396198090Srdivacky
397198090Srdivacky    // Insert a load in the Catch block, and a switch on its value.  By default,
398198090Srdivacky    // we go to a block that just does an unwind (which is the correct action
399198090Srdivacky    // for a standard call).
400198090Srdivacky    BasicBlock *UnwindBlock = BasicBlock::Create(F.getContext(), "unwindbb", &F);
401198090Srdivacky    Unwinds.push_back(new UnwindInst(F.getContext(), UnwindBlock));
402198090Srdivacky
403198090Srdivacky    Value *DispatchLoad = new LoadInst(CallSite, "invoke.num", true,
404198090Srdivacky                                       DispatchBlock);
405198090Srdivacky    SwitchInst *DispatchSwitch =
406198090Srdivacky      SwitchInst::Create(DispatchLoad, UnwindBlock, Invokes.size(), DispatchBlock);
407198090Srdivacky    // Split the entry block to insert the conditional branch for the setjmp.
408198090Srdivacky    BasicBlock *ContBlock = EntryBB->splitBasicBlock(EntryBB->getTerminator(),
409198090Srdivacky                                                     "eh.sjlj.setjmp.cont");
410198090Srdivacky
411198090Srdivacky    // Populate the Function Context
412198090Srdivacky    //   1. LSDA address
413198090Srdivacky    //   2. Personality function address
414198090Srdivacky    //   3. jmpbuf (save FP and call eh.sjlj.setjmp)
415198090Srdivacky
416198090Srdivacky    // LSDA address
417198090Srdivacky    Idxs[0] = Zero;
418198090Srdivacky    Idxs[1] = ConstantInt::get(Int32Ty, 4);
419198090Srdivacky    Value *LSDAFieldPtr =
420198090Srdivacky      GetElementPtrInst::Create(FunctionContext, Idxs, Idxs+2,
421198090Srdivacky                                "lsda_gep",
422198090Srdivacky                                EntryBB->getTerminator());
423198090Srdivacky    Value *LSDA = CallInst::Create(LSDAAddrFn, "lsda_addr",
424198090Srdivacky                                   EntryBB->getTerminator());
425198090Srdivacky    new StoreInst(LSDA, LSDAFieldPtr, true, EntryBB->getTerminator());
426198090Srdivacky
427198090Srdivacky    Idxs[1] = ConstantInt::get(Int32Ty, 3);
428198090Srdivacky    Value *PersonalityFieldPtr =
429198090Srdivacky      GetElementPtrInst::Create(FunctionContext, Idxs, Idxs+2,
430198090Srdivacky                                "lsda_gep",
431198090Srdivacky                                EntryBB->getTerminator());
432198090Srdivacky    new StoreInst(PersonalityFn, PersonalityFieldPtr, true,
433198090Srdivacky                  EntryBB->getTerminator());
434198090Srdivacky
435198090Srdivacky    //   Save the frame pointer.
436198090Srdivacky    Idxs[1] = ConstantInt::get(Int32Ty, 5);
437198090Srdivacky    Value *FieldPtr
438198090Srdivacky      = GetElementPtrInst::Create(FunctionContext, Idxs, Idxs+2,
439198090Srdivacky                                  "jbuf_gep",
440198090Srdivacky                                  EntryBB->getTerminator());
441198090Srdivacky    Idxs[1] = ConstantInt::get(Int32Ty, 0);
442198090Srdivacky    Value *ElemPtr =
443198090Srdivacky      GetElementPtrInst::Create(FieldPtr, Idxs, Idxs+2, "jbuf_fp_gep",
444198090Srdivacky                                EntryBB->getTerminator());
445198090Srdivacky
446198090Srdivacky    Value *Val = CallInst::Create(FrameAddrFn,
447198090Srdivacky                                  ConstantInt::get(Int32Ty, 0),
448198090Srdivacky                                  "fp",
449198090Srdivacky                                  EntryBB->getTerminator());
450198090Srdivacky    new StoreInst(Val, ElemPtr, true, EntryBB->getTerminator());
451198090Srdivacky    // Call the setjmp instrinsic. It fills in the rest of the jmpbuf
452198090Srdivacky    Value *SetjmpArg =
453198090Srdivacky      CastInst::Create(Instruction::BitCast, FieldPtr,
454198090Srdivacky                       Type::getInt8PtrTy(F.getContext()), "",
455198090Srdivacky                       EntryBB->getTerminator());
456198090Srdivacky    Value *DispatchVal = CallInst::Create(BuiltinSetjmpFn, SetjmpArg,
457198090Srdivacky                                          "dispatch",
458198090Srdivacky                                          EntryBB->getTerminator());
459198090Srdivacky    // check the return value of the setjmp. non-zero goes to dispatcher
460198090Srdivacky    Value *IsNormal = new ICmpInst(EntryBB->getTerminator(),
461198090Srdivacky                                   ICmpInst::ICMP_EQ, DispatchVal, Zero,
462198090Srdivacky                                   "notunwind");
463198090Srdivacky    // Nuke the uncond branch.
464198090Srdivacky    EntryBB->getTerminator()->eraseFromParent();
465198090Srdivacky
466198090Srdivacky    // Put in a new condbranch in its place.
467198090Srdivacky    BranchInst::Create(ContBlock, DispatchBlock, IsNormal, EntryBB);
468198090Srdivacky
469198090Srdivacky    // Register the function context and make sure it's known to not throw
470198090Srdivacky    CallInst *Register =
471198090Srdivacky      CallInst::Create(RegisterFn, FunctionContext, "",
472198090Srdivacky                       ContBlock->getTerminator());
473198090Srdivacky    Register->setDoesNotThrow();
474198090Srdivacky
475198090Srdivacky    // At this point, we are all set up, update the invoke instructions
476198090Srdivacky    // to mark their call_site values, and fill in the dispatch switch
477198090Srdivacky    // accordingly.
478198090Srdivacky    for (unsigned i = 0, e = Invokes.size(); i != e; ++i)
479198090Srdivacky      markInvokeCallSite(Invokes[i], i+1, CallSite, DispatchSwitch);
480198090Srdivacky
481198090Srdivacky    // The front end has likely added calls to _Unwind_Resume. We need
482198090Srdivacky    // to find those calls and mark the call_site as -1 immediately prior.
483198090Srdivacky    // resume is a noreturn function, so any block that has a call to it
484198090Srdivacky    // should end in an 'unreachable' instruction with the call immediately
485198090Srdivacky    // prior. That's how we'll search.
486198090Srdivacky    // ??? There's got to be a better way. this is fugly.
487198090Srdivacky    for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
488198090Srdivacky      if ((dyn_cast<UnreachableInst>(BB->getTerminator()))) {
489198090Srdivacky        BasicBlock::iterator I = BB->getTerminator();
490198090Srdivacky        // Check the previous instruction and see if it's a resume call
491198090Srdivacky        if (I == BB->begin()) continue;
492198090Srdivacky        if (CallInst *CI = dyn_cast<CallInst>(--I)) {
493198090Srdivacky          if (CI->getCalledFunction() == ResumeFn) {
494198090Srdivacky            Value *NegativeOne = Constant::getAllOnesValue(Int32Ty);
495198090Srdivacky            new StoreInst(NegativeOne, CallSite, true, I);  // volatile
496198090Srdivacky          }
497198090Srdivacky        }
498198090Srdivacky      }
499198090Srdivacky
500198090Srdivacky    // Replace all unwinds with a branch to the unwind handler.
501198090Srdivacky    // ??? Should this ever happen with sjlj exceptions?
502198090Srdivacky    for (unsigned i = 0, e = Unwinds.size(); i != e; ++i) {
503198090Srdivacky      BranchInst::Create(UnwindBlock, Unwinds[i]);
504198090Srdivacky      Unwinds[i]->eraseFromParent();
505198090Srdivacky    }
506198090Srdivacky
507198090Srdivacky    // Finally, for any returns from this function, if this function contains an
508198090Srdivacky    // invoke, add a call to unregister the function context.
509198090Srdivacky    for (unsigned i = 0, e = Returns.size(); i != e; ++i)
510198090Srdivacky      CallInst::Create(UnregisterFn, FunctionContext, "", Returns[i]);
511198090Srdivacky  }
512198090Srdivacky
513198090Srdivacky  return true;
514198090Srdivacky}
515198090Srdivacky
516198090Srdivackybool SjLjEHPass::runOnFunction(Function &F) {
517198090Srdivacky  bool Res = insertSjLjEHSupport(F);
518198090Srdivacky  return Res;
519198090Srdivacky}
520