fix naming
[oota-llvm.git] / lib / CodeGen / SjLjEHPrepare.cpp
1 //===- SjLjEHPass.cpp - Eliminate Invoke & Unwind instructions -----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This transformation is designed for use by code generators which use SjLj
11 // based exception handling.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "sjljehprepare"
16 #include "llvm/Transforms/Scalar.h"
17 #include "llvm/Constants.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/Intrinsics.h"
21 #include "llvm/LLVMContext.h"
22 #include "llvm/Module.h"
23 #include "llvm/Pass.h"
24 #include "llvm/CodeGen/Passes.h"
25 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
26 #include "llvm/Transforms/Utils/Local.h"
27 #include "llvm/ADT/Statistic.h"
28 #include "llvm/ADT/SmallVector.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/raw_ostream.h"
32 #include "llvm/Target/TargetLowering.h"
33 using namespace llvm;
34
35 STATISTIC(NumInvokes, "Number of invokes replaced");
36 STATISTIC(NumUnwinds, "Number of unwinds replaced");
37 STATISTIC(NumSpilled, "Number of registers live across unwind edges");
38
39 namespace {
40   class SjLjEHPass : public FunctionPass {
41
42     const TargetLowering *TLI;
43
44     const Type *FunctionContextTy;
45     Constant *RegisterFn;
46     Constant *UnregisterFn;
47     Constant *BuiltinSetjmpFn;
48     Constant *FrameAddrFn;
49     Constant *StackAddrFn;
50     Constant *StackRestoreFn;
51     Constant *LSDAAddrFn;
52     Value *PersonalityFn;
53     Constant *SelectorFn;
54     Constant *ExceptionFn;
55     Constant *CallSiteFn;
56
57     Value *CallSite;
58   public:
59     static char ID; // Pass identification, replacement for typeid
60     explicit SjLjEHPass(const TargetLowering *tli = NULL)
61       : FunctionPass(&ID), TLI(tli) { }
62     bool doInitialization(Module &M);
63     bool runOnFunction(Function &F);
64
65     virtual void getAnalysisUsage(AnalysisUsage &AU) const { }
66     const char *getPassName() const {
67       return "SJLJ Exception Handling preparation";
68     }
69
70   private:
71     void insertCallSiteStore(Instruction *I, int Number, Value *CallSite);
72     void markInvokeCallSite(InvokeInst *II, int InvokeNo, Value *CallSite,
73                             SwitchInst *CatchSwitch);
74     void splitLiveRangesAcrossInvokes(SmallVector<InvokeInst*,16> &Invokes);
75     bool insertSjLjEHSupport(Function &F);
76   };
77 } // end anonymous namespace
78
79 char SjLjEHPass::ID = 0;
80
81 // Public Interface To the SjLjEHPass pass.
82 FunctionPass *llvm::createSjLjEHPass(const TargetLowering *TLI) {
83   return new SjLjEHPass(TLI);
84 }
85 // doInitialization - Set up decalarations and types needed to process
86 // exceptions.
87 bool SjLjEHPass::doInitialization(Module &M) {
88   // Build the function context structure.
89   // builtin_setjmp uses a five word jbuf
90   const Type *VoidPtrTy =
91           Type::getInt8PtrTy(M.getContext());
92   const Type *Int32Ty = Type::getInt32Ty(M.getContext());
93   FunctionContextTy =
94     StructType::get(M.getContext(),
95                     VoidPtrTy,                        // __prev
96                     Int32Ty,                          // call_site
97                     ArrayType::get(Int32Ty, 4),       // __data
98                     VoidPtrTy,                        // __personality
99                     VoidPtrTy,                        // __lsda
100                     ArrayType::get(VoidPtrTy, 5),     // __jbuf
101                     NULL);
102   RegisterFn = M.getOrInsertFunction("_Unwind_SjLj_Register",
103                                      Type::getVoidTy(M.getContext()),
104                                      PointerType::getUnqual(FunctionContextTy),
105                                      (Type *)0);
106   UnregisterFn =
107     M.getOrInsertFunction("_Unwind_SjLj_Unregister",
108                           Type::getVoidTy(M.getContext()),
109                           PointerType::getUnqual(FunctionContextTy),
110                           (Type *)0);
111   FrameAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::frameaddress);
112   StackAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::stacksave);
113   StackRestoreFn = Intrinsic::getDeclaration(&M, Intrinsic::stackrestore);
114   BuiltinSetjmpFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_setjmp);
115   LSDAAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_lsda);
116   SelectorFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_selector);
117   ExceptionFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_exception);
118   CallSiteFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_callsite);
119   PersonalityFn = 0;
120
121   return true;
122 }
123
124 /// insertCallSiteStore - Insert a store of the call-site value to the
125 /// function context
126 void SjLjEHPass::insertCallSiteStore(Instruction *I, int Number,
127                                      Value *CallSite) {
128   ConstantInt *CallSiteNoC = ConstantInt::get(Type::getInt32Ty(I->getContext()),
129                                               Number);
130   // Insert a store of the call-site number
131   new StoreInst(CallSiteNoC, CallSite, true, I);  // volatile
132 }
133
134 /// markInvokeCallSite - Insert code to mark the call_site for this invoke
135 void SjLjEHPass::markInvokeCallSite(InvokeInst *II, int InvokeNo,
136                                     Value *CallSite,
137                                     SwitchInst *CatchSwitch) {
138   ConstantInt *CallSiteNoC= ConstantInt::get(Type::getInt32Ty(II->getContext()),
139                                               InvokeNo);
140   // The runtime comes back to the dispatcher with the call_site - 1 in
141   // the context. Odd, but there it is.
142   ConstantInt *SwitchValC = ConstantInt::get(Type::getInt32Ty(II->getContext()),
143                                             InvokeNo - 1);
144
145   // If the unwind edge has phi nodes, split the edge.
146   if (isa<PHINode>(II->getUnwindDest()->begin())) {
147     SplitCriticalEdge(II, 1, this);
148
149     // If there are any phi nodes left, they must have a single predecessor.
150     while (PHINode *PN = dyn_cast<PHINode>(II->getUnwindDest()->begin())) {
151       PN->replaceAllUsesWith(PN->getIncomingValue(0));
152       PN->eraseFromParent();
153     }
154   }
155
156   // Insert the store of the call site value
157   insertCallSiteStore(II, InvokeNo, CallSite);
158
159   // Record the call site value for the back end so it stays associated with
160   // the invoke.
161   CallInst::Create(CallSiteFn, CallSiteNoC, "", II);
162
163   // Add a switch case to our unwind block.
164   CatchSwitch->addCase(SwitchValC, II->getUnwindDest());
165   // We still want this to look like an invoke so we emit the LSDA properly,
166   // so we don't transform the invoke into a call here.
167 }
168
169 /// MarkBlocksLiveIn - Insert BB and all of its predescessors into LiveBBs until
170 /// we reach blocks we've already seen.
171 static void MarkBlocksLiveIn(BasicBlock *BB, std::set<BasicBlock*> &LiveBBs) {
172   if (!LiveBBs.insert(BB).second) return; // already been here.
173
174   for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
175     MarkBlocksLiveIn(*PI, LiveBBs);
176 }
177
178 /// splitLiveRangesAcrossInvokes - Each value that is live across an unwind edge
179 /// we spill into a stack location, guaranteeing that there is nothing live
180 /// across the unwind edge.  This process also splits all critical edges
181 /// coming out of invoke's.
182 /// FIXME: Move this function to a common utility file (Local.cpp?) so
183 /// both SjLj and LowerInvoke can use it.
184 void SjLjEHPass::
185 splitLiveRangesAcrossInvokes(SmallVector<InvokeInst*,16> &Invokes) {
186   // First step, split all critical edges from invoke instructions.
187   for (unsigned i = 0, e = Invokes.size(); i != e; ++i) {
188     InvokeInst *II = Invokes[i];
189     SplitCriticalEdge(II, 0, this);
190     SplitCriticalEdge(II, 1, this);
191     assert(!isa<PHINode>(II->getNormalDest()) &&
192            !isa<PHINode>(II->getUnwindDest()) &&
193            "critical edge splitting left single entry phi nodes?");
194   }
195
196   Function *F = Invokes.back()->getParent()->getParent();
197
198   // To avoid having to handle incoming arguments specially, we lower each arg
199   // to a copy instruction in the entry block.  This ensures that the argument
200   // value itself cannot be live across the entry block.
201   BasicBlock::iterator AfterAllocaInsertPt = F->begin()->begin();
202   while (isa<AllocaInst>(AfterAllocaInsertPt) &&
203         isa<ConstantInt>(cast<AllocaInst>(AfterAllocaInsertPt)->getArraySize()))
204     ++AfterAllocaInsertPt;
205   for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
206        AI != E; ++AI) {
207     const Type *Ty = AI->getType();
208     // StructType can't be cast, but is a legal argument type, so we have
209     // to handle them differently. We use an extract/insert pair as a
210     // lightweight method to achieve the same goal.
211     if (isa<StructType>(Ty)) {
212       Instruction *EI = ExtractValueInst::Create(AI, 0, "", AfterAllocaInsertPt);
213       Instruction *NI = InsertValueInst::Create(AI, EI, 0);
214       NI->insertAfter(EI);
215       AI->replaceAllUsesWith(NI);
216       // Set the struct operand of the instructions back to the AllocaInst.
217       EI->setOperand(0, AI);
218       NI->setOperand(0, AI);
219     } else {
220       // This is always a no-op cast because we're casting AI to AI->getType()
221       // so src and destination types are identical. BitCast is the only
222       // possibility.
223       CastInst *NC = new BitCastInst(
224         AI, AI->getType(), AI->getName()+".tmp", AfterAllocaInsertPt);
225       AI->replaceAllUsesWith(NC);
226       // Set the operand of the cast instruction back to the AllocaInst.
227       // Normally it's forbidden to replace a CastInst's operand because it
228       // could cause the opcode to reflect an illegal conversion. However,
229       // we're replacing it here with the same value it was constructed with.
230       // We do this because the above replaceAllUsesWith() clobbered the
231       // operand, but we want this one to remain.
232       NC->setOperand(0, AI);
233     }
234   }
235
236   // Finally, scan the code looking for instructions with bad live ranges.
237   for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
238     for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; ++II) {
239       // Ignore obvious cases we don't have to handle.  In particular, most
240       // instructions either have no uses or only have a single use inside the
241       // current block.  Ignore them quickly.
242       Instruction *Inst = II;
243       if (Inst->use_empty()) continue;
244       if (Inst->hasOneUse() &&
245           cast<Instruction>(Inst->use_back())->getParent() == BB &&
246           !isa<PHINode>(Inst->use_back())) continue;
247
248       // If this is an alloca in the entry block, it's not a real register
249       // value.
250       if (AllocaInst *AI = dyn_cast<AllocaInst>(Inst))
251         if (isa<ConstantInt>(AI->getArraySize()) && BB == F->begin())
252           continue;
253
254       // Avoid iterator invalidation by copying users to a temporary vector.
255       SmallVector<Instruction*,16> Users;
256       for (Value::use_iterator UI = Inst->use_begin(), E = Inst->use_end();
257            UI != E; ++UI) {
258         Instruction *User = cast<Instruction>(*UI);
259         if (User->getParent() != BB || isa<PHINode>(User))
260           Users.push_back(User);
261       }
262
263       // Find all of the blocks that this value is live in.
264       std::set<BasicBlock*> LiveBBs;
265       LiveBBs.insert(Inst->getParent());
266       while (!Users.empty()) {
267         Instruction *U = Users.back();
268         Users.pop_back();
269
270         if (!isa<PHINode>(U)) {
271           MarkBlocksLiveIn(U->getParent(), LiveBBs);
272         } else {
273           // Uses for a PHI node occur in their predecessor block.
274           PHINode *PN = cast<PHINode>(U);
275           for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
276             if (PN->getIncomingValue(i) == Inst)
277               MarkBlocksLiveIn(PN->getIncomingBlock(i), LiveBBs);
278         }
279       }
280
281       // Now that we know all of the blocks that this thing is live in, see if
282       // it includes any of the unwind locations.
283       bool NeedsSpill = false;
284       for (unsigned i = 0, e = Invokes.size(); i != e; ++i) {
285         BasicBlock *UnwindBlock = Invokes[i]->getUnwindDest();
286         if (UnwindBlock != BB && LiveBBs.count(UnwindBlock)) {
287           NeedsSpill = true;
288         }
289       }
290
291       // If we decided we need a spill, do it.
292       if (NeedsSpill) {
293         ++NumSpilled;
294         DemoteRegToStack(*Inst, true);
295       }
296     }
297 }
298
299 bool SjLjEHPass::insertSjLjEHSupport(Function &F) {
300   SmallVector<ReturnInst*,16> Returns;
301   SmallVector<UnwindInst*,16> Unwinds;
302   SmallVector<InvokeInst*,16> Invokes;
303
304   // Look through the terminators of the basic blocks to find invokes, returns
305   // and unwinds.
306   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
307     if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
308       // Remember all return instructions in case we insert an invoke into this
309       // function.
310       Returns.push_back(RI);
311     } else if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
312       Invokes.push_back(II);
313     } else if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator())) {
314       Unwinds.push_back(UI);
315     }
316   }
317   // If we don't have any invokes or unwinds, there's nothing to do.
318   if (Unwinds.empty() && Invokes.empty()) return false;
319
320   // Find the eh.selector.*, eh.exception and alloca calls.
321   //
322   // Remember any allocas() that aren't in the entry block, as the
323   // jmpbuf saved SP will need to be updated for them.
324   //
325   // We'll use the first eh.selector to determine the right personality
326   // function to use. For SJLJ, we always use the same personality for the
327   // whole function, not on a per-selector basis.
328   // FIXME: That's a bit ugly. Better way?
329   SmallVector<CallInst*,16> EH_Selectors;
330   SmallVector<CallInst*,16> EH_Exceptions;
331   SmallVector<Instruction*,16> JmpbufUpdatePoints;
332   // Note: Skip the entry block since there's nothing there that interests
333   // us. eh.selector and eh.exception shouldn't ever be there, and we
334   // want to disregard any allocas that are there.
335   for (Function::iterator BB = F.begin(), E = F.end(); ++BB != E;) {
336     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
337       if (CallInst *CI = dyn_cast<CallInst>(I)) {
338         if (CI->getCalledFunction() == SelectorFn) {
339           if (!PersonalityFn) PersonalityFn = CI->getOperand(2);
340           EH_Selectors.push_back(CI);
341         } else if (CI->getCalledFunction() == ExceptionFn) {
342           EH_Exceptions.push_back(CI);
343         } else if (CI->getCalledFunction() == StackRestoreFn) {
344           JmpbufUpdatePoints.push_back(CI);
345         }
346       } else if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) {
347         JmpbufUpdatePoints.push_back(AI);
348       }
349     }
350   }
351   // If we don't have any eh.selector calls, we can't determine the personality
352   // function. Without a personality function, we can't process exceptions.
353   if (!PersonalityFn) return false;
354
355   NumInvokes += Invokes.size();
356   NumUnwinds += Unwinds.size();
357
358   if (!Invokes.empty()) {
359     // We have invokes, so we need to add register/unregister calls to get
360     // this function onto the global unwind stack.
361     //
362     // First thing we need to do is scan the whole function for values that are
363     // live across unwind edges.  Each value that is live across an unwind edge
364     // we spill into a stack location, guaranteeing that there is nothing live
365     // across the unwind edge.  This process also splits all critical edges
366     // coming out of invoke's.
367     splitLiveRangesAcrossInvokes(Invokes);
368
369     BasicBlock *EntryBB = F.begin();
370     // Create an alloca for the incoming jump buffer ptr and the new jump buffer
371     // that needs to be restored on all exits from the function.  This is an
372     // alloca because the value needs to be added to the global context list.
373     unsigned Align = 4; // FIXME: Should be a TLI check?
374     AllocaInst *FunctionContext =
375       new AllocaInst(FunctionContextTy, 0, Align,
376                      "fcn_context", F.begin()->begin());
377
378     Value *Idxs[2];
379     const Type *Int32Ty = Type::getInt32Ty(F.getContext());
380     Value *Zero = ConstantInt::get(Int32Ty, 0);
381     // We need to also keep around a reference to the call_site field
382     Idxs[0] = Zero;
383     Idxs[1] = ConstantInt::get(Int32Ty, 1);
384     CallSite = GetElementPtrInst::Create(FunctionContext, Idxs, Idxs+2,
385                                          "call_site",
386                                          EntryBB->getTerminator());
387
388     // The exception selector comes back in context->data[1]
389     Idxs[1] = ConstantInt::get(Int32Ty, 2);
390     Value *FCData = GetElementPtrInst::Create(FunctionContext, Idxs, Idxs+2,
391                                               "fc_data",
392                                               EntryBB->getTerminator());
393     Idxs[1] = ConstantInt::get(Int32Ty, 1);
394     Value *SelectorAddr = GetElementPtrInst::Create(FCData, Idxs, Idxs+2,
395                                                     "exc_selector_gep",
396                                                     EntryBB->getTerminator());
397     // The exception value comes back in context->data[0]
398     Idxs[1] = Zero;
399     Value *ExceptionAddr = GetElementPtrInst::Create(FCData, Idxs, Idxs+2,
400                                                      "exception_gep",
401                                                      EntryBB->getTerminator());
402
403     // The result of the eh.selector call will be replaced with a
404     // a reference to the selector value returned in the function
405     // context. We leave the selector itself so the EH analysis later
406     // can use it.
407     for (int i = 0, e = EH_Selectors.size(); i < e; ++i) {
408       CallInst *I = EH_Selectors[i];
409       Value *SelectorVal = new LoadInst(SelectorAddr, "select_val", true, I);
410       I->replaceAllUsesWith(SelectorVal);
411     }
412     // eh.exception calls are replaced with references to the proper
413     // location in the context. Unlike eh.selector, the eh.exception
414     // calls are removed entirely.
415     for (int i = 0, e = EH_Exceptions.size(); i < e; ++i) {
416       CallInst *I = EH_Exceptions[i];
417       // Possible for there to be duplicates, so check to make sure
418       // the instruction hasn't already been removed.
419       if (!I->getParent()) continue;
420       Value *Val = new LoadInst(ExceptionAddr, "exception", true, I);
421       const Type *Ty = Type::getInt8PtrTy(F.getContext());
422       Val = CastInst::Create(Instruction::IntToPtr, Val, Ty, "", I);
423
424       I->replaceAllUsesWith(Val);
425       I->eraseFromParent();
426     }
427
428     // The entry block changes to have the eh.sjlj.setjmp, with a conditional
429     // branch to a dispatch block for non-zero returns. If we return normally,
430     // we're not handling an exception and just register the function context
431     // and continue.
432
433     // Create the dispatch block.  The dispatch block is basically a big switch
434     // statement that goes to all of the invoke landing pads.
435     BasicBlock *DispatchBlock =
436             BasicBlock::Create(F.getContext(), "eh.sjlj.setjmp.catch", &F);
437
438     // Insert a load in the Catch block, and a switch on its value.  By default,
439     // we go to a block that just does an unwind (which is the correct action
440     // for a standard call).
441     BasicBlock *UnwindBlock =
442       BasicBlock::Create(F.getContext(), "unwindbb", &F);
443     Unwinds.push_back(new UnwindInst(F.getContext(), UnwindBlock));
444
445     Value *DispatchLoad = new LoadInst(CallSite, "invoke.num", true,
446                                        DispatchBlock);
447     SwitchInst *DispatchSwitch =
448       SwitchInst::Create(DispatchLoad, UnwindBlock, Invokes.size(),
449                          DispatchBlock);
450     // Split the entry block to insert the conditional branch for the setjmp.
451     BasicBlock *ContBlock = EntryBB->splitBasicBlock(EntryBB->getTerminator(),
452                                                      "eh.sjlj.setjmp.cont");
453
454     // Populate the Function Context
455     //   1. LSDA address
456     //   2. Personality function address
457     //   3. jmpbuf (save SP, FP and call eh.sjlj.setjmp)
458
459     // LSDA address
460     Idxs[0] = Zero;
461     Idxs[1] = ConstantInt::get(Int32Ty, 4);
462     Value *LSDAFieldPtr =
463       GetElementPtrInst::Create(FunctionContext, Idxs, Idxs+2,
464                                 "lsda_gep",
465                                 EntryBB->getTerminator());
466     Value *LSDA = CallInst::Create(LSDAAddrFn, "lsda_addr",
467                                    EntryBB->getTerminator());
468     new StoreInst(LSDA, LSDAFieldPtr, true, EntryBB->getTerminator());
469
470     Idxs[1] = ConstantInt::get(Int32Ty, 3);
471     Value *PersonalityFieldPtr =
472       GetElementPtrInst::Create(FunctionContext, Idxs, Idxs+2,
473                                 "lsda_gep",
474                                 EntryBB->getTerminator());
475     new StoreInst(PersonalityFn, PersonalityFieldPtr, true,
476                   EntryBB->getTerminator());
477
478     // Save the frame pointer.
479     Idxs[1] = ConstantInt::get(Int32Ty, 5);
480     Value *JBufPtr
481       = GetElementPtrInst::Create(FunctionContext, Idxs, Idxs+2,
482                                   "jbuf_gep",
483                                   EntryBB->getTerminator());
484     Idxs[1] = ConstantInt::get(Int32Ty, 0);
485     Value *FramePtr =
486       GetElementPtrInst::Create(JBufPtr, Idxs, Idxs+2, "jbuf_fp_gep",
487                                 EntryBB->getTerminator());
488
489     Value *Val = CallInst::Create(FrameAddrFn,
490                                   ConstantInt::get(Int32Ty, 0),
491                                   "fp",
492                                   EntryBB->getTerminator());
493     new StoreInst(Val, FramePtr, true, EntryBB->getTerminator());
494
495     // Save the stack pointer.
496     Idxs[1] = ConstantInt::get(Int32Ty, 2);
497     Value *StackPtr =
498       GetElementPtrInst::Create(JBufPtr, Idxs, Idxs+2, "jbuf_sp_gep",
499                                 EntryBB->getTerminator());
500
501     Val = CallInst::Create(StackAddrFn, "sp", EntryBB->getTerminator());
502     new StoreInst(Val, StackPtr, true, EntryBB->getTerminator());
503
504     // Call the setjmp instrinsic. It fills in the rest of the jmpbuf.
505     Value *SetjmpArg =
506       CastInst::Create(Instruction::BitCast, JBufPtr,
507                        Type::getInt8PtrTy(F.getContext()), "",
508                        EntryBB->getTerminator());
509     Value *DispatchVal = CallInst::Create(BuiltinSetjmpFn, SetjmpArg,
510                                           "dispatch",
511                                           EntryBB->getTerminator());
512     // check the return value of the setjmp. non-zero goes to dispatcher.
513     Value *IsNormal = new ICmpInst(EntryBB->getTerminator(),
514                                    ICmpInst::ICMP_EQ, DispatchVal, Zero,
515                                    "notunwind");
516     // Nuke the uncond branch.
517     EntryBB->getTerminator()->eraseFromParent();
518
519     // Put in a new condbranch in its place.
520     BranchInst::Create(ContBlock, DispatchBlock, IsNormal, EntryBB);
521
522     // Register the function context and make sure it's known to not throw
523     CallInst *Register =
524       CallInst::Create(RegisterFn, FunctionContext, "",
525                        ContBlock->getTerminator());
526     Register->setDoesNotThrow();
527
528     // At this point, we are all set up, update the invoke instructions
529     // to mark their call_site values, and fill in the dispatch switch
530     // accordingly.
531     for (unsigned i = 0, e = Invokes.size(); i != e; ++i)
532       markInvokeCallSite(Invokes[i], i+1, CallSite, DispatchSwitch);
533
534     // Mark call instructions that aren't nounwind as no-action
535     // (call_site == -1). Skip the entry block, as prior to then, no function
536     // context has been created for this function and any unexpected exceptions
537     // thrown will go directly to the caller's context, which is what we want
538     // anyway, so no need to do anything here.
539     for (Function::iterator BB = F.begin(), E = F.end(); ++BB != E;) {
540       for (BasicBlock::iterator I = BB->begin(), end = BB->end(); I != end; ++I)
541         if (CallInst *CI = dyn_cast<CallInst>(I)) {
542           // Ignore calls to the EH builtins (eh.selector, eh.exception)
543           Constant *Callee = CI->getCalledFunction();
544           if (Callee != SelectorFn && Callee != ExceptionFn
545               && !CI->doesNotThrow())
546             insertCallSiteStore(CI, -1, CallSite);
547         }
548     }
549
550     // Replace all unwinds with a branch to the unwind handler.
551     // ??? Should this ever happen with sjlj exceptions?
552     for (unsigned i = 0, e = Unwinds.size(); i != e; ++i) {
553       BranchInst::Create(UnwindBlock, Unwinds[i]);
554       Unwinds[i]->eraseFromParent();
555     }
556
557     // Following any allocas not in the entry block, update the saved SP
558     // in the jmpbuf to the new value.
559     for (unsigned i = 0, e = JmpbufUpdatePoints.size(); i != e; ++i) {
560       Instruction *AI = JmpbufUpdatePoints[i];
561       Instruction *StackAddr = CallInst::Create(StackAddrFn, "sp");
562       StackAddr->insertAfter(AI);
563       Instruction *StoreStackAddr = new StoreInst(StackAddr, StackPtr, true);
564       StoreStackAddr->insertAfter(StackAddr);
565     }
566
567     // Finally, for any returns from this function, if this function contains an
568     // invoke, add a call to unregister the function context.
569     for (unsigned i = 0, e = Returns.size(); i != e; ++i)
570       CallInst::Create(UnregisterFn, FunctionContext, "", Returns[i]);
571   }
572
573   return true;
574 }
575
576 bool SjLjEHPass::runOnFunction(Function &F) {
577   bool Res = insertSjLjEHSupport(F);
578   return Res;
579 }