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