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/ADT/SetVector.h"
16 #include "llvm/ADT/SmallPtrSet.h"
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/ADT/Statistic.h"
19 #include "llvm/CodeGen/Passes.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 df_iterator_default_set<BasicBlock*> Visited;
130 for (BasicBlock *B : inverse_depth_first_ext(BB, Visited))
135 /// substituteLPadValues - Substitute the values returned by the landingpad
136 /// instruction with those returned by the personality function.
137 void SjLjEHPrepare::substituteLPadValues(LandingPadInst *LPI, Value *ExnVal,
139 SmallVector<Value *, 8> UseWorkList(LPI->user_begin(), LPI->user_end());
140 while (!UseWorkList.empty()) {
141 Value *Val = UseWorkList.pop_back_val();
142 auto *EVI = dyn_cast<ExtractValueInst>(Val);
145 if (EVI->getNumIndices() != 1)
147 if (*EVI->idx_begin() == 0)
148 EVI->replaceAllUsesWith(ExnVal);
149 else if (*EVI->idx_begin() == 1)
150 EVI->replaceAllUsesWith(SelVal);
151 if (EVI->use_empty())
152 EVI->eraseFromParent();
155 if (LPI->use_empty())
158 // There are still some uses of LPI. Construct an aggregate with the exception
159 // values and replace the LPI with that aggregate.
160 Type *LPadType = LPI->getType();
161 Value *LPadVal = UndefValue::get(LPadType);
162 auto *SelI = cast<Instruction>(SelVal);
163 IRBuilder<> Builder(SelI->getParent(), std::next(SelI->getIterator()));
164 LPadVal = Builder.CreateInsertValue(LPadVal, ExnVal, 0, "lpad.val");
165 LPadVal = Builder.CreateInsertValue(LPadVal, SelVal, 1, "lpad.val");
167 LPI->replaceAllUsesWith(LPadVal);
170 /// setupFunctionContext - Allocate the function context on the stack and fill
171 /// it with all of the data that we know at this point.
172 Value *SjLjEHPrepare::setupFunctionContext(Function &F,
173 ArrayRef<LandingPadInst *> LPads) {
174 BasicBlock *EntryBB = &F.front();
176 // Create an alloca for the incoming jump buffer ptr and the new jump buffer
177 // that needs to be restored on all exits from the function. This is an alloca
178 // because the value needs to be added to the global context list.
179 auto &DL = F.getParent()->getDataLayout();
180 unsigned Align = DL.getPrefTypeAlignment(FunctionContextTy);
181 FuncCtx = new AllocaInst(FunctionContextTy, DL.getAllocaAddrSpace(),
182 nullptr, Align, "fn_context", &EntryBB->front());
184 // Fill in the function context structure.
185 for (LandingPadInst *LPI : LPads) {
186 IRBuilder<> Builder(LPI->getParent(),
187 LPI->getParent()->getFirstInsertionPt());
189 // Reference the __data field.
191 Builder.CreateConstGEP2_32(FunctionContextTy, FuncCtx, 0, 2, "__data");
193 // The exception values come back in context->__data[0].
194 Value *ExceptionAddr = Builder.CreateConstGEP2_32(doubleUnderDataTy, FCData,
195 0, 0, "exception_gep");
196 Value *ExnVal = Builder.CreateLoad(ExceptionAddr, true, "exn_val");
197 ExnVal = Builder.CreateIntToPtr(ExnVal, Builder.getInt8PtrTy());
199 Value *SelectorAddr = Builder.CreateConstGEP2_32(doubleUnderDataTy, FCData,
200 0, 1, "exn_selector_gep");
201 Value *SelVal = Builder.CreateLoad(SelectorAddr, true, "exn_selector_val");
203 substituteLPadValues(LPI, ExnVal, SelVal);
206 // Personality function
207 IRBuilder<> Builder(EntryBB->getTerminator());
208 Value *PersonalityFn = F.getPersonalityFn();
209 Value *PersonalityFieldPtr = Builder.CreateConstGEP2_32(
210 FunctionContextTy, FuncCtx, 0, 3, "pers_fn_gep");
212 Builder.CreateBitCast(PersonalityFn, Builder.getInt8PtrTy()),
213 PersonalityFieldPtr, /*isVolatile=*/true);
216 Value *LSDA = Builder.CreateCall(LSDAAddrFn, {}, "lsda_addr");
217 Value *LSDAFieldPtr =
218 Builder.CreateConstGEP2_32(FunctionContextTy, FuncCtx, 0, 4, "lsda_gep");
219 Builder.CreateStore(LSDA, LSDAFieldPtr, /*isVolatile=*/true);
224 /// lowerIncomingArguments - To avoid having to handle incoming arguments
225 /// specially, we lower each arg to a copy instruction in the entry block. This
226 /// ensures that the argument value itself cannot be live out of the entry
228 void SjLjEHPrepare::lowerIncomingArguments(Function &F) {
229 BasicBlock::iterator AfterAllocaInsPt = F.begin()->begin();
230 while (isa<AllocaInst>(AfterAllocaInsPt) &&
231 cast<AllocaInst>(AfterAllocaInsPt)->isStaticAlloca())
233 assert(AfterAllocaInsPt != F.front().end());
235 for (auto &AI : F.args()) {
236 Type *Ty = AI.getType();
238 // Use 'select i8 true, %arg, undef' to simulate a 'no-op' instruction.
239 Value *TrueValue = ConstantInt::getTrue(F.getContext());
240 Value *UndefValue = UndefValue::get(Ty);
241 Instruction *SI = SelectInst::Create(
242 TrueValue, &AI, UndefValue, AI.getName() + ".tmp", &*AfterAllocaInsPt);
243 AI.replaceAllUsesWith(SI);
245 // Reset the operand, because it was clobbered by the RAUW above.
246 SI->setOperand(1, &AI);
250 /// lowerAcrossUnwindEdges - Find all variables which are alive across an unwind
251 /// edge and spill them.
252 void SjLjEHPrepare::lowerAcrossUnwindEdges(Function &F,
253 ArrayRef<InvokeInst *> Invokes) {
254 // Finally, scan the code looking for instructions with bad live ranges.
255 for (BasicBlock &BB : F) {
256 for (Instruction &Inst : BB) {
257 // Ignore obvious cases we don't have to handle. In particular, most
258 // instructions either have no uses or only have a single use inside the
259 // current block. Ignore them quickly.
260 if (Inst.use_empty())
262 if (Inst.hasOneUse() &&
263 cast<Instruction>(Inst.user_back())->getParent() == &BB &&
264 !isa<PHINode>(Inst.user_back()))
267 // If this is an alloca in the entry block, it's not a real register
269 if (auto *AI = dyn_cast<AllocaInst>(&Inst))
270 if (AI->isStaticAlloca())
273 // Avoid iterator invalidation by copying users to a temporary vector.
274 SmallVector<Instruction *, 16> Users;
275 for (User *U : Inst.users()) {
276 Instruction *UI = cast<Instruction>(U);
277 if (UI->getParent() != &BB || isa<PHINode>(UI))
281 // Find all of the blocks that this value is live in.
282 SmallPtrSet<BasicBlock *, 32> LiveBBs;
284 while (!Users.empty()) {
285 Instruction *U = Users.pop_back_val();
287 if (!isa<PHINode>(U)) {
288 MarkBlocksLiveIn(U->getParent(), LiveBBs);
290 // Uses for a PHI node occur in their predecessor block.
291 PHINode *PN = cast<PHINode>(U);
292 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
293 if (PN->getIncomingValue(i) == &Inst)
294 MarkBlocksLiveIn(PN->getIncomingBlock(i), LiveBBs);
298 // Now that we know all of the blocks that this thing is live in, see if
299 // it includes any of the unwind locations.
300 bool NeedsSpill = false;
301 for (InvokeInst *Invoke : Invokes) {
302 BasicBlock *UnwindBlock = Invoke->getUnwindDest();
303 if (UnwindBlock != &BB && LiveBBs.count(UnwindBlock)) {
304 DEBUG(dbgs() << "SJLJ Spill: " << Inst << " around "
305 << UnwindBlock->getName() << "\n");
311 // If we decided we need a spill, do it.
312 // FIXME: Spilling this way is overkill, as it forces all uses of
313 // the value to be reloaded from the stack slot, even those that aren't
314 // in the unwind blocks. We should be more selective.
316 DemoteRegToStack(Inst, true);
322 // Go through the landing pads and remove any PHIs there.
323 for (InvokeInst *Invoke : Invokes) {
324 BasicBlock *UnwindBlock = Invoke->getUnwindDest();
325 LandingPadInst *LPI = UnwindBlock->getLandingPadInst();
327 // Place PHIs into a set to avoid invalidating the iterator.
328 SmallPtrSet<PHINode *, 8> PHIsToDemote;
329 for (BasicBlock::iterator PN = UnwindBlock->begin(); isa<PHINode>(PN); ++PN)
330 PHIsToDemote.insert(cast<PHINode>(PN));
331 if (PHIsToDemote.empty())
334 // Demote the PHIs to the stack.
335 for (PHINode *PN : PHIsToDemote)
336 DemotePHIToStack(PN);
338 // Move the landingpad instruction back to the top of the landing pad block.
339 LPI->moveBefore(&UnwindBlock->front());
343 /// setupEntryBlockAndCallSites - Setup the entry block by creating and filling
344 /// the function context and marking the call sites with the appropriate
345 /// values. These values are used by the DWARF EH emitter.
346 bool SjLjEHPrepare::setupEntryBlockAndCallSites(Function &F) {
347 SmallVector<ReturnInst *, 16> Returns;
348 SmallVector<InvokeInst *, 16> Invokes;
349 SmallSetVector<LandingPadInst *, 16> LPads;
351 // Look through the terminators of the basic blocks to find invokes.
352 for (BasicBlock &BB : F)
353 if (auto *II = dyn_cast<InvokeInst>(BB.getTerminator())) {
354 if (Function *Callee = II->getCalledFunction())
355 if (Callee->getIntrinsicID() == Intrinsic::donothing) {
356 // Remove the NOP invoke.
357 BranchInst::Create(II->getNormalDest(), II);
358 II->eraseFromParent();
362 Invokes.push_back(II);
363 LPads.insert(II->getUnwindDest()->getLandingPadInst());
364 } else if (auto *RI = dyn_cast<ReturnInst>(BB.getTerminator())) {
365 Returns.push_back(RI);
371 NumInvokes += Invokes.size();
373 lowerIncomingArguments(F);
374 lowerAcrossUnwindEdges(F, Invokes);
377 setupFunctionContext(F, makeArrayRef(LPads.begin(), LPads.end()));
378 BasicBlock *EntryBB = &F.front();
379 IRBuilder<> Builder(EntryBB->getTerminator());
381 // Get a reference to the jump buffer.
383 Builder.CreateConstGEP2_32(FunctionContextTy, FuncCtx, 0, 5, "jbuf_gep");
385 // Save the frame pointer.
386 Value *FramePtr = Builder.CreateConstGEP2_32(doubleUnderJBufTy, JBufPtr, 0, 0,
389 Value *Val = Builder.CreateCall(FrameAddrFn, Builder.getInt32(0), "fp");
390 Builder.CreateStore(Val, FramePtr, /*isVolatile=*/true);
392 // Save the stack pointer.
393 Value *StackPtr = Builder.CreateConstGEP2_32(doubleUnderJBufTy, JBufPtr, 0, 2,
396 Val = Builder.CreateCall(StackAddrFn, {}, "sp");
397 Builder.CreateStore(Val, StackPtr, /*isVolatile=*/true);
399 // Call the setup_dispatch instrinsic. It fills in the rest of the jmpbuf.
400 Builder.CreateCall(BuiltinSetupDispatchFn, {});
402 // Store a pointer to the function context so that the back-end will know
403 // where to look for it.
404 Value *FuncCtxArg = Builder.CreateBitCast(FuncCtx, Builder.getInt8PtrTy());
405 Builder.CreateCall(FuncCtxFn, FuncCtxArg);
407 // At this point, we are all set up, update the invoke instructions to mark
408 // their call_site values.
409 for (unsigned I = 0, E = Invokes.size(); I != E; ++I) {
410 insertCallSiteStore(Invokes[I], I + 1);
412 ConstantInt *CallSiteNum =
413 ConstantInt::get(Type::getInt32Ty(F.getContext()), I + 1);
415 // Record the call site value for the back end so it stays associated with
417 CallInst::Create(CallSiteFn, CallSiteNum, "", Invokes[I]);
420 // Mark call instructions that aren't nounwind as no-action (call_site ==
421 // -1). Skip the entry block, as prior to then, no function context has been
422 // created for this function and any unexpected exceptions thrown will go
423 // directly to the caller's context, which is what we want anyway, so no need
424 // to do anything here.
425 for (BasicBlock &BB : F) {
426 if (&BB == &F.front())
428 for (Instruction &I : BB)
430 insertCallSiteStore(&I, -1);
433 // Register the function context and make sure it's known to not throw
435 CallInst::Create(RegisterFn, FuncCtx, "", EntryBB->getTerminator());
436 Register->setDoesNotThrow();
438 // Following any allocas not in the entry block, update the saved SP in the
439 // jmpbuf to the new value.
440 for (BasicBlock &BB : F) {
441 if (&BB == &F.front())
443 for (Instruction &I : BB) {
444 if (auto *CI = dyn_cast<CallInst>(&I)) {
445 if (CI->getCalledFunction() != StackRestoreFn)
447 } else if (!isa<AllocaInst>(&I)) {
450 Instruction *StackAddr = CallInst::Create(StackAddrFn, "sp");
451 StackAddr->insertAfter(&I);
452 Instruction *StoreStackAddr = new StoreInst(StackAddr, StackPtr, true);
453 StoreStackAddr->insertAfter(StackAddr);
457 // Finally, for any returns from this function, if this function contains an
458 // invoke, add a call to unregister the function context.
459 for (ReturnInst *Return : Returns)
460 CallInst::Create(UnregisterFn, FuncCtx, "", Return);
465 bool SjLjEHPrepare::undoSwiftErrorSelect(Function &F) {
466 // We have inserted dummy copies 'select true, arg, undef' in the entry block
467 // for arguments to simplify this pass.
468 // swifterror arguments cannot be used in this way. Undo the select for the
469 // swifterror argument.
470 for (auto &AI : F.args()) {
471 if (AI.isSwiftError()) {
472 assert(AI.hasOneUse() && "Must have converted the argument to a select");
473 auto *Select = dyn_cast<SelectInst>(AI.use_begin()->getUser());
474 assert(Select && "There must be single select user");
475 auto *OrigSwiftError = cast<Argument>(Select->getTrueValue());
476 Select->replaceAllUsesWith(OrigSwiftError);
477 Select->eraseFromParent();
484 bool SjLjEHPrepare::runOnFunction(Function &F) {
485 Module &M = *F.getParent();
486 RegisterFn = M.getOrInsertFunction(
487 "_Unwind_SjLj_Register", Type::getVoidTy(M.getContext()),
488 PointerType::getUnqual(FunctionContextTy));
489 UnregisterFn = M.getOrInsertFunction(
490 "_Unwind_SjLj_Unregister", Type::getVoidTy(M.getContext()),
491 PointerType::getUnqual(FunctionContextTy));
492 FrameAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::frameaddress);
493 StackAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::stacksave);
494 StackRestoreFn = Intrinsic::getDeclaration(&M, Intrinsic::stackrestore);
495 BuiltinSetupDispatchFn =
496 Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_setup_dispatch);
497 LSDAAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_lsda);
498 CallSiteFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_callsite);
499 FuncCtxFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_functioncontext);
501 bool Res = setupEntryBlockAndCallSites(F);
503 Res |= undoSwiftErrorSelect(F);