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