blob: f610e9c991441c01088b518b628b3b76e22a2f25 [file] [log] [blame]
Bill Wendling12e5adb2012-03-13 20:04:21 +00001//===- SjLjEHPrepare.cpp - Eliminate Invoke & Unwind instructions ---------===//
Jim Grosbach486be662009-08-17 16:41:22 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This transformation is designed for use by code generators which use SjLj
11// based exception handling.
12//
13//===----------------------------------------------------------------------===//
14
Chandler Carruthed0881b2012-12-03 16:50:05 +000015#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"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000021#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"
Jim Grosbach486be662009-08-17 16:41:22 +000029#include "llvm/Pass.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000030#include "llvm/Support/CommandLine.h"
31#include "llvm/Support/Debug.h"
32#include "llvm/Support/raw_ostream.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000033#include "llvm/Target/TargetLowering.h"
Eric Christopherd9134482014-08-04 21:25:23 +000034#include "llvm/Target/TargetSubtargetInfo.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000035#include "llvm/Transforms/Scalar.h"
36#include "llvm/Transforms/Utils/BasicBlockUtils.h"
37#include "llvm/Transforms/Utils/Local.h"
Benjamin Kramer63abc842010-11-06 11:45:59 +000038#include <set>
Jim Grosbach486be662009-08-17 16:41:22 +000039using namespace llvm;
40
Chandler Carruth1b9dde02014-04-22 02:02:50 +000041#define DEBUG_TYPE "sjljehprepare"
42
Jim Grosbach486be662009-08-17 16:41:22 +000043STATISTIC(NumInvokes, "Number of invokes replaced");
Jim Grosbach486be662009-08-17 16:41:22 +000044STATISTIC(NumSpilled, "Number of registers live across unwind edges");
45
46namespace {
Bill Wendling8faa30e2013-09-23 20:57:47 +000047class SjLjEHPrepare : public FunctionPass {
David Blaikie4e5d47f42015-04-04 21:07:10 +000048 Type *doubleUnderDataTy;
49 Type *doubleUnderJBufTy;
Bill Wendling8faa30e2013-09-23 20:57:47 +000050 Type *FunctionContextTy;
51 Constant *RegisterFn;
52 Constant *UnregisterFn;
Matthias Braun3cd00c12015-07-16 22:34:16 +000053 Constant *BuiltinSetupDispatchFn;
Bill Wendling8faa30e2013-09-23 20:57:47 +000054 Constant *FrameAddrFn;
55 Constant *StackAddrFn;
56 Constant *StackRestoreFn;
57 Constant *LSDAAddrFn;
Bill Wendling8faa30e2013-09-23 20:57:47 +000058 Constant *CallSiteFn;
59 Constant *FuncCtxFn;
60 AllocaInst *FuncCtx;
Jim Grosbach486be662009-08-17 16:41:22 +000061
Bill Wendling8faa30e2013-09-23 20:57:47 +000062public:
63 static char ID; // Pass identification, replacement for typeid
Mehdi Aminif50daed2015-07-08 01:00:31 +000064 explicit SjLjEHPrepare() : FunctionPass(ID) {}
Craig Topper4584cd52014-03-07 09:26:03 +000065 bool doInitialization(Module &M) override;
66 bool runOnFunction(Function &F) override;
Jim Grosbach486be662009-08-17 16:41:22 +000067
Craig Topper4584cd52014-03-07 09:26:03 +000068 void getAnalysisUsage(AnalysisUsage &AU) const override {}
69 const char *getPassName() const override {
Bill Wendling8faa30e2013-09-23 20:57:47 +000070 return "SJLJ Exception Handling preparation";
71 }
72
73private:
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);
80};
Jim Grosbach486be662009-08-17 16:41:22 +000081} // end anonymous namespace
82
Bill Wendling12e5adb2012-03-13 20:04:21 +000083char SjLjEHPrepare::ID = 0;
Reid Klecknerc16b1072015-07-09 21:48:40 +000084INITIALIZE_PASS(SjLjEHPrepare, "sjljehprepare", "Prepare SjLj exceptions",
85 false, false)
Jim Grosbach486be662009-08-17 16:41:22 +000086
Bill Wendling12e5adb2012-03-13 20:04:21 +000087// Public Interface To the SjLjEHPrepare pass.
Mehdi Aminif50daed2015-07-08 01:00:31 +000088FunctionPass *llvm::createSjLjEHPreparePass() { return new SjLjEHPrepare(); }
Jim Grosbach1b0436b2009-08-23 18:13:48 +000089// doInitialization - Set up decalarations and types needed to process
90// exceptions.
Bill Wendling12e5adb2012-03-13 20:04:21 +000091bool SjLjEHPrepare::doInitialization(Module &M) {
Jim Grosbach486be662009-08-17 16:41:22 +000092 // Build the function context structure.
93 // builtin_setjmp uses a five word jbuf
Jay Foadb804a2b2011-07-12 14:06:48 +000094 Type *VoidPtrTy = Type::getInt8PtrTy(M.getContext());
95 Type *Int32Ty = Type::getInt32Ty(M.getContext());
David Blaikie4e5d47f42015-04-04 21:07:10 +000096 doubleUnderDataTy = ArrayType::get(Int32Ty, 4);
97 doubleUnderJBufTy = ArrayType::get(VoidPtrTy, 5);
98 FunctionContextTy = StructType::get(VoidPtrTy, // __prev
99 Int32Ty, // call_site
100 doubleUnderDataTy, // __data
101 VoidPtrTy, // __personality
102 VoidPtrTy, // __lsda
103 doubleUnderJBufTy, // __jbuf
Reid Kleckner971c3ea2014-11-13 22:55:19 +0000104 nullptr);
Jim Grosbach486be662009-08-17 16:41:22 +0000105
106 return true;
107}
108
Jim Grosbach1201f292010-03-04 22:07:46 +0000109/// insertCallSiteStore - Insert a store of the call-site value to the
110/// function context
Bill Wendling12e5adb2012-03-13 20:04:21 +0000111void SjLjEHPrepare::insertCallSiteStore(Instruction *I, int Number) {
Bill Wendling7717e9f2012-01-27 02:02:24 +0000112 IRBuilder<> Builder(I);
113
114 // Get a reference to the call_site field.
115 Type *Int32Ty = Type::getInt32Ty(I->getContext());
116 Value *Zero = ConstantInt::get(Int32Ty, 0);
117 Value *One = ConstantInt::get(Int32Ty, 1);
118 Value *Idxs[2] = { Zero, One };
David Blaikie68d535c2015-03-24 22:38:16 +0000119 Value *CallSite =
120 Builder.CreateGEP(FunctionContextTy, FuncCtx, Idxs, "call_site");
Bill Wendling7717e9f2012-01-27 02:02:24 +0000121
122 // Insert a store of the call-site number
Bill Wendling8faa30e2013-09-23 20:57:47 +0000123 ConstantInt *CallSiteNoC =
124 ConstantInt::get(Type::getInt32Ty(I->getContext()), Number);
125 Builder.CreateStore(CallSiteNoC, CallSite, true /*volatile*/);
Jim Grosbach1201f292010-03-04 22:07:46 +0000126}
127
Chad Rosier1a9c17e2012-03-16 01:04:00 +0000128/// MarkBlocksLiveIn - Insert BB and all of its predescessors into LiveBBs until
Jim Grosbach486be662009-08-17 16:41:22 +0000129/// we reach blocks we've already seen.
Chad Rosier1a9c17e2012-03-16 01:04:00 +0000130static void MarkBlocksLiveIn(BasicBlock *BB,
Craig Topper71b7b682014-08-21 05:55:13 +0000131 SmallPtrSetImpl<BasicBlock *> &LiveBBs) {
David Blaikie70573dc2014-11-19 07:49:26 +0000132 if (!LiveBBs.insert(BB).second)
Bill Wendling8faa30e2013-09-23 20:57:47 +0000133 return; // already been here.
Jim Grosbach486be662009-08-17 16:41:22 +0000134
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +0000135 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
136 MarkBlocksLiveIn(*PI, LiveBBs);
Jim Grosbach486be662009-08-17 16:41:22 +0000137}
138
Bill Wendlingb108aae2011-12-14 22:45:33 +0000139/// substituteLPadValues - Substitute the values returned by the landingpad
140/// instruction with those returned by the personality function.
Bill Wendling12e5adb2012-03-13 20:04:21 +0000141void SjLjEHPrepare::substituteLPadValues(LandingPadInst *LPI, Value *ExnVal,
142 Value *SelVal) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000143 SmallVector<Value *, 8> UseWorkList(LPI->user_begin(), LPI->user_end());
Bill Wendlingb108aae2011-12-14 22:45:33 +0000144 while (!UseWorkList.empty()) {
145 Value *Val = UseWorkList.pop_back_val();
146 ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(Val);
Bill Wendling8faa30e2013-09-23 20:57:47 +0000147 if (!EVI)
148 continue;
149 if (EVI->getNumIndices() != 1)
150 continue;
Bill Wendlingb108aae2011-12-14 22:45:33 +0000151 if (*EVI->idx_begin() == 0)
152 EVI->replaceAllUsesWith(ExnVal);
153 else if (*EVI->idx_begin() == 1)
154 EVI->replaceAllUsesWith(SelVal);
155 if (EVI->getNumUses() == 0)
156 EVI->eraseFromParent();
157 }
158
Bill Wendling8faa30e2013-09-23 20:57:47 +0000159 if (LPI->getNumUses() == 0)
160 return;
Bill Wendlingb108aae2011-12-14 22:45:33 +0000161
162 // There are still some uses of LPI. Construct an aggregate with the exception
163 // values and replace the LPI with that aggregate.
164 Type *LPadType = LPI->getType();
165 Value *LPadVal = UndefValue::get(LPadType);
Duncan P. N. Exon Smithf1ff53e2015-10-09 22:56:24 +0000166 auto *SelI = cast<Instruction>(SelVal);
167 IRBuilder<> Builder(SelI->getParent(), std::next(SelI->getIterator()));
Bill Wendlingb108aae2011-12-14 22:45:33 +0000168 LPadVal = Builder.CreateInsertValue(LPadVal, ExnVal, 0, "lpad.val");
169 LPadVal = Builder.CreateInsertValue(LPadVal, SelVal, 1, "lpad.val");
170
171 LPI->replaceAllUsesWith(LPadVal);
172}
173
Bill Wendling2e76ca92011-09-28 03:14:05 +0000174/// setupFunctionContext - Allocate the function context on the stack and fill
175/// it with all of the data that we know at this point.
Bill Wendling8faa30e2013-09-23 20:57:47 +0000176Value *SjLjEHPrepare::setupFunctionContext(Function &F,
177 ArrayRef<LandingPadInst *> LPads) {
Duncan P. N. Exon Smithf1ff53e2015-10-09 22:56:24 +0000178 BasicBlock *EntryBB = &F.front();
Bill Wendling2e76ca92011-09-28 03:14:05 +0000179
180 // Create an alloca for the incoming jump buffer ptr and the new jump buffer
181 // that needs to be restored on all exits from the function. This is an alloca
182 // because the value needs to be added to the global context list.
Mehdi Aminif50daed2015-07-08 01:00:31 +0000183 auto &DL = F.getParent()->getDataLayout();
184 unsigned Align = DL.getPrefTypeAlignment(FunctionContextTy);
Craig Topperc0196b12014-04-14 00:51:57 +0000185 FuncCtx = new AllocaInst(FunctionContextTy, nullptr, Align, "fn_context",
Duncan P. N. Exon Smithf1ff53e2015-10-09 22:56:24 +0000186 &EntryBB->front());
Bill Wendling2e76ca92011-09-28 03:14:05 +0000187
188 // Fill in the function context structure.
Bill Wendling2e76ca92011-09-28 03:14:05 +0000189 for (unsigned I = 0, E = LPads.size(); I != E; ++I) {
190 LandingPadInst *LPI = LPads[I];
Duncan P. N. Exon Smithf1ff53e2015-10-09 22:56:24 +0000191 IRBuilder<> Builder(LPI->getParent(),
192 LPI->getParent()->getFirstInsertionPt());
Bill Wendling2e76ca92011-09-28 03:14:05 +0000193
Bill Wendling7717e9f2012-01-27 02:02:24 +0000194 // Reference the __data field.
David Blaikie4e5d47f42015-04-04 21:07:10 +0000195 Value *FCData =
196 Builder.CreateConstGEP2_32(FunctionContextTy, FuncCtx, 0, 2, "__data");
Bill Wendling7717e9f2012-01-27 02:02:24 +0000197
198 // The exception values come back in context->__data[0].
David Blaikie4e5d47f42015-04-04 21:07:10 +0000199 Value *ExceptionAddr = Builder.CreateConstGEP2_32(doubleUnderDataTy, FCData,
200 0, 0, "exception_gep");
Bill Wendling2e76ca92011-09-28 03:14:05 +0000201 Value *ExnVal = Builder.CreateLoad(ExceptionAddr, true, "exn_val");
Benjamin Kramer8d9890a2012-09-03 12:27:43 +0000202 ExnVal = Builder.CreateIntToPtr(ExnVal, Builder.getInt8PtrTy());
Bill Wendling7717e9f2012-01-27 02:02:24 +0000203
David Blaikie4e5d47f42015-04-04 21:07:10 +0000204 Value *SelectorAddr = Builder.CreateConstGEP2_32(doubleUnderDataTy, FCData,
205 0, 1, "exn_selector_gep");
Bill Wendling2e76ca92011-09-28 03:14:05 +0000206 Value *SelVal = Builder.CreateLoad(SelectorAddr, true, "exn_selector_val");
207
Bill Wendlingb108aae2011-12-14 22:45:33 +0000208 substituteLPadValues(LPI, ExnVal, SelVal);
Bill Wendling2e76ca92011-09-28 03:14:05 +0000209 }
210
211 // Personality function
Benjamin Kramer8d9890a2012-09-03 12:27:43 +0000212 IRBuilder<> Builder(EntryBB->getTerminator());
David Majnemerbd1b8c02016-02-19 03:13:40 +0000213 Value *PersonalityFn = F.getPersonalityFn();
David Blaikie4e5d47f42015-04-04 21:07:10 +0000214 Value *PersonalityFieldPtr = Builder.CreateConstGEP2_32(
215 FunctionContextTy, FuncCtx, 0, 3, "pers_fn_gep");
Bill Wendling8faa30e2013-09-23 20:57:47 +0000216 Builder.CreateStore(
217 Builder.CreateBitCast(PersonalityFn, Builder.getInt8PtrTy()),
218 PersonalityFieldPtr, /*isVolatile=*/true);
Bill Wendling2e76ca92011-09-28 03:14:05 +0000219
220 // LSDA address
David Blaikieff6409d2015-05-18 22:13:54 +0000221 Value *LSDA = Builder.CreateCall(LSDAAddrFn, {}, "lsda_addr");
David Blaikie4e5d47f42015-04-04 21:07:10 +0000222 Value *LSDAFieldPtr =
223 Builder.CreateConstGEP2_32(FunctionContextTy, FuncCtx, 0, 4, "lsda_gep");
Benjamin Kramer8d9890a2012-09-03 12:27:43 +0000224 Builder.CreateStore(LSDA, LSDAFieldPtr, /*isVolatile=*/true);
Bill Wendling2e76ca92011-09-28 03:14:05 +0000225
Bill Wendling6f3e73d2011-10-03 21:15:28 +0000226 return FuncCtx;
Bill Wendling899da522011-09-28 21:56:53 +0000227}
228
Bill Wendlinge9574be2011-10-08 00:56:47 +0000229/// lowerIncomingArguments - To avoid having to handle incoming arguments
230/// specially, we lower each arg to a copy instruction in the entry block. This
231/// ensures that the argument value itself cannot be live out of the entry
232/// block.
Bill Wendling12e5adb2012-03-13 20:04:21 +0000233void SjLjEHPrepare::lowerIncomingArguments(Function &F) {
Bill Wendlinge9574be2011-10-08 00:56:47 +0000234 BasicBlock::iterator AfterAllocaInsPt = F.begin()->begin();
235 while (isa<AllocaInst>(AfterAllocaInsPt) &&
236 isa<ConstantInt>(cast<AllocaInst>(AfterAllocaInsPt)->getArraySize()))
237 ++AfterAllocaInsPt;
Duncan P. N. Exon Smithf1ff53e2015-10-09 22:56:24 +0000238 assert(AfterAllocaInsPt != F.front().end());
Bill Wendlinge9574be2011-10-08 00:56:47 +0000239
Duncan P. N. Exon Smithf1ff53e2015-10-09 22:56:24 +0000240 for (auto &AI : F.args()) {
241 Type *Ty = AI.getType();
Bill Wendlinge9574be2011-10-08 00:56:47 +0000242
Bill Wendlingc80b6c92014-07-14 18:21:11 +0000243 // Use 'select i8 true, %arg, undef' to simulate a 'no-op' instruction.
244 Value *TrueValue = ConstantInt::getTrue(F.getContext());
245 Value *UndefValue = UndefValue::get(Ty);
Duncan P. N. Exon Smithf1ff53e2015-10-09 22:56:24 +0000246 Instruction *SI = SelectInst::Create(
247 TrueValue, &AI, UndefValue, AI.getName() + ".tmp", &*AfterAllocaInsPt);
248 AI.replaceAllUsesWith(SI);
Bill Wendlinge9574be2011-10-08 00:56:47 +0000249
Bill Wendlingc80b6c92014-07-14 18:21:11 +0000250 // Reset the operand, because it was clobbered by the RAUW above.
Duncan P. N. Exon Smithf1ff53e2015-10-09 22:56:24 +0000251 SI->setOperand(1, &AI);
Bill Wendlinge9574be2011-10-08 00:56:47 +0000252 }
253}
254
255/// lowerAcrossUnwindEdges - Find all variables which are alive across an unwind
256/// edge and spill them.
Bill Wendling12e5adb2012-03-13 20:04:21 +0000257void SjLjEHPrepare::lowerAcrossUnwindEdges(Function &F,
Bill Wendling8faa30e2013-09-23 20:57:47 +0000258 ArrayRef<InvokeInst *> Invokes) {
Bill Wendlinge9574be2011-10-08 00:56:47 +0000259 // Finally, scan the code looking for instructions with bad live ranges.
Bill Wendling8faa30e2013-09-23 20:57:47 +0000260 for (Function::iterator BB = F.begin(), BBE = F.end(); BB != BBE; ++BB) {
261 for (BasicBlock::iterator II = BB->begin(), IIE = BB->end(); II != IIE;
262 ++II) {
Bill Wendlinge9574be2011-10-08 00:56:47 +0000263 // Ignore obvious cases we don't have to handle. In particular, most
264 // instructions either have no uses or only have a single use inside the
265 // current block. Ignore them quickly.
Duncan P. N. Exon Smithf1ff53e2015-10-09 22:56:24 +0000266 Instruction *Inst = &*II;
Bill Wendling8faa30e2013-09-23 20:57:47 +0000267 if (Inst->use_empty())
268 continue;
Bill Wendlinge9574be2011-10-08 00:56:47 +0000269 if (Inst->hasOneUse() &&
Chandler Carruthcdf47882014-03-09 03:16:01 +0000270 cast<Instruction>(Inst->user_back())->getParent() == BB &&
271 !isa<PHINode>(Inst->user_back()))
Bill Wendling8faa30e2013-09-23 20:57:47 +0000272 continue;
Bill Wendlinge9574be2011-10-08 00:56:47 +0000273
274 // If this is an alloca in the entry block, it's not a real register
275 // value.
276 if (AllocaInst *AI = dyn_cast<AllocaInst>(Inst))
277 if (isa<ConstantInt>(AI->getArraySize()) && BB == F.begin())
278 continue;
279
280 // Avoid iterator invalidation by copying users to a temporary vector.
Bill Wendling8faa30e2013-09-23 20:57:47 +0000281 SmallVector<Instruction *, 16> Users;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000282 for (User *U : Inst->users()) {
283 Instruction *UI = cast<Instruction>(U);
284 if (UI->getParent() != BB || isa<PHINode>(UI))
285 Users.push_back(UI);
Bill Wendlinge9574be2011-10-08 00:56:47 +0000286 }
287
288 // Find all of the blocks that this value is live in.
Matthias Braunb30f2f512016-01-30 01:24:31 +0000289 SmallPtrSet<BasicBlock *, 32> LiveBBs;
Chad Rosier1a9c17e2012-03-16 01:04:00 +0000290 LiveBBs.insert(Inst->getParent());
Bill Wendlinge9574be2011-10-08 00:56:47 +0000291 while (!Users.empty()) {
Chad Rosier1a9c17e2012-03-16 01:04:00 +0000292 Instruction *U = Users.back();
293 Users.pop_back();
Bill Wendlinge9574be2011-10-08 00:56:47 +0000294
Chad Rosier1a9c17e2012-03-16 01:04:00 +0000295 if (!isa<PHINode>(U)) {
296 MarkBlocksLiveIn(U->getParent(), LiveBBs);
297 } else {
Bill Wendlinge9574be2011-10-08 00:56:47 +0000298 // Uses for a PHI node occur in their predecessor block.
Chad Rosier1a9c17e2012-03-16 01:04:00 +0000299 PHINode *PN = cast<PHINode>(U);
Bill Wendlinge9574be2011-10-08 00:56:47 +0000300 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
301 if (PN->getIncomingValue(i) == Inst)
Chad Rosier1a9c17e2012-03-16 01:04:00 +0000302 MarkBlocksLiveIn(PN->getIncomingBlock(i), LiveBBs);
Bill Wendlinge9574be2011-10-08 00:56:47 +0000303 }
304 }
305
Chad Rosier1a9c17e2012-03-16 01:04:00 +0000306 // 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 (unsigned i = 0, e = Invokes.size(); i != e; ++i) {
310 BasicBlock *UnwindBlock = Invokes[i]->getUnwindDest();
311 if (UnwindBlock != BB && LiveBBs.count(UnwindBlock)) {
312 DEBUG(dbgs() << "SJLJ Spill: " << *Inst << " around "
Bill Wendling8faa30e2013-09-23 20:57:47 +0000313 << UnwindBlock->getName() << "\n");
Chad Rosier1a9c17e2012-03-16 01:04:00 +0000314 NeedsSpill = true;
315 break;
Bill Wendlingd7c0aae2012-03-14 07:28:01 +0000316 }
Bill Wendling5ad91402012-03-12 20:19:41 +0000317 }
Bill Wendlingb1c43082011-10-21 22:08:56 +0000318
Chad Rosier1a9c17e2012-03-16 01:04:00 +0000319 // 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 }
Bill Wendlingd7c0aae2012-03-14 07:28:01 +0000327 }
328 }
329
Bill Wendlingb1c43082011-10-21 22:08:56 +0000330 // Go through the landing pads and remove any PHIs there.
331 for (unsigned i = 0, e = Invokes.size(); i != e; ++i) {
332 BasicBlock *UnwindBlock = Invokes[i]->getUnwindDest();
333 LandingPadInst *LPI = UnwindBlock->getLandingPadInst();
334
335 // Place PHIs into a set to avoid invalidating the iterator.
Bill Wendling8faa30e2013-09-23 20:57:47 +0000336 SmallPtrSet<PHINode *, 8> PHIsToDemote;
337 for (BasicBlock::iterator PN = UnwindBlock->begin(); isa<PHINode>(PN); ++PN)
Bill Wendlingb1c43082011-10-21 22:08:56 +0000338 PHIsToDemote.insert(cast<PHINode>(PN));
Bill Wendling8faa30e2013-09-23 20:57:47 +0000339 if (PHIsToDemote.empty())
340 continue;
Bill Wendlingb1c43082011-10-21 22:08:56 +0000341
342 // Demote the PHIs to the stack.
Craig Topper46276792014-08-24 23:23:06 +0000343 for (PHINode *PN : PHIsToDemote)
344 DemotePHIToStack(PN);
Bill Wendlingb1c43082011-10-21 22:08:56 +0000345
346 // Move the landingpad instruction back to the top of the landing pad block.
Duncan P. N. Exon Smithf1ff53e2015-10-09 22:56:24 +0000347 LPI->moveBefore(&UnwindBlock->front());
Bill Wendlingb1c43082011-10-21 22:08:56 +0000348 }
Bill Wendlinge9574be2011-10-08 00:56:47 +0000349}
350
Bill Wendling899da522011-09-28 21:56:53 +0000351/// 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.
Bill Wendling12e5adb2012-03-13 20:04:21 +0000354bool SjLjEHPrepare::setupEntryBlockAndCallSites(Function &F) {
Bill Wendling8faa30e2013-09-23 20:57:47 +0000355 SmallVector<ReturnInst *, 16> Returns;
356 SmallVector<InvokeInst *, 16> Invokes;
357 SmallSetVector<LandingPadInst *, 16> LPads;
Bill Wendling899da522011-09-28 21:56:53 +0000358
359 // Look through the terminators of the basic blocks to find invokes.
360 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
361 if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
Bill Wendling2d915e22013-03-08 02:21:08 +0000362 if (Function *Callee = II->getCalledFunction())
363 if (Callee->isIntrinsic() &&
364 Callee->getIntrinsicID() == Intrinsic::donothing) {
365 // Remove the NOP invoke.
366 BranchInst::Create(II->getNormalDest(), II);
367 II->eraseFromParent();
368 continue;
369 }
370
Bill Wendling899da522011-09-28 21:56:53 +0000371 Invokes.push_back(II);
Bob Wilsoncca9aa52011-11-16 07:57:21 +0000372 LPads.insert(II->getUnwindDest()->getLandingPadInst());
Bill Wendling899da522011-09-28 21:56:53 +0000373 } else if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
374 Returns.push_back(RI);
375 }
376
Bill Wendling8faa30e2013-09-23 20:57:47 +0000377 if (Invokes.empty())
378 return false;
Bill Wendling899da522011-09-28 21:56:53 +0000379
Bill Wendling38f86c52011-10-24 17:12:36 +0000380 NumInvokes += Invokes.size();
381
Bill Wendlinge9574be2011-10-08 00:56:47 +0000382 lowerIncomingArguments(F);
383 lowerAcrossUnwindEdges(F, Invokes);
384
Bob Wilsoncca9aa52011-11-16 07:57:21 +0000385 Value *FuncCtx =
Bill Wendling8faa30e2013-09-23 20:57:47 +0000386 setupFunctionContext(F, makeArrayRef(LPads.begin(), LPads.end()));
Duncan P. N. Exon Smithf1ff53e2015-10-09 22:56:24 +0000387 BasicBlock *EntryBB = &F.front();
Benjamin Kramer8d9890a2012-09-03 12:27:43 +0000388 IRBuilder<> Builder(EntryBB->getTerminator());
Bill Wendling6f3e73d2011-10-03 21:15:28 +0000389
390 // Get a reference to the jump buffer.
David Blaikie4e5d47f42015-04-04 21:07:10 +0000391 Value *JBufPtr =
392 Builder.CreateConstGEP2_32(FunctionContextTy, FuncCtx, 0, 5, "jbuf_gep");
Bill Wendling2e76ca92011-09-28 03:14:05 +0000393
Bill Wendling6f3e73d2011-10-03 21:15:28 +0000394 // Save the frame pointer.
David Blaikie4e5d47f42015-04-04 21:07:10 +0000395 Value *FramePtr = Builder.CreateConstGEP2_32(doubleUnderJBufTy, JBufPtr, 0, 0,
396 "jbuf_fp_gep");
Bill Wendling6f3e73d2011-10-03 21:15:28 +0000397
Benjamin Kramer8d9890a2012-09-03 12:27:43 +0000398 Value *Val = Builder.CreateCall(FrameAddrFn, Builder.getInt32(0), "fp");
399 Builder.CreateStore(Val, FramePtr, /*isVolatile=*/true);
Bill Wendling6f3e73d2011-10-03 21:15:28 +0000400
401 // Save the stack pointer.
David Blaikie4e5d47f42015-04-04 21:07:10 +0000402 Value *StackPtr = Builder.CreateConstGEP2_32(doubleUnderJBufTy, JBufPtr, 0, 2,
403 "jbuf_sp_gep");
Bill Wendling6f3e73d2011-10-03 21:15:28 +0000404
David Blaikieff6409d2015-05-18 22:13:54 +0000405 Val = Builder.CreateCall(StackAddrFn, {}, "sp");
Benjamin Kramer8d9890a2012-09-03 12:27:43 +0000406 Builder.CreateStore(Val, StackPtr, /*isVolatile=*/true);
Bill Wendling2e76ca92011-09-28 03:14:05 +0000407
Matthias Braun3cd00c12015-07-16 22:34:16 +0000408 // Call the setup_dispatch instrinsic. It fills in the rest of the jmpbuf.
409 Builder.CreateCall(BuiltinSetupDispatchFn, {});
Bill Wendling2e76ca92011-09-28 03:14:05 +0000410
Bill Wendling899da522011-09-28 21:56:53 +0000411 // Store a pointer to the function context so that the back-end will know
412 // where to look for it.
Benjamin Kramer8d9890a2012-09-03 12:27:43 +0000413 Value *FuncCtxArg = Builder.CreateBitCast(FuncCtx, Builder.getInt8PtrTy());
414 Builder.CreateCall(FuncCtxFn, FuncCtxArg);
Bill Wendling2e76ca92011-09-28 03:14:05 +0000415
416 // At this point, we are all set up, update the invoke instructions to mark
Bill Wendlingdb163352011-10-05 22:04:08 +0000417 // their call_site values.
Bill Wendling2e76ca92011-09-28 03:14:05 +0000418 for (unsigned I = 0, E = Invokes.size(); I != E; ++I) {
Bill Wendling7717e9f2012-01-27 02:02:24 +0000419 insertCallSiteStore(Invokes[I], I + 1);
Bill Wendling2e76ca92011-09-28 03:14:05 +0000420
421 ConstantInt *CallSiteNum =
Bill Wendling8faa30e2013-09-23 20:57:47 +0000422 ConstantInt::get(Type::getInt32Ty(F.getContext()), I + 1);
Bill Wendling2e76ca92011-09-28 03:14:05 +0000423
424 // Record the call site value for the back end so it stays associated with
425 // the invoke.
426 CallInst::Create(CallSiteFn, CallSiteNum, "", Invokes[I]);
427 }
428
429 // Mark call instructions that aren't nounwind as no-action (call_site ==
430 // -1). Skip the entry block, as prior to then, no function context has been
431 // created for this function and any unexpected exceptions thrown will go
432 // directly to the caller's context, which is what we want anyway, so no need
433 // to do anything here.
Bill Wendlingac3fb4c2011-10-04 00:16:40 +0000434 for (Function::iterator BB = F.begin(), E = F.end(); ++BB != E;)
Bill Wendling2e76ca92011-09-28 03:14:05 +0000435 for (BasicBlock::iterator I = BB->begin(), end = BB->end(); I != end; ++I)
436 if (CallInst *CI = dyn_cast<CallInst>(I)) {
437 if (!CI->doesNotThrow())
Bill Wendling7717e9f2012-01-27 02:02:24 +0000438 insertCallSiteStore(CI, -1);
Bill Wendling2e76ca92011-09-28 03:14:05 +0000439 } else if (ResumeInst *RI = dyn_cast<ResumeInst>(I)) {
Bill Wendling7717e9f2012-01-27 02:02:24 +0000440 insertCallSiteStore(RI, -1);
Bill Wendling2e76ca92011-09-28 03:14:05 +0000441 }
Bill Wendling2e76ca92011-09-28 03:14:05 +0000442
Bill Wendling899da522011-09-28 21:56:53 +0000443 // Register the function context and make sure it's known to not throw
Bill Wendling8faa30e2013-09-23 20:57:47 +0000444 CallInst *Register =
445 CallInst::Create(RegisterFn, FuncCtx, "", EntryBB->getTerminator());
Bill Wendling899da522011-09-28 21:56:53 +0000446 Register->setDoesNotThrow();
447
Bob Wilson643e63c2011-11-16 07:12:00 +0000448 // Following any allocas not in the entry block, update the saved SP in the
449 // jmpbuf to the new value.
450 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
451 if (BB == F.begin())
452 continue;
453 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
454 if (CallInst *CI = dyn_cast<CallInst>(I)) {
455 if (CI->getCalledFunction() != StackRestoreFn)
456 continue;
457 } else if (!isa<AllocaInst>(I)) {
458 continue;
459 }
460 Instruction *StackAddr = CallInst::Create(StackAddrFn, "sp");
Duncan P. N. Exon Smithf1ff53e2015-10-09 22:56:24 +0000461 StackAddr->insertAfter(&*I);
Bob Wilson643e63c2011-11-16 07:12:00 +0000462 Instruction *StoreStackAddr = new StoreInst(StackAddr, StackPtr, true);
463 StoreStackAddr->insertAfter(StackAddr);
464 }
465 }
466
Bill Wendling899da522011-09-28 21:56:53 +0000467 // Finally, for any returns from this function, if this function contains an
468 // invoke, add a call to unregister the function context.
469 for (unsigned I = 0, E = Returns.size(); I != E; ++I)
Bill Wendling6f3e73d2011-10-03 21:15:28 +0000470 CallInst::Create(UnregisterFn, FuncCtx, "", Returns[I]);
Bill Wendling899da522011-09-28 21:56:53 +0000471
Bill Wendling2e76ca92011-09-28 03:14:05 +0000472 return true;
473}
474
Bill Wendling12e5adb2012-03-13 20:04:21 +0000475bool SjLjEHPrepare::runOnFunction(Function &F) {
David Majnemerbd1b8c02016-02-19 03:13:40 +0000476 Module &M = *F.getParent();
477 RegisterFn = M.getOrInsertFunction(
478 "_Unwind_SjLj_Register", Type::getVoidTy(M.getContext()),
479 PointerType::getUnqual(FunctionContextTy), (Type *)nullptr);
480 UnregisterFn = M.getOrInsertFunction(
481 "_Unwind_SjLj_Unregister", Type::getVoidTy(M.getContext()),
482 PointerType::getUnqual(FunctionContextTy), (Type *)nullptr);
483 FrameAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::frameaddress);
484 StackAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::stacksave);
485 StackRestoreFn = Intrinsic::getDeclaration(&M, Intrinsic::stackrestore);
486 BuiltinSetupDispatchFn =
487 Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_setup_dispatch);
488 LSDAAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_lsda);
489 CallSiteFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_callsite);
490 FuncCtxFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_functioncontext);
491
Bill Wendling38f86c52011-10-24 17:12:36 +0000492 bool Res = setupEntryBlockAndCallSites(F);
Jim Grosbach486be662009-08-17 16:41:22 +0000493 return Res;
494}