1 //===- SjLjEHPrepare.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 #include "llvm/CodeGen/Passes.h"
16 #include "llvm/ADT/SetVector.h"
17 #include "llvm/ADT/SmallPtrSet.h"
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/ADT/Statistic.h"
20 #include "llvm/IR/Constants.h"
21 #include "llvm/IR/DataLayout.h"
22 #include "llvm/IR/DerivedTypes.h"
23 #include "llvm/IR/IRBuilder.h"
24 #include "llvm/IR/Instructions.h"
25 #include "llvm/IR/Intrinsics.h"
26 #include "llvm/IR/Module.h"
27 #include "llvm/Pass.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/raw_ostream.h"
30 #include "llvm/Transforms/Utils/Local.h"
33 #define DEBUG_TYPE "sjljehprepare"
35 STATISTIC(NumInvokes, "Number of invokes replaced");
36 STATISTIC(NumSpilled, "Number of registers live across unwind edges");
39 class SjLjEHPrepare : public FunctionPass {
40 Type *doubleUnderDataTy;
41 Type *doubleUnderJBufTy;
42 Type *FunctionContextTy;
44 Constant *UnregisterFn;
45 Constant *BuiltinSetupDispatchFn;
46 Constant *FrameAddrFn;
47 Constant *StackAddrFn;
48 Constant *StackRestoreFn;
55 static char ID; // Pass identification, replacement for typeid
56 explicit SjLjEHPrepare() : FunctionPass(ID) {}
57 bool doInitialization(Module &M) override;
58 bool runOnFunction(Function &F) override;
60 void getAnalysisUsage(AnalysisUsage &AU) const override {}
61 StringRef getPassName() const override {
62 return "SJLJ Exception Handling preparation";
66 bool setupEntryBlockAndCallSites(Function &F);
67 bool undoSwiftErrorSelect(Function &F);
68 void substituteLPadValues(LandingPadInst *LPI, Value *ExnVal, Value *SelVal);
69 Value *setupFunctionContext(Function &F, ArrayRef<LandingPadInst *> LPads);
70 void lowerIncomingArguments(Function &F);
71 void lowerAcrossUnwindEdges(Function &F, ArrayRef<InvokeInst *> Invokes);
72 void insertCallSiteStore(Instruction *I, int Number);
74 } // end anonymous namespace
76 char SjLjEHPrepare::ID = 0;
77 INITIALIZE_PASS(SjLjEHPrepare, DEBUG_TYPE, "Prepare SjLj exceptions",
80 // Public Interface To the SjLjEHPrepare pass.
81 FunctionPass *llvm::createSjLjEHPreparePass() { return new SjLjEHPrepare(); }
82 // doInitialization - Set up decalarations and types needed to process
84 bool SjLjEHPrepare::doInitialization(Module &M) {
85 // Build the function context structure.
86 // builtin_setjmp uses a five word jbuf
87 Type *VoidPtrTy = Type::getInt8PtrTy(M.getContext());
88 Type *Int32Ty = Type::getInt32Ty(M.getContext());
89 doubleUnderDataTy = ArrayType::get(Int32Ty, 4);
90 doubleUnderJBufTy = ArrayType::get(VoidPtrTy, 5);
91 FunctionContextTy = StructType::get(VoidPtrTy, // __prev
93 doubleUnderDataTy, // __data
94 VoidPtrTy, // __personality
96 doubleUnderJBufTy // __jbuf
102 /// insertCallSiteStore - Insert a store of the call-site value to the
104 void SjLjEHPrepare::insertCallSiteStore(Instruction *I, int Number) {
105 IRBuilder<> Builder(I);
107 // Get a reference to the call_site field.
108 Type *Int32Ty = Type::getInt32Ty(I->getContext());
109 Value *Zero = ConstantInt::get(Int32Ty, 0);
110 Value *One = ConstantInt::get(Int32Ty, 1);
111 Value *Idxs[2] = { Zero, One };
113 Builder.CreateGEP(FunctionContextTy, FuncCtx, Idxs, "call_site");
115 // Insert a store of the call-site number
116 ConstantInt *CallSiteNoC =
117 ConstantInt::get(Type::getInt32Ty(I->getContext()), Number);
118 Builder.CreateStore(CallSiteNoC, CallSite, true /*volatile*/);
121 /// MarkBlocksLiveIn - Insert BB and all of its predecessors into LiveBBs until
122 /// we reach blocks we've already seen.
123 static void MarkBlocksLiveIn(BasicBlock *BB,
124 SmallPtrSetImpl<BasicBlock *> &LiveBBs) {
125 if (!LiveBBs.insert(BB).second)
126 return; // already been here.
128 for (BasicBlock *PredBB : predecessors(BB))
129 MarkBlocksLiveIn(PredBB, LiveBBs);
132 /// substituteLPadValues - Substitute the values returned by the landingpad
133 /// instruction with those returned by the personality function.
134 void SjLjEHPrepare::substituteLPadValues(LandingPadInst *LPI, Value *ExnVal,
136 SmallVector<Value *, 8> UseWorkList(LPI->user_begin(), LPI->user_end());
137 while (!UseWorkList.empty()) {
138 Value *Val = UseWorkList.pop_back_val();
139 auto *EVI = dyn_cast<ExtractValueInst>(Val);
142 if (EVI->getNumIndices() != 1)
144 if (*EVI->idx_begin() == 0)
145 EVI->replaceAllUsesWith(ExnVal);
146 else if (*EVI->idx_begin() == 1)
147 EVI->replaceAllUsesWith(SelVal);
148 if (EVI->use_empty())
149 EVI->eraseFromParent();
152 if (LPI->use_empty())
155 // There are still some uses of LPI. Construct an aggregate with the exception
156 // values and replace the LPI with that aggregate.
157 Type *LPadType = LPI->getType();
158 Value *LPadVal = UndefValue::get(LPadType);
159 auto *SelI = cast<Instruction>(SelVal);
160 IRBuilder<> Builder(SelI->getParent(), std::next(SelI->getIterator()));
161 LPadVal = Builder.CreateInsertValue(LPadVal, ExnVal, 0, "lpad.val");
162 LPadVal = Builder.CreateInsertValue(LPadVal, SelVal, 1, "lpad.val");
164 LPI->replaceAllUsesWith(LPadVal);
167 /// setupFunctionContext - Allocate the function context on the stack and fill
168 /// it with all of the data that we know at this point.
169 Value *SjLjEHPrepare::setupFunctionContext(Function &F,
170 ArrayRef<LandingPadInst *> LPads) {
171 BasicBlock *EntryBB = &F.front();
173 // Create an alloca for the incoming jump buffer ptr and the new jump buffer
174 // that needs to be restored on all exits from the function. This is an alloca
175 // because the value needs to be added to the global context list.
176 auto &DL = F.getParent()->getDataLayout();
177 unsigned Align = DL.getPrefTypeAlignment(FunctionContextTy);
178 FuncCtx = new AllocaInst(FunctionContextTy, DL.getAllocaAddrSpace(),
179 nullptr, Align, "fn_context", &EntryBB->front());
181 // Fill in the function context structure.
182 for (LandingPadInst *LPI : LPads) {
183 IRBuilder<> Builder(LPI->getParent(),
184 LPI->getParent()->getFirstInsertionPt());
186 // Reference the __data field.
188 Builder.CreateConstGEP2_32(FunctionContextTy, FuncCtx, 0, 2, "__data");
190 // The exception values come back in context->__data[0].
191 Value *ExceptionAddr = Builder.CreateConstGEP2_32(doubleUnderDataTy, FCData,
192 0, 0, "exception_gep");
193 Value *ExnVal = Builder.CreateLoad(ExceptionAddr, true, "exn_val");
194 ExnVal = Builder.CreateIntToPtr(ExnVal, Builder.getInt8PtrTy());
196 Value *SelectorAddr = Builder.CreateConstGEP2_32(doubleUnderDataTy, FCData,
197 0, 1, "exn_selector_gep");
198 Value *SelVal = Builder.CreateLoad(SelectorAddr, true, "exn_selector_val");
200 substituteLPadValues(LPI, ExnVal, SelVal);
203 // Personality function
204 IRBuilder<> Builder(EntryBB->getTerminator());
205 Value *PersonalityFn = F.getPersonalityFn();
206 Value *PersonalityFieldPtr = Builder.CreateConstGEP2_32(
207 FunctionContextTy, FuncCtx, 0, 3, "pers_fn_gep");
209 Builder.CreateBitCast(PersonalityFn, Builder.getInt8PtrTy()),
210 PersonalityFieldPtr, /*isVolatile=*/true);
213 Value *LSDA = Builder.CreateCall(LSDAAddrFn, {}, "lsda_addr");
214 Value *LSDAFieldPtr =
215 Builder.CreateConstGEP2_32(FunctionContextTy, FuncCtx, 0, 4, "lsda_gep");
216 Builder.CreateStore(LSDA, LSDAFieldPtr, /*isVolatile=*/true);
221 /// lowerIncomingArguments - To avoid having to handle incoming arguments
222 /// specially, we lower each arg to a copy instruction in the entry block. This
223 /// ensures that the argument value itself cannot be live out of the entry
225 void SjLjEHPrepare::lowerIncomingArguments(Function &F) {
226 BasicBlock::iterator AfterAllocaInsPt = F.begin()->begin();
227 while (isa<AllocaInst>(AfterAllocaInsPt) &&
228 cast<AllocaInst>(AfterAllocaInsPt)->isStaticAlloca())
230 assert(AfterAllocaInsPt != F.front().end());
232 for (auto &AI : F.args()) {
233 Type *Ty = AI.getType();
235 // Use 'select i8 true, %arg, undef' to simulate a 'no-op' instruction.
236 Value *TrueValue = ConstantInt::getTrue(F.getContext());
237 Value *UndefValue = UndefValue::get(Ty);
238 Instruction *SI = SelectInst::Create(
239 TrueValue, &AI, UndefValue, AI.getName() + ".tmp", &*AfterAllocaInsPt);
240 AI.replaceAllUsesWith(SI);
242 // Reset the operand, because it was clobbered by the RAUW above.
243 SI->setOperand(1, &AI);
247 /// lowerAcrossUnwindEdges - Find all variables which are alive across an unwind
248 /// edge and spill them.
249 void SjLjEHPrepare::lowerAcrossUnwindEdges(Function &F,
250 ArrayRef<InvokeInst *> Invokes) {
251 // Finally, scan the code looking for instructions with bad live ranges.
252 for (BasicBlock &BB : F) {
253 for (Instruction &Inst : BB) {
254 // Ignore obvious cases we don't have to handle. In particular, most
255 // instructions either have no uses or only have a single use inside the
256 // current block. Ignore them quickly.
257 if (Inst.use_empty())
259 if (Inst.hasOneUse() &&
260 cast<Instruction>(Inst.user_back())->getParent() == &BB &&
261 !isa<PHINode>(Inst.user_back()))
264 // If this is an alloca in the entry block, it's not a real register
266 if (auto *AI = dyn_cast<AllocaInst>(&Inst))
267 if (AI->isStaticAlloca())
270 // Avoid iterator invalidation by copying users to a temporary vector.
271 SmallVector<Instruction *, 16> Users;
272 for (User *U : Inst.users()) {
273 Instruction *UI = cast<Instruction>(U);
274 if (UI->getParent() != &BB || isa<PHINode>(UI))
278 // Find all of the blocks that this value is live in.
279 SmallPtrSet<BasicBlock *, 32> LiveBBs;
281 while (!Users.empty()) {
282 Instruction *U = Users.pop_back_val();
284 if (!isa<PHINode>(U)) {
285 MarkBlocksLiveIn(U->getParent(), LiveBBs);
287 // Uses for a PHI node occur in their predecessor block.
288 PHINode *PN = cast<PHINode>(U);
289 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
290 if (PN->getIncomingValue(i) == &Inst)
291 MarkBlocksLiveIn(PN->getIncomingBlock(i), LiveBBs);
295 // Now that we know all of the blocks that this thing is live in, see if
296 // it includes any of the unwind locations.
297 bool NeedsSpill = false;
298 for (InvokeInst *Invoke : Invokes) {
299 BasicBlock *UnwindBlock = Invoke->getUnwindDest();
300 if (UnwindBlock != &BB && LiveBBs.count(UnwindBlock)) {
301 DEBUG(dbgs() << "SJLJ Spill: " << Inst << " around "
302 << UnwindBlock->getName() << "\n");
308 // If we decided we need a spill, do it.
309 // FIXME: Spilling this way is overkill, as it forces all uses of
310 // the value to be reloaded from the stack slot, even those that aren't
311 // in the unwind blocks. We should be more selective.
313 DemoteRegToStack(Inst, true);
319 // Go through the landing pads and remove any PHIs there.
320 for (InvokeInst *Invoke : Invokes) {
321 BasicBlock *UnwindBlock = Invoke->getUnwindDest();
322 LandingPadInst *LPI = UnwindBlock->getLandingPadInst();
324 // Place PHIs into a set to avoid invalidating the iterator.
325 SmallPtrSet<PHINode *, 8> PHIsToDemote;
326 for (BasicBlock::iterator PN = UnwindBlock->begin(); isa<PHINode>(PN); ++PN)
327 PHIsToDemote.insert(cast<PHINode>(PN));
328 if (PHIsToDemote.empty())
331 // Demote the PHIs to the stack.
332 for (PHINode *PN : PHIsToDemote)
333 DemotePHIToStack(PN);
335 // Move the landingpad instruction back to the top of the landing pad block.
336 LPI->moveBefore(&UnwindBlock->front());
340 /// setupEntryBlockAndCallSites - Setup the entry block by creating and filling
341 /// the function context and marking the call sites with the appropriate
342 /// values. These values are used by the DWARF EH emitter.
343 bool SjLjEHPrepare::setupEntryBlockAndCallSites(Function &F) {
344 SmallVector<ReturnInst *, 16> Returns;
345 SmallVector<InvokeInst *, 16> Invokes;
346 SmallSetVector<LandingPadInst *, 16> LPads;
348 // Look through the terminators of the basic blocks to find invokes.
349 for (BasicBlock &BB : F)
350 if (auto *II = dyn_cast<InvokeInst>(BB.getTerminator())) {
351 if (Function *Callee = II->getCalledFunction())
352 if (Callee->getIntrinsicID() == Intrinsic::donothing) {
353 // Remove the NOP invoke.
354 BranchInst::Create(II->getNormalDest(), II);
355 II->eraseFromParent();
359 Invokes.push_back(II);
360 LPads.insert(II->getUnwindDest()->getLandingPadInst());
361 } else if (auto *RI = dyn_cast<ReturnInst>(BB.getTerminator())) {
362 Returns.push_back(RI);
368 NumInvokes += Invokes.size();
370 lowerIncomingArguments(F);
371 lowerAcrossUnwindEdges(F, Invokes);
374 setupFunctionContext(F, makeArrayRef(LPads.begin(), LPads.end()));
375 BasicBlock *EntryBB = &F.front();
376 IRBuilder<> Builder(EntryBB->getTerminator());
378 // Get a reference to the jump buffer.
380 Builder.CreateConstGEP2_32(FunctionContextTy, FuncCtx, 0, 5, "jbuf_gep");
382 // Save the frame pointer.
383 Value *FramePtr = Builder.CreateConstGEP2_32(doubleUnderJBufTy, JBufPtr, 0, 0,
386 Value *Val = Builder.CreateCall(FrameAddrFn, Builder.getInt32(0), "fp");
387 Builder.CreateStore(Val, FramePtr, /*isVolatile=*/true);
389 // Save the stack pointer.
390 Value *StackPtr = Builder.CreateConstGEP2_32(doubleUnderJBufTy, JBufPtr, 0, 2,
393 Val = Builder.CreateCall(StackAddrFn, {}, "sp");
394 Builder.CreateStore(Val, StackPtr, /*isVolatile=*/true);
396 // Call the setup_dispatch instrinsic. It fills in the rest of the jmpbuf.
397 Builder.CreateCall(BuiltinSetupDispatchFn, {});
399 // Store a pointer to the function context so that the back-end will know
400 // where to look for it.
401 Value *FuncCtxArg = Builder.CreateBitCast(FuncCtx, Builder.getInt8PtrTy());
402 Builder.CreateCall(FuncCtxFn, FuncCtxArg);
404 // At this point, we are all set up, update the invoke instructions to mark
405 // their call_site values.
406 for (unsigned I = 0, E = Invokes.size(); I != E; ++I) {
407 insertCallSiteStore(Invokes[I], I + 1);
409 ConstantInt *CallSiteNum =
410 ConstantInt::get(Type::getInt32Ty(F.getContext()), I + 1);
412 // Record the call site value for the back end so it stays associated with
414 CallInst::Create(CallSiteFn, CallSiteNum, "", Invokes[I]);
417 // Mark call instructions that aren't nounwind as no-action (call_site ==
418 // -1). Skip the entry block, as prior to then, no function context has been
419 // created for this function and any unexpected exceptions thrown will go
420 // directly to the caller's context, which is what we want anyway, so no need
421 // to do anything here.
422 for (BasicBlock &BB : F) {
423 if (&BB == &F.front())
425 for (Instruction &I : BB)
427 insertCallSiteStore(&I, -1);
430 // Register the function context and make sure it's known to not throw
432 CallInst::Create(RegisterFn, FuncCtx, "", EntryBB->getTerminator());
433 Register->setDoesNotThrow();
435 // Following any allocas not in the entry block, update the saved SP in the
436 // jmpbuf to the new value.
437 for (BasicBlock &BB : F) {
438 if (&BB == &F.front())
440 for (Instruction &I : BB) {
441 if (auto *CI = dyn_cast<CallInst>(&I)) {
442 if (CI->getCalledFunction() != StackRestoreFn)
444 } else if (!isa<AllocaInst>(&I)) {
447 Instruction *StackAddr = CallInst::Create(StackAddrFn, "sp");
448 StackAddr->insertAfter(&I);
449 Instruction *StoreStackAddr = new StoreInst(StackAddr, StackPtr, true);
450 StoreStackAddr->insertAfter(StackAddr);
454 // Finally, for any returns from this function, if this function contains an
455 // invoke, add a call to unregister the function context.
456 for (ReturnInst *Return : Returns)
457 CallInst::Create(UnregisterFn, FuncCtx, "", Return);
462 bool SjLjEHPrepare::undoSwiftErrorSelect(Function &F) {
463 // We have inserted dummy copies 'select true, arg, undef' in the entry block
464 // for arguments to simplify this pass.
465 // swifterror arguments cannot be used in this way. Undo the select for the
466 // swifterror argument.
467 for (auto &AI : F.args()) {
468 if (AI.isSwiftError()) {
469 assert(AI.hasOneUse() && "Must have converted the argument to a select");
470 auto *Select = dyn_cast<SelectInst>(AI.use_begin()->getUser());
471 assert(Select && "There must be single select user");
472 auto *OrigSwiftError = cast<Argument>(Select->getTrueValue());
473 Select->replaceAllUsesWith(OrigSwiftError);
474 Select->eraseFromParent();
481 bool SjLjEHPrepare::runOnFunction(Function &F) {
482 Module &M = *F.getParent();
483 RegisterFn = M.getOrInsertFunction(
484 "_Unwind_SjLj_Register", Type::getVoidTy(M.getContext()),
485 PointerType::getUnqual(FunctionContextTy));
486 UnregisterFn = M.getOrInsertFunction(
487 "_Unwind_SjLj_Unregister", Type::getVoidTy(M.getContext()),
488 PointerType::getUnqual(FunctionContextTy));
489 FrameAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::frameaddress);
490 StackAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::stacksave);
491 StackRestoreFn = Intrinsic::getDeclaration(&M, Intrinsic::stackrestore);
492 BuiltinSetupDispatchFn =
493 Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_setup_dispatch);
494 LSDAAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_lsda);
495 CallSiteFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_callsite);
496 FuncCtxFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_functioncontext);
498 bool Res = setupEntryBlockAndCallSites(F);
500 Res |= undoSwiftErrorSelect(F);