LowerInvoke.cpp 25 KB

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