LLVM API Documentation

LowerInvoke.cpp

Go to the documentation of this file.
00001 //===- LowerInvoke.cpp - Eliminate Invoke & Unwind instructions -----------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file was developed by the LLVM research group and is distributed under
00006 // the University of Illinois Open Source License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This transformation is designed for use by code generators which do not yet
00011 // support stack unwinding.  This pass supports two models of exception handling
00012 // lowering, the 'cheap' support and the 'expensive' support.
00013 //
00014 // 'Cheap' exception handling support gives the program the ability to execute
00015 // any program which does not "throw an exception", by turning 'invoke'
00016 // instructions into calls and by turning 'unwind' instructions into calls to
00017 // abort().  If the program does dynamically use the unwind instruction, the
00018 // program will print a message then abort.
00019 //
00020 // 'Expensive' exception handling support gives the full exception handling
00021 // support to the program at the cost of making the 'invoke' instruction
00022 // really expensive.  It basically inserts setjmp/longjmp calls to emulate the
00023 // exception handling as necessary.
00024 //
00025 // Because the 'expensive' support slows down programs a lot, and EH is only
00026 // used for a subset of the programs, it must be specifically enabled by an
00027 // option.
00028 //
00029 // Note that after this pass runs the CFG is not entirely accurate (exceptional
00030 // control flow edges are not correct anymore) so only very simple things should
00031 // be done after the lowerinvoke pass has run (like generation of native code).
00032 // This should not be used as a general purpose "my LLVM-to-LLVM pass doesn't
00033 // support the invoke instruction yet" lowering pass.
00034 //
00035 //===----------------------------------------------------------------------===//
00036 
00037 #include "llvm/Transforms/Scalar.h"
00038 #include "llvm/Constants.h"
00039 #include "llvm/DerivedTypes.h"
00040 #include "llvm/Instructions.h"
00041 #include "llvm/Module.h"
00042 #include "llvm/Pass.h"
00043 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
00044 #include "llvm/Transforms/Utils/Local.h"
00045 #include "llvm/ADT/Statistic.h"
00046 #include "llvm/Support/CommandLine.h"
00047 #include <csetjmp>
00048 using namespace llvm;
00049 
00050 namespace {
00051   Statistic<> NumInvokes("lowerinvoke", "Number of invokes replaced");
00052   Statistic<> NumUnwinds("lowerinvoke", "Number of unwinds replaced");
00053   Statistic<> NumSpilled("lowerinvoke",
00054                          "Number of registers live across unwind edges");
00055   cl::opt<bool> ExpensiveEHSupport("enable-correct-eh-support",
00056  cl::desc("Make the -lowerinvoke pass insert expensive, but correct, EH code"));
00057 
00058   class LowerInvoke : public FunctionPass {
00059     // Used for both models.
00060     Function *WriteFn;
00061     Function *AbortFn;
00062     Value *AbortMessage;
00063     unsigned AbortMessageLength;
00064 
00065     // Used for expensive EH support.
00066     const Type *JBLinkTy;
00067     GlobalVariable *JBListHead;
00068     Function *SetJmpFn, *LongJmpFn;
00069   public:
00070     LowerInvoke(unsigned Size = 200, unsigned Align = 0) : JumpBufSize(Size),
00071       JumpBufAlign(Align) {}
00072     bool doInitialization(Module &M);
00073     bool runOnFunction(Function &F);
00074     
00075   private:
00076     void createAbortMessage();
00077     void writeAbortMessage(Instruction *IB);
00078     bool insertCheapEHSupport(Function &F);
00079     void splitLiveRangesLiveAcrossInvokes(std::vector<InvokeInst*> &Invokes);
00080     void rewriteExpensiveInvoke(InvokeInst *II, unsigned InvokeNo,
00081                                 AllocaInst *InvokeNum, SwitchInst *CatchSwitch);
00082     bool insertExpensiveEHSupport(Function &F);
00083     
00084     unsigned JumpBufSize;
00085     unsigned JumpBufAlign;
00086   };
00087 
00088   RegisterOpt<LowerInvoke>
00089   X("lowerinvoke", "Lower invoke and unwind, for unwindless code generators");
00090 }
00091 
00092 const PassInfo *llvm::LowerInvokePassID = X.getPassInfo();
00093 
00094 // Public Interface To the LowerInvoke pass.
00095 FunctionPass *llvm::createLowerInvokePass(unsigned JumpBufSize, 
00096                                           unsigned JumpBufAlign) { 
00097   return new LowerInvoke(JumpBufSize, JumpBufAlign); 
00098 }
00099 
00100 // doInitialization - Make sure that there is a prototype for abort in the
00101 // current module.
00102 bool LowerInvoke::doInitialization(Module &M) {
00103   const Type *VoidPtrTy = PointerType::get(Type::SByteTy);
00104   AbortMessage = 0;
00105   if (ExpensiveEHSupport) {
00106     // Insert a type for the linked list of jump buffers.
00107     const Type *JmpBufTy = ArrayType::get(VoidPtrTy, JumpBufSize);
00108 
00109     { // The type is recursive, so use a type holder.
00110       std::vector<const Type*> Elements;
00111       Elements.push_back(JmpBufTy);
00112       OpaqueType *OT = OpaqueType::get();
00113       Elements.push_back(PointerType::get(OT));
00114       PATypeHolder JBLType(StructType::get(Elements));
00115       OT->refineAbstractTypeTo(JBLType.get());  // Complete the cycle.
00116       JBLinkTy = JBLType.get();
00117       M.addTypeName("llvm.sjljeh.jmpbufty", JBLinkTy);
00118     }
00119 
00120     const Type *PtrJBList = PointerType::get(JBLinkTy);
00121 
00122     // Now that we've done that, insert the jmpbuf list head global, unless it
00123     // already exists.
00124     if (!(JBListHead = M.getGlobalVariable("llvm.sjljeh.jblist", PtrJBList)))
00125       JBListHead = new GlobalVariable(PtrJBList, false,
00126                                       GlobalValue::LinkOnceLinkage,
00127                                       Constant::getNullValue(PtrJBList),
00128                                       "llvm.sjljeh.jblist", &M);
00129     SetJmpFn = M.getOrInsertFunction("llvm.setjmp", Type::IntTy,
00130                                      PointerType::get(JmpBufTy), (Type *)0);
00131     LongJmpFn = M.getOrInsertFunction("llvm.longjmp", Type::VoidTy,
00132                                       PointerType::get(JmpBufTy),
00133                                       Type::IntTy, (Type *)0);
00134   }
00135 
00136   // We need the 'write' and 'abort' functions for both models.
00137   AbortFn = M.getOrInsertFunction("abort", Type::VoidTy, (Type *)0);
00138 
00139   // Unfortunately, 'write' can end up being prototyped in several different
00140   // ways.  If the user defines a three (or more) operand function named 'write'
00141   // we will use their prototype.  We _do not_ want to insert another instance
00142   // of a write prototype, because we don't know that the funcresolve pass will
00143   // run after us.  If there is a definition of a write function, but it's not
00144   // suitable for our uses, we just don't emit write calls.  If there is no
00145   // write prototype at all, we just add one.
00146   if (Function *WF = M.getNamedFunction("write")) {
00147     if (WF->getFunctionType()->getNumParams() > 3 ||
00148         WF->getFunctionType()->isVarArg())
00149       WriteFn = WF;
00150     else
00151       WriteFn = 0;
00152   } else {
00153     WriteFn = M.getOrInsertFunction("write", Type::VoidTy, Type::IntTy,
00154                                     VoidPtrTy, Type::IntTy, (Type *)0);
00155   }
00156   return true;
00157 }
00158 
00159 void LowerInvoke::createAbortMessage() {
00160   Module &M = *WriteFn->getParent();
00161   if (ExpensiveEHSupport) {
00162     // The abort message for expensive EH support tells the user that the
00163     // program 'unwound' without an 'invoke' instruction.
00164     Constant *Msg =
00165       ConstantArray::get("ERROR: Exception thrown, but not caught!\n");
00166     AbortMessageLength = Msg->getNumOperands()-1;  // don't include \0
00167 
00168     GlobalVariable *MsgGV = new GlobalVariable(Msg->getType(), true,
00169                                                GlobalValue::InternalLinkage,
00170                                                Msg, "abortmsg", &M);
00171     std::vector<Constant*> GEPIdx(2, Constant::getNullValue(Type::IntTy));
00172     AbortMessage = ConstantExpr::getGetElementPtr(MsgGV, GEPIdx);
00173   } else {
00174     // The abort message for cheap EH support tells the user that EH is not
00175     // enabled.
00176     Constant *Msg =
00177       ConstantArray::get("Exception handler needed, but not enabled.  Recompile"
00178                          " program with -enable-correct-eh-support.\n");
00179     AbortMessageLength = Msg->getNumOperands()-1;  // don't include \0
00180 
00181     GlobalVariable *MsgGV = new GlobalVariable(Msg->getType(), true,
00182                                                GlobalValue::InternalLinkage,
00183                                                Msg, "abortmsg", &M);
00184     std::vector<Constant*> GEPIdx(2, Constant::getNullValue(Type::IntTy));
00185     AbortMessage = ConstantExpr::getGetElementPtr(MsgGV, GEPIdx);
00186   }
00187 }
00188 
00189 
00190 void LowerInvoke::writeAbortMessage(Instruction *IB) {
00191   if (WriteFn) {
00192     if (AbortMessage == 0) createAbortMessage();
00193 
00194     // These are the arguments we WANT...
00195     std::vector<Value*> Args;
00196     Args.push_back(ConstantInt::get(Type::IntTy, 2));
00197     Args.push_back(AbortMessage);
00198     Args.push_back(ConstantInt::get(Type::IntTy, AbortMessageLength));
00199 
00200     // If the actual declaration of write disagrees, insert casts as
00201     // appropriate.
00202     const FunctionType *FT = WriteFn->getFunctionType();
00203     unsigned NumArgs = FT->getNumParams();
00204     for (unsigned i = 0; i != 3; ++i)
00205       if (i < NumArgs && FT->getParamType(i) != Args[i]->getType())
00206         Args[i] = ConstantExpr::getCast(cast<Constant>(Args[i]),
00207                                         FT->getParamType(i));
00208 
00209     (new CallInst(WriteFn, Args, "", IB))->setTailCall();
00210   }
00211 }
00212 
00213 bool LowerInvoke::insertCheapEHSupport(Function &F) {
00214   bool Changed = false;
00215   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
00216     if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
00217       // Insert a normal call instruction...
00218       std::string Name = II->getName(); II->setName("");
00219       CallInst *NewCall = new CallInst(II->getCalledValue(),
00220                                        std::vector<Value*>(II->op_begin()+3,
00221                                                        II->op_end()), Name, II);
00222       NewCall->setCallingConv(II->getCallingConv());
00223       II->replaceAllUsesWith(NewCall);
00224 
00225       // Insert an unconditional branch to the normal destination.
00226       new BranchInst(II->getNormalDest(), II);
00227 
00228       // Remove any PHI node entries from the exception destination.
00229       II->getUnwindDest()->removePredecessor(BB);
00230 
00231       // Remove the invoke instruction now.
00232       BB->getInstList().erase(II);
00233 
00234       ++NumInvokes; Changed = true;
00235     } else if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator())) {
00236       // Insert a new call to write(2, AbortMessage, AbortMessageLength);
00237       writeAbortMessage(UI);
00238 
00239       // Insert a call to abort()
00240       (new CallInst(AbortFn, std::vector<Value*>(), "", UI))->setTailCall();
00241 
00242       // Insert a return instruction.  This really should be a "barrier", as it
00243       // is unreachable.
00244       new ReturnInst(F.getReturnType() == Type::VoidTy ? 0 :
00245                             Constant::getNullValue(F.getReturnType()), UI);
00246 
00247       // Remove the unwind instruction now.
00248       BB->getInstList().erase(UI);
00249 
00250       ++NumUnwinds; Changed = true;
00251     }
00252   return Changed;
00253 }
00254 
00255 /// rewriteExpensiveInvoke - Insert code and hack the function to replace the
00256 /// specified invoke instruction with a call.
00257 void LowerInvoke::rewriteExpensiveInvoke(InvokeInst *II, unsigned InvokeNo,
00258                                          AllocaInst *InvokeNum,
00259                                          SwitchInst *CatchSwitch) {
00260   ConstantUInt *InvokeNoC = ConstantUInt::get(Type::UIntTy, InvokeNo);
00261 
00262   // Insert a store of the invoke num before the invoke and store zero into the
00263   // location afterward.
00264   new StoreInst(InvokeNoC, InvokeNum, true, II);  // volatile
00265   
00266   BasicBlock::iterator NI = II->getNormalDest()->begin();
00267   while (isa<PHINode>(NI)) ++NI;
00268   // nonvolatile.
00269   new StoreInst(Constant::getNullValue(Type::UIntTy), InvokeNum, false, NI);
00270   
00271   // Add a switch case to our unwind block.
00272   CatchSwitch->addCase(InvokeNoC, II->getUnwindDest());
00273   
00274   // Insert a normal call instruction.
00275   std::string Name = II->getName(); II->setName("");
00276   CallInst *NewCall = new CallInst(II->getCalledValue(),
00277                                    std::vector<Value*>(II->op_begin()+3,
00278                                                        II->op_end()), Name,
00279                                    II);
00280   NewCall->setCallingConv(II->getCallingConv());
00281   II->replaceAllUsesWith(NewCall);
00282   
00283   // Replace the invoke with an uncond branch.
00284   new BranchInst(II->getNormalDest(), NewCall->getParent());
00285   II->eraseFromParent();
00286 }
00287 
00288 /// MarkBlocksLiveIn - Insert BB and all of its predescessors into LiveBBs until
00289 /// we reach blocks we've already seen.
00290 static void MarkBlocksLiveIn(BasicBlock *BB, std::set<BasicBlock*> &LiveBBs) {
00291   if (!LiveBBs.insert(BB).second) return; // already been here.
00292   
00293   for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
00294     MarkBlocksLiveIn(*PI, LiveBBs);  
00295 }
00296 
00297 // First thing we need to do is scan the whole function for values that are
00298 // live across unwind edges.  Each value that is live across an unwind edge
00299 // we spill into a stack location, guaranteeing that there is nothing live
00300 // across the unwind edge.  This process also splits all critical edges
00301 // coming out of invoke's.
00302 void LowerInvoke::
00303 splitLiveRangesLiveAcrossInvokes(std::vector<InvokeInst*> &Invokes) {
00304   // First step, split all critical edges from invoke instructions.
00305   for (unsigned i = 0, e = Invokes.size(); i != e; ++i) {
00306     InvokeInst *II = Invokes[i];
00307     SplitCriticalEdge(II, 0, this);
00308     SplitCriticalEdge(II, 1, this);
00309     assert(!isa<PHINode>(II->getNormalDest()) &&
00310            !isa<PHINode>(II->getUnwindDest()) &&
00311            "critical edge splitting left single entry phi nodes?");
00312   }
00313 
00314   Function *F = Invokes.back()->getParent()->getParent();
00315   
00316   // To avoid having to handle incoming arguments specially, we lower each arg
00317   // to a copy instruction in the entry block.  This ensure that the argument
00318   // value itself cannot be live across the entry block.
00319   BasicBlock::iterator AfterAllocaInsertPt = F->begin()->begin();
00320   while (isa<AllocaInst>(AfterAllocaInsertPt) &&
00321         isa<ConstantInt>(cast<AllocaInst>(AfterAllocaInsertPt)->getArraySize()))
00322     ++AfterAllocaInsertPt;
00323   for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
00324        AI != E; ++AI) {
00325     CastInst *NC = new CastInst(AI, AI->getType(), AI->getName()+".tmp",
00326                                 AfterAllocaInsertPt);
00327     AI->replaceAllUsesWith(NC);
00328     NC->setOperand(0, AI);
00329   }
00330   
00331   // Finally, scan the code looking for instructions with bad live ranges.
00332   for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
00333     for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; ++II) {
00334       // Ignore obvious cases we don't have to handle.  In particular, most
00335       // instructions either have no uses or only have a single use inside the
00336       // current block.  Ignore them quickly.
00337       Instruction *Inst = II;
00338       if (Inst->use_empty()) continue;
00339       if (Inst->hasOneUse() &&
00340           cast<Instruction>(Inst->use_back())->getParent() == BB &&
00341           !isa<PHINode>(Inst->use_back())) continue;
00342       
00343       // If this is an alloca in the entry block, it's not a real register
00344       // value.
00345       if (AllocaInst *AI = dyn_cast<AllocaInst>(Inst))
00346         if (isa<ConstantInt>(AI->getArraySize()) && BB == F->begin())
00347           continue;
00348       
00349       // Avoid iterator invalidation by copying users to a temporary vector.
00350       std::vector<Instruction*> Users;
00351       for (Value::use_iterator UI = Inst->use_begin(), E = Inst->use_end();
00352            UI != E; ++UI) {
00353         Instruction *User = cast<Instruction>(*UI);
00354         if (User->getParent() != BB || isa<PHINode>(User))
00355           Users.push_back(User);
00356       }
00357 
00358       // Scan all of the uses and see if the live range is live across an unwind
00359       // edge.  If we find a use live across an invoke edge, create an alloca
00360       // and spill the value.
00361       AllocaInst *SpillLoc = 0;
00362       std::set<InvokeInst*> InvokesWithStoreInserted;
00363 
00364       // Find all of the blocks that this value is live in.
00365       std::set<BasicBlock*> LiveBBs;
00366       LiveBBs.insert(Inst->getParent());
00367       while (!Users.empty()) {
00368         Instruction *U = Users.back();
00369         Users.pop_back();
00370         
00371         if (!isa<PHINode>(U)) {
00372           MarkBlocksLiveIn(U->getParent(), LiveBBs);
00373         } else {
00374           // Uses for a PHI node occur in their predecessor block.
00375           PHINode *PN = cast<PHINode>(U);
00376           for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
00377             if (PN->getIncomingValue(i) == Inst)
00378               MarkBlocksLiveIn(PN->getIncomingBlock(i), LiveBBs);
00379         }
00380       }
00381       
00382       // Now that we know all of the blocks that this thing is live in, see if
00383       // it includes any of the unwind locations.
00384       bool NeedsSpill = false;
00385       for (unsigned i = 0, e = Invokes.size(); i != e; ++i) {
00386         BasicBlock *UnwindBlock = Invokes[i]->getUnwindDest();
00387         if (UnwindBlock != BB && LiveBBs.count(UnwindBlock)) {
00388           NeedsSpill = true;
00389         }
00390       }
00391 
00392       // If we decided we need a spill, do it.
00393       if (NeedsSpill) {
00394         ++NumSpilled;
00395         DemoteRegToStack(*Inst, true);
00396       }
00397     }
00398 }
00399 
00400 bool LowerInvoke::insertExpensiveEHSupport(Function &F) {
00401   std::vector<ReturnInst*> Returns;
00402   std::vector<UnwindInst*> Unwinds;
00403   std::vector<InvokeInst*> Invokes;
00404 
00405   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
00406     if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
00407       // Remember all return instructions in case we insert an invoke into this
00408       // function.
00409       Returns.push_back(RI);
00410     } else if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
00411       Invokes.push_back(II);
00412     } else if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator())) {
00413       Unwinds.push_back(UI);
00414     }
00415 
00416   if (Unwinds.empty() && Invokes.empty()) return false;
00417 
00418   NumInvokes += Invokes.size();
00419   NumUnwinds += Unwinds.size();
00420   
00421   // TODO: This is not an optimal way to do this.  In particular, this always
00422   // inserts setjmp calls into the entries of functions with invoke instructions
00423   // even though there are possibly paths through the function that do not
00424   // execute any invokes.  In particular, for functions with early exits, e.g.
00425   // the 'addMove' method in hexxagon, it would be nice to not have to do the
00426   // setjmp stuff on the early exit path.  This requires a bit of dataflow, but
00427   // would not be too hard to do.
00428 
00429   // If we have an invoke instruction, insert a setjmp that dominates all
00430   // invokes.  After the setjmp, use a cond branch that goes to the original
00431   // code path on zero, and to a designated 'catch' block of nonzero.
00432   Value *OldJmpBufPtr = 0;
00433   if (!Invokes.empty()) {
00434     // First thing we need to do is scan the whole function for values that are
00435     // live across unwind edges.  Each value that is live across an unwind edge
00436     // we spill into a stack location, guaranteeing that there is nothing live
00437     // across the unwind edge.  This process also splits all critical edges
00438     // coming out of invoke's.
00439     splitLiveRangesLiveAcrossInvokes(Invokes);    
00440     
00441     BasicBlock *EntryBB = F.begin();
00442     
00443     // Create an alloca for the incoming jump buffer ptr and the new jump buffer
00444     // that needs to be restored on all exits from the function.  This is an
00445     // alloca because the value needs to be live across invokes.
00446     AllocaInst *JmpBuf = 
00447       new AllocaInst(JBLinkTy, 0, JumpBufAlign, "jblink", F.begin()->begin());
00448     
00449     std::vector<Value*> Idx;
00450     Idx.push_back(Constant::getNullValue(Type::IntTy));
00451     Idx.push_back(ConstantUInt::get(Type::UIntTy, 1));
00452     OldJmpBufPtr = new GetElementPtrInst(JmpBuf, Idx, "OldBuf",
00453                                          EntryBB->getTerminator());
00454 
00455     // Copy the JBListHead to the alloca.
00456     Value *OldBuf = new LoadInst(JBListHead, "oldjmpbufptr", true,
00457                                  EntryBB->getTerminator());
00458     new StoreInst(OldBuf, OldJmpBufPtr, true, EntryBB->getTerminator());
00459     
00460     // Add the new jumpbuf to the list.
00461     new StoreInst(JmpBuf, JBListHead, true, EntryBB->getTerminator());
00462 
00463     // Create the catch block.  The catch block is basically a big switch
00464     // statement that goes to all of the invoke catch blocks.
00465     BasicBlock *CatchBB = new BasicBlock("setjmp.catch", &F);
00466     
00467     // Create an alloca which keeps track of which invoke is currently
00468     // executing.  For normal calls it contains zero.
00469     AllocaInst *InvokeNum = new AllocaInst(Type::UIntTy, 0, "invokenum",
00470                                            EntryBB->begin());
00471     new StoreInst(ConstantInt::get(Type::UIntTy, 0), InvokeNum, true,
00472                   EntryBB->getTerminator());
00473     
00474     // Insert a load in the Catch block, and a switch on its value.  By default,
00475     // we go to a block that just does an unwind (which is the correct action
00476     // for a standard call).
00477     BasicBlock *UnwindBB = new BasicBlock("unwindbb", &F);
00478     Unwinds.push_back(new UnwindInst(UnwindBB));
00479     
00480     Value *CatchLoad = new LoadInst(InvokeNum, "invoke.num", true, CatchBB);
00481     SwitchInst *CatchSwitch = 
00482       new SwitchInst(CatchLoad, UnwindBB, Invokes.size(), CatchBB);
00483 
00484     // Now that things are set up, insert the setjmp call itself.
00485     
00486     // Split the entry block to insert the conditional branch for the setjmp.
00487     BasicBlock *ContBlock = EntryBB->splitBasicBlock(EntryBB->getTerminator(),
00488                                                      "setjmp.cont");
00489 
00490     Idx[1] = ConstantUInt::get(Type::UIntTy, 0);
00491     Value *JmpBufPtr = new GetElementPtrInst(JmpBuf, Idx, "TheJmpBuf",
00492                                              EntryBB->getTerminator());
00493     Value *SJRet = new CallInst(SetJmpFn, JmpBufPtr, "sjret",
00494                                 EntryBB->getTerminator());
00495     
00496     // Compare the return value to zero.
00497     Value *IsNormal = BinaryOperator::createSetEQ(SJRet,
00498                                      Constant::getNullValue(SJRet->getType()),
00499                                         "notunwind", EntryBB->getTerminator());
00500     // Nuke the uncond branch.
00501     EntryBB->getTerminator()->eraseFromParent();
00502     
00503     // Put in a new condbranch in its place.
00504     new BranchInst(ContBlock, CatchBB, IsNormal, EntryBB);
00505 
00506     // At this point, we are all set up, rewrite each invoke instruction.
00507     for (unsigned i = 0, e = Invokes.size(); i != e; ++i)
00508       rewriteExpensiveInvoke(Invokes[i], i+1, InvokeNum, CatchSwitch);
00509   }
00510 
00511   // We know that there is at least one unwind.
00512   
00513   // Create three new blocks, the block to load the jmpbuf ptr and compare
00514   // against null, the block to do the longjmp, and the error block for if it
00515   // is null.  Add them at the end of the function because they are not hot.
00516   BasicBlock *UnwindHandler = new BasicBlock("dounwind", &F);
00517   BasicBlock *UnwindBlock = new BasicBlock("unwind", &F);
00518   BasicBlock *TermBlock = new BasicBlock("unwinderror", &F);
00519 
00520   // If this function contains an invoke, restore the old jumpbuf ptr.
00521   Value *BufPtr;
00522   if (OldJmpBufPtr) {
00523     // Before the return, insert a copy from the saved value to the new value.
00524     BufPtr = new LoadInst(OldJmpBufPtr, "oldjmpbufptr", UnwindHandler);
00525     new StoreInst(BufPtr, JBListHead, UnwindHandler);
00526   } else {
00527     BufPtr = new LoadInst(JBListHead, "ehlist", UnwindHandler);
00528   }
00529   
00530   // Load the JBList, if it's null, then there was no catch!
00531   Value *NotNull = BinaryOperator::createSetNE(BufPtr,
00532                                       Constant::getNullValue(BufPtr->getType()),
00533                                           "notnull", UnwindHandler);
00534   new BranchInst(UnwindBlock, TermBlock, NotNull, UnwindHandler);
00535   
00536   // Create the block to do the longjmp.
00537   // Get a pointer to the jmpbuf and longjmp.
00538   std::vector<Value*> Idx;
00539   Idx.push_back(Constant::getNullValue(Type::IntTy));
00540   Idx.push_back(ConstantUInt::get(Type::UIntTy, 0));
00541   Idx[0] = new GetElementPtrInst(BufPtr, Idx, "JmpBuf", UnwindBlock);
00542   Idx[1] = ConstantInt::get(Type::IntTy, 1);
00543   new CallInst(LongJmpFn, Idx, "", UnwindBlock);
00544   new UnreachableInst(UnwindBlock);
00545   
00546   // Set up the term block ("throw without a catch").
00547   new UnreachableInst(TermBlock);
00548 
00549   // Insert a new call to write(2, AbortMessage, AbortMessageLength);
00550   writeAbortMessage(TermBlock->getTerminator());
00551   
00552   // Insert a call to abort()
00553   (new CallInst(AbortFn, std::vector<Value*>(), "",
00554                 TermBlock->getTerminator()))->setTailCall();
00555     
00556   
00557   // Replace all unwinds with a branch to the unwind handler.
00558   for (unsigned i = 0, e = Unwinds.size(); i != e; ++i) {
00559     new BranchInst(UnwindHandler, Unwinds[i]);
00560     Unwinds[i]->eraseFromParent();    
00561   } 
00562   
00563   // Finally, for any returns from this function, if this function contains an
00564   // invoke, restore the old jmpbuf pointer to its input value.
00565   if (OldJmpBufPtr) {
00566     for (unsigned i = 0, e = Returns.size(); i != e; ++i) {
00567       ReturnInst *R = Returns[i];
00568       
00569       // Before the return, insert a copy from the saved value to the new value.
00570       Value *OldBuf = new LoadInst(OldJmpBufPtr, "oldjmpbufptr", true, R);
00571       new StoreInst(OldBuf, JBListHead, true, R);
00572     }
00573   }
00574   
00575   return true;
00576 }
00577 
00578 bool LowerInvoke::runOnFunction(Function &F) {
00579   if (ExpensiveEHSupport)
00580     return insertExpensiveEHSupport(F);
00581   else
00582     return insertCheapEHSupport(F);
00583 }