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/DenseMap.h"
17 #include "llvm/ADT/SetVector.h"
18 #include "llvm/ADT/SmallPtrSet.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/ADT/Statistic.h"
21 #include "llvm/IR/Constants.h"
22 #include "llvm/IR/DataLayout.h"
23 #include "llvm/IR/DerivedTypes.h"
24 #include "llvm/IR/IRBuilder.h"
25 #include "llvm/IR/Instructions.h"
26 #include "llvm/IR/Intrinsics.h"
27 #include "llvm/IR/LLVMContext.h"
28 #include "llvm/IR/Module.h"
29 #include "llvm/Pass.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include "llvm/Target/TargetLowering.h"
34 #include "llvm/Target/TargetSubtargetInfo.h"
35 #include "llvm/Transforms/Scalar.h"
36 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
37 #include "llvm/Transforms/Utils/Local.h"
41 #define DEBUG_TYPE "sjljehprepare"
43 STATISTIC(NumInvokes, "Number of invokes replaced");
44 STATISTIC(NumSpilled, "Number of registers live across unwind edges");
47 class SjLjEHPrepare : public FunctionPass {
48 const TargetMachine *TM;
49 Type *FunctionContextTy;
51 Constant *UnregisterFn;
52 Constant *BuiltinSetjmpFn;
53 Constant *FrameAddrFn;
54 Constant *StackAddrFn;
55 Constant *StackRestoreFn;
63 static char ID; // Pass identification, replacement for typeid
64 explicit SjLjEHPrepare(const TargetMachine *TM) : FunctionPass(ID), TM(TM) {}
65 bool doInitialization(Module &M) override;
66 bool runOnFunction(Function &F) override;
68 void getAnalysisUsage(AnalysisUsage &AU) const override {}
69 const char *getPassName() const override {
70 return "SJLJ Exception Handling preparation";
74 bool setupEntryBlockAndCallSites(Function &F);
75 void substituteLPadValues(LandingPadInst *LPI, Value *ExnVal, Value *SelVal);
76 Value *setupFunctionContext(Function &F, ArrayRef<LandingPadInst *> LPads);
77 void lowerIncomingArguments(Function &F);
78 void lowerAcrossUnwindEdges(Function &F, ArrayRef<InvokeInst *> Invokes);
79 void insertCallSiteStore(Instruction *I, int Number);
81 } // end anonymous namespace
83 char SjLjEHPrepare::ID = 0;
85 // Public Interface To the SjLjEHPrepare pass.
86 FunctionPass *llvm::createSjLjEHPreparePass(const TargetMachine *TM) {
87 return new SjLjEHPrepare(TM);
89 // doInitialization - Set up decalarations and types needed to process
91 bool SjLjEHPrepare::doInitialization(Module &M) {
92 // Build the function context structure.
93 // builtin_setjmp uses a five word jbuf
94 Type *VoidPtrTy = Type::getInt8PtrTy(M.getContext());
95 Type *Int32Ty = Type::getInt32Ty(M.getContext());
96 FunctionContextTy = StructType::get(VoidPtrTy, // __prev
98 ArrayType::get(Int32Ty, 4), // __data
99 VoidPtrTy, // __personality
101 ArrayType::get(VoidPtrTy, 5), // __jbuf
103 RegisterFn = M.getOrInsertFunction(
104 "_Unwind_SjLj_Register", Type::getVoidTy(M.getContext()),
105 PointerType::getUnqual(FunctionContextTy), (Type *)nullptr);
106 UnregisterFn = M.getOrInsertFunction(
107 "_Unwind_SjLj_Unregister", Type::getVoidTy(M.getContext()),
108 PointerType::getUnqual(FunctionContextTy), (Type *)nullptr);
109 FrameAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::frameaddress);
110 StackAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::stacksave);
111 StackRestoreFn = Intrinsic::getDeclaration(&M, Intrinsic::stackrestore);
112 BuiltinSetjmpFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_setjmp);
113 LSDAAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_lsda);
114 CallSiteFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_callsite);
115 FuncCtxFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_functioncontext);
116 PersonalityFn = nullptr;
121 /// insertCallSiteStore - Insert a store of the call-site value to the
123 void SjLjEHPrepare::insertCallSiteStore(Instruction *I, int Number) {
124 IRBuilder<> Builder(I);
126 // Get a reference to the call_site field.
127 Type *Int32Ty = Type::getInt32Ty(I->getContext());
128 Value *Zero = ConstantInt::get(Int32Ty, 0);
129 Value *One = ConstantInt::get(Int32Ty, 1);
130 Value *Idxs[2] = { Zero, One };
132 Builder.CreateGEP(FunctionContextTy, FuncCtx, Idxs, "call_site");
134 // Insert a store of the call-site number
135 ConstantInt *CallSiteNoC =
136 ConstantInt::get(Type::getInt32Ty(I->getContext()), Number);
137 Builder.CreateStore(CallSiteNoC, CallSite, true /*volatile*/);
140 /// MarkBlocksLiveIn - Insert BB and all of its predescessors into LiveBBs until
141 /// we reach blocks we've already seen.
142 static void MarkBlocksLiveIn(BasicBlock *BB,
143 SmallPtrSetImpl<BasicBlock *> &LiveBBs) {
144 if (!LiveBBs.insert(BB).second)
145 return; // already been here.
147 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
148 MarkBlocksLiveIn(*PI, LiveBBs);
151 /// substituteLPadValues - Substitute the values returned by the landingpad
152 /// instruction with those returned by the personality function.
153 void SjLjEHPrepare::substituteLPadValues(LandingPadInst *LPI, Value *ExnVal,
155 SmallVector<Value *, 8> UseWorkList(LPI->user_begin(), LPI->user_end());
156 while (!UseWorkList.empty()) {
157 Value *Val = UseWorkList.pop_back_val();
158 ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(Val);
161 if (EVI->getNumIndices() != 1)
163 if (*EVI->idx_begin() == 0)
164 EVI->replaceAllUsesWith(ExnVal);
165 else if (*EVI->idx_begin() == 1)
166 EVI->replaceAllUsesWith(SelVal);
167 if (EVI->getNumUses() == 0)
168 EVI->eraseFromParent();
171 if (LPI->getNumUses() == 0)
174 // There are still some uses of LPI. Construct an aggregate with the exception
175 // values and replace the LPI with that aggregate.
176 Type *LPadType = LPI->getType();
177 Value *LPadVal = UndefValue::get(LPadType);
179 std::next(BasicBlock::iterator(cast<Instruction>(SelVal))));
180 LPadVal = Builder.CreateInsertValue(LPadVal, ExnVal, 0, "lpad.val");
181 LPadVal = Builder.CreateInsertValue(LPadVal, SelVal, 1, "lpad.val");
183 LPI->replaceAllUsesWith(LPadVal);
186 /// setupFunctionContext - Allocate the function context on the stack and fill
187 /// it with all of the data that we know at this point.
188 Value *SjLjEHPrepare::setupFunctionContext(Function &F,
189 ArrayRef<LandingPadInst *> LPads) {
190 BasicBlock *EntryBB = F.begin();
192 // Create an alloca for the incoming jump buffer ptr and the new jump buffer
193 // that needs to be restored on all exits from the function. This is an alloca
194 // because the value needs to be added to the global context list.
195 const TargetLowering *TLI = TM->getSubtargetImpl(F)->getTargetLowering();
197 TLI->getDataLayout()->getPrefTypeAlignment(FunctionContextTy);
198 FuncCtx = new AllocaInst(FunctionContextTy, nullptr, Align, "fn_context",
201 // Fill in the function context structure.
202 for (unsigned I = 0, E = LPads.size(); I != E; ++I) {
203 LandingPadInst *LPI = LPads[I];
204 IRBuilder<> Builder(LPI->getParent()->getFirstInsertionPt());
206 // Reference the __data field.
207 Value *FCData = Builder.CreateConstGEP2_32(FuncCtx, 0, 2, "__data");
209 // The exception values come back in context->__data[0].
210 Value *ExceptionAddr =
211 Builder.CreateConstGEP2_32(FCData, 0, 0, "exception_gep");
212 Value *ExnVal = Builder.CreateLoad(ExceptionAddr, true, "exn_val");
213 ExnVal = Builder.CreateIntToPtr(ExnVal, Builder.getInt8PtrTy());
215 Value *SelectorAddr =
216 Builder.CreateConstGEP2_32(FCData, 0, 1, "exn_selector_gep");
217 Value *SelVal = Builder.CreateLoad(SelectorAddr, true, "exn_selector_val");
219 substituteLPadValues(LPI, ExnVal, SelVal);
222 // Personality function
223 IRBuilder<> Builder(EntryBB->getTerminator());
225 PersonalityFn = LPads[0]->getPersonalityFn();
226 Value *PersonalityFieldPtr =
227 Builder.CreateConstGEP2_32(FuncCtx, 0, 3, "pers_fn_gep");
229 Builder.CreateBitCast(PersonalityFn, Builder.getInt8PtrTy()),
230 PersonalityFieldPtr, /*isVolatile=*/true);
233 Value *LSDA = Builder.CreateCall(LSDAAddrFn, "lsda_addr");
234 Value *LSDAFieldPtr = Builder.CreateConstGEP2_32(FuncCtx, 0, 4, "lsda_gep");
235 Builder.CreateStore(LSDA, LSDAFieldPtr, /*isVolatile=*/true);
240 /// lowerIncomingArguments - To avoid having to handle incoming arguments
241 /// specially, we lower each arg to a copy instruction in the entry block. This
242 /// ensures that the argument value itself cannot be live out of the entry
244 void SjLjEHPrepare::lowerIncomingArguments(Function &F) {
245 BasicBlock::iterator AfterAllocaInsPt = F.begin()->begin();
246 while (isa<AllocaInst>(AfterAllocaInsPt) &&
247 isa<ConstantInt>(cast<AllocaInst>(AfterAllocaInsPt)->getArraySize()))
250 for (Function::arg_iterator AI = F.arg_begin(), AE = F.arg_end(); AI != AE;
252 Type *Ty = AI->getType();
254 // Use 'select i8 true, %arg, undef' to simulate a 'no-op' instruction.
255 Value *TrueValue = ConstantInt::getTrue(F.getContext());
256 Value *UndefValue = UndefValue::get(Ty);
257 Instruction *SI = SelectInst::Create(TrueValue, AI, UndefValue,
258 AI->getName() + ".tmp",
260 AI->replaceAllUsesWith(SI);
262 // Reset the operand, because it was clobbered by the RAUW above.
263 SI->setOperand(1, AI);
267 /// lowerAcrossUnwindEdges - Find all variables which are alive across an unwind
268 /// edge and spill them.
269 void SjLjEHPrepare::lowerAcrossUnwindEdges(Function &F,
270 ArrayRef<InvokeInst *> Invokes) {
271 // Finally, scan the code looking for instructions with bad live ranges.
272 for (Function::iterator BB = F.begin(), BBE = F.end(); BB != BBE; ++BB) {
273 for (BasicBlock::iterator II = BB->begin(), IIE = BB->end(); II != IIE;
275 // Ignore obvious cases we don't have to handle. In particular, most
276 // instructions either have no uses or only have a single use inside the
277 // current block. Ignore them quickly.
278 Instruction *Inst = II;
279 if (Inst->use_empty())
281 if (Inst->hasOneUse() &&
282 cast<Instruction>(Inst->user_back())->getParent() == BB &&
283 !isa<PHINode>(Inst->user_back()))
286 // If this is an alloca in the entry block, it's not a real register
288 if (AllocaInst *AI = dyn_cast<AllocaInst>(Inst))
289 if (isa<ConstantInt>(AI->getArraySize()) && BB == F.begin())
292 // Avoid iterator invalidation by copying users to a temporary vector.
293 SmallVector<Instruction *, 16> Users;
294 for (User *U : Inst->users()) {
295 Instruction *UI = cast<Instruction>(U);
296 if (UI->getParent() != BB || isa<PHINode>(UI))
300 // Find all of the blocks that this value is live in.
301 SmallPtrSet<BasicBlock *, 64> LiveBBs;
302 LiveBBs.insert(Inst->getParent());
303 while (!Users.empty()) {
304 Instruction *U = Users.back();
307 if (!isa<PHINode>(U)) {
308 MarkBlocksLiveIn(U->getParent(), LiveBBs);
310 // Uses for a PHI node occur in their predecessor block.
311 PHINode *PN = cast<PHINode>(U);
312 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
313 if (PN->getIncomingValue(i) == Inst)
314 MarkBlocksLiveIn(PN->getIncomingBlock(i), LiveBBs);
318 // Now that we know all of the blocks that this thing is live in, see if
319 // it includes any of the unwind locations.
320 bool NeedsSpill = false;
321 for (unsigned i = 0, e = Invokes.size(); i != e; ++i) {
322 BasicBlock *UnwindBlock = Invokes[i]->getUnwindDest();
323 if (UnwindBlock != BB && LiveBBs.count(UnwindBlock)) {
324 DEBUG(dbgs() << "SJLJ Spill: " << *Inst << " around "
325 << UnwindBlock->getName() << "\n");
331 // If we decided we need a spill, do it.
332 // FIXME: Spilling this way is overkill, as it forces all uses of
333 // the value to be reloaded from the stack slot, even those that aren't
334 // in the unwind blocks. We should be more selective.
336 DemoteRegToStack(*Inst, true);
342 // Go through the landing pads and remove any PHIs there.
343 for (unsigned i = 0, e = Invokes.size(); i != e; ++i) {
344 BasicBlock *UnwindBlock = Invokes[i]->getUnwindDest();
345 LandingPadInst *LPI = UnwindBlock->getLandingPadInst();
347 // Place PHIs into a set to avoid invalidating the iterator.
348 SmallPtrSet<PHINode *, 8> PHIsToDemote;
349 for (BasicBlock::iterator PN = UnwindBlock->begin(); isa<PHINode>(PN); ++PN)
350 PHIsToDemote.insert(cast<PHINode>(PN));
351 if (PHIsToDemote.empty())
354 // Demote the PHIs to the stack.
355 for (PHINode *PN : PHIsToDemote)
356 DemotePHIToStack(PN);
358 // Move the landingpad instruction back to the top of the landing pad block.
359 LPI->moveBefore(UnwindBlock->begin());
363 /// setupEntryBlockAndCallSites - Setup the entry block by creating and filling
364 /// the function context and marking the call sites with the appropriate
365 /// values. These values are used by the DWARF EH emitter.
366 bool SjLjEHPrepare::setupEntryBlockAndCallSites(Function &F) {
367 SmallVector<ReturnInst *, 16> Returns;
368 SmallVector<InvokeInst *, 16> Invokes;
369 SmallSetVector<LandingPadInst *, 16> LPads;
371 // Look through the terminators of the basic blocks to find invokes.
372 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
373 if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
374 if (Function *Callee = II->getCalledFunction())
375 if (Callee->isIntrinsic() &&
376 Callee->getIntrinsicID() == Intrinsic::donothing) {
377 // Remove the NOP invoke.
378 BranchInst::Create(II->getNormalDest(), II);
379 II->eraseFromParent();
383 Invokes.push_back(II);
384 LPads.insert(II->getUnwindDest()->getLandingPadInst());
385 } else if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
386 Returns.push_back(RI);
392 NumInvokes += Invokes.size();
394 lowerIncomingArguments(F);
395 lowerAcrossUnwindEdges(F, Invokes);
398 setupFunctionContext(F, makeArrayRef(LPads.begin(), LPads.end()));
399 BasicBlock *EntryBB = F.begin();
400 IRBuilder<> Builder(EntryBB->getTerminator());
402 // Get a reference to the jump buffer.
403 Value *JBufPtr = Builder.CreateConstGEP2_32(FuncCtx, 0, 5, "jbuf_gep");
405 // Save the frame pointer.
406 Value *FramePtr = Builder.CreateConstGEP2_32(JBufPtr, 0, 0, "jbuf_fp_gep");
408 Value *Val = Builder.CreateCall(FrameAddrFn, Builder.getInt32(0), "fp");
409 Builder.CreateStore(Val, FramePtr, /*isVolatile=*/true);
411 // Save the stack pointer.
412 Value *StackPtr = Builder.CreateConstGEP2_32(JBufPtr, 0, 2, "jbuf_sp_gep");
414 Val = Builder.CreateCall(StackAddrFn, "sp");
415 Builder.CreateStore(Val, StackPtr, /*isVolatile=*/true);
417 // Call the setjmp instrinsic. It fills in the rest of the jmpbuf.
418 Value *SetjmpArg = Builder.CreateBitCast(JBufPtr, Builder.getInt8PtrTy());
419 Builder.CreateCall(BuiltinSetjmpFn, SetjmpArg);
421 // Store a pointer to the function context so that the back-end will know
422 // where to look for it.
423 Value *FuncCtxArg = Builder.CreateBitCast(FuncCtx, Builder.getInt8PtrTy());
424 Builder.CreateCall(FuncCtxFn, FuncCtxArg);
426 // At this point, we are all set up, update the invoke instructions to mark
427 // their call_site values.
428 for (unsigned I = 0, E = Invokes.size(); I != E; ++I) {
429 insertCallSiteStore(Invokes[I], I + 1);
431 ConstantInt *CallSiteNum =
432 ConstantInt::get(Type::getInt32Ty(F.getContext()), I + 1);
434 // Record the call site value for the back end so it stays associated with
436 CallInst::Create(CallSiteFn, CallSiteNum, "", Invokes[I]);
439 // Mark call instructions that aren't nounwind as no-action (call_site ==
440 // -1). Skip the entry block, as prior to then, no function context has been
441 // created for this function and any unexpected exceptions thrown will go
442 // directly to the caller's context, which is what we want anyway, so no need
443 // to do anything here.
444 for (Function::iterator BB = F.begin(), E = F.end(); ++BB != E;)
445 for (BasicBlock::iterator I = BB->begin(), end = BB->end(); I != end; ++I)
446 if (CallInst *CI = dyn_cast<CallInst>(I)) {
447 if (!CI->doesNotThrow())
448 insertCallSiteStore(CI, -1);
449 } else if (ResumeInst *RI = dyn_cast<ResumeInst>(I)) {
450 insertCallSiteStore(RI, -1);
453 // Register the function context and make sure it's known to not throw
455 CallInst::Create(RegisterFn, FuncCtx, "", EntryBB->getTerminator());
456 Register->setDoesNotThrow();
458 // Following any allocas not in the entry block, update the saved SP in the
459 // jmpbuf to the new value.
460 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
463 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
464 if (CallInst *CI = dyn_cast<CallInst>(I)) {
465 if (CI->getCalledFunction() != StackRestoreFn)
467 } else if (!isa<AllocaInst>(I)) {
470 Instruction *StackAddr = CallInst::Create(StackAddrFn, "sp");
471 StackAddr->insertAfter(I);
472 Instruction *StoreStackAddr = new StoreInst(StackAddr, StackPtr, true);
473 StoreStackAddr->insertAfter(StackAddr);
477 // Finally, for any returns from this function, if this function contains an
478 // invoke, add a call to unregister the function context.
479 for (unsigned I = 0, E = Returns.size(); I != E; ++I)
480 CallInst::Create(UnregisterFn, FuncCtx, "", Returns[I]);
485 bool SjLjEHPrepare::runOnFunction(Function &F) {
486 bool Res = setupEntryBlockAndCallSites(F);