blob: 7886737b879c22bc03a0c538bc1fb7020d3ad45e [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/ADT/SetVector.h"
16#include "llvm/ADT/SmallPtrSet.h"
17#include "llvm/ADT/SmallVector.h"
18#include "llvm/ADT/Statistic.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000019#include "llvm/CodeGen/Passes.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000020#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"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000026#include "llvm/IR/Module.h"
Jim Grosbach486be662009-08-17 16:41:22 +000027#include "llvm/Pass.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000028#include "llvm/Support/Debug.h"
29#include "llvm/Support/raw_ostream.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000030#include "llvm/Transforms/Utils/Local.h"
Jim Grosbach486be662009-08-17 16:41:22 +000031using namespace llvm;
32
Chandler Carruth1b9dde02014-04-22 02:02:50 +000033#define DEBUG_TYPE "sjljehprepare"
34
Jim Grosbach486be662009-08-17 16:41:22 +000035STATISTIC(NumInvokes, "Number of invokes replaced");
Jim Grosbach486be662009-08-17 16:41:22 +000036STATISTIC(NumSpilled, "Number of registers live across unwind edges");
37
38namespace {
Bill Wendling8faa30e2013-09-23 20:57:47 +000039class SjLjEHPrepare : public FunctionPass {
David Blaikie4e5d47f42015-04-04 21:07:10 +000040 Type *doubleUnderDataTy;
41 Type *doubleUnderJBufTy;
Bill Wendling8faa30e2013-09-23 20:57:47 +000042 Type *FunctionContextTy;
43 Constant *RegisterFn;
44 Constant *UnregisterFn;
Matthias Braun3cd00c12015-07-16 22:34:16 +000045 Constant *BuiltinSetupDispatchFn;
Bill Wendling8faa30e2013-09-23 20:57:47 +000046 Constant *FrameAddrFn;
47 Constant *StackAddrFn;
48 Constant *StackRestoreFn;
49 Constant *LSDAAddrFn;
Bill Wendling8faa30e2013-09-23 20:57:47 +000050 Constant *CallSiteFn;
51 Constant *FuncCtxFn;
52 AllocaInst *FuncCtx;
Jim Grosbach486be662009-08-17 16:41:22 +000053
Bill Wendling8faa30e2013-09-23 20:57:47 +000054public:
55 static char ID; // Pass identification, replacement for typeid
Mehdi Aminif50daed2015-07-08 01:00:31 +000056 explicit SjLjEHPrepare() : FunctionPass(ID) {}
Craig Topper4584cd52014-03-07 09:26:03 +000057 bool doInitialization(Module &M) override;
58 bool runOnFunction(Function &F) override;
Jim Grosbach486be662009-08-17 16:41:22 +000059
Craig Topper4584cd52014-03-07 09:26:03 +000060 void getAnalysisUsage(AnalysisUsage &AU) const override {}
Mehdi Amini117296c2016-10-01 02:56:57 +000061 StringRef getPassName() const override {
Bill Wendling8faa30e2013-09-23 20:57:47 +000062 return "SJLJ Exception Handling preparation";
63 }
64
65private:
66 bool setupEntryBlockAndCallSites(Function &F);
Arnold Schwaighofer69e74b42017-03-07 20:29:02 +000067 bool undoSwiftErrorSelect(Function &F);
Bill Wendling8faa30e2013-09-23 20:57:47 +000068 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);
73};
Jim Grosbach486be662009-08-17 16:41:22 +000074} // end anonymous namespace
75
Bill Wendling12e5adb2012-03-13 20:04:21 +000076char SjLjEHPrepare::ID = 0;
Matthias Braun1527baa2017-05-25 21:26:32 +000077INITIALIZE_PASS(SjLjEHPrepare, DEBUG_TYPE, "Prepare SjLj exceptions",
Reid Klecknerc16b1072015-07-09 21:48:40 +000078 false, false)
Jim Grosbach486be662009-08-17 16:41:22 +000079
Bill Wendling12e5adb2012-03-13 20:04:21 +000080// Public Interface To the SjLjEHPrepare pass.
Mehdi Aminif50daed2015-07-08 01:00:31 +000081FunctionPass *llvm::createSjLjEHPreparePass() { return new SjLjEHPrepare(); }
Jim Grosbach1b0436b2009-08-23 18:13:48 +000082// doInitialization - Set up decalarations and types needed to process
83// exceptions.
Bill Wendling12e5adb2012-03-13 20:04:21 +000084bool SjLjEHPrepare::doInitialization(Module &M) {
Jim Grosbach486be662009-08-17 16:41:22 +000085 // Build the function context structure.
86 // builtin_setjmp uses a five word jbuf
Jay Foadb804a2b2011-07-12 14:06:48 +000087 Type *VoidPtrTy = Type::getInt8PtrTy(M.getContext());
88 Type *Int32Ty = Type::getInt32Ty(M.getContext());
David Blaikie4e5d47f42015-04-04 21:07:10 +000089 doubleUnderDataTy = ArrayType::get(Int32Ty, 4);
90 doubleUnderJBufTy = ArrayType::get(VoidPtrTy, 5);
91 FunctionContextTy = StructType::get(VoidPtrTy, // __prev
92 Int32Ty, // call_site
93 doubleUnderDataTy, // __data
94 VoidPtrTy, // __personality
95 VoidPtrTy, // __lsda
Serge Gueltone38003f2017-05-09 19:31:13 +000096 doubleUnderJBufTy // __jbuf
97 );
Jim Grosbach486be662009-08-17 16:41:22 +000098
99 return true;
100}
101
Jim Grosbach1201f292010-03-04 22:07:46 +0000102/// insertCallSiteStore - Insert a store of the call-site value to the
103/// function context
Bill Wendling12e5adb2012-03-13 20:04:21 +0000104void SjLjEHPrepare::insertCallSiteStore(Instruction *I, int Number) {
Bill Wendling7717e9f2012-01-27 02:02:24 +0000105 IRBuilder<> Builder(I);
106
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 };
David Blaikie68d535c2015-03-24 22:38:16 +0000112 Value *CallSite =
113 Builder.CreateGEP(FunctionContextTy, FuncCtx, Idxs, "call_site");
Bill Wendling7717e9f2012-01-27 02:02:24 +0000114
115 // Insert a store of the call-site number
Bill Wendling8faa30e2013-09-23 20:57:47 +0000116 ConstantInt *CallSiteNoC =
117 ConstantInt::get(Type::getInt32Ty(I->getContext()), Number);
118 Builder.CreateStore(CallSiteNoC, CallSite, true /*volatile*/);
Jim Grosbach1201f292010-03-04 22:07:46 +0000119}
120
David Majnemerb61fd7f2016-02-19 04:46:06 +0000121/// MarkBlocksLiveIn - Insert BB and all of its predecessors into LiveBBs until
Jim Grosbach486be662009-08-17 16:41:22 +0000122/// we reach blocks we've already seen.
Chad Rosier1a9c17e2012-03-16 01:04:00 +0000123static void MarkBlocksLiveIn(BasicBlock *BB,
Craig Topper71b7b682014-08-21 05:55:13 +0000124 SmallPtrSetImpl<BasicBlock *> &LiveBBs) {
David Blaikie70573dc2014-11-19 07:49:26 +0000125 if (!LiveBBs.insert(BB).second)
Bill Wendling8faa30e2013-09-23 20:57:47 +0000126 return; // already been here.
Jim Grosbach486be662009-08-17 16:41:22 +0000127
David Majnemerb61fd7f2016-02-19 04:46:06 +0000128 for (BasicBlock *PredBB : predecessors(BB))
129 MarkBlocksLiveIn(PredBB, LiveBBs);
Jim Grosbach486be662009-08-17 16:41:22 +0000130}
131
Bill Wendlingb108aae2011-12-14 22:45:33 +0000132/// substituteLPadValues - Substitute the values returned by the landingpad
133/// instruction with those returned by the personality function.
Bill Wendling12e5adb2012-03-13 20:04:21 +0000134void SjLjEHPrepare::substituteLPadValues(LandingPadInst *LPI, Value *ExnVal,
135 Value *SelVal) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000136 SmallVector<Value *, 8> UseWorkList(LPI->user_begin(), LPI->user_end());
Bill Wendlingb108aae2011-12-14 22:45:33 +0000137 while (!UseWorkList.empty()) {
138 Value *Val = UseWorkList.pop_back_val();
David Majnemerb61fd7f2016-02-19 04:46:06 +0000139 auto *EVI = dyn_cast<ExtractValueInst>(Val);
Bill Wendling8faa30e2013-09-23 20:57:47 +0000140 if (!EVI)
141 continue;
142 if (EVI->getNumIndices() != 1)
143 continue;
Bill Wendlingb108aae2011-12-14 22:45:33 +0000144 if (*EVI->idx_begin() == 0)
145 EVI->replaceAllUsesWith(ExnVal);
146 else if (*EVI->idx_begin() == 1)
147 EVI->replaceAllUsesWith(SelVal);
David Majnemerb61fd7f2016-02-19 04:46:06 +0000148 if (EVI->use_empty())
Bill Wendlingb108aae2011-12-14 22:45:33 +0000149 EVI->eraseFromParent();
150 }
151
David Majnemerb61fd7f2016-02-19 04:46:06 +0000152 if (LPI->use_empty())
Bill Wendling8faa30e2013-09-23 20:57:47 +0000153 return;
Bill Wendlingb108aae2011-12-14 22:45:33 +0000154
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);
Duncan P. N. Exon Smithf1ff53e2015-10-09 22:56:24 +0000159 auto *SelI = cast<Instruction>(SelVal);
160 IRBuilder<> Builder(SelI->getParent(), std::next(SelI->getIterator()));
Bill Wendlingb108aae2011-12-14 22:45:33 +0000161 LPadVal = Builder.CreateInsertValue(LPadVal, ExnVal, 0, "lpad.val");
162 LPadVal = Builder.CreateInsertValue(LPadVal, SelVal, 1, "lpad.val");
163
164 LPI->replaceAllUsesWith(LPadVal);
165}
166
Bill Wendling2e76ca92011-09-28 03:14:05 +0000167/// setupFunctionContext - Allocate the function context on the stack and fill
168/// it with all of the data that we know at this point.
Bill Wendling8faa30e2013-09-23 20:57:47 +0000169Value *SjLjEHPrepare::setupFunctionContext(Function &F,
170 ArrayRef<LandingPadInst *> LPads) {
Duncan P. N. Exon Smithf1ff53e2015-10-09 22:56:24 +0000171 BasicBlock *EntryBB = &F.front();
Bill Wendling2e76ca92011-09-28 03:14:05 +0000172
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.
Mehdi Aminif50daed2015-07-08 01:00:31 +0000176 auto &DL = F.getParent()->getDataLayout();
177 unsigned Align = DL.getPrefTypeAlignment(FunctionContextTy);
Matt Arsenault3c1fc762017-04-10 22:27:50 +0000178 FuncCtx = new AllocaInst(FunctionContextTy, DL.getAllocaAddrSpace(),
179 nullptr, Align, "fn_context", &EntryBB->front());
Bill Wendling2e76ca92011-09-28 03:14:05 +0000180
181 // Fill in the function context structure.
David Majnemerb61fd7f2016-02-19 04:46:06 +0000182 for (LandingPadInst *LPI : LPads) {
Duncan P. N. Exon Smithf1ff53e2015-10-09 22:56:24 +0000183 IRBuilder<> Builder(LPI->getParent(),
184 LPI->getParent()->getFirstInsertionPt());
Bill Wendling2e76ca92011-09-28 03:14:05 +0000185
Bill Wendling7717e9f2012-01-27 02:02:24 +0000186 // Reference the __data field.
David Blaikie4e5d47f42015-04-04 21:07:10 +0000187 Value *FCData =
188 Builder.CreateConstGEP2_32(FunctionContextTy, FuncCtx, 0, 2, "__data");
Bill Wendling7717e9f2012-01-27 02:02:24 +0000189
190 // The exception values come back in context->__data[0].
David Blaikie4e5d47f42015-04-04 21:07:10 +0000191 Value *ExceptionAddr = Builder.CreateConstGEP2_32(doubleUnderDataTy, FCData,
192 0, 0, "exception_gep");
Bill Wendling2e76ca92011-09-28 03:14:05 +0000193 Value *ExnVal = Builder.CreateLoad(ExceptionAddr, true, "exn_val");
Benjamin Kramer8d9890a2012-09-03 12:27:43 +0000194 ExnVal = Builder.CreateIntToPtr(ExnVal, Builder.getInt8PtrTy());
Bill Wendling7717e9f2012-01-27 02:02:24 +0000195
David Blaikie4e5d47f42015-04-04 21:07:10 +0000196 Value *SelectorAddr = Builder.CreateConstGEP2_32(doubleUnderDataTy, FCData,
197 0, 1, "exn_selector_gep");
Bill Wendling2e76ca92011-09-28 03:14:05 +0000198 Value *SelVal = Builder.CreateLoad(SelectorAddr, true, "exn_selector_val");
199
Bill Wendlingb108aae2011-12-14 22:45:33 +0000200 substituteLPadValues(LPI, ExnVal, SelVal);
Bill Wendling2e76ca92011-09-28 03:14:05 +0000201 }
202
203 // Personality function
Benjamin Kramer8d9890a2012-09-03 12:27:43 +0000204 IRBuilder<> Builder(EntryBB->getTerminator());
David Majnemerbd1b8c02016-02-19 03:13:40 +0000205 Value *PersonalityFn = F.getPersonalityFn();
David Blaikie4e5d47f42015-04-04 21:07:10 +0000206 Value *PersonalityFieldPtr = Builder.CreateConstGEP2_32(
207 FunctionContextTy, FuncCtx, 0, 3, "pers_fn_gep");
Bill Wendling8faa30e2013-09-23 20:57:47 +0000208 Builder.CreateStore(
209 Builder.CreateBitCast(PersonalityFn, Builder.getInt8PtrTy()),
210 PersonalityFieldPtr, /*isVolatile=*/true);
Bill Wendling2e76ca92011-09-28 03:14:05 +0000211
212 // LSDA address
David Blaikieff6409d2015-05-18 22:13:54 +0000213 Value *LSDA = Builder.CreateCall(LSDAAddrFn, {}, "lsda_addr");
David Blaikie4e5d47f42015-04-04 21:07:10 +0000214 Value *LSDAFieldPtr =
215 Builder.CreateConstGEP2_32(FunctionContextTy, FuncCtx, 0, 4, "lsda_gep");
Benjamin Kramer8d9890a2012-09-03 12:27:43 +0000216 Builder.CreateStore(LSDA, LSDAFieldPtr, /*isVolatile=*/true);
Bill Wendling2e76ca92011-09-28 03:14:05 +0000217
Bill Wendling6f3e73d2011-10-03 21:15:28 +0000218 return FuncCtx;
Bill Wendling899da522011-09-28 21:56:53 +0000219}
220
Bill Wendlinge9574be2011-10-08 00:56:47 +0000221/// 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
224/// block.
Bill Wendling12e5adb2012-03-13 20:04:21 +0000225void SjLjEHPrepare::lowerIncomingArguments(Function &F) {
Bill Wendlinge9574be2011-10-08 00:56:47 +0000226 BasicBlock::iterator AfterAllocaInsPt = F.begin()->begin();
227 while (isa<AllocaInst>(AfterAllocaInsPt) &&
David Majnemerb61fd7f2016-02-19 04:46:06 +0000228 cast<AllocaInst>(AfterAllocaInsPt)->isStaticAlloca())
Bill Wendlinge9574be2011-10-08 00:56:47 +0000229 ++AfterAllocaInsPt;
Duncan P. N. Exon Smithf1ff53e2015-10-09 22:56:24 +0000230 assert(AfterAllocaInsPt != F.front().end());
Bill Wendlinge9574be2011-10-08 00:56:47 +0000231
Duncan P. N. Exon Smithf1ff53e2015-10-09 22:56:24 +0000232 for (auto &AI : F.args()) {
233 Type *Ty = AI.getType();
Bill Wendlinge9574be2011-10-08 00:56:47 +0000234
Bill Wendlingc80b6c92014-07-14 18:21:11 +0000235 // 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);
Duncan P. N. Exon Smithf1ff53e2015-10-09 22:56:24 +0000238 Instruction *SI = SelectInst::Create(
239 TrueValue, &AI, UndefValue, AI.getName() + ".tmp", &*AfterAllocaInsPt);
240 AI.replaceAllUsesWith(SI);
Bill Wendlinge9574be2011-10-08 00:56:47 +0000241
Bill Wendlingc80b6c92014-07-14 18:21:11 +0000242 // Reset the operand, because it was clobbered by the RAUW above.
Duncan P. N. Exon Smithf1ff53e2015-10-09 22:56:24 +0000243 SI->setOperand(1, &AI);
Bill Wendlinge9574be2011-10-08 00:56:47 +0000244 }
245}
246
247/// lowerAcrossUnwindEdges - Find all variables which are alive across an unwind
248/// edge and spill them.
Bill Wendling12e5adb2012-03-13 20:04:21 +0000249void SjLjEHPrepare::lowerAcrossUnwindEdges(Function &F,
Bill Wendling8faa30e2013-09-23 20:57:47 +0000250 ArrayRef<InvokeInst *> Invokes) {
Bill Wendlinge9574be2011-10-08 00:56:47 +0000251 // Finally, scan the code looking for instructions with bad live ranges.
David Majnemerb61fd7f2016-02-19 04:46:06 +0000252 for (BasicBlock &BB : F) {
253 for (Instruction &Inst : BB) {
Bill Wendlinge9574be2011-10-08 00:56:47 +0000254 // 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.
David Majnemerb61fd7f2016-02-19 04:46:06 +0000257 if (Inst.use_empty())
Bill Wendling8faa30e2013-09-23 20:57:47 +0000258 continue;
David Majnemerb61fd7f2016-02-19 04:46:06 +0000259 if (Inst.hasOneUse() &&
260 cast<Instruction>(Inst.user_back())->getParent() == &BB &&
261 !isa<PHINode>(Inst.user_back()))
Bill Wendling8faa30e2013-09-23 20:57:47 +0000262 continue;
Bill Wendlinge9574be2011-10-08 00:56:47 +0000263
264 // If this is an alloca in the entry block, it's not a real register
265 // value.
David Majnemerb61fd7f2016-02-19 04:46:06 +0000266 if (auto *AI = dyn_cast<AllocaInst>(&Inst))
267 if (AI->isStaticAlloca())
Bill Wendlinge9574be2011-10-08 00:56:47 +0000268 continue;
269
270 // Avoid iterator invalidation by copying users to a temporary vector.
Bill Wendling8faa30e2013-09-23 20:57:47 +0000271 SmallVector<Instruction *, 16> Users;
David Majnemerb61fd7f2016-02-19 04:46:06 +0000272 for (User *U : Inst.users()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000273 Instruction *UI = cast<Instruction>(U);
David Majnemerb61fd7f2016-02-19 04:46:06 +0000274 if (UI->getParent() != &BB || isa<PHINode>(UI))
Chandler Carruthcdf47882014-03-09 03:16:01 +0000275 Users.push_back(UI);
Bill Wendlinge9574be2011-10-08 00:56:47 +0000276 }
277
278 // Find all of the blocks that this value is live in.
Matthias Braunb30f2f512016-01-30 01:24:31 +0000279 SmallPtrSet<BasicBlock *, 32> LiveBBs;
David Majnemerb61fd7f2016-02-19 04:46:06 +0000280 LiveBBs.insert(&BB);
Bill Wendlinge9574be2011-10-08 00:56:47 +0000281 while (!Users.empty()) {
David Majnemerb61fd7f2016-02-19 04:46:06 +0000282 Instruction *U = Users.pop_back_val();
Bill Wendlinge9574be2011-10-08 00:56:47 +0000283
Chad Rosier1a9c17e2012-03-16 01:04:00 +0000284 if (!isa<PHINode>(U)) {
285 MarkBlocksLiveIn(U->getParent(), LiveBBs);
286 } else {
Bill Wendlinge9574be2011-10-08 00:56:47 +0000287 // Uses for a PHI node occur in their predecessor block.
Chad Rosier1a9c17e2012-03-16 01:04:00 +0000288 PHINode *PN = cast<PHINode>(U);
Bill Wendlinge9574be2011-10-08 00:56:47 +0000289 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
David Majnemerb61fd7f2016-02-19 04:46:06 +0000290 if (PN->getIncomingValue(i) == &Inst)
Chad Rosier1a9c17e2012-03-16 01:04:00 +0000291 MarkBlocksLiveIn(PN->getIncomingBlock(i), LiveBBs);
Bill Wendlinge9574be2011-10-08 00:56:47 +0000292 }
293 }
294
Chad Rosier1a9c17e2012-03-16 01:04:00 +0000295 // 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;
David Majnemerb61fd7f2016-02-19 04:46:06 +0000298 for (InvokeInst *Invoke : Invokes) {
299 BasicBlock *UnwindBlock = Invoke->getUnwindDest();
300 if (UnwindBlock != &BB && LiveBBs.count(UnwindBlock)) {
301 DEBUG(dbgs() << "SJLJ Spill: " << Inst << " around "
Bill Wendling8faa30e2013-09-23 20:57:47 +0000302 << UnwindBlock->getName() << "\n");
Chad Rosier1a9c17e2012-03-16 01:04:00 +0000303 NeedsSpill = true;
304 break;
Bill Wendlingd7c0aae2012-03-14 07:28:01 +0000305 }
Bill Wendling5ad91402012-03-12 20:19:41 +0000306 }
Bill Wendlingb1c43082011-10-21 22:08:56 +0000307
Chad Rosier1a9c17e2012-03-16 01:04:00 +0000308 // 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.
312 if (NeedsSpill) {
David Majnemerb61fd7f2016-02-19 04:46:06 +0000313 DemoteRegToStack(Inst, true);
Chad Rosier1a9c17e2012-03-16 01:04:00 +0000314 ++NumSpilled;
315 }
Bill Wendlingd7c0aae2012-03-14 07:28:01 +0000316 }
317 }
318
Bill Wendlingb1c43082011-10-21 22:08:56 +0000319 // Go through the landing pads and remove any PHIs there.
David Majnemerb61fd7f2016-02-19 04:46:06 +0000320 for (InvokeInst *Invoke : Invokes) {
321 BasicBlock *UnwindBlock = Invoke->getUnwindDest();
Bill Wendlingb1c43082011-10-21 22:08:56 +0000322 LandingPadInst *LPI = UnwindBlock->getLandingPadInst();
323
324 // Place PHIs into a set to avoid invalidating the iterator.
Bill Wendling8faa30e2013-09-23 20:57:47 +0000325 SmallPtrSet<PHINode *, 8> PHIsToDemote;
326 for (BasicBlock::iterator PN = UnwindBlock->begin(); isa<PHINode>(PN); ++PN)
Bill Wendlingb1c43082011-10-21 22:08:56 +0000327 PHIsToDemote.insert(cast<PHINode>(PN));
Bill Wendling8faa30e2013-09-23 20:57:47 +0000328 if (PHIsToDemote.empty())
329 continue;
Bill Wendlingb1c43082011-10-21 22:08:56 +0000330
331 // Demote the PHIs to the stack.
Craig Topper46276792014-08-24 23:23:06 +0000332 for (PHINode *PN : PHIsToDemote)
333 DemotePHIToStack(PN);
Bill Wendlingb1c43082011-10-21 22:08:56 +0000334
335 // Move the landingpad instruction back to the top of the landing pad block.
Duncan P. N. Exon Smithf1ff53e2015-10-09 22:56:24 +0000336 LPI->moveBefore(&UnwindBlock->front());
Bill Wendlingb1c43082011-10-21 22:08:56 +0000337 }
Bill Wendlinge9574be2011-10-08 00:56:47 +0000338}
339
Bill Wendling899da522011-09-28 21:56:53 +0000340/// 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.
Bill Wendling12e5adb2012-03-13 20:04:21 +0000343bool SjLjEHPrepare::setupEntryBlockAndCallSites(Function &F) {
Bill Wendling8faa30e2013-09-23 20:57:47 +0000344 SmallVector<ReturnInst *, 16> Returns;
345 SmallVector<InvokeInst *, 16> Invokes;
346 SmallSetVector<LandingPadInst *, 16> LPads;
Bill Wendling899da522011-09-28 21:56:53 +0000347
348 // Look through the terminators of the basic blocks to find invokes.
David Majnemerb61fd7f2016-02-19 04:46:06 +0000349 for (BasicBlock &BB : F)
350 if (auto *II = dyn_cast<InvokeInst>(BB.getTerminator())) {
Bill Wendling2d915e22013-03-08 02:21:08 +0000351 if (Function *Callee = II->getCalledFunction())
David Majnemerb61fd7f2016-02-19 04:46:06 +0000352 if (Callee->getIntrinsicID() == Intrinsic::donothing) {
Bill Wendling2d915e22013-03-08 02:21:08 +0000353 // Remove the NOP invoke.
354 BranchInst::Create(II->getNormalDest(), II);
355 II->eraseFromParent();
356 continue;
357 }
358
Bill Wendling899da522011-09-28 21:56:53 +0000359 Invokes.push_back(II);
Bob Wilsoncca9aa52011-11-16 07:57:21 +0000360 LPads.insert(II->getUnwindDest()->getLandingPadInst());
David Majnemerb61fd7f2016-02-19 04:46:06 +0000361 } else if (auto *RI = dyn_cast<ReturnInst>(BB.getTerminator())) {
Bill Wendling899da522011-09-28 21:56:53 +0000362 Returns.push_back(RI);
363 }
364
Bill Wendling8faa30e2013-09-23 20:57:47 +0000365 if (Invokes.empty())
366 return false;
Bill Wendling899da522011-09-28 21:56:53 +0000367
Bill Wendling38f86c52011-10-24 17:12:36 +0000368 NumInvokes += Invokes.size();
369
Bill Wendlinge9574be2011-10-08 00:56:47 +0000370 lowerIncomingArguments(F);
371 lowerAcrossUnwindEdges(F, Invokes);
372
Bob Wilsoncca9aa52011-11-16 07:57:21 +0000373 Value *FuncCtx =
Bill Wendling8faa30e2013-09-23 20:57:47 +0000374 setupFunctionContext(F, makeArrayRef(LPads.begin(), LPads.end()));
Duncan P. N. Exon Smithf1ff53e2015-10-09 22:56:24 +0000375 BasicBlock *EntryBB = &F.front();
Benjamin Kramer8d9890a2012-09-03 12:27:43 +0000376 IRBuilder<> Builder(EntryBB->getTerminator());
Bill Wendling6f3e73d2011-10-03 21:15:28 +0000377
378 // Get a reference to the jump buffer.
David Blaikie4e5d47f42015-04-04 21:07:10 +0000379 Value *JBufPtr =
380 Builder.CreateConstGEP2_32(FunctionContextTy, FuncCtx, 0, 5, "jbuf_gep");
Bill Wendling2e76ca92011-09-28 03:14:05 +0000381
Bill Wendling6f3e73d2011-10-03 21:15:28 +0000382 // Save the frame pointer.
David Blaikie4e5d47f42015-04-04 21:07:10 +0000383 Value *FramePtr = Builder.CreateConstGEP2_32(doubleUnderJBufTy, JBufPtr, 0, 0,
384 "jbuf_fp_gep");
Bill Wendling6f3e73d2011-10-03 21:15:28 +0000385
Benjamin Kramer8d9890a2012-09-03 12:27:43 +0000386 Value *Val = Builder.CreateCall(FrameAddrFn, Builder.getInt32(0), "fp");
387 Builder.CreateStore(Val, FramePtr, /*isVolatile=*/true);
Bill Wendling6f3e73d2011-10-03 21:15:28 +0000388
389 // Save the stack pointer.
David Blaikie4e5d47f42015-04-04 21:07:10 +0000390 Value *StackPtr = Builder.CreateConstGEP2_32(doubleUnderJBufTy, JBufPtr, 0, 2,
391 "jbuf_sp_gep");
Bill Wendling6f3e73d2011-10-03 21:15:28 +0000392
David Blaikieff6409d2015-05-18 22:13:54 +0000393 Val = Builder.CreateCall(StackAddrFn, {}, "sp");
Benjamin Kramer8d9890a2012-09-03 12:27:43 +0000394 Builder.CreateStore(Val, StackPtr, /*isVolatile=*/true);
Bill Wendling2e76ca92011-09-28 03:14:05 +0000395
Matthias Braun3cd00c12015-07-16 22:34:16 +0000396 // Call the setup_dispatch instrinsic. It fills in the rest of the jmpbuf.
397 Builder.CreateCall(BuiltinSetupDispatchFn, {});
Bill Wendling2e76ca92011-09-28 03:14:05 +0000398
Bill Wendling899da522011-09-28 21:56:53 +0000399 // Store a pointer to the function context so that the back-end will know
400 // where to look for it.
Benjamin Kramer8d9890a2012-09-03 12:27:43 +0000401 Value *FuncCtxArg = Builder.CreateBitCast(FuncCtx, Builder.getInt8PtrTy());
402 Builder.CreateCall(FuncCtxFn, FuncCtxArg);
Bill Wendling2e76ca92011-09-28 03:14:05 +0000403
404 // At this point, we are all set up, update the invoke instructions to mark
Bill Wendlingdb163352011-10-05 22:04:08 +0000405 // their call_site values.
Bill Wendling2e76ca92011-09-28 03:14:05 +0000406 for (unsigned I = 0, E = Invokes.size(); I != E; ++I) {
Bill Wendling7717e9f2012-01-27 02:02:24 +0000407 insertCallSiteStore(Invokes[I], I + 1);
Bill Wendling2e76ca92011-09-28 03:14:05 +0000408
409 ConstantInt *CallSiteNum =
Bill Wendling8faa30e2013-09-23 20:57:47 +0000410 ConstantInt::get(Type::getInt32Ty(F.getContext()), I + 1);
Bill Wendling2e76ca92011-09-28 03:14:05 +0000411
412 // Record the call site value for the back end so it stays associated with
413 // the invoke.
414 CallInst::Create(CallSiteFn, CallSiteNum, "", Invokes[I]);
415 }
416
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.
David Majnemerb61fd7f2016-02-19 04:46:06 +0000422 for (BasicBlock &BB : F) {
Duncan P. N. Exon Smithe9bc5792016-02-21 20:39:50 +0000423 if (&BB == &F.front())
David Majnemerb61fd7f2016-02-19 04:46:06 +0000424 continue;
425 for (Instruction &I : BB)
426 if (I.mayThrow())
427 insertCallSiteStore(&I, -1);
428 }
Bill Wendling2e76ca92011-09-28 03:14:05 +0000429
Bill Wendling899da522011-09-28 21:56:53 +0000430 // Register the function context and make sure it's known to not throw
Bill Wendling8faa30e2013-09-23 20:57:47 +0000431 CallInst *Register =
432 CallInst::Create(RegisterFn, FuncCtx, "", EntryBB->getTerminator());
Bill Wendling899da522011-09-28 21:56:53 +0000433 Register->setDoesNotThrow();
434
Bob Wilson643e63c2011-11-16 07:12:00 +0000435 // Following any allocas not in the entry block, update the saved SP in the
436 // jmpbuf to the new value.
David Majnemerb61fd7f2016-02-19 04:46:06 +0000437 for (BasicBlock &BB : F) {
Duncan P. N. Exon Smithe9bc5792016-02-21 20:39:50 +0000438 if (&BB == &F.front())
Bob Wilson643e63c2011-11-16 07:12:00 +0000439 continue;
David Majnemerb61fd7f2016-02-19 04:46:06 +0000440 for (Instruction &I : BB) {
441 if (auto *CI = dyn_cast<CallInst>(&I)) {
Bob Wilson643e63c2011-11-16 07:12:00 +0000442 if (CI->getCalledFunction() != StackRestoreFn)
443 continue;
David Majnemerb61fd7f2016-02-19 04:46:06 +0000444 } else if (!isa<AllocaInst>(&I)) {
Bob Wilson643e63c2011-11-16 07:12:00 +0000445 continue;
446 }
447 Instruction *StackAddr = CallInst::Create(StackAddrFn, "sp");
David Majnemerb61fd7f2016-02-19 04:46:06 +0000448 StackAddr->insertAfter(&I);
Bob Wilson643e63c2011-11-16 07:12:00 +0000449 Instruction *StoreStackAddr = new StoreInst(StackAddr, StackPtr, true);
450 StoreStackAddr->insertAfter(StackAddr);
451 }
452 }
453
Bill Wendling899da522011-09-28 21:56:53 +0000454 // Finally, for any returns from this function, if this function contains an
455 // invoke, add a call to unregister the function context.
David Majnemerb61fd7f2016-02-19 04:46:06 +0000456 for (ReturnInst *Return : Returns)
457 CallInst::Create(UnregisterFn, FuncCtx, "", Return);
Bill Wendling899da522011-09-28 21:56:53 +0000458
Bill Wendling2e76ca92011-09-28 03:14:05 +0000459 return true;
460}
461
Arnold Schwaighofer69e74b42017-03-07 20:29:02 +0000462bool 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();
475 return true;
476 }
477 }
478 return false;
479}
480
Bill Wendling12e5adb2012-03-13 20:04:21 +0000481bool SjLjEHPrepare::runOnFunction(Function &F) {
David Majnemerbd1b8c02016-02-19 03:13:40 +0000482 Module &M = *F.getParent();
Mehdi Aminidb11fdf2017-04-06 20:23:57 +0000483 RegisterFn = M.getOrInsertFunction(
484 "_Unwind_SjLj_Register", Type::getVoidTy(M.getContext()),
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000485 PointerType::getUnqual(FunctionContextTy));
David Majnemerbd1b8c02016-02-19 03:13:40 +0000486 UnregisterFn = M.getOrInsertFunction(
487 "_Unwind_SjLj_Unregister", Type::getVoidTy(M.getContext()),
Serge Guelton59a2d7b2017-04-11 15:01:18 +0000488 PointerType::getUnqual(FunctionContextTy));
David Majnemerbd1b8c02016-02-19 03:13:40 +0000489 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);
497
Bill Wendling38f86c52011-10-24 17:12:36 +0000498 bool Res = setupEntryBlockAndCallSites(F);
Arnold Schwaighofer69e74b42017-03-07 20:29:02 +0000499 if (Res)
500 Res |= undoSwiftErrorSelect(F);
Jim Grosbach486be662009-08-17 16:41:22 +0000501 return Res;
502}