SjLjEHPrepare.cpp revision 204792
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 *BuiltinSetjmpFn;
48198090Srdivacky    Constant *FrameAddrFn;
49198090Srdivacky    Constant *LSDAAddrFn;
50198090Srdivacky    Value *PersonalityFn;
51198090Srdivacky    Constant *SelectorFn;
52198090Srdivacky    Constant *ExceptionFn;
53203954Srdivacky    Constant *CallSiteFn;
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:
69204792Srdivacky    void insertCallSiteStore(Instruction *I, int Number, Value *CallSite);
70204792Srdivacky    void markInvokeCallSite(InvokeInst *II, int InvokeNo, 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  FrameAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::frameaddress);
110198090Srdivacky  BuiltinSetjmpFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_setjmp);
111198090Srdivacky  LSDAAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_lsda);
112198090Srdivacky  SelectorFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_selector);
113198090Srdivacky  ExceptionFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_exception);
114203954Srdivacky  CallSiteFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_callsite);
115198090Srdivacky  PersonalityFn = 0;
116198090Srdivacky
117198090Srdivacky  return true;
118198090Srdivacky}
119198090Srdivacky
120204792Srdivacky/// insertCallSiteStore - Insert a store of the call-site value to the
121204792Srdivacky/// function context
122204792Srdivackyvoid SjLjEHPass::insertCallSiteStore(Instruction *I, int Number,
123204792Srdivacky                                     Value *CallSite) {
124204792Srdivacky  ConstantInt *CallSiteNoC = ConstantInt::get(Type::getInt32Ty(I->getContext()),
125204792Srdivacky                                              Number);
126204792Srdivacky  // Insert a store of the call-site number
127204792Srdivacky  new StoreInst(CallSiteNoC, CallSite, true, I);  // volatile
128204792Srdivacky}
129204792Srdivacky
130198090Srdivacky/// markInvokeCallSite - Insert code to mark the call_site for this invoke
131204792Srdivackyvoid SjLjEHPass::markInvokeCallSite(InvokeInst *II, int InvokeNo,
132198090Srdivacky                                    Value *CallSite,
133198090Srdivacky                                    SwitchInst *CatchSwitch) {
134198090Srdivacky  ConstantInt *CallSiteNoC= ConstantInt::get(Type::getInt32Ty(II->getContext()),
135204792Srdivacky                                              InvokeNo);
136198090Srdivacky  // The runtime comes back to the dispatcher with the call_site - 1 in
137198090Srdivacky  // the context. Odd, but there it is.
138198090Srdivacky  ConstantInt *SwitchValC = ConstantInt::get(Type::getInt32Ty(II->getContext()),
139198090Srdivacky                                            InvokeNo - 1);
140198090Srdivacky
141198090Srdivacky  // If the unwind edge has phi nodes, split the edge.
142198090Srdivacky  if (isa<PHINode>(II->getUnwindDest()->begin())) {
143198090Srdivacky    SplitCriticalEdge(II, 1, this);
144198090Srdivacky
145198090Srdivacky    // If there are any phi nodes left, they must have a single predecessor.
146198090Srdivacky    while (PHINode *PN = dyn_cast<PHINode>(II->getUnwindDest()->begin())) {
147198090Srdivacky      PN->replaceAllUsesWith(PN->getIncomingValue(0));
148198090Srdivacky      PN->eraseFromParent();
149198090Srdivacky    }
150198090Srdivacky  }
151198090Srdivacky
152204792Srdivacky  // Insert the store of the call site value
153204792Srdivacky  insertCallSiteStore(II, InvokeNo, CallSite);
154204792Srdivacky
155204792Srdivacky  // Record the call site value for the back end so it stays associated with
156204792Srdivacky  // the invoke.
157203954Srdivacky  CallInst::Create(CallSiteFn, CallSiteNoC, "", II);
158198090Srdivacky
159198090Srdivacky  // Add a switch case to our unwind block.
160198090Srdivacky  CatchSwitch->addCase(SwitchValC, II->getUnwindDest());
161203954Srdivacky  // We still want this to look like an invoke so we emit the LSDA properly,
162203954Srdivacky  // so we don't transform the invoke into a call here.
163198090Srdivacky}
164198090Srdivacky
165198090Srdivacky/// MarkBlocksLiveIn - Insert BB and all of its predescessors into LiveBBs until
166198090Srdivacky/// we reach blocks we've already seen.
167198090Srdivackystatic void MarkBlocksLiveIn(BasicBlock *BB, std::set<BasicBlock*> &LiveBBs) {
168198090Srdivacky  if (!LiveBBs.insert(BB).second) return; // already been here.
169198090Srdivacky
170198090Srdivacky  for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
171198090Srdivacky    MarkBlocksLiveIn(*PI, LiveBBs);
172198090Srdivacky}
173198090Srdivacky
174198090Srdivacky/// splitLiveRangesAcrossInvokes - Each value that is live across an unwind edge
175198090Srdivacky/// we spill into a stack location, guaranteeing that there is nothing live
176198090Srdivacky/// across the unwind edge.  This process also splits all critical edges
177198090Srdivacky/// coming out of invoke's.
178198090Srdivackyvoid SjLjEHPass::
179198090SrdivackysplitLiveRangesLiveAcrossInvokes(SmallVector<InvokeInst*,16> &Invokes) {
180198090Srdivacky  // First step, split all critical edges from invoke instructions.
181198090Srdivacky  for (unsigned i = 0, e = Invokes.size(); i != e; ++i) {
182198090Srdivacky    InvokeInst *II = Invokes[i];
183198090Srdivacky    SplitCriticalEdge(II, 0, this);
184198090Srdivacky    SplitCriticalEdge(II, 1, this);
185198090Srdivacky    assert(!isa<PHINode>(II->getNormalDest()) &&
186198090Srdivacky           !isa<PHINode>(II->getUnwindDest()) &&
187198090Srdivacky           "critical edge splitting left single entry phi nodes?");
188198090Srdivacky  }
189198090Srdivacky
190198090Srdivacky  Function *F = Invokes.back()->getParent()->getParent();
191198090Srdivacky
192198090Srdivacky  // To avoid having to handle incoming arguments specially, we lower each arg
193198090Srdivacky  // to a copy instruction in the entry block.  This ensures that the argument
194198090Srdivacky  // value itself cannot be live across the entry block.
195198090Srdivacky  BasicBlock::iterator AfterAllocaInsertPt = F->begin()->begin();
196198090Srdivacky  while (isa<AllocaInst>(AfterAllocaInsertPt) &&
197198090Srdivacky        isa<ConstantInt>(cast<AllocaInst>(AfterAllocaInsertPt)->getArraySize()))
198198090Srdivacky    ++AfterAllocaInsertPt;
199198090Srdivacky  for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
200198090Srdivacky       AI != E; ++AI) {
201198090Srdivacky    // This is always a no-op cast because we're casting AI to AI->getType() so
202198090Srdivacky    // src and destination types are identical. BitCast is the only possibility.
203198090Srdivacky    CastInst *NC = new BitCastInst(
204198090Srdivacky      AI, AI->getType(), AI->getName()+".tmp", AfterAllocaInsertPt);
205198090Srdivacky    AI->replaceAllUsesWith(NC);
206198090Srdivacky    // Normally its is forbidden to replace a CastInst's operand because it
207198090Srdivacky    // could cause the opcode to reflect an illegal conversion. However, we're
208198090Srdivacky    // replacing it here with the same value it was constructed with to simply
209198090Srdivacky    // make NC its user.
210198090Srdivacky    NC->setOperand(0, AI);
211198090Srdivacky  }
212198090Srdivacky
213198090Srdivacky  // Finally, scan the code looking for instructions with bad live ranges.
214198090Srdivacky  for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
215198090Srdivacky    for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; ++II) {
216198090Srdivacky      // Ignore obvious cases we don't have to handle.  In particular, most
217198090Srdivacky      // instructions either have no uses or only have a single use inside the
218198090Srdivacky      // current block.  Ignore them quickly.
219198090Srdivacky      Instruction *Inst = II;
220198090Srdivacky      if (Inst->use_empty()) continue;
221198090Srdivacky      if (Inst->hasOneUse() &&
222198090Srdivacky          cast<Instruction>(Inst->use_back())->getParent() == BB &&
223198090Srdivacky          !isa<PHINode>(Inst->use_back())) continue;
224198090Srdivacky
225198090Srdivacky      // If this is an alloca in the entry block, it's not a real register
226198090Srdivacky      // value.
227198090Srdivacky      if (AllocaInst *AI = dyn_cast<AllocaInst>(Inst))
228198090Srdivacky        if (isa<ConstantInt>(AI->getArraySize()) && BB == F->begin())
229198090Srdivacky          continue;
230198090Srdivacky
231198090Srdivacky      // Avoid iterator invalidation by copying users to a temporary vector.
232198090Srdivacky      SmallVector<Instruction*,16> Users;
233198090Srdivacky      for (Value::use_iterator UI = Inst->use_begin(), E = Inst->use_end();
234198090Srdivacky           UI != E; ++UI) {
235198090Srdivacky        Instruction *User = cast<Instruction>(*UI);
236198090Srdivacky        if (User->getParent() != BB || isa<PHINode>(User))
237198090Srdivacky          Users.push_back(User);
238198090Srdivacky      }
239198090Srdivacky
240198090Srdivacky      // Find all of the blocks that this value is live in.
241198090Srdivacky      std::set<BasicBlock*> LiveBBs;
242198090Srdivacky      LiveBBs.insert(Inst->getParent());
243198090Srdivacky      while (!Users.empty()) {
244198090Srdivacky        Instruction *U = Users.back();
245198090Srdivacky        Users.pop_back();
246198090Srdivacky
247198090Srdivacky        if (!isa<PHINode>(U)) {
248198090Srdivacky          MarkBlocksLiveIn(U->getParent(), LiveBBs);
249198090Srdivacky        } else {
250198090Srdivacky          // Uses for a PHI node occur in their predecessor block.
251198090Srdivacky          PHINode *PN = cast<PHINode>(U);
252198090Srdivacky          for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
253198090Srdivacky            if (PN->getIncomingValue(i) == Inst)
254198090Srdivacky              MarkBlocksLiveIn(PN->getIncomingBlock(i), LiveBBs);
255198090Srdivacky        }
256198090Srdivacky      }
257198090Srdivacky
258198090Srdivacky      // Now that we know all of the blocks that this thing is live in, see if
259198090Srdivacky      // it includes any of the unwind locations.
260198090Srdivacky      bool NeedsSpill = false;
261198090Srdivacky      for (unsigned i = 0, e = Invokes.size(); i != e; ++i) {
262198090Srdivacky        BasicBlock *UnwindBlock = Invokes[i]->getUnwindDest();
263198090Srdivacky        if (UnwindBlock != BB && LiveBBs.count(UnwindBlock)) {
264198090Srdivacky          NeedsSpill = true;
265198090Srdivacky        }
266198090Srdivacky      }
267198090Srdivacky
268198090Srdivacky      // If we decided we need a spill, do it.
269198090Srdivacky      if (NeedsSpill) {
270198090Srdivacky        ++NumSpilled;
271198090Srdivacky        DemoteRegToStack(*Inst, true);
272198090Srdivacky      }
273198090Srdivacky    }
274198090Srdivacky}
275198090Srdivacky
276198090Srdivackybool SjLjEHPass::insertSjLjEHSupport(Function &F) {
277198090Srdivacky  SmallVector<ReturnInst*,16> Returns;
278198090Srdivacky  SmallVector<UnwindInst*,16> Unwinds;
279198090Srdivacky  SmallVector<InvokeInst*,16> Invokes;
280198090Srdivacky
281198090Srdivacky  // Look through the terminators of the basic blocks to find invokes, returns
282204792Srdivacky  // and unwinds.
283204792Srdivacky  for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
284198090Srdivacky    if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
285198090Srdivacky      // Remember all return instructions in case we insert an invoke into this
286198090Srdivacky      // function.
287198090Srdivacky      Returns.push_back(RI);
288198090Srdivacky    } else if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
289198090Srdivacky      Invokes.push_back(II);
290198090Srdivacky    } else if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator())) {
291198090Srdivacky      Unwinds.push_back(UI);
292198090Srdivacky    }
293204792Srdivacky  }
294198090Srdivacky  // If we don't have any invokes or unwinds, there's nothing to do.
295198090Srdivacky  if (Unwinds.empty() && Invokes.empty()) return false;
296198090Srdivacky
297198090Srdivacky  // Find the eh.selector.*  and eh.exception calls. We'll use the first
298198090Srdivacky  // eh.selector to determine the right personality function to use. For
299198090Srdivacky  // SJLJ, we always use the same personality for the whole function,
300198090Srdivacky  // not on a per-selector basis.
301198090Srdivacky  // FIXME: That's a bit ugly. Better way?
302198090Srdivacky  SmallVector<CallInst*,16> EH_Selectors;
303198090Srdivacky  SmallVector<CallInst*,16> EH_Exceptions;
304198090Srdivacky  for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
305198090Srdivacky    for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
306198090Srdivacky      if (CallInst *CI = dyn_cast<CallInst>(I)) {
307198090Srdivacky        if (CI->getCalledFunction() == SelectorFn) {
308198090Srdivacky          if (!PersonalityFn) PersonalityFn = CI->getOperand(2);
309198090Srdivacky          EH_Selectors.push_back(CI);
310198090Srdivacky        } else if (CI->getCalledFunction() == ExceptionFn) {
311198090Srdivacky          EH_Exceptions.push_back(CI);
312198090Srdivacky        }
313198090Srdivacky      }
314198090Srdivacky    }
315198090Srdivacky  }
316198090Srdivacky  // If we don't have any eh.selector calls, we can't determine the personality
317198090Srdivacky  // function. Without a personality function, we can't process exceptions.
318198090Srdivacky  if (!PersonalityFn) return false;
319198090Srdivacky
320198090Srdivacky  NumInvokes += Invokes.size();
321198090Srdivacky  NumUnwinds += Unwinds.size();
322198090Srdivacky
323198090Srdivacky  if (!Invokes.empty()) {
324198090Srdivacky    // We have invokes, so we need to add register/unregister calls to get
325198090Srdivacky    // this function onto the global unwind stack.
326198090Srdivacky    //
327198090Srdivacky    // First thing we need to do is scan the whole function for values that are
328198090Srdivacky    // live across unwind edges.  Each value that is live across an unwind edge
329198090Srdivacky    // we spill into a stack location, guaranteeing that there is nothing live
330198090Srdivacky    // across the unwind edge.  This process also splits all critical edges
331198090Srdivacky    // coming out of invoke's.
332198090Srdivacky    splitLiveRangesLiveAcrossInvokes(Invokes);
333198090Srdivacky
334198090Srdivacky    BasicBlock *EntryBB = F.begin();
335198090Srdivacky    // Create an alloca for the incoming jump buffer ptr and the new jump buffer
336198090Srdivacky    // that needs to be restored on all exits from the function.  This is an
337198090Srdivacky    // alloca because the value needs to be added to the global context list.
338198090Srdivacky    unsigned Align = 4; // FIXME: Should be a TLI check?
339198090Srdivacky    AllocaInst *FunctionContext =
340198090Srdivacky      new AllocaInst(FunctionContextTy, 0, Align,
341198090Srdivacky                     "fcn_context", F.begin()->begin());
342198090Srdivacky
343198090Srdivacky    Value *Idxs[2];
344198090Srdivacky    const Type *Int32Ty = Type::getInt32Ty(F.getContext());
345198090Srdivacky    Value *Zero = ConstantInt::get(Int32Ty, 0);
346198090Srdivacky    // We need to also keep around a reference to the call_site field
347198090Srdivacky    Idxs[0] = Zero;
348198090Srdivacky    Idxs[1] = ConstantInt::get(Int32Ty, 1);
349198090Srdivacky    CallSite = GetElementPtrInst::Create(FunctionContext, Idxs, Idxs+2,
350198090Srdivacky                                         "call_site",
351198090Srdivacky                                         EntryBB->getTerminator());
352198090Srdivacky
353198090Srdivacky    // The exception selector comes back in context->data[1]
354198090Srdivacky    Idxs[1] = ConstantInt::get(Int32Ty, 2);
355198090Srdivacky    Value *FCData = GetElementPtrInst::Create(FunctionContext, Idxs, Idxs+2,
356198090Srdivacky                                              "fc_data",
357198090Srdivacky                                              EntryBB->getTerminator());
358198090Srdivacky    Idxs[1] = ConstantInt::get(Int32Ty, 1);
359198090Srdivacky    Value *SelectorAddr = GetElementPtrInst::Create(FCData, Idxs, Idxs+2,
360198090Srdivacky                                                    "exc_selector_gep",
361198090Srdivacky                                                    EntryBB->getTerminator());
362198090Srdivacky    // The exception value comes back in context->data[0]
363198090Srdivacky    Idxs[1] = Zero;
364198090Srdivacky    Value *ExceptionAddr = GetElementPtrInst::Create(FCData, Idxs, Idxs+2,
365198090Srdivacky                                                     "exception_gep",
366198090Srdivacky                                                     EntryBB->getTerminator());
367198090Srdivacky
368198090Srdivacky    // The result of the eh.selector call will be replaced with a
369198090Srdivacky    // a reference to the selector value returned in the function
370198090Srdivacky    // context. We leave the selector itself so the EH analysis later
371198090Srdivacky    // can use it.
372198090Srdivacky    for (int i = 0, e = EH_Selectors.size(); i < e; ++i) {
373198090Srdivacky      CallInst *I = EH_Selectors[i];
374198090Srdivacky      Value *SelectorVal = new LoadInst(SelectorAddr, "select_val", true, I);
375198090Srdivacky      I->replaceAllUsesWith(SelectorVal);
376198090Srdivacky    }
377198090Srdivacky    // eh.exception calls are replaced with references to the proper
378198090Srdivacky    // location in the context. Unlike eh.selector, the eh.exception
379198090Srdivacky    // calls are removed entirely.
380198090Srdivacky    for (int i = 0, e = EH_Exceptions.size(); i < e; ++i) {
381198090Srdivacky      CallInst *I = EH_Exceptions[i];
382198090Srdivacky      // Possible for there to be duplicates, so check to make sure
383198090Srdivacky      // the instruction hasn't already been removed.
384198090Srdivacky      if (!I->getParent()) continue;
385198090Srdivacky      Value *Val = new LoadInst(ExceptionAddr, "exception", true, I);
386198090Srdivacky      const Type *Ty = Type::getInt8PtrTy(F.getContext());
387198090Srdivacky      Val = CastInst::Create(Instruction::IntToPtr, Val, Ty, "", I);
388198090Srdivacky
389198090Srdivacky      I->replaceAllUsesWith(Val);
390198090Srdivacky      I->eraseFromParent();
391198090Srdivacky    }
392198090Srdivacky
393198090Srdivacky    // The entry block changes to have the eh.sjlj.setjmp, with a conditional
394198090Srdivacky    // branch to a dispatch block for non-zero returns. If we return normally,
395198090Srdivacky    // we're not handling an exception and just register the function context
396198090Srdivacky    // and continue.
397198090Srdivacky
398198090Srdivacky    // Create the dispatch block.  The dispatch block is basically a big switch
399198090Srdivacky    // statement that goes to all of the invoke landing pads.
400198090Srdivacky    BasicBlock *DispatchBlock =
401198090Srdivacky            BasicBlock::Create(F.getContext(), "eh.sjlj.setjmp.catch", &F);
402198090Srdivacky
403198090Srdivacky    // Insert a load in the Catch block, and a switch on its value.  By default,
404198090Srdivacky    // we go to a block that just does an unwind (which is the correct action
405198090Srdivacky    // for a standard call).
406202375Srdivacky    BasicBlock *UnwindBlock =
407202375Srdivacky      BasicBlock::Create(F.getContext(), "unwindbb", &F);
408198090Srdivacky    Unwinds.push_back(new UnwindInst(F.getContext(), UnwindBlock));
409198090Srdivacky
410198090Srdivacky    Value *DispatchLoad = new LoadInst(CallSite, "invoke.num", true,
411198090Srdivacky                                       DispatchBlock);
412198090Srdivacky    SwitchInst *DispatchSwitch =
413202375Srdivacky      SwitchInst::Create(DispatchLoad, UnwindBlock, Invokes.size(),
414202375Srdivacky                         DispatchBlock);
415198090Srdivacky    // Split the entry block to insert the conditional branch for the setjmp.
416198090Srdivacky    BasicBlock *ContBlock = EntryBB->splitBasicBlock(EntryBB->getTerminator(),
417198090Srdivacky                                                     "eh.sjlj.setjmp.cont");
418198090Srdivacky
419198090Srdivacky    // Populate the Function Context
420198090Srdivacky    //   1. LSDA address
421198090Srdivacky    //   2. Personality function address
422198090Srdivacky    //   3. jmpbuf (save FP and call eh.sjlj.setjmp)
423198090Srdivacky
424198090Srdivacky    // LSDA address
425198090Srdivacky    Idxs[0] = Zero;
426198090Srdivacky    Idxs[1] = ConstantInt::get(Int32Ty, 4);
427198090Srdivacky    Value *LSDAFieldPtr =
428198090Srdivacky      GetElementPtrInst::Create(FunctionContext, Idxs, Idxs+2,
429198090Srdivacky                                "lsda_gep",
430198090Srdivacky                                EntryBB->getTerminator());
431198090Srdivacky    Value *LSDA = CallInst::Create(LSDAAddrFn, "lsda_addr",
432198090Srdivacky                                   EntryBB->getTerminator());
433198090Srdivacky    new StoreInst(LSDA, LSDAFieldPtr, true, EntryBB->getTerminator());
434198090Srdivacky
435198090Srdivacky    Idxs[1] = ConstantInt::get(Int32Ty, 3);
436198090Srdivacky    Value *PersonalityFieldPtr =
437198090Srdivacky      GetElementPtrInst::Create(FunctionContext, Idxs, Idxs+2,
438198090Srdivacky                                "lsda_gep",
439198090Srdivacky                                EntryBB->getTerminator());
440198090Srdivacky    new StoreInst(PersonalityFn, PersonalityFieldPtr, true,
441198090Srdivacky                  EntryBB->getTerminator());
442198090Srdivacky
443198090Srdivacky    //   Save the frame pointer.
444198090Srdivacky    Idxs[1] = ConstantInt::get(Int32Ty, 5);
445198090Srdivacky    Value *FieldPtr
446198090Srdivacky      = GetElementPtrInst::Create(FunctionContext, Idxs, Idxs+2,
447198090Srdivacky                                  "jbuf_gep",
448198090Srdivacky                                  EntryBB->getTerminator());
449198090Srdivacky    Idxs[1] = ConstantInt::get(Int32Ty, 0);
450198090Srdivacky    Value *ElemPtr =
451198090Srdivacky      GetElementPtrInst::Create(FieldPtr, Idxs, Idxs+2, "jbuf_fp_gep",
452198090Srdivacky                                EntryBB->getTerminator());
453198090Srdivacky
454198090Srdivacky    Value *Val = CallInst::Create(FrameAddrFn,
455198090Srdivacky                                  ConstantInt::get(Int32Ty, 0),
456198090Srdivacky                                  "fp",
457198090Srdivacky                                  EntryBB->getTerminator());
458198090Srdivacky    new StoreInst(Val, ElemPtr, true, EntryBB->getTerminator());
459198090Srdivacky    // Call the setjmp instrinsic. It fills in the rest of the jmpbuf
460198090Srdivacky    Value *SetjmpArg =
461198090Srdivacky      CastInst::Create(Instruction::BitCast, FieldPtr,
462198090Srdivacky                       Type::getInt8PtrTy(F.getContext()), "",
463198090Srdivacky                       EntryBB->getTerminator());
464198090Srdivacky    Value *DispatchVal = CallInst::Create(BuiltinSetjmpFn, SetjmpArg,
465198090Srdivacky                                          "dispatch",
466198090Srdivacky                                          EntryBB->getTerminator());
467198090Srdivacky    // check the return value of the setjmp. non-zero goes to dispatcher
468198090Srdivacky    Value *IsNormal = new ICmpInst(EntryBB->getTerminator(),
469198090Srdivacky                                   ICmpInst::ICMP_EQ, DispatchVal, Zero,
470198090Srdivacky                                   "notunwind");
471198090Srdivacky    // Nuke the uncond branch.
472198090Srdivacky    EntryBB->getTerminator()->eraseFromParent();
473198090Srdivacky
474198090Srdivacky    // Put in a new condbranch in its place.
475198090Srdivacky    BranchInst::Create(ContBlock, DispatchBlock, IsNormal, EntryBB);
476198090Srdivacky
477198090Srdivacky    // Register the function context and make sure it's known to not throw
478198090Srdivacky    CallInst *Register =
479198090Srdivacky      CallInst::Create(RegisterFn, FunctionContext, "",
480198090Srdivacky                       ContBlock->getTerminator());
481198090Srdivacky    Register->setDoesNotThrow();
482198090Srdivacky
483198090Srdivacky    // At this point, we are all set up, update the invoke instructions
484198090Srdivacky    // to mark their call_site values, and fill in the dispatch switch
485198090Srdivacky    // accordingly.
486198090Srdivacky    for (unsigned i = 0, e = Invokes.size(); i != e; ++i)
487198090Srdivacky      markInvokeCallSite(Invokes[i], i+1, CallSite, DispatchSwitch);
488198090Srdivacky
489204792Srdivacky    // Mark call instructions that aren't nounwind as no-action
490204792Srdivacky    // (call_site == -1). Skip the entry block, as prior to then, no function
491204792Srdivacky    // context has been created for this function and any unexpected exceptions
492204792Srdivacky    // thrown will go directly to the caller's context, which is what we want
493204792Srdivacky    // anyway, so no need to do anything here.
494204792Srdivacky    for (Function::iterator BB = F.begin(), E = F.end(); ++BB != E;) {
495204792Srdivacky      for (BasicBlock::iterator I = BB->begin(), end = BB->end(); I != end; ++I)
496204792Srdivacky        if (CallInst *CI = dyn_cast<CallInst>(I)) {
497204792Srdivacky          // Ignore calls to the EH builtins (eh.selector, eh.exception)
498204792Srdivacky          Constant *Callee = CI->getCalledFunction();
499204792Srdivacky          if (Callee != SelectorFn && Callee != ExceptionFn
500204792Srdivacky              && !CI->doesNotThrow())
501204792Srdivacky            insertCallSiteStore(CI, -1, CallSite);
502198090Srdivacky        }
503204792Srdivacky    }
504198090Srdivacky
505198090Srdivacky    // Replace all unwinds with a branch to the unwind handler.
506198090Srdivacky    // ??? Should this ever happen with sjlj exceptions?
507198090Srdivacky    for (unsigned i = 0, e = Unwinds.size(); i != e; ++i) {
508198090Srdivacky      BranchInst::Create(UnwindBlock, Unwinds[i]);
509198090Srdivacky      Unwinds[i]->eraseFromParent();
510198090Srdivacky    }
511198090Srdivacky
512198090Srdivacky    // Finally, for any returns from this function, if this function contains an
513198090Srdivacky    // invoke, add a call to unregister the function context.
514198090Srdivacky    for (unsigned i = 0, e = Returns.size(); i != e; ++i)
515198090Srdivacky      CallInst::Create(UnregisterFn, FunctionContext, "", Returns[i]);
516198090Srdivacky  }
517198090Srdivacky
518198090Srdivacky  return true;
519198090Srdivacky}
520198090Srdivacky
521198090Srdivackybool SjLjEHPass::runOnFunction(Function &F) {
522198090Srdivacky  bool Res = insertSjLjEHSupport(F);
523198090Srdivacky  return Res;
524198090Srdivacky}
525