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