LowerInvoke.cpp revision 3bcb3a6b8d95a19a3b4d61e7a59c38ac2fd392c1
1//===- LowerInvoke.cpp - Eliminate Invoke & Unwind instructions -----------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// 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#define DEBUG_TYPE "lowerinvoke" 38#include "llvm/Transforms/Scalar.h" 39#include "llvm/Constants.h" 40#include "llvm/DerivedTypes.h" 41#include "llvm/Instructions.h" 42#include "llvm/Intrinsics.h" 43#include "llvm/LLVMContext.h" 44#include "llvm/Module.h" 45#include "llvm/Pass.h" 46#include "llvm/Transforms/Utils/BasicBlockUtils.h" 47#include "llvm/Transforms/Utils/Local.h" 48#include "llvm/ADT/SmallVector.h" 49#include "llvm/ADT/Statistic.h" 50#include "llvm/Support/CommandLine.h" 51#include "llvm/Target/TargetLowering.h" 52#include <csetjmp> 53#include <set> 54using namespace llvm; 55 56STATISTIC(NumInvokes, "Number of invokes replaced"); 57STATISTIC(NumUnwinds, "Number of unwinds replaced"); 58STATISTIC(NumSpilled, "Number of registers live across unwind edges"); 59 60static cl::opt<bool> ExpensiveEHSupport("enable-correct-eh-support", 61 cl::desc("Make the -lowerinvoke pass insert expensive, but correct, EH code")); 62 63namespace { 64 class LowerInvoke : public FunctionPass { 65 // Used for both models. 66 Constant *AbortFn; 67 68 // Used for expensive EH support. 69 const Type *JBLinkTy; 70 GlobalVariable *JBListHead; 71 Constant *SetJmpFn, *LongJmpFn, *StackSaveFn, *StackRestoreFn; 72 bool useExpensiveEHSupport; 73 74 // We peek in TLI to grab the target's jmp_buf size and alignment 75 const TargetLowering *TLI; 76 77 public: 78 static char ID; // Pass identification, replacement for typeid 79 explicit LowerInvoke(const TargetLowering *tli = NULL, 80 bool useExpensiveEHSupport = ExpensiveEHSupport) 81 : FunctionPass(ID), useExpensiveEHSupport(useExpensiveEHSupport), 82 TLI(tli) { } 83 bool doInitialization(Module &M); 84 bool runOnFunction(Function &F); 85 86 virtual void getAnalysisUsage(AnalysisUsage &AU) const { 87 // This is a cluster of orthogonal Transforms 88 AU.addPreserved("mem2reg"); 89 AU.addPreservedID(LowerSwitchID); 90 } 91 92 private: 93 bool insertCheapEHSupport(Function &F); 94 void splitLiveRangesLiveAcrossInvokes(SmallVectorImpl<InvokeInst*>&Invokes); 95 void rewriteExpensiveInvoke(InvokeInst *II, unsigned InvokeNo, 96 AllocaInst *InvokeNum, AllocaInst *StackPtr, 97 SwitchInst *CatchSwitch); 98 bool insertExpensiveEHSupport(Function &F); 99 }; 100} 101 102char LowerInvoke::ID = 0; 103INITIALIZE_PASS(LowerInvoke, "lowerinvoke", 104 "Lower invoke and unwind, for unwindless code generators", 105 false, false) 106 107char &llvm::LowerInvokePassID = LowerInvoke::ID; 108 109// Public Interface To the LowerInvoke pass. 110FunctionPass *llvm::createLowerInvokePass(const TargetLowering *TLI) { 111 return new LowerInvoke(TLI, ExpensiveEHSupport); 112} 113FunctionPass *llvm::createLowerInvokePass(const TargetLowering *TLI, 114 bool useExpensiveEHSupport) { 115 return new LowerInvoke(TLI, useExpensiveEHSupport); 116} 117 118// doInitialization - Make sure that there is a prototype for abort in the 119// current module. 120bool LowerInvoke::doInitialization(Module &M) { 121 const Type *VoidPtrTy = 122 Type::getInt8PtrTy(M.getContext()); 123 if (useExpensiveEHSupport) { 124 // Insert a type for the linked list of jump buffers. 125 unsigned JBSize = TLI ? TLI->getJumpBufSize() : 0; 126 JBSize = JBSize ? JBSize : 200; 127 const Type *JmpBufTy = ArrayType::get(VoidPtrTy, JBSize); 128 129 { // The type is recursive, so use a type holder. 130 std::vector<const Type*> Elements; 131 Elements.push_back(JmpBufTy); 132 OpaqueType *OT = OpaqueType::get(M.getContext()); 133 Elements.push_back(PointerType::getUnqual(OT)); 134 PATypeHolder JBLType(StructType::get(M.getContext(), Elements)); 135 OT->refineAbstractTypeTo(JBLType.get()); // Complete the cycle. 136 JBLinkTy = JBLType.get(); 137 M.addTypeName("llvm.sjljeh.jmpbufty", JBLinkTy); 138 } 139 140 const Type *PtrJBList = PointerType::getUnqual(JBLinkTy); 141 142 // Now that we've done that, insert the jmpbuf list head global, unless it 143 // already exists. 144 if (!(JBListHead = M.getGlobalVariable("llvm.sjljeh.jblist", PtrJBList))) { 145 JBListHead = new GlobalVariable(M, PtrJBList, false, 146 GlobalValue::LinkOnceAnyLinkage, 147 Constant::getNullValue(PtrJBList), 148 "llvm.sjljeh.jblist"); 149 } 150 151// VisualStudio defines setjmp as _setjmp 152#if defined(_MSC_VER) && defined(setjmp) && \ 153 !defined(setjmp_undefined_for_msvc) 154# pragma push_macro("setjmp") 155# undef setjmp 156# define setjmp_undefined_for_msvc 157#endif 158 159 SetJmpFn = Intrinsic::getDeclaration(&M, Intrinsic::setjmp); 160 161#if defined(_MSC_VER) && defined(setjmp_undefined_for_msvc) 162 // let's return it to _setjmp state 163# pragma pop_macro("setjmp") 164# undef setjmp_undefined_for_msvc 165#endif 166 167 LongJmpFn = Intrinsic::getDeclaration(&M, Intrinsic::longjmp); 168 StackSaveFn = Intrinsic::getDeclaration(&M, Intrinsic::stacksave); 169 StackRestoreFn = Intrinsic::getDeclaration(&M, Intrinsic::stackrestore); 170 } 171 172 // We need the 'write' and 'abort' functions for both models. 173 AbortFn = M.getOrInsertFunction("abort", Type::getVoidTy(M.getContext()), 174 (Type *)0); 175 return true; 176} 177 178bool LowerInvoke::insertCheapEHSupport(Function &F) { 179 bool Changed = false; 180 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) 181 if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator())) { 182 SmallVector<Value*,16> CallArgs(II->op_begin(), II->op_end() - 3); 183 // Insert a normal call instruction... 184 CallInst *NewCall = CallInst::Create(II->getCalledValue(), 185 CallArgs.begin(), CallArgs.end(), 186 "",II); 187 NewCall->takeName(II); 188 NewCall->setCallingConv(II->getCallingConv()); 189 NewCall->setAttributes(II->getAttributes()); 190 NewCall->setDebugLoc(II->getDebugLoc()); 191 II->replaceAllUsesWith(NewCall); 192 193 // Insert an unconditional branch to the normal destination. 194 BranchInst::Create(II->getNormalDest(), II); 195 196 // Remove any PHI node entries from the exception destination. 197 II->getUnwindDest()->removePredecessor(BB); 198 199 // Remove the invoke instruction now. 200 BB->getInstList().erase(II); 201 202 ++NumInvokes; Changed = true; 203 } else if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator())) { 204 // Insert a call to abort() 205 CallInst::Create(AbortFn, "", UI)->setTailCall(); 206 207 // Insert a return instruction. This really should be a "barrier", as it 208 // is unreachable. 209 ReturnInst::Create(F.getContext(), 210 F.getReturnType()->isVoidTy() ? 211 0 : Constant::getNullValue(F.getReturnType()), UI); 212 213 // Remove the unwind instruction now. 214 BB->getInstList().erase(UI); 215 216 ++NumUnwinds; Changed = true; 217 } 218 return Changed; 219} 220 221/// rewriteExpensiveInvoke - Insert code and hack the function to replace the 222/// specified invoke instruction with a call. 223void LowerInvoke::rewriteExpensiveInvoke(InvokeInst *II, unsigned InvokeNo, 224 AllocaInst *InvokeNum, 225 AllocaInst *StackPtr, 226 SwitchInst *CatchSwitch) { 227 ConstantInt *InvokeNoC = ConstantInt::get(Type::getInt32Ty(II->getContext()), 228 InvokeNo); 229 230 // If the unwind edge has phi nodes, split the edge. 231 if (isa<PHINode>(II->getUnwindDest()->begin())) { 232 SplitCriticalEdge(II, 1, this); 233 234 // If there are any phi nodes left, they must have a single predecessor. 235 while (PHINode *PN = dyn_cast<PHINode>(II->getUnwindDest()->begin())) { 236 PN->replaceAllUsesWith(PN->getIncomingValue(0)); 237 PN->eraseFromParent(); 238 } 239 } 240 241 // Insert a store of the invoke num before the invoke and store zero into the 242 // location afterward. 243 new StoreInst(InvokeNoC, InvokeNum, true, II); // volatile 244 245 // Insert a store of the stack ptr before the invoke, so we can restore it 246 // later in the exception case. 247 CallInst* StackSaveRet = CallInst::Create(StackSaveFn, "ssret", II); 248 new StoreInst(StackSaveRet, StackPtr, true, II); // volatile 249 250 BasicBlock::iterator NI = II->getNormalDest()->getFirstNonPHI(); 251 // nonvolatile. 252 new StoreInst(Constant::getNullValue(Type::getInt32Ty(II->getContext())), 253 InvokeNum, false, NI); 254 255 Instruction* StackPtrLoad = new LoadInst(StackPtr, "stackptr.restore", true, 256 II->getUnwindDest()->getFirstNonPHI() 257 ); 258 CallInst::Create(StackRestoreFn, StackPtrLoad, "")->insertAfter(StackPtrLoad); 259 260 // Add a switch case to our unwind block. 261 CatchSwitch->addCase(InvokeNoC, II->getUnwindDest()); 262 263 // Insert a normal call instruction. 264 SmallVector<Value*,16> CallArgs(II->op_begin(), II->op_end() - 3); 265 CallInst *NewCall = CallInst::Create(II->getCalledValue(), 266 CallArgs.begin(), CallArgs.end(), "", 267 II); 268 NewCall->takeName(II); 269 NewCall->setCallingConv(II->getCallingConv()); 270 NewCall->setAttributes(II->getAttributes()); 271 NewCall->setDebugLoc(II->getDebugLoc()); 272 II->replaceAllUsesWith(NewCall); 273 274 // Replace the invoke with an uncond branch. 275 BranchInst::Create(II->getNormalDest(), NewCall->getParent()); 276 II->eraseFromParent(); 277} 278 279/// MarkBlocksLiveIn - Insert BB and all of its predescessors into LiveBBs until 280/// we reach blocks we've already seen. 281static void MarkBlocksLiveIn(BasicBlock *BB, std::set<BasicBlock*> &LiveBBs) { 282 if (!LiveBBs.insert(BB).second) return; // already been here. 283 284 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) 285 MarkBlocksLiveIn(*PI, LiveBBs); 286} 287 288// First thing we need to do is scan the whole function for values that are 289// live across unwind edges. Each value that is live across an unwind edge 290// we spill into a stack location, guaranteeing that there is nothing live 291// across the unwind edge. This process also splits all critical edges 292// coming out of invoke's. 293void LowerInvoke:: 294splitLiveRangesLiveAcrossInvokes(SmallVectorImpl<InvokeInst*> &Invokes) { 295 // First step, split all critical edges from invoke instructions. 296 for (unsigned i = 0, e = Invokes.size(); i != e; ++i) { 297 InvokeInst *II = Invokes[i]; 298 SplitCriticalEdge(II, 0, this); 299 SplitCriticalEdge(II, 1, this); 300 assert(!isa<PHINode>(II->getNormalDest()) && 301 !isa<PHINode>(II->getUnwindDest()) && 302 "critical edge splitting left single entry phi nodes?"); 303 } 304 305 Function *F = Invokes.back()->getParent()->getParent(); 306 307 // To avoid having to handle incoming arguments specially, we lower each arg 308 // to a copy instruction in the entry block. This ensures that the argument 309 // value itself cannot be live across the entry block. 310 BasicBlock::iterator AfterAllocaInsertPt = F->begin()->begin(); 311 while (isa<AllocaInst>(AfterAllocaInsertPt) && 312 isa<ConstantInt>(cast<AllocaInst>(AfterAllocaInsertPt)->getArraySize())) 313 ++AfterAllocaInsertPt; 314 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); 315 AI != E; ++AI) { 316 const Type *Ty = AI->getType(); 317 // Aggregate types can't be cast, but are legal argument types, so we have 318 // to handle them differently. We use an extract/insert pair as a 319 // lightweight method to achieve the same goal. 320 if (isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<VectorType>(Ty)) { 321 Instruction *EI = ExtractValueInst::Create(AI, 0, "",AfterAllocaInsertPt); 322 Instruction *NI = InsertValueInst::Create(AI, EI, 0); 323 NI->insertAfter(EI); 324 AI->replaceAllUsesWith(NI); 325 // Set the operand of the instructions back to the AllocaInst. 326 EI->setOperand(0, AI); 327 NI->setOperand(0, AI); 328 } else { 329 // This is always a no-op cast because we're casting AI to AI->getType() 330 // so src and destination types are identical. BitCast is the only 331 // possibility. 332 CastInst *NC = new BitCastInst( 333 AI, AI->getType(), AI->getName()+".tmp", AfterAllocaInsertPt); 334 AI->replaceAllUsesWith(NC); 335 // Set the operand of the cast instruction back to the AllocaInst. 336 // Normally it's forbidden to replace a CastInst's operand because it 337 // could cause the opcode to reflect an illegal conversion. However, 338 // we're replacing it here with the same value it was constructed with. 339 // We do this because the above replaceAllUsesWith() clobbered the 340 // operand, but we want this one to remain. 341 NC->setOperand(0, AI); 342 } 343 } 344 345 // Finally, scan the code looking for instructions with bad live ranges. 346 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) 347 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; ++II) { 348 // Ignore obvious cases we don't have to handle. In particular, most 349 // instructions either have no uses or only have a single use inside the 350 // current block. Ignore them quickly. 351 Instruction *Inst = II; 352 if (Inst->use_empty()) continue; 353 if (Inst->hasOneUse() && 354 cast<Instruction>(Inst->use_back())->getParent() == BB && 355 !isa<PHINode>(Inst->use_back())) continue; 356 357 // If this is an alloca in the entry block, it's not a real register 358 // value. 359 if (AllocaInst *AI = dyn_cast<AllocaInst>(Inst)) 360 if (isa<ConstantInt>(AI->getArraySize()) && BB == F->begin()) 361 continue; 362 363 // Avoid iterator invalidation by copying users to a temporary vector. 364 SmallVector<Instruction*,16> Users; 365 for (Value::use_iterator UI = Inst->use_begin(), E = Inst->use_end(); 366 UI != E; ++UI) { 367 Instruction *User = cast<Instruction>(*UI); 368 if (User->getParent() != BB || isa<PHINode>(User)) 369 Users.push_back(User); 370 } 371 372 // Scan all of the uses and see if the live range is live across an unwind 373 // edge. If we find a use live across an invoke edge, create an alloca 374 // and spill the value. 375 std::set<InvokeInst*> InvokesWithStoreInserted; 376 377 // Find all of the blocks that this value is live in. 378 std::set<BasicBlock*> LiveBBs; 379 LiveBBs.insert(Inst->getParent()); 380 while (!Users.empty()) { 381 Instruction *U = Users.back(); 382 Users.pop_back(); 383 384 if (!isa<PHINode>(U)) { 385 MarkBlocksLiveIn(U->getParent(), LiveBBs); 386 } else { 387 // Uses for a PHI node occur in their predecessor block. 388 PHINode *PN = cast<PHINode>(U); 389 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 390 if (PN->getIncomingValue(i) == Inst) 391 MarkBlocksLiveIn(PN->getIncomingBlock(i), LiveBBs); 392 } 393 } 394 395 // Now that we know all of the blocks that this thing is live in, see if 396 // it includes any of the unwind locations. 397 bool NeedsSpill = false; 398 for (unsigned i = 0, e = Invokes.size(); i != e; ++i) { 399 BasicBlock *UnwindBlock = Invokes[i]->getUnwindDest(); 400 if (UnwindBlock != BB && LiveBBs.count(UnwindBlock)) { 401 NeedsSpill = true; 402 } 403 } 404 405 // If we decided we need a spill, do it. 406 if (NeedsSpill) { 407 ++NumSpilled; 408 DemoteRegToStack(*Inst, true); 409 } 410 } 411} 412 413bool LowerInvoke::insertExpensiveEHSupport(Function &F) { 414 SmallVector<ReturnInst*,16> Returns; 415 SmallVector<UnwindInst*,16> Unwinds; 416 SmallVector<InvokeInst*,16> Invokes; 417 418 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) 419 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) { 420 // Remember all return instructions in case we insert an invoke into this 421 // function. 422 Returns.push_back(RI); 423 } else if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator())) { 424 Invokes.push_back(II); 425 } else if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator())) { 426 Unwinds.push_back(UI); 427 } 428 429 if (Unwinds.empty() && Invokes.empty()) return false; 430 431 NumInvokes += Invokes.size(); 432 NumUnwinds += Unwinds.size(); 433 434 // TODO: This is not an optimal way to do this. In particular, this always 435 // inserts setjmp calls into the entries of functions with invoke instructions 436 // even though there are possibly paths through the function that do not 437 // execute any invokes. In particular, for functions with early exits, e.g. 438 // the 'addMove' method in hexxagon, it would be nice to not have to do the 439 // setjmp stuff on the early exit path. This requires a bit of dataflow, but 440 // would not be too hard to do. 441 442 // If we have an invoke instruction, insert a setjmp that dominates all 443 // invokes. After the setjmp, use a cond branch that goes to the original 444 // code path on zero, and to a designated 'catch' block of nonzero. 445 Value *OldJmpBufPtr = 0; 446 if (!Invokes.empty()) { 447 // First thing we need to do is scan the whole function for values that are 448 // live across unwind edges. Each value that is live across an unwind edge 449 // we spill into a stack location, guaranteeing that there is nothing live 450 // across the unwind edge. This process also splits all critical edges 451 // coming out of invoke's. 452 splitLiveRangesLiveAcrossInvokes(Invokes); 453 454 BasicBlock *EntryBB = F.begin(); 455 456 // Create an alloca for the incoming jump buffer ptr and the new jump buffer 457 // that needs to be restored on all exits from the function. This is an 458 // alloca because the value needs to be live across invokes. 459 unsigned Align = TLI ? TLI->getJumpBufAlignment() : 0; 460 AllocaInst *JmpBuf = 461 new AllocaInst(JBLinkTy, 0, Align, 462 "jblink", F.begin()->begin()); 463 464 Value *Idx[] = { Constant::getNullValue(Type::getInt32Ty(F.getContext())), 465 ConstantInt::get(Type::getInt32Ty(F.getContext()), 1) }; 466 OldJmpBufPtr = GetElementPtrInst::Create(JmpBuf, &Idx[0], &Idx[2], 467 "OldBuf", 468 EntryBB->getTerminator()); 469 470 // Copy the JBListHead to the alloca. 471 Value *OldBuf = new LoadInst(JBListHead, "oldjmpbufptr", true, 472 EntryBB->getTerminator()); 473 new StoreInst(OldBuf, OldJmpBufPtr, true, EntryBB->getTerminator()); 474 475 // Add the new jumpbuf to the list. 476 new StoreInst(JmpBuf, JBListHead, true, EntryBB->getTerminator()); 477 478 // Create the catch block. The catch block is basically a big switch 479 // statement that goes to all of the invoke catch blocks. 480 BasicBlock *CatchBB = 481 BasicBlock::Create(F.getContext(), "setjmp.catch", &F); 482 483 // Create an alloca which keeps track of the stack pointer before every 484 // invoke, this allows us to properly restore the stack pointer after 485 // long jumping. 486 AllocaInst *StackPtr = new AllocaInst(Type::getInt8PtrTy(F.getContext()), 0, 487 "stackptr", EntryBB->begin()); 488 489 // Create an alloca which keeps track of which invoke is currently 490 // executing. For normal calls it contains zero. 491 AllocaInst *InvokeNum = new AllocaInst(Type::getInt32Ty(F.getContext()), 0, 492 "invokenum",EntryBB->begin()); 493 new StoreInst(ConstantInt::get(Type::getInt32Ty(F.getContext()), 0), 494 InvokeNum, true, EntryBB->getTerminator()); 495 496 // Insert a load in the Catch block, and a switch on its value. By default, 497 // we go to a block that just does an unwind (which is the correct action 498 // for a standard call). 499 BasicBlock *UnwindBB = BasicBlock::Create(F.getContext(), "unwindbb", &F); 500 Unwinds.push_back(new UnwindInst(F.getContext(), UnwindBB)); 501 502 Value *CatchLoad = new LoadInst(InvokeNum, "invoke.num", true, CatchBB); 503 SwitchInst *CatchSwitch = 504 SwitchInst::Create(CatchLoad, UnwindBB, Invokes.size(), CatchBB); 505 506 // Now that things are set up, insert the setjmp call itself. 507 508 // Split the entry block to insert the conditional branch for the setjmp. 509 BasicBlock *ContBlock = EntryBB->splitBasicBlock(EntryBB->getTerminator(), 510 "setjmp.cont"); 511 512 Idx[1] = ConstantInt::get(Type::getInt32Ty(F.getContext()), 0); 513 Value *JmpBufPtr = GetElementPtrInst::Create(JmpBuf, &Idx[0], &Idx[2], 514 "TheJmpBuf", 515 EntryBB->getTerminator()); 516 JmpBufPtr = new BitCastInst(JmpBufPtr, 517 Type::getInt8PtrTy(F.getContext()), 518 "tmp", EntryBB->getTerminator()); 519 Value *SJRet = CallInst::Create(SetJmpFn, JmpBufPtr, "sjret", 520 EntryBB->getTerminator()); 521 522 // Compare the return value to zero. 523 Value *IsNormal = new ICmpInst(EntryBB->getTerminator(), 524 ICmpInst::ICMP_EQ, SJRet, 525 Constant::getNullValue(SJRet->getType()), 526 "notunwind"); 527 // Nuke the uncond branch. 528 EntryBB->getTerminator()->eraseFromParent(); 529 530 // Put in a new condbranch in its place. 531 BranchInst::Create(ContBlock, CatchBB, IsNormal, EntryBB); 532 533 // At this point, we are all set up, rewrite each invoke instruction. 534 for (unsigned i = 0, e = Invokes.size(); i != e; ++i) 535 rewriteExpensiveInvoke(Invokes[i], i+1, InvokeNum, StackPtr, CatchSwitch); 536 } 537 538 // We know that there is at least one unwind. 539 540 // Create three new blocks, the block to load the jmpbuf ptr and compare 541 // against null, the block to do the longjmp, and the error block for if it 542 // is null. Add them at the end of the function because they are not hot. 543 BasicBlock *UnwindHandler = BasicBlock::Create(F.getContext(), 544 "dounwind", &F); 545 BasicBlock *UnwindBlock = BasicBlock::Create(F.getContext(), "unwind", &F); 546 BasicBlock *TermBlock = BasicBlock::Create(F.getContext(), "unwinderror", &F); 547 548 // If this function contains an invoke, restore the old jumpbuf ptr. 549 Value *BufPtr; 550 if (OldJmpBufPtr) { 551 // Before the return, insert a copy from the saved value to the new value. 552 BufPtr = new LoadInst(OldJmpBufPtr, "oldjmpbufptr", UnwindHandler); 553 new StoreInst(BufPtr, JBListHead, UnwindHandler); 554 } else { 555 BufPtr = new LoadInst(JBListHead, "ehlist", UnwindHandler); 556 } 557 558 // Load the JBList, if it's null, then there was no catch! 559 Value *NotNull = new ICmpInst(*UnwindHandler, ICmpInst::ICMP_NE, BufPtr, 560 Constant::getNullValue(BufPtr->getType()), 561 "notnull"); 562 BranchInst::Create(UnwindBlock, TermBlock, NotNull, UnwindHandler); 563 564 // Create the block to do the longjmp. 565 // Get a pointer to the jmpbuf and longjmp. 566 Value *Idx[] = { Constant::getNullValue(Type::getInt32Ty(F.getContext())), 567 ConstantInt::get(Type::getInt32Ty(F.getContext()), 0) }; 568 Idx[0] = GetElementPtrInst::Create(BufPtr, &Idx[0], &Idx[2], "JmpBuf", 569 UnwindBlock); 570 Idx[0] = new BitCastInst(Idx[0], 571 Type::getInt8PtrTy(F.getContext()), 572 "tmp", UnwindBlock); 573 Idx[1] = ConstantInt::get(Type::getInt32Ty(F.getContext()), 1); 574 CallInst::Create(LongJmpFn, &Idx[0], &Idx[2], "", UnwindBlock); 575 new UnreachableInst(F.getContext(), UnwindBlock); 576 577 // Set up the term block ("throw without a catch"). 578 new UnreachableInst(F.getContext(), TermBlock); 579 580 // Insert a call to abort() 581 CallInst::Create(AbortFn, "", 582 TermBlock->getTerminator())->setTailCall(); 583 584 585 // Replace all unwinds with a branch to the unwind handler. 586 for (unsigned i = 0, e = Unwinds.size(); i != e; ++i) { 587 BranchInst::Create(UnwindHandler, Unwinds[i]); 588 Unwinds[i]->eraseFromParent(); 589 } 590 591 // Finally, for any returns from this function, if this function contains an 592 // invoke, restore the old jmpbuf pointer to its input value. 593 if (OldJmpBufPtr) { 594 for (unsigned i = 0, e = Returns.size(); i != e; ++i) { 595 ReturnInst *R = Returns[i]; 596 597 // Before the return, insert a copy from the saved value to the new value. 598 Value *OldBuf = new LoadInst(OldJmpBufPtr, "oldjmpbufptr", true, R); 599 new StoreInst(OldBuf, JBListHead, true, R); 600 } 601 } 602 603 return true; 604} 605 606bool LowerInvoke::runOnFunction(Function &F) { 607 if (useExpensiveEHSupport) 608 return insertExpensiveEHSupport(F); 609 else 610 return insertCheapEHSupport(F); 611} 612