1 //===- SjLjEHPass.cpp - Eliminate Invoke & Unwind instructions -----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This transformation is designed for use by code generators which use SjLj
11 // based exception handling.
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "sjljehprepare"
16 #include "llvm/Transforms/Scalar.h"
17 #include "llvm/Constants.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/Intrinsics.h"
21 #include "llvm/LLVMContext.h"
22 #include "llvm/Module.h"
23 #include "llvm/Pass.h"
24 #include "llvm/CodeGen/Passes.h"
25 #include "llvm/Target/TargetData.h"
26 #include "llvm/Target/TargetLowering.h"
27 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
28 #include "llvm/Transforms/Utils/Local.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/IRBuilder.h"
32 #include "llvm/ADT/DenseMap.h"
33 #include "llvm/ADT/SmallVector.h"
34 #include "llvm/ADT/Statistic.h"
38 static cl::opt<bool> DisableOldSjLjEH("disable-old-sjlj-eh", cl::Hidden,
39 cl::desc("Disable the old SjLj EH preparation pass"));
41 STATISTIC(NumInvokes, "Number of invokes replaced");
42 STATISTIC(NumUnwinds, "Number of unwinds replaced");
43 STATISTIC(NumSpilled, "Number of registers live across unwind edges");
46 class SjLjEHPass : public FunctionPass {
47 const TargetLowering *TLI;
48 Type *FunctionContextTy;
50 Constant *UnregisterFn;
51 Constant *BuiltinSetjmpFn;
52 Constant *FrameAddrFn;
53 Constant *StackAddrFn;
54 Constant *StackRestoreFn;
58 Constant *ExceptionFn;
60 Constant *DispatchSetupFn;
63 DenseMap<InvokeInst*, BasicBlock*> LPadSuccMap;
65 static char ID; // Pass identification, replacement for typeid
66 explicit SjLjEHPass(const TargetLowering *tli = NULL)
67 : FunctionPass(ID), TLI(tli) { }
68 bool doInitialization(Module &M);
69 bool runOnFunction(Function &F);
71 virtual void getAnalysisUsage(AnalysisUsage &AU) const {}
72 const char *getPassName() const {
73 return "SJLJ Exception Handling preparation";
77 bool setupEntryBlockAndCallSites(Function &F);
78 Value *setupFunctionContext(Function &F, ArrayRef<LandingPadInst*> LPads);
80 void insertCallSiteStore(Instruction *I, int Number, Value *CallSite);
81 void markInvokeCallSite(InvokeInst *II, int InvokeNo, Value *CallSite,
82 SwitchInst *CatchSwitch);
83 void splitLiveRangesAcrossInvokes(SmallVector<InvokeInst*,16> &Invokes);
84 void splitLandingPad(InvokeInst *II);
85 bool insertSjLjEHSupport(Function &F);
87 } // end anonymous namespace
89 char SjLjEHPass::ID = 0;
91 // Public Interface To the SjLjEHPass pass.
92 FunctionPass *llvm::createSjLjEHPass(const TargetLowering *TLI) {
93 return new SjLjEHPass(TLI);
95 // doInitialization - Set up decalarations and types needed to process
97 bool SjLjEHPass::doInitialization(Module &M) {
98 // Build the function context structure.
99 // builtin_setjmp uses a five word jbuf
100 Type *VoidPtrTy = Type::getInt8PtrTy(M.getContext());
101 Type *Int32Ty = Type::getInt32Ty(M.getContext());
103 StructType::get(VoidPtrTy, // __prev
104 Int32Ty, // call_site
105 ArrayType::get(Int32Ty, 4), // __data
106 VoidPtrTy, // __personality
108 ArrayType::get(VoidPtrTy, 5), // __jbuf
110 RegisterFn = M.getOrInsertFunction("_Unwind_SjLj_Register",
111 Type::getVoidTy(M.getContext()),
112 PointerType::getUnqual(FunctionContextTy),
115 M.getOrInsertFunction("_Unwind_SjLj_Unregister",
116 Type::getVoidTy(M.getContext()),
117 PointerType::getUnqual(FunctionContextTy),
119 FrameAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::frameaddress);
120 StackAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::stacksave);
121 StackRestoreFn = Intrinsic::getDeclaration(&M, Intrinsic::stackrestore);
122 BuiltinSetjmpFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_setjmp);
123 LSDAAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_lsda);
124 SelectorFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_selector);
125 ExceptionFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_exception);
126 CallSiteFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_callsite);
128 = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_dispatch_setup);
129 FuncCtxFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_functioncontext);
135 /// insertCallSiteStore - Insert a store of the call-site value to the
137 void SjLjEHPass::insertCallSiteStore(Instruction *I, int Number,
139 ConstantInt *CallSiteNoC = ConstantInt::get(Type::getInt32Ty(I->getContext()),
141 // Insert a store of the call-site number
142 new StoreInst(CallSiteNoC, CallSite, true, I); // volatile
145 /// splitLandingPad - Split a landing pad. This takes considerable care because
146 /// of PHIs and other nasties. The problem is that the jump table needs to jump
147 /// to the landing pad block. However, the landing pad block can be jumped to
148 /// only by an invoke instruction. So we clone the landingpad instruction into
149 /// its own basic block, have the invoke jump to there. The landingpad
150 /// instruction's basic block's successor is now the target for the jump table.
152 /// But because of PHI nodes, we need to create another basic block for the jump
153 /// table to jump to. This is definitely a hack, because the values for the PHI
154 /// nodes may not be defined on the edge from the jump table. But that's okay,
155 /// because the jump table is simply a construct to mimic what is happening in
156 /// the CFG. So the values are mysteriously there, even though there is no value
157 /// for the PHI from the jump table's edge (hence calling this a hack).
158 void SjLjEHPass::splitLandingPad(InvokeInst *II) {
159 SmallVector<BasicBlock*, 2> NewBBs;
160 SplitLandingPadPredecessors(II->getUnwindDest(), II->getParent(),
161 ".1", ".2", this, NewBBs);
163 // Create an empty block so that the jump table has something to jump to
164 // which doesn't have any PHI nodes.
165 BasicBlock *LPad = NewBBs[0];
166 BasicBlock *Succ = *succ_begin(LPad);
167 BasicBlock *JumpTo = BasicBlock::Create(II->getContext(), "jt.land",
168 LPad->getParent(), Succ);
169 LPad->getTerminator()->eraseFromParent();
170 BranchInst::Create(JumpTo, LPad);
171 BranchInst::Create(Succ, JumpTo);
172 LPadSuccMap[II] = JumpTo;
174 for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
175 PHINode *PN = cast<PHINode>(I);
176 Value *Val = PN->removeIncomingValue(LPad, false);
177 PN->addIncoming(Val, JumpTo);
181 /// markInvokeCallSite - Insert code to mark the call_site for this invoke
182 void SjLjEHPass::markInvokeCallSite(InvokeInst *II, int InvokeNo,
184 SwitchInst *CatchSwitch) {
185 ConstantInt *CallSiteNoC= ConstantInt::get(Type::getInt32Ty(II->getContext()),
187 // The runtime comes back to the dispatcher with the call_site - 1 in
188 // the context. Odd, but there it is.
189 ConstantInt *SwitchValC = ConstantInt::get(Type::getInt32Ty(II->getContext()),
192 // If the unwind edge has phi nodes, split the edge.
193 if (isa<PHINode>(II->getUnwindDest()->begin())) {
194 // FIXME: New EH - This if-condition will be always true in the new scheme.
195 if (II->getUnwindDest()->isLandingPad())
198 SplitCriticalEdge(II, 1, this);
200 // If there are any phi nodes left, they must have a single predecessor.
201 while (PHINode *PN = dyn_cast<PHINode>(II->getUnwindDest()->begin())) {
202 PN->replaceAllUsesWith(PN->getIncomingValue(0));
203 PN->eraseFromParent();
207 // Insert the store of the call site value
208 insertCallSiteStore(II, InvokeNo, CallSite);
210 // Record the call site value for the back end so it stays associated with
212 CallInst::Create(CallSiteFn, CallSiteNoC, "", II);
214 // Add a switch case to our unwind block.
215 if (BasicBlock *SuccBB = LPadSuccMap[II]) {
216 CatchSwitch->addCase(SwitchValC, SuccBB);
218 CatchSwitch->addCase(SwitchValC, II->getUnwindDest());
221 // We still want this to look like an invoke so we emit the LSDA properly,
222 // so we don't transform the invoke into a call here.
225 /// MarkBlocksLiveIn - Insert BB and all of its predescessors into LiveBBs until
226 /// we reach blocks we've already seen.
227 static void MarkBlocksLiveIn(BasicBlock *BB, std::set<BasicBlock*> &LiveBBs) {
228 if (!LiveBBs.insert(BB).second) return; // already been here.
230 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
231 MarkBlocksLiveIn(*PI, LiveBBs);
234 /// splitLiveRangesAcrossInvokes - Each value that is live across an unwind edge
235 /// we spill into a stack location, guaranteeing that there is nothing live
236 /// across the unwind edge. This process also splits all critical edges
237 /// coming out of invoke's.
238 /// FIXME: Move this function to a common utility file (Local.cpp?) so
239 /// both SjLj and LowerInvoke can use it.
241 splitLiveRangesAcrossInvokes(SmallVector<InvokeInst*,16> &Invokes) {
242 // First step, split all critical edges from invoke instructions.
243 for (unsigned i = 0, e = Invokes.size(); i != e; ++i) {
244 InvokeInst *II = Invokes[i];
245 SplitCriticalEdge(II, 0, this);
247 // FIXME: New EH - This if-condition will be always true in the new scheme.
248 if (II->getUnwindDest()->isLandingPad())
251 SplitCriticalEdge(II, 1, this);
253 assert(!isa<PHINode>(II->getNormalDest()) &&
254 !isa<PHINode>(II->getUnwindDest()) &&
255 "Critical edge splitting left single entry phi nodes?");
258 Function *F = Invokes.back()->getParent()->getParent();
260 // To avoid having to handle incoming arguments specially, we lower each arg
261 // to a copy instruction in the entry block. This ensures that the argument
262 // value itself cannot be live across the entry block.
263 BasicBlock::iterator AfterAllocaInsertPt = F->begin()->begin();
264 while (isa<AllocaInst>(AfterAllocaInsertPt) &&
265 isa<ConstantInt>(cast<AllocaInst>(AfterAllocaInsertPt)->getArraySize()))
266 ++AfterAllocaInsertPt;
267 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
269 Type *Ty = AI->getType();
270 // Aggregate types can't be cast, but are legal argument types, so we have
271 // to handle them differently. We use an extract/insert pair as a
272 // lightweight method to achieve the same goal.
273 if (isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<VectorType>(Ty)) {
274 Instruction *EI = ExtractValueInst::Create(AI, 0, "",AfterAllocaInsertPt);
275 Instruction *NI = InsertValueInst::Create(AI, EI, 0);
277 AI->replaceAllUsesWith(NI);
278 // Set the operand of the instructions back to the AllocaInst.
279 EI->setOperand(0, AI);
280 NI->setOperand(0, AI);
282 // This is always a no-op cast because we're casting AI to AI->getType()
283 // so src and destination types are identical. BitCast is the only
285 CastInst *NC = new BitCastInst(
286 AI, AI->getType(), AI->getName()+".tmp", AfterAllocaInsertPt);
287 AI->replaceAllUsesWith(NC);
288 // Set the operand of the cast instruction back to the AllocaInst.
289 // Normally it's forbidden to replace a CastInst's operand because it
290 // could cause the opcode to reflect an illegal conversion. However,
291 // we're replacing it here with the same value it was constructed with.
292 // We do this because the above replaceAllUsesWith() clobbered the
293 // operand, but we want this one to remain.
294 NC->setOperand(0, AI);
298 // Finally, scan the code looking for instructions with bad live ranges.
299 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
300 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; ++II) {
301 // Ignore obvious cases we don't have to handle. In particular, most
302 // instructions either have no uses or only have a single use inside the
303 // current block. Ignore them quickly.
304 Instruction *Inst = II;
305 if (Inst->use_empty()) continue;
306 if (Inst->hasOneUse() &&
307 cast<Instruction>(Inst->use_back())->getParent() == BB &&
308 !isa<PHINode>(Inst->use_back())) continue;
310 // If this is an alloca in the entry block, it's not a real register
312 if (AllocaInst *AI = dyn_cast<AllocaInst>(Inst))
313 if (isa<ConstantInt>(AI->getArraySize()) && BB == F->begin())
316 // Avoid iterator invalidation by copying users to a temporary vector.
317 SmallVector<Instruction*,16> Users;
318 for (Value::use_iterator UI = Inst->use_begin(), E = Inst->use_end();
320 Instruction *User = cast<Instruction>(*UI);
321 if (User->getParent() != BB || isa<PHINode>(User))
322 Users.push_back(User);
325 // Find all of the blocks that this value is live in.
326 std::set<BasicBlock*> LiveBBs;
327 LiveBBs.insert(Inst->getParent());
328 while (!Users.empty()) {
329 Instruction *U = Users.back();
332 if (!isa<PHINode>(U)) {
333 MarkBlocksLiveIn(U->getParent(), LiveBBs);
335 // Uses for a PHI node occur in their predecessor block.
336 PHINode *PN = cast<PHINode>(U);
337 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
338 if (PN->getIncomingValue(i) == Inst)
339 MarkBlocksLiveIn(PN->getIncomingBlock(i), LiveBBs);
343 // Now that we know all of the blocks that this thing is live in, see if
344 // it includes any of the unwind locations.
345 bool NeedsSpill = false;
346 for (unsigned i = 0, e = Invokes.size(); i != e; ++i) {
347 BasicBlock *UnwindBlock = Invokes[i]->getUnwindDest();
348 if (UnwindBlock != BB && LiveBBs.count(UnwindBlock)) {
353 // If we decided we need a spill, do it.
354 // FIXME: Spilling this way is overkill, as it forces all uses of
355 // the value to be reloaded from the stack slot, even those that aren't
356 // in the unwind blocks. We should be more selective.
359 DemoteRegToStack(*Inst, true);
364 /// CreateLandingPadLoad - Load the exception handling values and insert them
365 /// into a structure.
366 static Instruction *CreateLandingPadLoad(Function &F, Value *ExnAddr,
368 BasicBlock::iterator InsertPt) {
369 Value *Exn = new LoadInst(ExnAddr, "exn", false,
371 Type *Ty = Type::getInt8PtrTy(F.getContext());
372 Exn = CastInst::Create(Instruction::IntToPtr, Exn, Ty, "", InsertPt);
373 Value *Sel = new LoadInst(SelAddr, "sel", false, InsertPt);
375 Ty = StructType::get(Exn->getType(), Sel->getType(), NULL);
376 InsertValueInst *LPadVal = InsertValueInst::Create(llvm::UndefValue::get(Ty),
378 "lpad.val", InsertPt);
379 return InsertValueInst::Create(LPadVal, Sel, 1, "lpad.val", InsertPt);
382 /// ReplaceLandingPadVal - Replace the landingpad instruction's value with a
383 /// load from the stored values (via CreateLandingPadLoad). This looks through
384 /// PHI nodes, and removes them if they are dead.
385 static void ReplaceLandingPadVal(Function &F, Instruction *Inst, Value *ExnAddr,
387 if (Inst->use_empty()) return;
389 while (!Inst->use_empty()) {
390 Instruction *I = cast<Instruction>(Inst->use_back());
392 if (PHINode *PN = dyn_cast<PHINode>(I)) {
393 ReplaceLandingPadVal(F, PN, ExnAddr, SelAddr);
394 if (PN->use_empty()) PN->eraseFromParent();
398 I->replaceUsesOfWith(Inst, CreateLandingPadLoad(F, ExnAddr, SelAddr, I));
402 bool SjLjEHPass::insertSjLjEHSupport(Function &F) {
403 SmallVector<ReturnInst*,16> Returns;
404 SmallVector<UnwindInst*,16> Unwinds;
405 SmallVector<InvokeInst*,16> Invokes;
407 // Look through the terminators of the basic blocks to find invokes, returns
409 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
410 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
411 // Remember all return instructions in case we insert an invoke into this
413 Returns.push_back(RI);
414 } else if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
415 Invokes.push_back(II);
416 } else if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator())) {
417 Unwinds.push_back(UI);
421 NumInvokes += Invokes.size();
422 NumUnwinds += Unwinds.size();
424 // If we don't have any invokes, there's nothing to do.
425 if (Invokes.empty()) return false;
427 // Find the eh.selector.*, eh.exception and alloca calls.
429 // Remember any allocas() that aren't in the entry block, as the
430 // jmpbuf saved SP will need to be updated for them.
432 // We'll use the first eh.selector to determine the right personality
433 // function to use. For SJLJ, we always use the same personality for the
434 // whole function, not on a per-selector basis.
435 // FIXME: That's a bit ugly. Better way?
436 SmallVector<CallInst*,16> EH_Selectors;
437 SmallVector<CallInst*,16> EH_Exceptions;
438 SmallVector<Instruction*,16> JmpbufUpdatePoints;
440 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
441 // Note: Skip the entry block since there's nothing there that interests
442 // us. eh.selector and eh.exception shouldn't ever be there, and we
443 // want to disregard any allocas that are there.
445 // FIXME: This is awkward. The new EH scheme won't need to skip the entry
447 if (BB == F.begin()) {
448 if (InvokeInst *II = dyn_cast<InvokeInst>(F.begin()->getTerminator())) {
449 // FIXME: This will be always non-NULL in the new EH.
450 if (LandingPadInst *LPI = II->getUnwindDest()->getLandingPadInst())
451 if (!PersonalityFn) PersonalityFn = LPI->getPersonalityFn();
457 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
458 if (CallInst *CI = dyn_cast<CallInst>(I)) {
459 if (CI->getCalledFunction() == SelectorFn) {
460 if (!PersonalityFn) PersonalityFn = CI->getArgOperand(1);
461 EH_Selectors.push_back(CI);
462 } else if (CI->getCalledFunction() == ExceptionFn) {
463 EH_Exceptions.push_back(CI);
464 } else if (CI->getCalledFunction() == StackRestoreFn) {
465 JmpbufUpdatePoints.push_back(CI);
467 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) {
468 JmpbufUpdatePoints.push_back(AI);
469 } else if (InvokeInst *II = dyn_cast<InvokeInst>(I)) {
470 // FIXME: This will be always non-NULL in the new EH.
471 if (LandingPadInst *LPI = II->getUnwindDest()->getLandingPadInst())
472 if (!PersonalityFn) PersonalityFn = LPI->getPersonalityFn();
477 // If we don't have any eh.selector calls, we can't determine the personality
478 // function. Without a personality function, we can't process exceptions.
479 if (!PersonalityFn) return false;
481 // We have invokes, so we need to add register/unregister calls to get this
482 // function onto the global unwind stack.
484 // First thing we need to do is scan the whole function for values that are
485 // live across unwind edges. Each value that is live across an unwind edge we
486 // spill into a stack location, guaranteeing that there is nothing live across
487 // the unwind edge. This process also splits all critical edges coming out of
489 splitLiveRangesAcrossInvokes(Invokes);
492 SmallVector<LandingPadInst*, 16> LandingPads;
493 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
494 if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator()))
495 // FIXME: This will be always non-NULL in the new EH.
496 if (LandingPadInst *LPI = II->getUnwindDest()->getLandingPadInst())
497 LandingPads.push_back(LPI);
501 BasicBlock *EntryBB = F.begin();
502 // Create an alloca for the incoming jump buffer ptr and the new jump buffer
503 // that needs to be restored on all exits from the function. This is an
504 // alloca because the value needs to be added to the global context list.
505 unsigned Align = 4; // FIXME: Should be a TLI check?
506 AllocaInst *FunctionContext =
507 new AllocaInst(FunctionContextTy, 0, Align,
508 "fcn_context", F.begin()->begin());
511 Type *Int32Ty = Type::getInt32Ty(F.getContext());
512 Value *Zero = ConstantInt::get(Int32Ty, 0);
513 // We need to also keep around a reference to the call_site field
515 Idxs[1] = ConstantInt::get(Int32Ty, 1);
516 CallSite = GetElementPtrInst::Create(FunctionContext, Idxs, "call_site",
517 EntryBB->getTerminator());
519 // The exception selector comes back in context->data[1]
520 Idxs[1] = ConstantInt::get(Int32Ty, 2);
521 Value *FCData = GetElementPtrInst::Create(FunctionContext, Idxs, "fc_data",
522 EntryBB->getTerminator());
523 Idxs[1] = ConstantInt::get(Int32Ty, 1);
524 Value *SelectorAddr = GetElementPtrInst::Create(FCData, Idxs,
526 EntryBB->getTerminator());
527 // The exception value comes back in context->data[0]
529 Value *ExceptionAddr = GetElementPtrInst::Create(FCData, Idxs,
531 EntryBB->getTerminator());
533 // The result of the eh.selector call will be replaced with a a reference to
534 // the selector value returned in the function context. We leave the selector
535 // itself so the EH analysis later can use it.
536 for (int i = 0, e = EH_Selectors.size(); i < e; ++i) {
537 CallInst *I = EH_Selectors[i];
538 Value *SelectorVal = new LoadInst(SelectorAddr, "select_val", true, I);
539 I->replaceAllUsesWith(SelectorVal);
542 // eh.exception calls are replaced with references to the proper location in
543 // the context. Unlike eh.selector, the eh.exception calls are removed
545 for (int i = 0, e = EH_Exceptions.size(); i < e; ++i) {
546 CallInst *I = EH_Exceptions[i];
547 // Possible for there to be duplicates, so check to make sure the
548 // instruction hasn't already been removed.
549 if (!I->getParent()) continue;
550 Value *Val = new LoadInst(ExceptionAddr, "exception", true, I);
551 Type *Ty = Type::getInt8PtrTy(F.getContext());
552 Val = CastInst::Create(Instruction::IntToPtr, Val, Ty, "", I);
554 I->replaceAllUsesWith(Val);
555 I->eraseFromParent();
558 for (unsigned i = 0, e = LandingPads.size(); i != e; ++i)
559 ReplaceLandingPadVal(F, LandingPads[i], ExceptionAddr, SelectorAddr);
561 // The entry block changes to have the eh.sjlj.setjmp, with a conditional
562 // branch to a dispatch block for non-zero returns. If we return normally,
563 // we're not handling an exception and just register the function context and
566 // Create the dispatch block. The dispatch block is basically a big switch
567 // statement that goes to all of the invoke landing pads.
568 BasicBlock *DispatchBlock =
569 BasicBlock::Create(F.getContext(), "eh.sjlj.setjmp.catch", &F);
571 // Insert a load of the callsite in the dispatch block, and a switch on its
572 // value. By default, we issue a trap statement.
573 BasicBlock *TrapBlock =
574 BasicBlock::Create(F.getContext(), "trapbb", &F);
575 CallInst::Create(Intrinsic::getDeclaration(F.getParent(), Intrinsic::trap),
577 new UnreachableInst(F.getContext(), TrapBlock);
579 Value *DispatchLoad = new LoadInst(CallSite, "invoke.num", true,
581 SwitchInst *DispatchSwitch =
582 SwitchInst::Create(DispatchLoad, TrapBlock, Invokes.size(),
584 // Split the entry block to insert the conditional branch for the setjmp.
585 BasicBlock *ContBlock = EntryBB->splitBasicBlock(EntryBB->getTerminator(),
586 "eh.sjlj.setjmp.cont");
588 // Populate the Function Context
590 // 2. Personality function address
591 // 3. jmpbuf (save SP, FP and call eh.sjlj.setjmp)
595 Idxs[1] = ConstantInt::get(Int32Ty, 4);
596 Value *LSDAFieldPtr =
597 GetElementPtrInst::Create(FunctionContext, Idxs, "lsda_gep",
598 EntryBB->getTerminator());
599 Value *LSDA = CallInst::Create(LSDAAddrFn, "lsda_addr",
600 EntryBB->getTerminator());
601 new StoreInst(LSDA, LSDAFieldPtr, true, EntryBB->getTerminator());
603 Idxs[1] = ConstantInt::get(Int32Ty, 3);
604 Value *PersonalityFieldPtr =
605 GetElementPtrInst::Create(FunctionContext, Idxs, "lsda_gep",
606 EntryBB->getTerminator());
607 new StoreInst(PersonalityFn, PersonalityFieldPtr, true,
608 EntryBB->getTerminator());
610 // Save the frame pointer.
611 Idxs[1] = ConstantInt::get(Int32Ty, 5);
613 = GetElementPtrInst::Create(FunctionContext, Idxs, "jbuf_gep",
614 EntryBB->getTerminator());
615 Idxs[1] = ConstantInt::get(Int32Ty, 0);
617 GetElementPtrInst::Create(JBufPtr, Idxs, "jbuf_fp_gep",
618 EntryBB->getTerminator());
620 Value *Val = CallInst::Create(FrameAddrFn,
621 ConstantInt::get(Int32Ty, 0),
623 EntryBB->getTerminator());
624 new StoreInst(Val, FramePtr, true, EntryBB->getTerminator());
626 // Save the stack pointer.
627 Idxs[1] = ConstantInt::get(Int32Ty, 2);
629 GetElementPtrInst::Create(JBufPtr, Idxs, "jbuf_sp_gep",
630 EntryBB->getTerminator());
632 Val = CallInst::Create(StackAddrFn, "sp", EntryBB->getTerminator());
633 new StoreInst(Val, StackPtr, true, EntryBB->getTerminator());
635 // Call the setjmp instrinsic. It fills in the rest of the jmpbuf.
637 CastInst::Create(Instruction::BitCast, JBufPtr,
638 Type::getInt8PtrTy(F.getContext()), "",
639 EntryBB->getTerminator());
640 Value *DispatchVal = CallInst::Create(BuiltinSetjmpFn, SetjmpArg,
642 EntryBB->getTerminator());
644 // Add a call to dispatch_setup after the setjmp call. This is expanded to any
645 // target-specific setup that needs to be done.
646 CallInst::Create(DispatchSetupFn, DispatchVal, "", EntryBB->getTerminator());
648 // check the return value of the setjmp. non-zero goes to dispatcher.
649 Value *IsNormal = new ICmpInst(EntryBB->getTerminator(),
650 ICmpInst::ICMP_EQ, DispatchVal, Zero,
652 // Nuke the uncond branch.
653 EntryBB->getTerminator()->eraseFromParent();
655 // Put in a new condbranch in its place.
656 BranchInst::Create(ContBlock, DispatchBlock, IsNormal, EntryBB);
658 // Register the function context and make sure it's known to not throw
660 CallInst::Create(RegisterFn, FunctionContext, "",
661 ContBlock->getTerminator());
662 Register->setDoesNotThrow();
664 // At this point, we are all set up, update the invoke instructions to mark
665 // their call_site values, and fill in the dispatch switch accordingly.
666 for (unsigned i = 0, e = Invokes.size(); i != e; ++i)
667 markInvokeCallSite(Invokes[i], i+1, CallSite, DispatchSwitch);
669 // Mark call instructions that aren't nounwind as no-action (call_site ==
670 // -1). Skip the entry block, as prior to then, no function context has been
671 // created for this function and any unexpected exceptions thrown will go
672 // directly to the caller's context, which is what we want anyway, so no need
673 // to do anything here.
674 for (Function::iterator BB = F.begin(), E = F.end(); ++BB != E;) {
675 for (BasicBlock::iterator I = BB->begin(), end = BB->end(); I != end; ++I)
676 if (CallInst *CI = dyn_cast<CallInst>(I)) {
677 // Ignore calls to the EH builtins (eh.selector, eh.exception)
678 Constant *Callee = CI->getCalledFunction();
679 if (Callee != SelectorFn && Callee != ExceptionFn
680 && !CI->doesNotThrow())
681 insertCallSiteStore(CI, -1, CallSite);
682 } else if (ResumeInst *RI = dyn_cast<ResumeInst>(I)) {
683 insertCallSiteStore(RI, -1, CallSite);
687 // Replace all unwinds with a branch to the unwind handler.
688 // ??? Should this ever happen with sjlj exceptions?
689 for (unsigned i = 0, e = Unwinds.size(); i != e; ++i) {
690 BranchInst::Create(TrapBlock, Unwinds[i]);
691 Unwinds[i]->eraseFromParent();
694 // Following any allocas not in the entry block, update the saved SP in the
695 // jmpbuf to the new value.
696 for (unsigned i = 0, e = JmpbufUpdatePoints.size(); i != e; ++i) {
697 Instruction *AI = JmpbufUpdatePoints[i];
698 Instruction *StackAddr = CallInst::Create(StackAddrFn, "sp");
699 StackAddr->insertAfter(AI);
700 Instruction *StoreStackAddr = new StoreInst(StackAddr, StackPtr, true);
701 StoreStackAddr->insertAfter(StackAddr);
704 // Finally, for any returns from this function, if this function contains an
705 // invoke, add a call to unregister the function context.
706 for (unsigned i = 0, e = Returns.size(); i != e; ++i)
707 CallInst::Create(UnregisterFn, FunctionContext, "", Returns[i]);
712 /// setupFunctionContext - Allocate the function context on the stack and fill
713 /// it with all of the data that we know at this point.
715 setupFunctionContext(Function &F, ArrayRef<LandingPadInst*> LPads) {
716 BasicBlock *EntryBB = F.begin();
718 // Create an alloca for the incoming jump buffer ptr and the new jump buffer
719 // that needs to be restored on all exits from the function. This is an alloca
720 // because the value needs to be added to the global context list.
722 TLI->getTargetData()->getPrefTypeAlignment(FunctionContextTy);
723 AllocaInst *FuncCtx =
724 new AllocaInst(FunctionContextTy, 0, Align, "fn_context", EntryBB->begin());
726 // Fill in the function context structure.
728 Type *Int32Ty = Type::getInt32Ty(F.getContext());
729 Value *Zero = ConstantInt::get(Int32Ty, 0);
730 Value *One = ConstantInt::get(Int32Ty, 1);
732 // Keep around a reference to the call_site field.
735 CallSite = GetElementPtrInst::Create(FuncCtx, Idxs, "call_site",
736 EntryBB->getTerminator());
738 // Reference the __data field.
739 Idxs[1] = ConstantInt::get(Int32Ty, 2);
740 Value *FCData = GetElementPtrInst::Create(FuncCtx, Idxs, "__data",
741 EntryBB->getTerminator());
743 // The exception value comes back in context->__data[0].
745 Value *ExceptionAddr = GetElementPtrInst::Create(FCData, Idxs,
747 EntryBB->getTerminator());
749 // The exception selector comes back in context->__data[1].
751 Value *SelectorAddr = GetElementPtrInst::Create(FCData, Idxs,
753 EntryBB->getTerminator());
755 for (unsigned I = 0, E = LPads.size(); I != E; ++I) {
756 LandingPadInst *LPI = LPads[I];
757 IRBuilder<> Builder(LPI->getParent()->getFirstInsertionPt());
759 Value *ExnVal = Builder.CreateLoad(ExceptionAddr, true, "exn_val");
760 ExnVal = Builder.CreateIntToPtr(ExnVal, Type::getInt8PtrTy(F.getContext()));
761 Value *SelVal = Builder.CreateLoad(SelectorAddr, true, "exn_selector_val");
763 Type *LPadType = LPI->getType();
764 Value *LPadVal = UndefValue::get(LPadType);
765 LPadVal = Builder.CreateInsertValue(LPadVal, ExnVal, 0, "lpad.val");
766 LPadVal = Builder.CreateInsertValue(LPadVal, SelVal, 1, "lpad.val");
768 LPI->replaceAllUsesWith(LPadVal);
771 // Personality function
772 Idxs[1] = ConstantInt::get(Int32Ty, 3);
774 PersonalityFn = LPads[0]->getPersonalityFn();
775 Value *PersonalityFieldPtr =
776 GetElementPtrInst::Create(FuncCtx, Idxs, "pers_fn_gep",
777 EntryBB->getTerminator());
778 new StoreInst(PersonalityFn, PersonalityFieldPtr, true,
779 EntryBB->getTerminator());
782 Idxs[1] = ConstantInt::get(Int32Ty, 4);
783 Value *LSDAFieldPtr =
784 GetElementPtrInst::Create(FuncCtx, Idxs, "lsda_gep",
785 EntryBB->getTerminator());
786 Value *LSDA = CallInst::Create(LSDAAddrFn, "lsda_addr",
787 EntryBB->getTerminator());
788 new StoreInst(LSDA, LSDAFieldPtr, true, EntryBB->getTerminator());
793 /// setupEntryBlockAndCallSites - Setup the entry block by creating and filling
794 /// the function context and marking the call sites with the appropriate
795 /// values. These values are used by the DWARF EH emitter.
796 bool SjLjEHPass::setupEntryBlockAndCallSites(Function &F) {
797 SmallVector<ReturnInst*, 16> Returns;
798 SmallVector<InvokeInst*, 16> Invokes;
799 SmallVector<LandingPadInst*, 16> LPads;
801 // Look through the terminators of the basic blocks to find invokes.
802 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
803 if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
804 Invokes.push_back(II);
805 LPads.push_back(II->getUnwindDest()->getLandingPadInst());
806 } else if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
807 Returns.push_back(RI);
810 if (Invokes.empty()) return false;
812 Value *FuncCtx = setupFunctionContext(F, LPads);
813 BasicBlock *EntryBB = F.begin();
814 Type *Int32Ty = Type::getInt32Ty(F.getContext());
817 ConstantInt::get(Int32Ty, 0), 0
820 // Get a reference to the jump buffer.
821 Idxs[1] = ConstantInt::get(Int32Ty, 5);
823 GetElementPtrInst::Create(FuncCtx, Idxs, "jbuf_gep",
824 EntryBB->getTerminator());
826 // Save the frame pointer.
827 Idxs[1] = ConstantInt::get(Int32Ty, 0);
829 GetElementPtrInst::Create(JBufPtr, Idxs, "jbuf_fp_gep",
830 EntryBB->getTerminator());
832 Value *Val = CallInst::Create(FrameAddrFn,
833 ConstantInt::get(Int32Ty, 0),
835 EntryBB->getTerminator());
836 new StoreInst(Val, FramePtr, true, EntryBB->getTerminator());
838 // Save the stack pointer.
839 Idxs[1] = ConstantInt::get(Int32Ty, 2);
841 GetElementPtrInst::Create(JBufPtr, Idxs, "jbuf_sp_gep",
842 EntryBB->getTerminator());
844 Val = CallInst::Create(StackAddrFn, "sp", EntryBB->getTerminator());
845 new StoreInst(Val, StackPtr, true, EntryBB->getTerminator());
847 // Call the setjmp instrinsic. It fills in the rest of the jmpbuf.
849 CastInst::Create(Instruction::BitCast, JBufPtr,
850 Type::getInt8PtrTy(F.getContext()), "",
851 EntryBB->getTerminator());
852 CallInst::Create(BuiltinSetjmpFn, SetjmpArg, "", EntryBB->getTerminator());
854 // Store a pointer to the function context so that the back-end will know
855 // where to look for it.
857 CastInst::Create(Instruction::BitCast, FuncCtx,
858 Type::getInt8PtrTy(F.getContext()), "",
859 EntryBB->getTerminator());
860 CallInst::Create(FuncCtxFn, FuncCtxArg, "", EntryBB->getTerminator());
862 // At this point, we are all set up, update the invoke instructions to mark
863 // their call_site values, and fill in the dispatch switch accordingly.
864 for (unsigned I = 0, E = Invokes.size(); I != E; ++I) {
865 insertCallSiteStore(Invokes[I], I + 1, CallSite);
867 ConstantInt *CallSiteNum =
868 ConstantInt::get(Type::getInt32Ty(F.getContext()), I + 1);
870 // Record the call site value for the back end so it stays associated with
872 CallInst::Create(CallSiteFn, CallSiteNum, "", Invokes[I]);
875 // Mark call instructions that aren't nounwind as no-action (call_site ==
876 // -1). Skip the entry block, as prior to then, no function context has been
877 // created for this function and any unexpected exceptions thrown will go
878 // directly to the caller's context, which is what we want anyway, so no need
879 // to do anything here.
880 for (Function::iterator BB = F.begin(), E = F.end(); ++BB != E;) {
881 for (BasicBlock::iterator I = BB->begin(), end = BB->end(); I != end; ++I)
882 if (CallInst *CI = dyn_cast<CallInst>(I)) {
883 if (!CI->doesNotThrow())
884 insertCallSiteStore(CI, -1, CallSite);
885 } else if (ResumeInst *RI = dyn_cast<ResumeInst>(I)) {
886 insertCallSiteStore(RI, -1, CallSite);
890 // Register the function context and make sure it's known to not throw
891 CallInst *Register = CallInst::Create(RegisterFn, FuncCtx, "",
892 EntryBB->getTerminator());
893 Register->setDoesNotThrow();
895 // Finally, for any returns from this function, if this function contains an
896 // invoke, add a call to unregister the function context.
897 for (unsigned I = 0, E = Returns.size(); I != E; ++I)
898 CallInst::Create(UnregisterFn, FuncCtx, "", Returns[I]);
903 bool SjLjEHPass::runOnFunction(Function &F) {
905 if (!DisableOldSjLjEH)
906 Res = insertSjLjEHSupport(F);
908 Res = setupEntryBlockAndCallSites(F);