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