Change the interface to Module::getOrInsertFunction to be easier to use,to resolve...
[oota-llvm.git] / lib / Transforms / Utils / LowerInvoke.cpp
1 //===- LowerInvoke.cpp - Eliminate Invoke & Unwind instructions -----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
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.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This transformation is designed for use by code generators which do not yet
11 // support stack unwinding.  This pass supports two models of exception handling
12 // lowering, the 'cheap' support and the 'expensive' support.
13 //
14 // 'Cheap' exception handling support gives the program the ability to execute
15 // any program which does not "throw an exception", by turning 'invoke'
16 // instructions into calls and by turning 'unwind' instructions into calls to
17 // abort().  If the program does dynamically use the unwind instruction, the
18 // program will print a message then abort.
19 //
20 // 'Expensive' exception handling support gives the full exception handling
21 // support to the program at the cost of making the 'invoke' instruction
22 // really expensive.  It basically inserts setjmp/longjmp calls to emulate the
23 // exception handling as necessary.
24 //
25 // Because the 'expensive' support slows down programs a lot, and EH is only
26 // used for a subset of the programs, it must be specifically enabled by an
27 // option.
28 //
29 // Note that after this pass runs the CFG is not entirely accurate (exceptional
30 // control flow edges are not correct anymore) so only very simple things should
31 // be done after the lowerinvoke pass has run (like generation of native code).
32 // This should not be used as a general purpose "my LLVM-to-LLVM pass doesn't
33 // support the invoke instruction yet" lowering pass.
34 //
35 //===----------------------------------------------------------------------===//
36
37 #define DEBUG_TYPE "lowerinvoke"
38 #include "llvm/Transforms/Scalar.h"
39 #include "llvm/Constants.h"
40 #include "llvm/DerivedTypes.h"
41 #include "llvm/Instructions.h"
42 #include "llvm/Module.h"
43 #include "llvm/Pass.h"
44 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
45 #include "llvm/Transforms/Utils/Local.h"
46 #include "llvm/ADT/Statistic.h"
47 #include "llvm/Support/CommandLine.h"
48 #include "llvm/Support/Compiler.h"
49 #include "llvm/Target/TargetLowering.h"
50 #include <csetjmp>
51 using namespace llvm;
52
53 STATISTIC(NumInvokes, "Number of invokes replaced");
54 STATISTIC(NumUnwinds, "Number of unwinds replaced");
55 STATISTIC(NumSpilled, "Number of registers live across unwind edges");
56
57 static cl::opt<bool> ExpensiveEHSupport("enable-correct-eh-support",
58  cl::desc("Make the -lowerinvoke pass insert expensive, but correct, EH code"));
59
60 namespace {
61   class VISIBILITY_HIDDEN LowerInvoke : public FunctionPass {
62     // Used for both models.
63     Constant *WriteFn;
64     Constant *AbortFn;
65     Value *AbortMessage;
66     unsigned AbortMessageLength;
67
68     // Used for expensive EH support.
69     const Type *JBLinkTy;
70     GlobalVariable *JBListHead;
71     Constant *SetJmpFn, *LongJmpFn;
72     
73     // We peek in TLI to grab the target's jmp_buf size and alignment
74     const TargetLowering *TLI;
75     
76   public:
77     LowerInvoke(const TargetLowering *tli = NULL) : TLI(tli) { }
78     bool doInitialization(Module &M);
79     bool runOnFunction(Function &F);
80  
81     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
82       // This is a cluster of orthogonal Transforms     
83       AU.addPreservedID(PromoteMemoryToRegisterID);
84       AU.addPreservedID(LowerSelectID);
85       AU.addPreservedID(LowerSwitchID);
86       AU.addPreservedID(LowerAllocationsID);
87     }
88        
89   private:
90     void createAbortMessage(Module *M);
91     void writeAbortMessage(Instruction *IB);
92     bool insertCheapEHSupport(Function &F);
93     void splitLiveRangesLiveAcrossInvokes(std::vector<InvokeInst*> &Invokes);
94     void rewriteExpensiveInvoke(InvokeInst *II, unsigned InvokeNo,
95                                 AllocaInst *InvokeNum, SwitchInst *CatchSwitch);
96     bool insertExpensiveEHSupport(Function &F);
97   };
98
99   RegisterPass<LowerInvoke>
100   X("lowerinvoke", "Lower invoke and unwind, for unwindless code generators");
101 }
102
103 const PassInfo *llvm::LowerInvokePassID = X.getPassInfo();
104
105 // Public Interface To the LowerInvoke pass.
106 FunctionPass *llvm::createLowerInvokePass(const TargetLowering *TLI) { 
107   return new LowerInvoke(TLI); 
108 }
109
110 // doInitialization - Make sure that there is a prototype for abort in the
111 // current module.
112 bool LowerInvoke::doInitialization(Module &M) {
113   const Type *VoidPtrTy = PointerType::get(Type::Int8Ty);
114   AbortMessage = 0;
115   if (ExpensiveEHSupport) {
116     // Insert a type for the linked list of jump buffers.
117     unsigned JBSize = TLI ? TLI->getJumpBufSize() : 0;
118     JBSize = JBSize ? JBSize : 200;
119     const Type *JmpBufTy = ArrayType::get(VoidPtrTy, JBSize);
120
121     { // The type is recursive, so use a type holder.
122       std::vector<const Type*> Elements;
123       Elements.push_back(JmpBufTy);
124       OpaqueType *OT = OpaqueType::get();
125       Elements.push_back(PointerType::get(OT));
126       PATypeHolder JBLType(StructType::get(Elements));
127       OT->refineAbstractTypeTo(JBLType.get());  // Complete the cycle.
128       JBLinkTy = JBLType.get();
129       M.addTypeName("llvm.sjljeh.jmpbufty", JBLinkTy);
130     }
131
132     const Type *PtrJBList = PointerType::get(JBLinkTy);
133
134     // Now that we've done that, insert the jmpbuf list head global, unless it
135     // already exists.
136     if (!(JBListHead = M.getGlobalVariable("llvm.sjljeh.jblist", PtrJBList))) {
137       JBListHead = new GlobalVariable(PtrJBList, false,
138                                       GlobalValue::LinkOnceLinkage,
139                                       Constant::getNullValue(PtrJBList),
140                                       "llvm.sjljeh.jblist", &M);
141     }
142     SetJmpFn = M.getOrInsertFunction("llvm.setjmp", Type::Int32Ty,
143                                      PointerType::get(JmpBufTy), (Type *)0);
144     LongJmpFn = M.getOrInsertFunction("llvm.longjmp", Type::VoidTy,
145                                       PointerType::get(JmpBufTy),
146                                       Type::Int32Ty, (Type *)0);
147   }
148
149   // We need the 'write' and 'abort' functions for both models.
150   AbortFn = M.getOrInsertFunction("abort", Type::VoidTy, (Type *)0);
151   WriteFn = M.getOrInsertFunction("write", Type::VoidTy, Type::Int32Ty,
152                                   VoidPtrTy, Type::Int32Ty, (Type *)0);
153   return true;
154 }
155
156 void LowerInvoke::createAbortMessage(Module *M) {
157   if (ExpensiveEHSupport) {
158     // The abort message for expensive EH support tells the user that the
159     // program 'unwound' without an 'invoke' instruction.
160     Constant *Msg =
161       ConstantArray::get("ERROR: Exception thrown, but not caught!\n");
162     AbortMessageLength = Msg->getNumOperands()-1;  // don't include \0
163
164     GlobalVariable *MsgGV = new GlobalVariable(Msg->getType(), true,
165                                                GlobalValue::InternalLinkage,
166                                                Msg, "abortmsg", M);
167     std::vector<Constant*> GEPIdx(2, Constant::getNullValue(Type::Int32Ty));
168     AbortMessage = ConstantExpr::getGetElementPtr(MsgGV, GEPIdx);
169   } else {
170     // The abort message for cheap EH support tells the user that EH is not
171     // enabled.
172     Constant *Msg =
173       ConstantArray::get("Exception handler needed, but not enabled.  Recompile"
174                          " program with -enable-correct-eh-support.\n");
175     AbortMessageLength = Msg->getNumOperands()-1;  // don't include \0
176
177     GlobalVariable *MsgGV = new GlobalVariable(Msg->getType(), true,
178                                                GlobalValue::InternalLinkage,
179                                                Msg, "abortmsg", M);
180     std::vector<Constant*> GEPIdx(2, Constant::getNullValue(Type::Int32Ty));
181     AbortMessage = ConstantExpr::getGetElementPtr(MsgGV, GEPIdx);
182   }
183 }
184
185
186 void LowerInvoke::writeAbortMessage(Instruction *IB) {
187   if (AbortMessage == 0)
188     createAbortMessage(IB->getParent()->getParent()->getParent());
189
190   // These are the arguments we WANT...
191   std::vector<Value*> Args;
192   Args.push_back(ConstantInt::get(Type::Int32Ty, 2));
193   Args.push_back(AbortMessage);
194   Args.push_back(ConstantInt::get(Type::Int32Ty, AbortMessageLength));
195   (new CallInst(WriteFn, Args, "", IB))->setTailCall();
196 }
197
198 bool LowerInvoke::insertCheapEHSupport(Function &F) {
199   bool Changed = false;
200   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
201     if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
202       // Insert a normal call instruction...
203       std::string Name = II->getName(); II->setName("");
204       CallInst *NewCall = new CallInst(II->getCalledValue(),
205                                        std::vector<Value*>(II->op_begin()+3,
206                                                        II->op_end()), Name, II);
207       NewCall->setCallingConv(II->getCallingConv());
208       II->replaceAllUsesWith(NewCall);
209
210       // Insert an unconditional branch to the normal destination.
211       new BranchInst(II->getNormalDest(), II);
212
213       // Remove any PHI node entries from the exception destination.
214       II->getUnwindDest()->removePredecessor(BB);
215
216       // Remove the invoke instruction now.
217       BB->getInstList().erase(II);
218
219       ++NumInvokes; Changed = true;
220     } else if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator())) {
221       // Insert a new call to write(2, AbortMessage, AbortMessageLength);
222       writeAbortMessage(UI);
223
224       // Insert a call to abort()
225       (new CallInst(AbortFn, std::vector<Value*>(), "", UI))->setTailCall();
226
227       // Insert a return instruction.  This really should be a "barrier", as it
228       // is unreachable.
229       new ReturnInst(F.getReturnType() == Type::VoidTy ? 0 :
230                             Constant::getNullValue(F.getReturnType()), UI);
231
232       // Remove the unwind instruction now.
233       BB->getInstList().erase(UI);
234
235       ++NumUnwinds; Changed = true;
236     }
237   return Changed;
238 }
239
240 /// rewriteExpensiveInvoke - Insert code and hack the function to replace the
241 /// specified invoke instruction with a call.
242 void LowerInvoke::rewriteExpensiveInvoke(InvokeInst *II, unsigned InvokeNo,
243                                          AllocaInst *InvokeNum,
244                                          SwitchInst *CatchSwitch) {
245   ConstantInt *InvokeNoC = ConstantInt::get(Type::Int32Ty, InvokeNo);
246
247   // Insert a store of the invoke num before the invoke and store zero into the
248   // location afterward.
249   new StoreInst(InvokeNoC, InvokeNum, true, II);  // volatile
250   
251   BasicBlock::iterator NI = II->getNormalDest()->begin();
252   while (isa<PHINode>(NI)) ++NI;
253   // nonvolatile.
254   new StoreInst(Constant::getNullValue(Type::Int32Ty), InvokeNum, false, NI);
255   
256   // Add a switch case to our unwind block.
257   CatchSwitch->addCase(InvokeNoC, II->getUnwindDest());
258   
259   // Insert a normal call instruction.
260   std::string Name = II->getName(); II->setName("");
261   CallInst *NewCall = new CallInst(II->getCalledValue(),
262                                    std::vector<Value*>(II->op_begin()+3,
263                                                        II->op_end()), Name,
264                                    II);
265   NewCall->setCallingConv(II->getCallingConv());
266   II->replaceAllUsesWith(NewCall);
267   
268   // Replace the invoke with an uncond branch.
269   new BranchInst(II->getNormalDest(), NewCall->getParent());
270   II->eraseFromParent();
271 }
272
273 /// MarkBlocksLiveIn - Insert BB and all of its predescessors into LiveBBs until
274 /// we reach blocks we've already seen.
275 static void MarkBlocksLiveIn(BasicBlock *BB, std::set<BasicBlock*> &LiveBBs) {
276   if (!LiveBBs.insert(BB).second) return; // already been here.
277   
278   for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
279     MarkBlocksLiveIn(*PI, LiveBBs);  
280 }
281
282 // First thing we need to do is scan the whole function for values that are
283 // live across unwind edges.  Each value that is live across an unwind edge
284 // we spill into a stack location, guaranteeing that there is nothing live
285 // across the unwind edge.  This process also splits all critical edges
286 // coming out of invoke's.
287 void LowerInvoke::
288 splitLiveRangesLiveAcrossInvokes(std::vector<InvokeInst*> &Invokes) {
289   // First step, split all critical edges from invoke instructions.
290   for (unsigned i = 0, e = Invokes.size(); i != e; ++i) {
291     InvokeInst *II = Invokes[i];
292     SplitCriticalEdge(II, 0, this);
293     SplitCriticalEdge(II, 1, this);
294     assert(!isa<PHINode>(II->getNormalDest()) &&
295            !isa<PHINode>(II->getUnwindDest()) &&
296            "critical edge splitting left single entry phi nodes?");
297   }
298
299   Function *F = Invokes.back()->getParent()->getParent();
300   
301   // To avoid having to handle incoming arguments specially, we lower each arg
302   // to a copy instruction in the entry block.  This ensures that the argument
303   // value itself cannot be live across the entry block.
304   BasicBlock::iterator AfterAllocaInsertPt = F->begin()->begin();
305   while (isa<AllocaInst>(AfterAllocaInsertPt) &&
306         isa<ConstantInt>(cast<AllocaInst>(AfterAllocaInsertPt)->getArraySize()))
307     ++AfterAllocaInsertPt;
308   for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
309        AI != E; ++AI) {
310     // This is always a no-op cast because we're casting AI to AI->getType() so
311     // src and destination types are identical. BitCast is the only possibility.
312     CastInst *NC = new BitCastInst(
313       AI, AI->getType(), AI->getName()+".tmp", AfterAllocaInsertPt);
314     AI->replaceAllUsesWith(NC);
315     // Normally its is forbidden to replace a CastInst's operand because it
316     // could cause the opcode to reflect an illegal conversion. However, we're
317     // replacing it here with the same value it was constructed with to simply
318     // make NC its user.
319     NC->setOperand(0, AI); 
320   }
321   
322   // Finally, scan the code looking for instructions with bad live ranges.
323   for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
324     for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; ++II) {
325       // Ignore obvious cases we don't have to handle.  In particular, most
326       // instructions either have no uses or only have a single use inside the
327       // current block.  Ignore them quickly.
328       Instruction *Inst = II;
329       if (Inst->use_empty()) continue;
330       if (Inst->hasOneUse() &&
331           cast<Instruction>(Inst->use_back())->getParent() == BB &&
332           !isa<PHINode>(Inst->use_back())) continue;
333       
334       // If this is an alloca in the entry block, it's not a real register
335       // value.
336       if (AllocaInst *AI = dyn_cast<AllocaInst>(Inst))
337         if (isa<ConstantInt>(AI->getArraySize()) && BB == F->begin())
338           continue;
339       
340       // Avoid iterator invalidation by copying users to a temporary vector.
341       std::vector<Instruction*> Users;
342       for (Value::use_iterator UI = Inst->use_begin(), E = Inst->use_end();
343            UI != E; ++UI) {
344         Instruction *User = cast<Instruction>(*UI);
345         if (User->getParent() != BB || isa<PHINode>(User))
346           Users.push_back(User);
347       }
348
349       // Scan all of the uses and see if the live range is live across an unwind
350       // edge.  If we find a use live across an invoke edge, create an alloca
351       // and spill the value.
352       std::set<InvokeInst*> InvokesWithStoreInserted;
353
354       // Find all of the blocks that this value is live in.
355       std::set<BasicBlock*> LiveBBs;
356       LiveBBs.insert(Inst->getParent());
357       while (!Users.empty()) {
358         Instruction *U = Users.back();
359         Users.pop_back();
360         
361         if (!isa<PHINode>(U)) {
362           MarkBlocksLiveIn(U->getParent(), LiveBBs);
363         } else {
364           // Uses for a PHI node occur in their predecessor block.
365           PHINode *PN = cast<PHINode>(U);
366           for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
367             if (PN->getIncomingValue(i) == Inst)
368               MarkBlocksLiveIn(PN->getIncomingBlock(i), LiveBBs);
369         }
370       }
371       
372       // Now that we know all of the blocks that this thing is live in, see if
373       // it includes any of the unwind locations.
374       bool NeedsSpill = false;
375       for (unsigned i = 0, e = Invokes.size(); i != e; ++i) {
376         BasicBlock *UnwindBlock = Invokes[i]->getUnwindDest();
377         if (UnwindBlock != BB && LiveBBs.count(UnwindBlock)) {
378           NeedsSpill = true;
379         }
380       }
381
382       // If we decided we need a spill, do it.
383       if (NeedsSpill) {
384         ++NumSpilled;
385         DemoteRegToStack(*Inst, true);
386       }
387     }
388 }
389
390 bool LowerInvoke::insertExpensiveEHSupport(Function &F) {
391   std::vector<ReturnInst*> Returns;
392   std::vector<UnwindInst*> Unwinds;
393   std::vector<InvokeInst*> Invokes;
394
395   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
396     if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
397       // Remember all return instructions in case we insert an invoke into this
398       // function.
399       Returns.push_back(RI);
400     } else if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
401       Invokes.push_back(II);
402     } else if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator())) {
403       Unwinds.push_back(UI);
404     }
405
406   if (Unwinds.empty() && Invokes.empty()) return false;
407
408   NumInvokes += Invokes.size();
409   NumUnwinds += Unwinds.size();
410   
411   // TODO: This is not an optimal way to do this.  In particular, this always
412   // inserts setjmp calls into the entries of functions with invoke instructions
413   // even though there are possibly paths through the function that do not
414   // execute any invokes.  In particular, for functions with early exits, e.g.
415   // the 'addMove' method in hexxagon, it would be nice to not have to do the
416   // setjmp stuff on the early exit path.  This requires a bit of dataflow, but
417   // would not be too hard to do.
418
419   // If we have an invoke instruction, insert a setjmp that dominates all
420   // invokes.  After the setjmp, use a cond branch that goes to the original
421   // code path on zero, and to a designated 'catch' block of nonzero.
422   Value *OldJmpBufPtr = 0;
423   if (!Invokes.empty()) {
424     // First thing we need to do is scan the whole function for values that are
425     // live across unwind edges.  Each value that is live across an unwind edge
426     // we spill into a stack location, guaranteeing that there is nothing live
427     // across the unwind edge.  This process also splits all critical edges
428     // coming out of invoke's.
429     splitLiveRangesLiveAcrossInvokes(Invokes);    
430     
431     BasicBlock *EntryBB = F.begin();
432     
433     // Create an alloca for the incoming jump buffer ptr and the new jump buffer
434     // that needs to be restored on all exits from the function.  This is an
435     // alloca because the value needs to be live across invokes.
436     unsigned Align = TLI ? TLI->getJumpBufAlignment() : 0;
437     AllocaInst *JmpBuf = 
438       new AllocaInst(JBLinkTy, 0, Align, "jblink", F.begin()->begin());
439     
440     std::vector<Value*> Idx;
441     Idx.push_back(Constant::getNullValue(Type::Int32Ty));
442     Idx.push_back(ConstantInt::get(Type::Int32Ty, 1));
443     OldJmpBufPtr = new GetElementPtrInst(JmpBuf, Idx, "OldBuf",
444                                          EntryBB->getTerminator());
445
446     // Copy the JBListHead to the alloca.
447     Value *OldBuf = new LoadInst(JBListHead, "oldjmpbufptr", true,
448                                  EntryBB->getTerminator());
449     new StoreInst(OldBuf, OldJmpBufPtr, true, EntryBB->getTerminator());
450     
451     // Add the new jumpbuf to the list.
452     new StoreInst(JmpBuf, JBListHead, true, EntryBB->getTerminator());
453
454     // Create the catch block.  The catch block is basically a big switch
455     // statement that goes to all of the invoke catch blocks.
456     BasicBlock *CatchBB = new BasicBlock("setjmp.catch", &F);
457     
458     // Create an alloca which keeps track of which invoke is currently
459     // executing.  For normal calls it contains zero.
460     AllocaInst *InvokeNum = new AllocaInst(Type::Int32Ty, 0, "invokenum",
461                                            EntryBB->begin());
462     new StoreInst(ConstantInt::get(Type::Int32Ty, 0), InvokeNum, true,
463                   EntryBB->getTerminator());
464     
465     // Insert a load in the Catch block, and a switch on its value.  By default,
466     // we go to a block that just does an unwind (which is the correct action
467     // for a standard call).
468     BasicBlock *UnwindBB = new BasicBlock("unwindbb", &F);
469     Unwinds.push_back(new UnwindInst(UnwindBB));
470     
471     Value *CatchLoad = new LoadInst(InvokeNum, "invoke.num", true, CatchBB);
472     SwitchInst *CatchSwitch = 
473       new SwitchInst(CatchLoad, UnwindBB, Invokes.size(), CatchBB);
474
475     // Now that things are set up, insert the setjmp call itself.
476     
477     // Split the entry block to insert the conditional branch for the setjmp.
478     BasicBlock *ContBlock = EntryBB->splitBasicBlock(EntryBB->getTerminator(),
479                                                      "setjmp.cont");
480
481     Idx[1] = ConstantInt::get(Type::Int32Ty, 0);
482     Value *JmpBufPtr = new GetElementPtrInst(JmpBuf, Idx, "TheJmpBuf",
483                                              EntryBB->getTerminator());
484     Value *SJRet = new CallInst(SetJmpFn, JmpBufPtr, "sjret",
485                                 EntryBB->getTerminator());
486     
487     // Compare the return value to zero.
488     Value *IsNormal = new ICmpInst(ICmpInst::ICMP_EQ, SJRet, 
489                                    Constant::getNullValue(SJRet->getType()),
490       "notunwind", EntryBB->getTerminator());
491     // Nuke the uncond branch.
492     EntryBB->getTerminator()->eraseFromParent();
493     
494     // Put in a new condbranch in its place.
495     new BranchInst(ContBlock, CatchBB, IsNormal, EntryBB);
496
497     // At this point, we are all set up, rewrite each invoke instruction.
498     for (unsigned i = 0, e = Invokes.size(); i != e; ++i)
499       rewriteExpensiveInvoke(Invokes[i], i+1, InvokeNum, CatchSwitch);
500   }
501
502   // We know that there is at least one unwind.
503   
504   // Create three new blocks, the block to load the jmpbuf ptr and compare
505   // against null, the block to do the longjmp, and the error block for if it
506   // is null.  Add them at the end of the function because they are not hot.
507   BasicBlock *UnwindHandler = new BasicBlock("dounwind", &F);
508   BasicBlock *UnwindBlock = new BasicBlock("unwind", &F);
509   BasicBlock *TermBlock = new BasicBlock("unwinderror", &F);
510
511   // If this function contains an invoke, restore the old jumpbuf ptr.
512   Value *BufPtr;
513   if (OldJmpBufPtr) {
514     // Before the return, insert a copy from the saved value to the new value.
515     BufPtr = new LoadInst(OldJmpBufPtr, "oldjmpbufptr", UnwindHandler);
516     new StoreInst(BufPtr, JBListHead, UnwindHandler);
517   } else {
518     BufPtr = new LoadInst(JBListHead, "ehlist", UnwindHandler);
519   }
520   
521   // Load the JBList, if it's null, then there was no catch!
522   Value *NotNull = new ICmpInst(ICmpInst::ICMP_NE, BufPtr, 
523                                 Constant::getNullValue(BufPtr->getType()),
524     "notnull", UnwindHandler);
525   new BranchInst(UnwindBlock, TermBlock, NotNull, UnwindHandler);
526   
527   // Create the block to do the longjmp.
528   // Get a pointer to the jmpbuf and longjmp.
529   std::vector<Value*> Idx;
530   Idx.push_back(Constant::getNullValue(Type::Int32Ty));
531   Idx.push_back(ConstantInt::get(Type::Int32Ty, 0));
532   Idx[0] = new GetElementPtrInst(BufPtr, Idx, "JmpBuf", UnwindBlock);
533   Idx[1] = ConstantInt::get(Type::Int32Ty, 1);
534   new CallInst(LongJmpFn, Idx, "", UnwindBlock);
535   new UnreachableInst(UnwindBlock);
536   
537   // Set up the term block ("throw without a catch").
538   new UnreachableInst(TermBlock);
539
540   // Insert a new call to write(2, AbortMessage, AbortMessageLength);
541   writeAbortMessage(TermBlock->getTerminator());
542   
543   // Insert a call to abort()
544   (new CallInst(AbortFn, std::vector<Value*>(), "",
545                 TermBlock->getTerminator()))->setTailCall();
546     
547   
548   // Replace all unwinds with a branch to the unwind handler.
549   for (unsigned i = 0, e = Unwinds.size(); i != e; ++i) {
550     new BranchInst(UnwindHandler, Unwinds[i]);
551     Unwinds[i]->eraseFromParent();    
552   } 
553   
554   // Finally, for any returns from this function, if this function contains an
555   // invoke, restore the old jmpbuf pointer to its input value.
556   if (OldJmpBufPtr) {
557     for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
558       ReturnInst *R = Returns[i];
559       
560       // Before the return, insert a copy from the saved value to the new value.
561       Value *OldBuf = new LoadInst(OldJmpBufPtr, "oldjmpbufptr", true, R);
562       new StoreInst(OldBuf, JBListHead, true, R);
563     }
564   }
565   
566   return true;
567 }
568
569 bool LowerInvoke::runOnFunction(Function &F) {
570   if (ExpensiveEHSupport)
571     return insertExpensiveEHSupport(F);
572   else
573     return insertCheapEHSupport(F);
574 }