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