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