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);
79 void lowerIncomingArguments(Function &F);
80 void lowerAcrossUnwindEdges(Function &F, ArrayRef<InvokeInst*> Invokes);
82 void insertCallSiteStore(Instruction *I, int Number, Value *CallSite);
83 void markInvokeCallSite(InvokeInst *II, int InvokeNo, Value *CallSite,
84 SwitchInst *CatchSwitch);
85 void splitLiveRangesAcrossInvokes(SmallVector<InvokeInst*,16> &Invokes);
86 void splitLandingPad(InvokeInst *II);
87 bool insertSjLjEHSupport(Function &F);
89 } // end anonymous namespace
91 char SjLjEHPass::ID = 0;
93 // Public Interface To the SjLjEHPass pass.
94 FunctionPass *llvm::createSjLjEHPass(const TargetLowering *TLI) {
95 return new SjLjEHPass(TLI);
97 // doInitialization - Set up decalarations and types needed to process
99 bool SjLjEHPass::doInitialization(Module &M) {
100 // Build the function context structure.
101 // builtin_setjmp uses a five word jbuf
102 Type *VoidPtrTy = Type::getInt8PtrTy(M.getContext());
103 Type *Int32Ty = Type::getInt32Ty(M.getContext());
105 StructType::get(VoidPtrTy, // __prev
106 Int32Ty, // call_site
107 ArrayType::get(Int32Ty, 4), // __data
108 VoidPtrTy, // __personality
110 ArrayType::get(VoidPtrTy, 5), // __jbuf
112 RegisterFn = M.getOrInsertFunction("_Unwind_SjLj_Register",
113 Type::getVoidTy(M.getContext()),
114 PointerType::getUnqual(FunctionContextTy),
117 M.getOrInsertFunction("_Unwind_SjLj_Unregister",
118 Type::getVoidTy(M.getContext()),
119 PointerType::getUnqual(FunctionContextTy),
121 FrameAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::frameaddress);
122 StackAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::stacksave);
123 StackRestoreFn = Intrinsic::getDeclaration(&M, Intrinsic::stackrestore);
124 BuiltinSetjmpFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_setjmp);
125 LSDAAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_lsda);
126 SelectorFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_selector);
127 ExceptionFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_exception);
128 CallSiteFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_callsite);
130 = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_dispatch_setup);
131 FuncCtxFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_functioncontext);
137 /// insertCallSiteStore - Insert a store of the call-site value to the
139 void SjLjEHPass::insertCallSiteStore(Instruction *I, int Number,
141 ConstantInt *CallSiteNoC = ConstantInt::get(Type::getInt32Ty(I->getContext()),
143 // Insert a store of the call-site number
144 new StoreInst(CallSiteNoC, CallSite, true, I); // volatile
147 /// splitLandingPad - Split a landing pad. This takes considerable care because
148 /// of PHIs and other nasties. The problem is that the jump table needs to jump
149 /// to the landing pad block. However, the landing pad block can be jumped to
150 /// only by an invoke instruction. So we clone the landingpad instruction into
151 /// its own basic block, have the invoke jump to there. The landingpad
152 /// instruction's basic block's successor is now the target for the jump table.
154 /// But because of PHI nodes, we need to create another basic block for the jump
155 /// table to jump to. This is definitely a hack, because the values for the PHI
156 /// nodes may not be defined on the edge from the jump table. But that's okay,
157 /// because the jump table is simply a construct to mimic what is happening in
158 /// the CFG. So the values are mysteriously there, even though there is no value
159 /// for the PHI from the jump table's edge (hence calling this a hack).
160 void SjLjEHPass::splitLandingPad(InvokeInst *II) {
161 SmallVector<BasicBlock*, 2> NewBBs;
162 SplitLandingPadPredecessors(II->getUnwindDest(), II->getParent(),
163 ".1", ".2", this, NewBBs);
165 // Create an empty block so that the jump table has something to jump to
166 // which doesn't have any PHI nodes.
167 BasicBlock *LPad = NewBBs[0];
168 BasicBlock *Succ = *succ_begin(LPad);
169 BasicBlock *JumpTo = BasicBlock::Create(II->getContext(), "jt.land",
170 LPad->getParent(), Succ);
171 LPad->getTerminator()->eraseFromParent();
172 BranchInst::Create(JumpTo, LPad);
173 BranchInst::Create(Succ, JumpTo);
174 LPadSuccMap[II] = JumpTo;
176 for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
177 PHINode *PN = cast<PHINode>(I);
178 Value *Val = PN->removeIncomingValue(LPad, false);
179 PN->addIncoming(Val, JumpTo);
183 /// markInvokeCallSite - Insert code to mark the call_site for this invoke
184 void SjLjEHPass::markInvokeCallSite(InvokeInst *II, int InvokeNo,
186 SwitchInst *CatchSwitch) {
187 ConstantInt *CallSiteNoC= ConstantInt::get(Type::getInt32Ty(II->getContext()),
189 // The runtime comes back to the dispatcher with the call_site - 1 in
190 // the context. Odd, but there it is.
191 ConstantInt *SwitchValC = ConstantInt::get(Type::getInt32Ty(II->getContext()),
194 // If the unwind edge has phi nodes, split the edge.
195 if (isa<PHINode>(II->getUnwindDest()->begin())) {
196 // FIXME: New EH - This if-condition will be always true in the new scheme.
197 if (II->getUnwindDest()->isLandingPad())
200 SplitCriticalEdge(II, 1, this);
202 // If there are any phi nodes left, they must have a single predecessor.
203 while (PHINode *PN = dyn_cast<PHINode>(II->getUnwindDest()->begin())) {
204 PN->replaceAllUsesWith(PN->getIncomingValue(0));
205 PN->eraseFromParent();
209 // Insert the store of the call site value
210 insertCallSiteStore(II, InvokeNo, CallSite);
212 // Record the call site value for the back end so it stays associated with
214 CallInst::Create(CallSiteFn, CallSiteNoC, "", II);
216 // Add a switch case to our unwind block.
217 if (BasicBlock *SuccBB = LPadSuccMap[II]) {
218 CatchSwitch->addCase(SwitchValC, SuccBB);
220 CatchSwitch->addCase(SwitchValC, II->getUnwindDest());
223 // We still want this to look like an invoke so we emit the LSDA properly,
224 // so we don't transform the invoke into a call here.
227 /// MarkBlocksLiveIn - Insert BB and all of its predescessors into LiveBBs until
228 /// we reach blocks we've already seen.
229 static void MarkBlocksLiveIn(BasicBlock *BB, std::set<BasicBlock*> &LiveBBs) {
230 if (!LiveBBs.insert(BB).second) return; // already been here.
232 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
233 MarkBlocksLiveIn(*PI, LiveBBs);
236 /// splitLiveRangesAcrossInvokes - Each value that is live across an unwind edge
237 /// we spill into a stack location, guaranteeing that there is nothing live
238 /// across the unwind edge. This process also splits all critical edges
239 /// coming out of invoke's.
240 /// FIXME: Move this function to a common utility file (Local.cpp?) so
241 /// both SjLj and LowerInvoke can use it.
243 splitLiveRangesAcrossInvokes(SmallVector<InvokeInst*,16> &Invokes) {
244 // First step, split all critical edges from invoke instructions.
245 for (unsigned i = 0, e = Invokes.size(); i != e; ++i) {
246 InvokeInst *II = Invokes[i];
247 SplitCriticalEdge(II, 0, this);
249 // FIXME: New EH - This if-condition will be always true in the new scheme.
250 if (II->getUnwindDest()->isLandingPad())
253 SplitCriticalEdge(II, 1, this);
255 assert(!isa<PHINode>(II->getNormalDest()) &&
256 !isa<PHINode>(II->getUnwindDest()) &&
257 "Critical edge splitting left single entry phi nodes?");
260 Function *F = Invokes.back()->getParent()->getParent();
262 // To avoid having to handle incoming arguments specially, we lower each arg
263 // to a copy instruction in the entry block. This ensures that the argument
264 // value itself cannot be live across the entry block.
265 BasicBlock::iterator AfterAllocaInsertPt = F->begin()->begin();
266 while (isa<AllocaInst>(AfterAllocaInsertPt) &&
267 isa<ConstantInt>(cast<AllocaInst>(AfterAllocaInsertPt)->getArraySize()))
268 ++AfterAllocaInsertPt;
269 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
271 Type *Ty = AI->getType();
272 // Aggregate types can't be cast, but are legal argument types, so we have
273 // to handle them differently. We use an extract/insert pair as a
274 // lightweight method to achieve the same goal.
275 if (isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<VectorType>(Ty)) {
276 Instruction *EI = ExtractValueInst::Create(AI, 0, "",AfterAllocaInsertPt);
277 Instruction *NI = InsertValueInst::Create(AI, EI, 0);
279 AI->replaceAllUsesWith(NI);
280 // Set the operand of the instructions back to the AllocaInst.
281 EI->setOperand(0, AI);
282 NI->setOperand(0, AI);
284 // This is always a no-op cast because we're casting AI to AI->getType()
285 // so src and destination types are identical. BitCast is the only
287 CastInst *NC = new BitCastInst(
288 AI, AI->getType(), AI->getName()+".tmp", AfterAllocaInsertPt);
289 AI->replaceAllUsesWith(NC);
290 // Set the operand of the cast instruction back to the AllocaInst.
291 // Normally it's forbidden to replace a CastInst's operand because it
292 // could cause the opcode to reflect an illegal conversion. However,
293 // we're replacing it here with the same value it was constructed with.
294 // We do this because the above replaceAllUsesWith() clobbered the
295 // operand, but we want this one to remain.
296 NC->setOperand(0, AI);
300 // Finally, scan the code looking for instructions with bad live ranges.
301 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
302 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; ++II) {
303 // Ignore obvious cases we don't have to handle. In particular, most
304 // instructions either have no uses or only have a single use inside the
305 // current block. Ignore them quickly.
306 Instruction *Inst = II;
307 if (Inst->use_empty()) continue;
308 if (Inst->hasOneUse() &&
309 cast<Instruction>(Inst->use_back())->getParent() == BB &&
310 !isa<PHINode>(Inst->use_back())) continue;
312 // If this is an alloca in the entry block, it's not a real register
314 if (AllocaInst *AI = dyn_cast<AllocaInst>(Inst))
315 if (isa<ConstantInt>(AI->getArraySize()) && BB == F->begin())
318 // Avoid iterator invalidation by copying users to a temporary vector.
319 SmallVector<Instruction*,16> Users;
320 for (Value::use_iterator UI = Inst->use_begin(), E = Inst->use_end();
322 Instruction *User = cast<Instruction>(*UI);
323 if (User->getParent() != BB || isa<PHINode>(User))
324 Users.push_back(User);
327 // Find all of the blocks that this value is live in.
328 std::set<BasicBlock*> LiveBBs;
329 LiveBBs.insert(Inst->getParent());
330 while (!Users.empty()) {
331 Instruction *U = Users.back();
334 if (!isa<PHINode>(U)) {
335 MarkBlocksLiveIn(U->getParent(), LiveBBs);
337 // Uses for a PHI node occur in their predecessor block.
338 PHINode *PN = cast<PHINode>(U);
339 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
340 if (PN->getIncomingValue(i) == Inst)
341 MarkBlocksLiveIn(PN->getIncomingBlock(i), LiveBBs);
345 // Now that we know all of the blocks that this thing is live in, see if
346 // it includes any of the unwind locations.
347 bool NeedsSpill = false;
348 for (unsigned i = 0, e = Invokes.size(); i != e; ++i) {
349 BasicBlock *UnwindBlock = Invokes[i]->getUnwindDest();
350 if (UnwindBlock != BB && LiveBBs.count(UnwindBlock))
354 // If we decided we need a spill, do it.
355 // FIXME: Spilling this way is overkill, as it forces all uses of
356 // the value to be reloaded from the stack slot, even those that aren't
357 // in the unwind blocks. We should be more selective.
360 DemoteRegToStack(*Inst, true);
365 /// CreateLandingPadLoad - Load the exception handling values and insert them
366 /// into a structure.
367 static Instruction *CreateLandingPadLoad(Function &F, Value *ExnAddr,
369 BasicBlock::iterator InsertPt) {
370 Value *Exn = new LoadInst(ExnAddr, "exn", false,
372 Type *Ty = Type::getInt8PtrTy(F.getContext());
373 Exn = CastInst::Create(Instruction::IntToPtr, Exn, Ty, "", InsertPt);
374 Value *Sel = new LoadInst(SelAddr, "sel", false, InsertPt);
376 Ty = StructType::get(Exn->getType(), Sel->getType(), NULL);
377 InsertValueInst *LPadVal = InsertValueInst::Create(llvm::UndefValue::get(Ty),
379 "lpad.val", InsertPt);
380 return InsertValueInst::Create(LPadVal, Sel, 1, "lpad.val", InsertPt);
383 /// ReplaceLandingPadVal - Replace the landingpad instruction's value with a
384 /// load from the stored values (via CreateLandingPadLoad). This looks through
385 /// PHI nodes, and removes them if they are dead.
386 static void ReplaceLandingPadVal(Function &F, Instruction *Inst, Value *ExnAddr,
388 if (Inst->use_empty()) return;
390 while (!Inst->use_empty()) {
391 Instruction *I = cast<Instruction>(Inst->use_back());
393 if (PHINode *PN = dyn_cast<PHINode>(I)) {
394 ReplaceLandingPadVal(F, PN, ExnAddr, SelAddr);
395 if (PN->use_empty()) PN->eraseFromParent();
399 I->replaceUsesOfWith(Inst, CreateLandingPadLoad(F, ExnAddr, SelAddr, I));
403 bool SjLjEHPass::insertSjLjEHSupport(Function &F) {
404 SmallVector<ReturnInst*,16> Returns;
405 SmallVector<UnwindInst*,16> Unwinds;
406 SmallVector<InvokeInst*,16> Invokes;
408 // Look through the terminators of the basic blocks to find invokes, returns
410 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
411 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
412 // Remember all return instructions in case we insert an invoke into this
414 Returns.push_back(RI);
415 } else if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
416 Invokes.push_back(II);
417 } else if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator())) {
418 Unwinds.push_back(UI);
422 NumInvokes += Invokes.size();
423 NumUnwinds += Unwinds.size();
425 // If we don't have any invokes, there's nothing to do.
426 if (Invokes.empty()) return false;
428 // Find the eh.selector.*, eh.exception and alloca calls.
430 // Remember any allocas() that aren't in the entry block, as the
431 // jmpbuf saved SP will need to be updated for them.
433 // We'll use the first eh.selector to determine the right personality
434 // function to use. For SJLJ, we always use the same personality for the
435 // whole function, not on a per-selector basis.
436 // FIXME: That's a bit ugly. Better way?
437 SmallVector<CallInst*,16> EH_Selectors;
438 SmallVector<CallInst*,16> EH_Exceptions;
439 SmallVector<Instruction*,16> JmpbufUpdatePoints;
441 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
442 // Note: Skip the entry block since there's nothing there that interests
443 // us. eh.selector and eh.exception shouldn't ever be there, and we
444 // want to disregard any allocas that are there.
446 // FIXME: This is awkward. The new EH scheme won't need to skip the entry
448 if (BB == F.begin()) {
449 if (InvokeInst *II = dyn_cast<InvokeInst>(F.begin()->getTerminator())) {
450 // FIXME: This will be always non-NULL in the new EH.
451 if (LandingPadInst *LPI = II->getUnwindDest()->getLandingPadInst())
452 if (!PersonalityFn) PersonalityFn = LPI->getPersonalityFn();
458 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
459 if (CallInst *CI = dyn_cast<CallInst>(I)) {
460 if (CI->getCalledFunction() == SelectorFn) {
461 if (!PersonalityFn) PersonalityFn = CI->getArgOperand(1);
462 EH_Selectors.push_back(CI);
463 } else if (CI->getCalledFunction() == ExceptionFn) {
464 EH_Exceptions.push_back(CI);
465 } else if (CI->getCalledFunction() == StackRestoreFn) {
466 JmpbufUpdatePoints.push_back(CI);
468 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) {
469 JmpbufUpdatePoints.push_back(AI);
470 } else if (InvokeInst *II = dyn_cast<InvokeInst>(I)) {
471 // FIXME: This will be always non-NULL in the new EH.
472 if (LandingPadInst *LPI = II->getUnwindDest()->getLandingPadInst())
473 if (!PersonalityFn) PersonalityFn = LPI->getPersonalityFn();
478 // If we don't have any eh.selector calls, we can't determine the personality
479 // function. Without a personality function, we can't process exceptions.
480 if (!PersonalityFn) return false;
482 // We have invokes, so we need to add register/unregister calls to get this
483 // function onto the global unwind stack.
485 // First thing we need to do is scan the whole function for values that are
486 // live across unwind edges. Each value that is live across an unwind edge we
487 // spill into a stack location, guaranteeing that there is nothing live across
488 // the unwind edge. This process also splits all critical edges coming out of
490 splitLiveRangesAcrossInvokes(Invokes);
493 SmallVector<LandingPadInst*, 16> LandingPads;
494 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
495 if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator()))
496 // FIXME: This will be always non-NULL in the new EH.
497 if (LandingPadInst *LPI = II->getUnwindDest()->getLandingPadInst())
498 LandingPads.push_back(LPI);
502 BasicBlock *EntryBB = F.begin();
503 // Create an alloca for the incoming jump buffer ptr and the new jump buffer
504 // that needs to be restored on all exits from the function. This is an
505 // alloca because the value needs to be added to the global context list.
506 unsigned Align = 4; // FIXME: Should be a TLI check?
507 AllocaInst *FunctionContext =
508 new AllocaInst(FunctionContextTy, 0, Align,
509 "fcn_context", F.begin()->begin());
512 Type *Int32Ty = Type::getInt32Ty(F.getContext());
513 Value *Zero = ConstantInt::get(Int32Ty, 0);
514 // We need to also keep around a reference to the call_site field
516 Idxs[1] = ConstantInt::get(Int32Ty, 1);
517 CallSite = GetElementPtrInst::Create(FunctionContext, Idxs, "call_site",
518 EntryBB->getTerminator());
520 // The exception selector comes back in context->data[1]
521 Idxs[1] = ConstantInt::get(Int32Ty, 2);
522 Value *FCData = GetElementPtrInst::Create(FunctionContext, Idxs, "fc_data",
523 EntryBB->getTerminator());
524 Idxs[1] = ConstantInt::get(Int32Ty, 1);
525 Value *SelectorAddr = GetElementPtrInst::Create(FCData, Idxs,
527 EntryBB->getTerminator());
528 // The exception value comes back in context->data[0]
530 Value *ExceptionAddr = GetElementPtrInst::Create(FCData, Idxs,
532 EntryBB->getTerminator());
534 // The result of the eh.selector call will be replaced with a a reference to
535 // the selector value returned in the function context. We leave the selector
536 // itself so the EH analysis later can use it.
537 for (int i = 0, e = EH_Selectors.size(); i < e; ++i) {
538 CallInst *I = EH_Selectors[i];
539 Value *SelectorVal = new LoadInst(SelectorAddr, "select_val", true, I);
540 I->replaceAllUsesWith(SelectorVal);
543 // eh.exception calls are replaced with references to the proper location in
544 // the context. Unlike eh.selector, the eh.exception calls are removed
546 for (int i = 0, e = EH_Exceptions.size(); i < e; ++i) {
547 CallInst *I = EH_Exceptions[i];
548 // Possible for there to be duplicates, so check to make sure the
549 // instruction hasn't already been removed.
550 if (!I->getParent()) continue;
551 Value *Val = new LoadInst(ExceptionAddr, "exception", true, I);
552 Type *Ty = Type::getInt8PtrTy(F.getContext());
553 Val = CastInst::Create(Instruction::IntToPtr, Val, Ty, "", I);
555 I->replaceAllUsesWith(Val);
556 I->eraseFromParent();
559 for (unsigned i = 0, e = LandingPads.size(); i != e; ++i)
560 ReplaceLandingPadVal(F, LandingPads[i], ExceptionAddr, SelectorAddr);
562 // The entry block changes to have the eh.sjlj.setjmp, with a conditional
563 // branch to a dispatch block for non-zero returns. If we return normally,
564 // we're not handling an exception and just register the function context and
567 // Create the dispatch block. The dispatch block is basically a big switch
568 // statement that goes to all of the invoke landing pads.
569 BasicBlock *DispatchBlock =
570 BasicBlock::Create(F.getContext(), "eh.sjlj.setjmp.catch", &F);
572 // Insert a load of the callsite in the dispatch block, and a switch on its
573 // value. By default, we issue a trap statement.
574 BasicBlock *TrapBlock =
575 BasicBlock::Create(F.getContext(), "trapbb", &F);
576 CallInst::Create(Intrinsic::getDeclaration(F.getParent(), Intrinsic::trap),
578 new UnreachableInst(F.getContext(), TrapBlock);
580 Value *DispatchLoad = new LoadInst(CallSite, "invoke.num", true,
582 SwitchInst *DispatchSwitch =
583 SwitchInst::Create(DispatchLoad, TrapBlock, Invokes.size(),
585 // Split the entry block to insert the conditional branch for the setjmp.
586 BasicBlock *ContBlock = EntryBB->splitBasicBlock(EntryBB->getTerminator(),
587 "eh.sjlj.setjmp.cont");
589 // Populate the Function Context
591 // 2. Personality function address
592 // 3. jmpbuf (save SP, FP and call eh.sjlj.setjmp)
596 Idxs[1] = ConstantInt::get(Int32Ty, 4);
597 Value *LSDAFieldPtr =
598 GetElementPtrInst::Create(FunctionContext, Idxs, "lsda_gep",
599 EntryBB->getTerminator());
600 Value *LSDA = CallInst::Create(LSDAAddrFn, "lsda_addr",
601 EntryBB->getTerminator());
602 new StoreInst(LSDA, LSDAFieldPtr, true, EntryBB->getTerminator());
604 Idxs[1] = ConstantInt::get(Int32Ty, 3);
605 Value *PersonalityFieldPtr =
606 GetElementPtrInst::Create(FunctionContext, Idxs, "lsda_gep",
607 EntryBB->getTerminator());
608 new StoreInst(PersonalityFn, PersonalityFieldPtr, true,
609 EntryBB->getTerminator());
611 // Save the frame pointer.
612 Idxs[1] = ConstantInt::get(Int32Ty, 5);
614 = GetElementPtrInst::Create(FunctionContext, Idxs, "jbuf_gep",
615 EntryBB->getTerminator());
616 Idxs[1] = ConstantInt::get(Int32Ty, 0);
618 GetElementPtrInst::Create(JBufPtr, Idxs, "jbuf_fp_gep",
619 EntryBB->getTerminator());
621 Value *Val = CallInst::Create(FrameAddrFn,
622 ConstantInt::get(Int32Ty, 0),
624 EntryBB->getTerminator());
625 new StoreInst(Val, FramePtr, true, EntryBB->getTerminator());
627 // Save the stack pointer.
628 Idxs[1] = ConstantInt::get(Int32Ty, 2);
630 GetElementPtrInst::Create(JBufPtr, Idxs, "jbuf_sp_gep",
631 EntryBB->getTerminator());
633 Val = CallInst::Create(StackAddrFn, "sp", EntryBB->getTerminator());
634 new StoreInst(Val, StackPtr, true, EntryBB->getTerminator());
636 // Call the setjmp instrinsic. It fills in the rest of the jmpbuf.
638 CastInst::Create(Instruction::BitCast, JBufPtr,
639 Type::getInt8PtrTy(F.getContext()), "",
640 EntryBB->getTerminator());
641 Value *DispatchVal = CallInst::Create(BuiltinSetjmpFn, SetjmpArg,
643 EntryBB->getTerminator());
645 // Add a call to dispatch_setup after the setjmp call. This is expanded to any
646 // target-specific setup that needs to be done.
647 CallInst::Create(DispatchSetupFn, DispatchVal, "", EntryBB->getTerminator());
649 // check the return value of the setjmp. non-zero goes to dispatcher.
650 Value *IsNormal = new ICmpInst(EntryBB->getTerminator(),
651 ICmpInst::ICMP_EQ, DispatchVal, Zero,
653 // Nuke the uncond branch.
654 EntryBB->getTerminator()->eraseFromParent();
656 // Put in a new condbranch in its place.
657 BranchInst::Create(ContBlock, DispatchBlock, IsNormal, EntryBB);
659 // Register the function context and make sure it's known to not throw
661 CallInst::Create(RegisterFn, FunctionContext, "",
662 ContBlock->getTerminator());
663 Register->setDoesNotThrow();
665 // At this point, we are all set up, update the invoke instructions to mark
666 // their call_site values, and fill in the dispatch switch accordingly.
667 for (unsigned i = 0, e = Invokes.size(); i != e; ++i)
668 markInvokeCallSite(Invokes[i], i+1, CallSite, DispatchSwitch);
670 // Mark call instructions that aren't nounwind as no-action (call_site ==
671 // -1). Skip the entry block, as prior to then, no function context has been
672 // created for this function and any unexpected exceptions thrown will go
673 // directly to the caller's context, which is what we want anyway, so no need
674 // to do anything here.
675 for (Function::iterator BB = F.begin(), E = F.end(); ++BB != E;) {
676 for (BasicBlock::iterator I = BB->begin(), end = BB->end(); I != end; ++I)
677 if (CallInst *CI = dyn_cast<CallInst>(I)) {
678 // Ignore calls to the EH builtins (eh.selector, eh.exception)
679 Constant *Callee = CI->getCalledFunction();
680 if (Callee != SelectorFn && Callee != ExceptionFn
681 && !CI->doesNotThrow())
682 insertCallSiteStore(CI, -1, CallSite);
683 } else if (ResumeInst *RI = dyn_cast<ResumeInst>(I)) {
684 insertCallSiteStore(RI, -1, CallSite);
688 // Replace all unwinds with a branch to the unwind handler.
689 // ??? Should this ever happen with sjlj exceptions?
690 for (unsigned i = 0, e = Unwinds.size(); i != e; ++i) {
691 BranchInst::Create(TrapBlock, Unwinds[i]);
692 Unwinds[i]->eraseFromParent();
695 // Following any allocas not in the entry block, update the saved SP in the
696 // jmpbuf to the new value.
697 for (unsigned i = 0, e = JmpbufUpdatePoints.size(); i != e; ++i) {
698 Instruction *AI = JmpbufUpdatePoints[i];
699 Instruction *StackAddr = CallInst::Create(StackAddrFn, "sp");
700 StackAddr->insertAfter(AI);
701 Instruction *StoreStackAddr = new StoreInst(StackAddr, StackPtr, true);
702 StoreStackAddr->insertAfter(StackAddr);
705 // Finally, for any returns from this function, if this function contains an
706 // invoke, add a call to unregister the function context.
707 for (unsigned i = 0, e = Returns.size(); i != e; ++i)
708 CallInst::Create(UnregisterFn, FunctionContext, "", Returns[i]);
713 /// setupFunctionContext - Allocate the function context on the stack and fill
714 /// it with all of the data that we know at this point.
716 setupFunctionContext(Function &F, ArrayRef<LandingPadInst*> LPads) {
717 BasicBlock *EntryBB = F.begin();
719 // Create an alloca for the incoming jump buffer ptr and the new jump buffer
720 // that needs to be restored on all exits from the function. This is an alloca
721 // because the value needs to be added to the global context list.
723 TLI->getTargetData()->getPrefTypeAlignment(FunctionContextTy);
724 AllocaInst *FuncCtx =
725 new AllocaInst(FunctionContextTy, 0, Align, "fn_context", EntryBB->begin());
727 // Fill in the function context structure.
729 Type *Int32Ty = Type::getInt32Ty(F.getContext());
730 Value *Zero = ConstantInt::get(Int32Ty, 0);
731 Value *One = ConstantInt::get(Int32Ty, 1);
733 // Keep around a reference to the call_site field.
736 CallSite = GetElementPtrInst::Create(FuncCtx, Idxs, "call_site",
737 EntryBB->getTerminator());
739 // Reference the __data field.
740 Idxs[1] = ConstantInt::get(Int32Ty, 2);
741 Value *FCData = GetElementPtrInst::Create(FuncCtx, Idxs, "__data",
742 EntryBB->getTerminator());
744 // The exception value comes back in context->__data[0].
746 Value *ExceptionAddr = GetElementPtrInst::Create(FCData, Idxs,
748 EntryBB->getTerminator());
750 // The exception selector comes back in context->__data[1].
752 Value *SelectorAddr = GetElementPtrInst::Create(FCData, Idxs,
754 EntryBB->getTerminator());
756 for (unsigned I = 0, E = LPads.size(); I != E; ++I) {
757 LandingPadInst *LPI = LPads[I];
758 IRBuilder<> Builder(LPI->getParent()->getFirstInsertionPt());
760 Value *ExnVal = Builder.CreateLoad(ExceptionAddr, true, "exn_val");
761 ExnVal = Builder.CreateIntToPtr(ExnVal, Type::getInt8PtrTy(F.getContext()));
762 Value *SelVal = Builder.CreateLoad(SelectorAddr, true, "exn_selector_val");
764 Type *LPadType = LPI->getType();
765 Value *LPadVal = UndefValue::get(LPadType);
766 LPadVal = Builder.CreateInsertValue(LPadVal, ExnVal, 0, "lpad.val");
767 LPadVal = Builder.CreateInsertValue(LPadVal, SelVal, 1, "lpad.val");
769 LPI->replaceAllUsesWith(LPadVal);
772 // Personality function
773 Idxs[1] = ConstantInt::get(Int32Ty, 3);
775 PersonalityFn = LPads[0]->getPersonalityFn();
776 Value *PersonalityFieldPtr =
777 GetElementPtrInst::Create(FuncCtx, Idxs, "pers_fn_gep",
778 EntryBB->getTerminator());
779 new StoreInst(PersonalityFn, PersonalityFieldPtr, true,
780 EntryBB->getTerminator());
783 Idxs[1] = ConstantInt::get(Int32Ty, 4);
784 Value *LSDAFieldPtr = 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 /// lowerIncomingArguments - To avoid having to handle incoming arguments
794 /// specially, we lower each arg to a copy instruction in the entry block. This
795 /// ensures that the argument value itself cannot be live out of the entry
797 void SjLjEHPass::lowerIncomingArguments(Function &F) {
798 BasicBlock::iterator AfterAllocaInsPt = F.begin()->begin();
799 while (isa<AllocaInst>(AfterAllocaInsPt) &&
800 isa<ConstantInt>(cast<AllocaInst>(AfterAllocaInsPt)->getArraySize()))
803 for (Function::arg_iterator
804 AI = F.arg_begin(), AE = F.arg_end(); AI != AE; ++AI) {
805 Type *Ty = AI->getType();
807 // Aggregate types can't be cast, but are legal argument types, so we have
808 // to handle them differently. We use an extract/insert pair as a
809 // lightweight method to achieve the same goal.
810 if (isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<VectorType>(Ty)) {
811 Instruction *EI = ExtractValueInst::Create(AI, 0, "", AfterAllocaInsPt);
812 Instruction *NI = InsertValueInst::Create(AI, EI, 0);
814 AI->replaceAllUsesWith(NI);
816 // Set the operand of the instructions back to the AllocaInst.
817 EI->setOperand(0, AI);
818 NI->setOperand(0, AI);
820 // This is always a no-op cast because we're casting AI to AI->getType()
821 // so src and destination types are identical. BitCast is the only
824 new BitCastInst(AI, AI->getType(), AI->getName() + ".tmp",
826 AI->replaceAllUsesWith(NC);
828 // Set the operand of the cast instruction back to the AllocaInst.
829 // Normally it's forbidden to replace a CastInst's operand because it
830 // could cause the opcode to reflect an illegal conversion. However, we're
831 // replacing it here with the same value it was constructed with. We do
832 // this because the above replaceAllUsesWith() clobbered the operand, but
833 // we want this one to remain.
834 NC->setOperand(0, AI);
839 /// lowerAcrossUnwindEdges - Find all variables which are alive across an unwind
840 /// edge and spill them.
841 void SjLjEHPass::lowerAcrossUnwindEdges(Function &F,
842 ArrayRef<InvokeInst*> Invokes) {
843 // Finally, scan the code looking for instructions with bad live ranges.
844 for (Function::iterator
845 BB = F.begin(), BBE = F.end(); BB != BBE; ++BB) {
846 for (BasicBlock::iterator
847 II = BB->begin(), IIE = BB->end(); II != IIE; ++II) {
848 // Ignore obvious cases we don't have to handle. In particular, most
849 // instructions either have no uses or only have a single use inside the
850 // current block. Ignore them quickly.
851 Instruction *Inst = II;
852 if (Inst->use_empty()) continue;
853 if (Inst->hasOneUse() &&
854 cast<Instruction>(Inst->use_back())->getParent() == BB &&
855 !isa<PHINode>(Inst->use_back())) continue;
857 // If this is an alloca in the entry block, it's not a real register
859 if (AllocaInst *AI = dyn_cast<AllocaInst>(Inst))
860 if (isa<ConstantInt>(AI->getArraySize()) && BB == F.begin())
863 // Avoid iterator invalidation by copying users to a temporary vector.
864 SmallVector<Instruction*, 16> Users;
865 for (Value::use_iterator
866 UI = Inst->use_begin(), E = Inst->use_end(); UI != E; ++UI) {
867 Instruction *User = cast<Instruction>(*UI);
868 if (User->getParent() != BB || isa<PHINode>(User))
869 Users.push_back(User);
872 // Find all of the blocks that this value is live in.
873 std::set<BasicBlock*> LiveBBs;
874 LiveBBs.insert(Inst->getParent());
875 while (!Users.empty()) {
876 Instruction *U = Users.back();
879 if (!isa<PHINode>(U)) {
880 MarkBlocksLiveIn(U->getParent(), LiveBBs);
882 // Uses for a PHI node occur in their predecessor block.
883 PHINode *PN = cast<PHINode>(U);
884 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
885 if (PN->getIncomingValue(i) == Inst)
886 MarkBlocksLiveIn(PN->getIncomingBlock(i), LiveBBs);
890 // Now that we know all of the blocks that this thing is live in, see if
891 // it includes any of the unwind locations.
892 bool NeedsSpill = false;
893 for (unsigned i = 0, e = Invokes.size(); i != e; ++i) {
894 BasicBlock *UnwindBlock = Invokes[i]->getUnwindDest();
895 if (UnwindBlock != BB && LiveBBs.count(UnwindBlock)) {
900 // If we decided we need a spill, do it.
901 // FIXME: Spilling this way is overkill, as it forces all uses of
902 // the value to be reloaded from the stack slot, even those that aren't
903 // in the unwind blocks. We should be more selective.
906 DemoteRegToStack(*Inst, true);
912 /// setupEntryBlockAndCallSites - Setup the entry block by creating and filling
913 /// the function context and marking the call sites with the appropriate
914 /// values. These values are used by the DWARF EH emitter.
915 bool SjLjEHPass::setupEntryBlockAndCallSites(Function &F) {
916 SmallVector<ReturnInst*, 16> Returns;
917 SmallVector<InvokeInst*, 16> Invokes;
918 SmallVector<LandingPadInst*, 16> LPads;
920 // Look through the terminators of the basic blocks to find invokes.
921 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
922 if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
923 Invokes.push_back(II);
924 LPads.push_back(II->getUnwindDest()->getLandingPadInst());
925 } else if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
926 Returns.push_back(RI);
929 if (Invokes.empty()) return false;
931 lowerIncomingArguments(F);
932 lowerAcrossUnwindEdges(F, Invokes);
934 Value *FuncCtx = setupFunctionContext(F, LPads);
935 BasicBlock *EntryBB = F.begin();
936 Type *Int32Ty = Type::getInt32Ty(F.getContext());
939 ConstantInt::get(Int32Ty, 0), 0
942 // Get a reference to the jump buffer.
943 Idxs[1] = ConstantInt::get(Int32Ty, 5);
944 Value *JBufPtr = GetElementPtrInst::Create(FuncCtx, Idxs, "jbuf_gep",
945 EntryBB->getTerminator());
947 // Save the frame pointer.
948 Idxs[1] = ConstantInt::get(Int32Ty, 0);
949 Value *FramePtr = GetElementPtrInst::Create(JBufPtr, Idxs, "jbuf_fp_gep",
950 EntryBB->getTerminator());
952 Value *Val = CallInst::Create(FrameAddrFn,
953 ConstantInt::get(Int32Ty, 0),
955 EntryBB->getTerminator());
956 new StoreInst(Val, FramePtr, true, EntryBB->getTerminator());
958 // Save the stack pointer.
959 Idxs[1] = ConstantInt::get(Int32Ty, 2);
960 Value *StackPtr = GetElementPtrInst::Create(JBufPtr, Idxs, "jbuf_sp_gep",
961 EntryBB->getTerminator());
963 Val = CallInst::Create(StackAddrFn, "sp", EntryBB->getTerminator());
964 new StoreInst(Val, StackPtr, true, EntryBB->getTerminator());
966 // Call the setjmp instrinsic. It fills in the rest of the jmpbuf.
967 Value *SetjmpArg = CastInst::Create(Instruction::BitCast, JBufPtr,
968 Type::getInt8PtrTy(F.getContext()), "",
969 EntryBB->getTerminator());
970 CallInst::Create(BuiltinSetjmpFn, SetjmpArg, "", EntryBB->getTerminator());
972 // Store a pointer to the function context so that the back-end will know
973 // where to look for it.
974 Value *FuncCtxArg = CastInst::Create(Instruction::BitCast, FuncCtx,
975 Type::getInt8PtrTy(F.getContext()), "",
976 EntryBB->getTerminator());
977 CallInst::Create(FuncCtxFn, FuncCtxArg, "", EntryBB->getTerminator());
979 // At this point, we are all set up, update the invoke instructions to mark
980 // their call_site values.
981 for (unsigned I = 0, E = Invokes.size(); I != E; ++I) {
982 insertCallSiteStore(Invokes[I], I + 1, CallSite);
984 ConstantInt *CallSiteNum =
985 ConstantInt::get(Type::getInt32Ty(F.getContext()), I + 1);
987 // Record the call site value for the back end so it stays associated with
989 CallInst::Create(CallSiteFn, CallSiteNum, "", Invokes[I]);
992 // Mark call instructions that aren't nounwind as no-action (call_site ==
993 // -1). Skip the entry block, as prior to then, no function context has been
994 // created for this function and any unexpected exceptions thrown will go
995 // directly to the caller's context, which is what we want anyway, so no need
996 // to do anything here.
997 for (Function::iterator BB = F.begin(), E = F.end(); ++BB != E;)
998 for (BasicBlock::iterator I = BB->begin(), end = BB->end(); I != end; ++I)
999 if (CallInst *CI = dyn_cast<CallInst>(I)) {
1000 if (!CI->doesNotThrow())
1001 insertCallSiteStore(CI, -1, CallSite);
1002 } else if (ResumeInst *RI = dyn_cast<ResumeInst>(I)) {
1003 insertCallSiteStore(RI, -1, CallSite);
1006 // Register the function context and make sure it's known to not throw
1007 CallInst *Register = CallInst::Create(RegisterFn, FuncCtx, "",
1008 EntryBB->getTerminator());
1009 Register->setDoesNotThrow();
1011 // Finally, for any returns from this function, if this function contains an
1012 // invoke, add a call to unregister the function context.
1013 for (unsigned I = 0, E = Returns.size(); I != E; ++I)
1014 CallInst::Create(UnregisterFn, FuncCtx, "", Returns[I]);
1019 bool SjLjEHPass::runOnFunction(Function &F) {
1021 if (!DisableOldSjLjEH)
1022 Res = insertSjLjEHSupport(F);
1024 Res = setupEntryBlockAndCallSites(F);