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