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