1 //===- SjLjEHPrepare.cpp - Eliminate Invoke & Unwind instructions ---------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This transformation is designed for use by code generators which use SjLj
10 // based exception handling.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/ADT/SetVector.h"
15 #include "llvm/ADT/SmallPtrSet.h"
16 #include "llvm/ADT/SmallVector.h"
17 #include "llvm/ADT/Statistic.h"
18 #include "llvm/CodeGen/Passes.h"
19 #include "llvm/IR/Constants.h"
20 #include "llvm/IR/DataLayout.h"
21 #include "llvm/IR/DerivedTypes.h"
22 #include "llvm/IR/IRBuilder.h"
23 #include "llvm/IR/Instructions.h"
24 #include "llvm/IR/Intrinsics.h"
25 #include "llvm/IR/Module.h"
26 #include "llvm/InitializePasses.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"
31 using namespace llvm;
32
33 #define DEBUG_TYPE "sjljehprepare"
34
35 STATISTIC(NumInvokes, "Number of invokes replaced");
36 STATISTIC(NumSpilled, "Number of registers live across unwind edges");
37
38 namespace {
39 class SjLjEHPrepare : public FunctionPass {
40 Type *doubleUnderDataTy;
41 Type *doubleUnderJBufTy;
42 Type *FunctionContextTy;
43 FunctionCallee RegisterFn;
44 FunctionCallee UnregisterFn;
45 Function *BuiltinSetupDispatchFn;
46 Function *FrameAddrFn;
47 Function *StackAddrFn;
48 Function *StackRestoreFn;
49 Function *LSDAAddrFn;
50 Function *CallSiteFn;
51 Function *FuncCtxFn;
52 AllocaInst *FuncCtx;
53
54 public:
55 static char ID; // Pass identification, replacement for typeid
SjLjEHPrepare()56 explicit SjLjEHPrepare() : FunctionPass(ID) {}
57 bool doInitialization(Module &M) override;
58 bool runOnFunction(Function &F) override;
59
getAnalysisUsage(AnalysisUsage & AU) const60 void getAnalysisUsage(AnalysisUsage &AU) const override {}
getPassName() const61 StringRef getPassName() const override {
62 return "SJLJ Exception Handling preparation";
63 }
64
65 private:
66 bool setupEntryBlockAndCallSites(Function &F);
67 void substituteLPadValues(LandingPadInst *LPI, Value *ExnVal, Value *SelVal);
68 Value *setupFunctionContext(Function &F, ArrayRef<LandingPadInst *> LPads);
69 void lowerIncomingArguments(Function &F);
70 void lowerAcrossUnwindEdges(Function &F, ArrayRef<InvokeInst *> Invokes);
71 void insertCallSiteStore(Instruction *I, int Number);
72 };
73 } // end anonymous namespace
74
75 char SjLjEHPrepare::ID = 0;
76 INITIALIZE_PASS(SjLjEHPrepare, DEBUG_TYPE, "Prepare SjLj exceptions",
77 false, false)
78
79 // Public Interface To the SjLjEHPrepare pass.
createSjLjEHPreparePass()80 FunctionPass *llvm::createSjLjEHPreparePass() { return new SjLjEHPrepare(); }
81 // doInitialization - Set up decalarations and types needed to process
82 // exceptions.
doInitialization(Module & M)83 bool SjLjEHPrepare::doInitialization(Module &M) {
84 // Build the function context structure.
85 // builtin_setjmp uses a five word jbuf
86 Type *VoidPtrTy = Type::getInt8PtrTy(M.getContext());
87 Type *Int32Ty = Type::getInt32Ty(M.getContext());
88 doubleUnderDataTy = ArrayType::get(Int32Ty, 4);
89 doubleUnderJBufTy = ArrayType::get(VoidPtrTy, 5);
90 FunctionContextTy = StructType::get(VoidPtrTy, // __prev
91 Int32Ty, // call_site
92 doubleUnderDataTy, // __data
93 VoidPtrTy, // __personality
94 VoidPtrTy, // __lsda
95 doubleUnderJBufTy // __jbuf
96 );
97
98 return true;
99 }
100
101 /// insertCallSiteStore - Insert a store of the call-site value to the
102 /// function context
insertCallSiteStore(Instruction * I,int Number)103 void SjLjEHPrepare::insertCallSiteStore(Instruction *I, int Number) {
104 IRBuilder<> Builder(I);
105
106 // Get a reference to the call_site field.
107 Type *Int32Ty = Type::getInt32Ty(I->getContext());
108 Value *Zero = ConstantInt::get(Int32Ty, 0);
109 Value *One = ConstantInt::get(Int32Ty, 1);
110 Value *Idxs[2] = { Zero, One };
111 Value *CallSite =
112 Builder.CreateGEP(FunctionContextTy, FuncCtx, Idxs, "call_site");
113
114 // Insert a store of the call-site number
115 ConstantInt *CallSiteNoC =
116 ConstantInt::get(Type::getInt32Ty(I->getContext()), Number);
117 Builder.CreateStore(CallSiteNoC, CallSite, true /*volatile*/);
118 }
119
120 /// MarkBlocksLiveIn - Insert BB and all of its predecessors into LiveBBs until
121 /// we reach blocks we've already seen.
MarkBlocksLiveIn(BasicBlock * BB,SmallPtrSetImpl<BasicBlock * > & LiveBBs)122 static void MarkBlocksLiveIn(BasicBlock *BB,
123 SmallPtrSetImpl<BasicBlock *> &LiveBBs) {
124 if (!LiveBBs.insert(BB).second)
125 return; // already been here.
126
127 df_iterator_default_set<BasicBlock*> Visited;
128
129 for (BasicBlock *B : inverse_depth_first_ext(BB, Visited))
130 LiveBBs.insert(B);
131
132 }
133
134 /// substituteLPadValues - Substitute the values returned by the landingpad
135 /// instruction with those returned by the personality function.
substituteLPadValues(LandingPadInst * LPI,Value * ExnVal,Value * SelVal)136 void SjLjEHPrepare::substituteLPadValues(LandingPadInst *LPI, Value *ExnVal,
137 Value *SelVal) {
138 SmallVector<Value *, 8> UseWorkList(LPI->user_begin(), LPI->user_end());
139 while (!UseWorkList.empty()) {
140 Value *Val = UseWorkList.pop_back_val();
141 auto *EVI = dyn_cast<ExtractValueInst>(Val);
142 if (!EVI)
143 continue;
144 if (EVI->getNumIndices() != 1)
145 continue;
146 if (*EVI->idx_begin() == 0)
147 EVI->replaceAllUsesWith(ExnVal);
148 else if (*EVI->idx_begin() == 1)
149 EVI->replaceAllUsesWith(SelVal);
150 if (EVI->use_empty())
151 EVI->eraseFromParent();
152 }
153
154 if (LPI->use_empty())
155 return;
156
157 // There are still some uses of LPI. Construct an aggregate with the exception
158 // values and replace the LPI with that aggregate.
159 Type *LPadType = LPI->getType();
160 Value *LPadVal = UndefValue::get(LPadType);
161 auto *SelI = cast<Instruction>(SelVal);
162 IRBuilder<> Builder(SelI->getParent(), std::next(SelI->getIterator()));
163 LPadVal = Builder.CreateInsertValue(LPadVal, ExnVal, 0, "lpad.val");
164 LPadVal = Builder.CreateInsertValue(LPadVal, SelVal, 1, "lpad.val");
165
166 LPI->replaceAllUsesWith(LPadVal);
167 }
168
169 /// setupFunctionContext - Allocate the function context on the stack and fill
170 /// it with all of the data that we know at this point.
setupFunctionContext(Function & F,ArrayRef<LandingPadInst * > LPads)171 Value *SjLjEHPrepare::setupFunctionContext(Function &F,
172 ArrayRef<LandingPadInst *> LPads) {
173 BasicBlock *EntryBB = &F.front();
174
175 // Create an alloca for the incoming jump buffer ptr and the new jump buffer
176 // that needs to be restored on all exits from the function. This is an alloca
177 // because the value needs to be added to the global context list.
178 auto &DL = F.getParent()->getDataLayout();
179 const Align Alignment(DL.getPrefTypeAlignment(FunctionContextTy));
180 FuncCtx = new AllocaInst(FunctionContextTy, DL.getAllocaAddrSpace(), nullptr,
181 Alignment, "fn_context", &EntryBB->front());
182
183 // Fill in the function context structure.
184 for (LandingPadInst *LPI : LPads) {
185 IRBuilder<> Builder(LPI->getParent(),
186 LPI->getParent()->getFirstInsertionPt());
187
188 // Reference the __data field.
189 Value *FCData =
190 Builder.CreateConstGEP2_32(FunctionContextTy, FuncCtx, 0, 2, "__data");
191
192 // The exception values come back in context->__data[0].
193 Type *Int32Ty = Type::getInt32Ty(F.getContext());
194 Value *ExceptionAddr = Builder.CreateConstGEP2_32(doubleUnderDataTy, FCData,
195 0, 0, "exception_gep");
196 Value *ExnVal = Builder.CreateLoad(Int32Ty, ExceptionAddr, true, "exn_val");
197 ExnVal = Builder.CreateIntToPtr(ExnVal, Builder.getInt8PtrTy());
198
199 Value *SelectorAddr = Builder.CreateConstGEP2_32(doubleUnderDataTy, FCData,
200 0, 1, "exn_selector_gep");
201 Value *SelVal =
202 Builder.CreateLoad(Int32Ty, SelectorAddr, true, "exn_selector_val");
203
204 substituteLPadValues(LPI, ExnVal, SelVal);
205 }
206
207 // Personality function
208 IRBuilder<> Builder(EntryBB->getTerminator());
209 Value *PersonalityFn = F.getPersonalityFn();
210 Value *PersonalityFieldPtr = Builder.CreateConstGEP2_32(
211 FunctionContextTy, FuncCtx, 0, 3, "pers_fn_gep");
212 Builder.CreateStore(
213 Builder.CreateBitCast(PersonalityFn, Builder.getInt8PtrTy()),
214 PersonalityFieldPtr, /*isVolatile=*/true);
215
216 // LSDA address
217 Value *LSDA = Builder.CreateCall(LSDAAddrFn, {}, "lsda_addr");
218 Value *LSDAFieldPtr =
219 Builder.CreateConstGEP2_32(FunctionContextTy, FuncCtx, 0, 4, "lsda_gep");
220 Builder.CreateStore(LSDA, LSDAFieldPtr, /*isVolatile=*/true);
221
222 return FuncCtx;
223 }
224
225 /// lowerIncomingArguments - To avoid having to handle incoming arguments
226 /// specially, we lower each arg to a copy instruction in the entry block. This
227 /// ensures that the argument value itself cannot be live out of the entry
228 /// block.
lowerIncomingArguments(Function & F)229 void SjLjEHPrepare::lowerIncomingArguments(Function &F) {
230 BasicBlock::iterator AfterAllocaInsPt = F.begin()->begin();
231 while (isa<AllocaInst>(AfterAllocaInsPt) &&
232 cast<AllocaInst>(AfterAllocaInsPt)->isStaticAlloca())
233 ++AfterAllocaInsPt;
234 assert(AfterAllocaInsPt != F.front().end());
235
236 for (auto &AI : F.args()) {
237 // Swift error really is a register that we model as memory -- instruction
238 // selection will perform mem-to-reg for us and spill/reload appropriately
239 // around calls that clobber it. There is no need to spill this
240 // value to the stack and doing so would not be allowed.
241 if (AI.isSwiftError())
242 continue;
243
244 Type *Ty = AI.getType();
245
246 // Use 'select i8 true, %arg, undef' to simulate a 'no-op' instruction.
247 Value *TrueValue = ConstantInt::getTrue(F.getContext());
248 Value *UndefValue = UndefValue::get(Ty);
249 Instruction *SI = SelectInst::Create(
250 TrueValue, &AI, UndefValue, AI.getName() + ".tmp", &*AfterAllocaInsPt);
251 AI.replaceAllUsesWith(SI);
252
253 // Reset the operand, because it was clobbered by the RAUW above.
254 SI->setOperand(1, &AI);
255 }
256 }
257
258 /// lowerAcrossUnwindEdges - Find all variables which are alive across an unwind
259 /// edge and spill them.
lowerAcrossUnwindEdges(Function & F,ArrayRef<InvokeInst * > Invokes)260 void SjLjEHPrepare::lowerAcrossUnwindEdges(Function &F,
261 ArrayRef<InvokeInst *> Invokes) {
262 // Finally, scan the code looking for instructions with bad live ranges.
263 for (BasicBlock &BB : F) {
264 for (Instruction &Inst : BB) {
265 // Ignore obvious cases we don't have to handle. In particular, most
266 // instructions either have no uses or only have a single use inside the
267 // current block. Ignore them quickly.
268 if (Inst.use_empty())
269 continue;
270 if (Inst.hasOneUse() &&
271 cast<Instruction>(Inst.user_back())->getParent() == &BB &&
272 !isa<PHINode>(Inst.user_back()))
273 continue;
274
275 // If this is an alloca in the entry block, it's not a real register
276 // value.
277 if (auto *AI = dyn_cast<AllocaInst>(&Inst))
278 if (AI->isStaticAlloca())
279 continue;
280
281 // Avoid iterator invalidation by copying users to a temporary vector.
282 SmallVector<Instruction *, 16> Users;
283 for (User *U : Inst.users()) {
284 Instruction *UI = cast<Instruction>(U);
285 if (UI->getParent() != &BB || isa<PHINode>(UI))
286 Users.push_back(UI);
287 }
288
289 // Find all of the blocks that this value is live in.
290 SmallPtrSet<BasicBlock *, 32> LiveBBs;
291 LiveBBs.insert(&BB);
292 while (!Users.empty()) {
293 Instruction *U = Users.pop_back_val();
294
295 if (!isa<PHINode>(U)) {
296 MarkBlocksLiveIn(U->getParent(), LiveBBs);
297 } else {
298 // Uses for a PHI node occur in their predecessor block.
299 PHINode *PN = cast<PHINode>(U);
300 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
301 if (PN->getIncomingValue(i) == &Inst)
302 MarkBlocksLiveIn(PN->getIncomingBlock(i), LiveBBs);
303 }
304 }
305
306 // Now that we know all of the blocks that this thing is live in, see if
307 // it includes any of the unwind locations.
308 bool NeedsSpill = false;
309 for (InvokeInst *Invoke : Invokes) {
310 BasicBlock *UnwindBlock = Invoke->getUnwindDest();
311 if (UnwindBlock != &BB && LiveBBs.count(UnwindBlock)) {
312 LLVM_DEBUG(dbgs() << "SJLJ Spill: " << Inst << " around "
313 << UnwindBlock->getName() << "\n");
314 NeedsSpill = true;
315 break;
316 }
317 }
318
319 // If we decided we need a spill, do it.
320 // FIXME: Spilling this way is overkill, as it forces all uses of
321 // the value to be reloaded from the stack slot, even those that aren't
322 // in the unwind blocks. We should be more selective.
323 if (NeedsSpill) {
324 DemoteRegToStack(Inst, true);
325 ++NumSpilled;
326 }
327 }
328 }
329
330 // Go through the landing pads and remove any PHIs there.
331 for (InvokeInst *Invoke : Invokes) {
332 BasicBlock *UnwindBlock = Invoke->getUnwindDest();
333 LandingPadInst *LPI = UnwindBlock->getLandingPadInst();
334
335 // Place PHIs into a set to avoid invalidating the iterator.
336 SmallPtrSet<PHINode *, 8> PHIsToDemote;
337 for (BasicBlock::iterator PN = UnwindBlock->begin(); isa<PHINode>(PN); ++PN)
338 PHIsToDemote.insert(cast<PHINode>(PN));
339 if (PHIsToDemote.empty())
340 continue;
341
342 // Demote the PHIs to the stack.
343 for (PHINode *PN : PHIsToDemote)
344 DemotePHIToStack(PN);
345
346 // Move the landingpad instruction back to the top of the landing pad block.
347 LPI->moveBefore(&UnwindBlock->front());
348 }
349 }
350
351 /// setupEntryBlockAndCallSites - Setup the entry block by creating and filling
352 /// the function context and marking the call sites with the appropriate
353 /// values. These values are used by the DWARF EH emitter.
setupEntryBlockAndCallSites(Function & F)354 bool SjLjEHPrepare::setupEntryBlockAndCallSites(Function &F) {
355 SmallVector<ReturnInst *, 16> Returns;
356 SmallVector<InvokeInst *, 16> Invokes;
357 SmallSetVector<LandingPadInst *, 16> LPads;
358
359 // Look through the terminators of the basic blocks to find invokes.
360 for (BasicBlock &BB : F)
361 if (auto *II = dyn_cast<InvokeInst>(BB.getTerminator())) {
362 if (Function *Callee = II->getCalledFunction())
363 if (Callee->getIntrinsicID() == Intrinsic::donothing) {
364 // Remove the NOP invoke.
365 BranchInst::Create(II->getNormalDest(), II);
366 II->eraseFromParent();
367 continue;
368 }
369
370 Invokes.push_back(II);
371 LPads.insert(II->getUnwindDest()->getLandingPadInst());
372 } else if (auto *RI = dyn_cast<ReturnInst>(BB.getTerminator())) {
373 Returns.push_back(RI);
374 }
375
376 if (Invokes.empty())
377 return false;
378
379 NumInvokes += Invokes.size();
380
381 lowerIncomingArguments(F);
382 lowerAcrossUnwindEdges(F, Invokes);
383
384 Value *FuncCtx =
385 setupFunctionContext(F, makeArrayRef(LPads.begin(), LPads.end()));
386 BasicBlock *EntryBB = &F.front();
387 IRBuilder<> Builder(EntryBB->getTerminator());
388
389 // Get a reference to the jump buffer.
390 Value *JBufPtr =
391 Builder.CreateConstGEP2_32(FunctionContextTy, FuncCtx, 0, 5, "jbuf_gep");
392
393 // Save the frame pointer.
394 Value *FramePtr = Builder.CreateConstGEP2_32(doubleUnderJBufTy, JBufPtr, 0, 0,
395 "jbuf_fp_gep");
396
397 Value *Val = Builder.CreateCall(FrameAddrFn, Builder.getInt32(0), "fp");
398 Builder.CreateStore(Val, FramePtr, /*isVolatile=*/true);
399
400 // Save the stack pointer.
401 Value *StackPtr = Builder.CreateConstGEP2_32(doubleUnderJBufTy, JBufPtr, 0, 2,
402 "jbuf_sp_gep");
403
404 Val = Builder.CreateCall(StackAddrFn, {}, "sp");
405 Builder.CreateStore(Val, StackPtr, /*isVolatile=*/true);
406
407 // Call the setup_dispatch instrinsic. It fills in the rest of the jmpbuf.
408 Builder.CreateCall(BuiltinSetupDispatchFn, {});
409
410 // Store a pointer to the function context so that the back-end will know
411 // where to look for it.
412 Value *FuncCtxArg = Builder.CreateBitCast(FuncCtx, Builder.getInt8PtrTy());
413 Builder.CreateCall(FuncCtxFn, FuncCtxArg);
414
415 // At this point, we are all set up, update the invoke instructions to mark
416 // their call_site values.
417 for (unsigned I = 0, E = Invokes.size(); I != E; ++I) {
418 insertCallSiteStore(Invokes[I], I + 1);
419
420 ConstantInt *CallSiteNum =
421 ConstantInt::get(Type::getInt32Ty(F.getContext()), I + 1);
422
423 // Record the call site value for the back end so it stays associated with
424 // the invoke.
425 CallInst::Create(CallSiteFn, CallSiteNum, "", Invokes[I]);
426 }
427
428 // Mark call instructions that aren't nounwind as no-action (call_site ==
429 // -1). Skip the entry block, as prior to then, no function context has been
430 // created for this function and any unexpected exceptions thrown will go
431 // directly to the caller's context, which is what we want anyway, so no need
432 // to do anything here.
433 for (BasicBlock &BB : F) {
434 if (&BB == &F.front())
435 continue;
436 for (Instruction &I : BB)
437 if (I.mayThrow())
438 insertCallSiteStore(&I, -1);
439 }
440
441 // Register the function context and make sure it's known to not throw
442 CallInst *Register =
443 CallInst::Create(RegisterFn, FuncCtx, "", EntryBB->getTerminator());
444 Register->setDoesNotThrow();
445
446 // Following any allocas not in the entry block, update the saved SP in the
447 // jmpbuf to the new value.
448 for (BasicBlock &BB : F) {
449 if (&BB == &F.front())
450 continue;
451 for (Instruction &I : BB) {
452 if (auto *CI = dyn_cast<CallInst>(&I)) {
453 if (CI->getCalledFunction() != StackRestoreFn)
454 continue;
455 } else if (!isa<AllocaInst>(&I)) {
456 continue;
457 }
458 Instruction *StackAddr = CallInst::Create(StackAddrFn, "sp");
459 StackAddr->insertAfter(&I);
460 Instruction *StoreStackAddr = new StoreInst(StackAddr, StackPtr, true);
461 StoreStackAddr->insertAfter(StackAddr);
462 }
463 }
464
465 // Finally, for any returns from this function, if this function contains an
466 // invoke, add a call to unregister the function context.
467 for (ReturnInst *Return : Returns)
468 CallInst::Create(UnregisterFn, FuncCtx, "", Return);
469
470 return true;
471 }
472
runOnFunction(Function & F)473 bool SjLjEHPrepare::runOnFunction(Function &F) {
474 Module &M = *F.getParent();
475 RegisterFn = M.getOrInsertFunction(
476 "_Unwind_SjLj_Register", Type::getVoidTy(M.getContext()),
477 PointerType::getUnqual(FunctionContextTy));
478 UnregisterFn = M.getOrInsertFunction(
479 "_Unwind_SjLj_Unregister", Type::getVoidTy(M.getContext()),
480 PointerType::getUnqual(FunctionContextTy));
481 FrameAddrFn = Intrinsic::getDeclaration(
482 &M, Intrinsic::frameaddress,
483 {Type::getInt8PtrTy(M.getContext(),
484 M.getDataLayout().getAllocaAddrSpace())});
485 StackAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::stacksave);
486 StackRestoreFn = Intrinsic::getDeclaration(&M, Intrinsic::stackrestore);
487 BuiltinSetupDispatchFn =
488 Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_setup_dispatch);
489 LSDAAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_lsda);
490 CallSiteFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_callsite);
491 FuncCtxFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_functioncontext);
492
493 bool Res = setupEntryBlockAndCallSites(F);
494 return Res;
495 }
496