blob: 2fc8f46f48b1bf50110006cf9973a0018900df2b [file] [log] [blame]
Bill Wendlingeabae1d2012-03-13 20:04:21 +00001//===- SjLjEHPrepare.cpp - Eliminate Invoke & Unwind instructions ---------===//
Jim Grosbach8b818d72009-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
15#define DEBUG_TYPE "sjljehprepare"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000016#include "llvm/CodeGen/Passes.h"
17#include "llvm/ADT/DenseMap.h"
18#include "llvm/ADT/SetVector.h"
19#include "llvm/ADT/SmallPtrSet.h"
20#include "llvm/ADT/SmallVector.h"
21#include "llvm/ADT/Statistic.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000022#include "llvm/IR/Constants.h"
23#include "llvm/IR/DataLayout.h"
24#include "llvm/IR/DerivedTypes.h"
25#include "llvm/IR/IRBuilder.h"
26#include "llvm/IR/Instructions.h"
27#include "llvm/IR/Intrinsics.h"
28#include "llvm/IR/LLVMContext.h"
29#include "llvm/IR/Module.h"
Jim Grosbach8b818d72009-08-17 16:41:22 +000030#include "llvm/Pass.h"
Chandler Carruth06cb8ed2012-06-29 12:38:19 +000031#include "llvm/Support/CommandLine.h"
32#include "llvm/Support/Debug.h"
33#include "llvm/Support/raw_ostream.h"
Chandler Carruth06cb8ed2012-06-29 12:38:19 +000034#include "llvm/Target/TargetLowering.h"
35#include "llvm/Transforms/Scalar.h"
36#include "llvm/Transforms/Utils/BasicBlockUtils.h"
37#include "llvm/Transforms/Utils/Local.h"
Benjamin Kramerf7888542010-11-06 11:45:59 +000038#include <set>
Jim Grosbach8b818d72009-08-17 16:41:22 +000039using namespace llvm;
40
41STATISTIC(NumInvokes, "Number of invokes replaced");
Jim Grosbach8b818d72009-08-17 16:41:22 +000042STATISTIC(NumSpilled, "Number of registers live across unwind edges");
43
44namespace {
Bill Wendlingeabae1d2012-03-13 20:04:21 +000045 class SjLjEHPrepare : public FunctionPass {
Bill Wendlingea442812013-06-19 20:51:24 +000046 const TargetMachine *TM;
Chris Lattnerdb125cf2011-07-18 04:54:35 +000047 Type *FunctionContextTy;
Jim Grosbach8b818d72009-08-17 16:41:22 +000048 Constant *RegisterFn;
49 Constant *UnregisterFn;
Jim Grosbach8b818d72009-08-17 16:41:22 +000050 Constant *BuiltinSetjmpFn;
51 Constant *FrameAddrFn;
Jim Grosbach0798edd2010-05-27 23:49:24 +000052 Constant *StackAddrFn;
Bob Wilson20c918d2011-11-16 07:12:00 +000053 Constant *StackRestoreFn;
Jim Grosbach8b818d72009-08-17 16:41:22 +000054 Constant *LSDAAddrFn;
55 Value *PersonalityFn;
Jim Grosbachca752c92010-01-28 01:45:32 +000056 Constant *CallSiteFn;
Bill Wendlingcc8cf972011-09-28 21:56:53 +000057 Constant *FuncCtxFn;
Bill Wendling4cc46662012-01-27 02:02:24 +000058 AllocaInst *FuncCtx;
Jim Grosbach8b818d72009-08-17 16:41:22 +000059 public:
60 static char ID; // Pass identification, replacement for typeid
Bill Wendlingea442812013-06-19 20:51:24 +000061 explicit SjLjEHPrepare(const TargetMachine *TM)
62 : FunctionPass(ID), TM(TM) { }
Jim Grosbach8b818d72009-08-17 16:41:22 +000063 bool doInitialization(Module &M);
64 bool runOnFunction(Function &F);
65
Chad Rosierbace5da2012-03-16 01:04:00 +000066 virtual void getAnalysisUsage(AnalysisUsage &AU) const {}
Jim Grosbach8b818d72009-08-17 16:41:22 +000067 const char *getPassName() const {
68 return "SJLJ Exception Handling preparation";
69 }
70
71 private:
Bill Wendling2b6bd7b2011-09-28 03:14:05 +000072 bool setupEntryBlockAndCallSites(Function &F);
Bill Wendling69fdcd72011-12-14 22:45:33 +000073 void substituteLPadValues(LandingPadInst *LPI, Value *ExnVal,
74 Value *SelVal);
Bill Wendling631d1172011-10-03 21:15:28 +000075 Value *setupFunctionContext(Function &F, ArrayRef<LandingPadInst*> LPads);
Bill Wendlingd5d17002011-10-08 00:56:47 +000076 void lowerIncomingArguments(Function &F);
77 void lowerAcrossUnwindEdges(Function &F, ArrayRef<InvokeInst*> Invokes);
Bill Wendling4cc46662012-01-27 02:02:24 +000078 void insertCallSiteStore(Instruction *I, int Number);
Jim Grosbach8b818d72009-08-17 16:41:22 +000079 };
80} // end anonymous namespace
81
Bill Wendlingeabae1d2012-03-13 20:04:21 +000082char SjLjEHPrepare::ID = 0;
Jim Grosbach8b818d72009-08-17 16:41:22 +000083
Bill Wendlingeabae1d2012-03-13 20:04:21 +000084// Public Interface To the SjLjEHPrepare pass.
Bill Wendlingea442812013-06-19 20:51:24 +000085FunctionPass *llvm::createSjLjEHPreparePass(const TargetMachine *TM) {
86 return new SjLjEHPrepare(TM);
Jim Grosbach8b818d72009-08-17 16:41:22 +000087}
Jim Grosbacha235d132009-08-23 18:13:48 +000088// doInitialization - Set up decalarations and types needed to process
89// exceptions.
Bill Wendlingeabae1d2012-03-13 20:04:21 +000090bool SjLjEHPrepare::doInitialization(Module &M) {
Jim Grosbach8b818d72009-08-17 16:41:22 +000091 // Build the function context structure.
92 // builtin_setjmp uses a five word jbuf
Jay Foad5fdd6c82011-07-12 14:06:48 +000093 Type *VoidPtrTy = Type::getInt8PtrTy(M.getContext());
94 Type *Int32Ty = Type::getInt32Ty(M.getContext());
Jim Grosbach8b818d72009-08-17 16:41:22 +000095 FunctionContextTy =
Chris Lattnerb2318662011-06-18 22:48:56 +000096 StructType::get(VoidPtrTy, // __prev
Jim Grosbach8b818d72009-08-17 16:41:22 +000097 Int32Ty, // call_site
98 ArrayType::get(Int32Ty, 4), // __data
99 VoidPtrTy, // __personality
100 VoidPtrTy, // __lsda
101 ArrayType::get(VoidPtrTy, 5), // __jbuf
102 NULL);
103 RegisterFn = M.getOrInsertFunction("_Unwind_SjLj_Register",
104 Type::getVoidTy(M.getContext()),
105 PointerType::getUnqual(FunctionContextTy),
106 (Type *)0);
107 UnregisterFn =
108 M.getOrInsertFunction("_Unwind_SjLj_Unregister",
109 Type::getVoidTy(M.getContext()),
110 PointerType::getUnqual(FunctionContextTy),
111 (Type *)0);
Jim Grosbach8b818d72009-08-17 16:41:22 +0000112 FrameAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::frameaddress);
Jim Grosbach0798edd2010-05-27 23:49:24 +0000113 StackAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::stacksave);
Bob Wilson20c918d2011-11-16 07:12:00 +0000114 StackRestoreFn = Intrinsic::getDeclaration(&M, Intrinsic::stackrestore);
Jim Grosbach8b818d72009-08-17 16:41:22 +0000115 BuiltinSetjmpFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_setjmp);
116 LSDAAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_lsda);
Jim Grosbachca752c92010-01-28 01:45:32 +0000117 CallSiteFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_callsite);
Bill Wendlingcc8cf972011-09-28 21:56:53 +0000118 FuncCtxFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_functioncontext);
Jim Grosbacha235d132009-08-23 18:13:48 +0000119 PersonalityFn = 0;
Jim Grosbach8b818d72009-08-17 16:41:22 +0000120
121 return true;
122}
123
Jim Grosbachb58a59b2010-03-04 22:07:46 +0000124/// insertCallSiteStore - Insert a store of the call-site value to the
125/// function context
Bill Wendlingeabae1d2012-03-13 20:04:21 +0000126void SjLjEHPrepare::insertCallSiteStore(Instruction *I, int Number) {
Bill Wendling4cc46662012-01-27 02:02:24 +0000127 IRBuilder<> Builder(I);
128
129 // Get a reference to the call_site field.
130 Type *Int32Ty = Type::getInt32Ty(I->getContext());
131 Value *Zero = ConstantInt::get(Int32Ty, 0);
132 Value *One = ConstantInt::get(Int32Ty, 1);
133 Value *Idxs[2] = { Zero, One };
134 Value *CallSite = Builder.CreateGEP(FuncCtx, Idxs, "call_site");
135
136 // Insert a store of the call-site number
Jim Grosbachb58a59b2010-03-04 22:07:46 +0000137 ConstantInt *CallSiteNoC = ConstantInt::get(Type::getInt32Ty(I->getContext()),
138 Number);
Bill Wendling4cc46662012-01-27 02:02:24 +0000139 Builder.CreateStore(CallSiteNoC, CallSite, true/*volatile*/);
Jim Grosbachb58a59b2010-03-04 22:07:46 +0000140}
141
Chad Rosierbace5da2012-03-16 01:04:00 +0000142/// MarkBlocksLiveIn - Insert BB and all of its predescessors into LiveBBs until
Jim Grosbach8b818d72009-08-17 16:41:22 +0000143/// we reach blocks we've already seen.
Chad Rosierbace5da2012-03-16 01:04:00 +0000144static void MarkBlocksLiveIn(BasicBlock *BB,
145 SmallPtrSet<BasicBlock*, 64> &LiveBBs) {
146 if (!LiveBBs.insert(BB)) return; // already been here.
Jim Grosbach8b818d72009-08-17 16:41:22 +0000147
Chad Rosierbace5da2012-03-16 01:04:00 +0000148 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
149 MarkBlocksLiveIn(*PI, LiveBBs);
Jim Grosbach8b818d72009-08-17 16:41:22 +0000150}
151
Bill Wendling69fdcd72011-12-14 22:45:33 +0000152/// substituteLPadValues - Substitute the values returned by the landingpad
153/// instruction with those returned by the personality function.
Bill Wendlingeabae1d2012-03-13 20:04:21 +0000154void SjLjEHPrepare::substituteLPadValues(LandingPadInst *LPI, Value *ExnVal,
155 Value *SelVal) {
Bill Wendling69fdcd72011-12-14 22:45:33 +0000156 SmallVector<Value*, 8> UseWorkList(LPI->use_begin(), LPI->use_end());
157 while (!UseWorkList.empty()) {
158 Value *Val = UseWorkList.pop_back_val();
159 ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(Val);
160 if (!EVI) continue;
161 if (EVI->getNumIndices() != 1) continue;
162 if (*EVI->idx_begin() == 0)
163 EVI->replaceAllUsesWith(ExnVal);
164 else if (*EVI->idx_begin() == 1)
165 EVI->replaceAllUsesWith(SelVal);
166 if (EVI->getNumUses() == 0)
167 EVI->eraseFromParent();
168 }
169
170 if (LPI->getNumUses() == 0) return;
171
172 // There are still some uses of LPI. Construct an aggregate with the exception
173 // values and replace the LPI with that aggregate.
174 Type *LPadType = LPI->getType();
175 Value *LPadVal = UndefValue::get(LPadType);
176 IRBuilder<>
177 Builder(llvm::next(BasicBlock::iterator(cast<Instruction>(SelVal))));
178 LPadVal = Builder.CreateInsertValue(LPadVal, ExnVal, 0, "lpad.val");
179 LPadVal = Builder.CreateInsertValue(LPadVal, SelVal, 1, "lpad.val");
180
181 LPI->replaceAllUsesWith(LPadVal);
182}
183
Bill Wendling2b6bd7b2011-09-28 03:14:05 +0000184/// setupFunctionContext - Allocate the function context on the stack and fill
185/// it with all of the data that we know at this point.
Bill Wendlingeabae1d2012-03-13 20:04:21 +0000186Value *SjLjEHPrepare::
Bill Wendlingcc8cf972011-09-28 21:56:53 +0000187setupFunctionContext(Function &F, ArrayRef<LandingPadInst*> LPads) {
Bill Wendling2b6bd7b2011-09-28 03:14:05 +0000188 BasicBlock *EntryBB = F.begin();
189
190 // Create an alloca for the incoming jump buffer ptr and the new jump buffer
191 // that needs to be restored on all exits from the function. This is an alloca
192 // because the value needs to be added to the global context list.
Bill Wendlingea442812013-06-19 20:51:24 +0000193 const TargetLowering *TLI = TM->getTargetLowering();
Bill Wendling2b6bd7b2011-09-28 03:14:05 +0000194 unsigned Align =
Micah Villmow3574eca2012-10-08 16:38:25 +0000195 TLI->getDataLayout()->getPrefTypeAlignment(FunctionContextTy);
Bill Wendling4cc46662012-01-27 02:02:24 +0000196 FuncCtx =
Bill Wendling2b6bd7b2011-09-28 03:14:05 +0000197 new AllocaInst(FunctionContextTy, 0, Align, "fn_context", EntryBB->begin());
198
199 // Fill in the function context structure.
Bill Wendling2b6bd7b2011-09-28 03:14:05 +0000200 for (unsigned I = 0, E = LPads.size(); I != E; ++I) {
201 LandingPadInst *LPI = LPads[I];
202 IRBuilder<> Builder(LPI->getParent()->getFirstInsertionPt());
203
Bill Wendling4cc46662012-01-27 02:02:24 +0000204 // Reference the __data field.
Benjamin Kramerf68b87f2012-09-03 12:27:43 +0000205 Value *FCData = Builder.CreateConstGEP2_32(FuncCtx, 0, 2, "__data");
Bill Wendling4cc46662012-01-27 02:02:24 +0000206
207 // The exception values come back in context->__data[0].
Benjamin Kramerf68b87f2012-09-03 12:27:43 +0000208 Value *ExceptionAddr = Builder.CreateConstGEP2_32(FCData, 0, 0,
209 "exception_gep");
Bill Wendling2b6bd7b2011-09-28 03:14:05 +0000210 Value *ExnVal = Builder.CreateLoad(ExceptionAddr, true, "exn_val");
Benjamin Kramerf68b87f2012-09-03 12:27:43 +0000211 ExnVal = Builder.CreateIntToPtr(ExnVal, Builder.getInt8PtrTy());
Bill Wendling4cc46662012-01-27 02:02:24 +0000212
Benjamin Kramerf68b87f2012-09-03 12:27:43 +0000213 Value *SelectorAddr = Builder.CreateConstGEP2_32(FCData, 0, 1,
214 "exn_selector_gep");
Bill Wendling2b6bd7b2011-09-28 03:14:05 +0000215 Value *SelVal = Builder.CreateLoad(SelectorAddr, true, "exn_selector_val");
216
Bill Wendling69fdcd72011-12-14 22:45:33 +0000217 substituteLPadValues(LPI, ExnVal, SelVal);
Bill Wendling2b6bd7b2011-09-28 03:14:05 +0000218 }
219
220 // Personality function
Benjamin Kramerf68b87f2012-09-03 12:27:43 +0000221 IRBuilder<> Builder(EntryBB->getTerminator());
Bill Wendling2b6bd7b2011-09-28 03:14:05 +0000222 if (!PersonalityFn)
223 PersonalityFn = LPads[0]->getPersonalityFn();
Benjamin Kramerf68b87f2012-09-03 12:27:43 +0000224 Value *PersonalityFieldPtr = Builder.CreateConstGEP2_32(FuncCtx, 0, 3,
225 "pers_fn_gep");
Kai Nackee4642bc2013-05-14 16:30:51 +0000226 Builder.CreateStore(Builder.CreateBitCast(PersonalityFn,
227 Builder.getInt8PtrTy()),
228 PersonalityFieldPtr, /*isVolatile=*/true);
Bill Wendling2b6bd7b2011-09-28 03:14:05 +0000229
230 // LSDA address
Benjamin Kramerf68b87f2012-09-03 12:27:43 +0000231 Value *LSDA = Builder.CreateCall(LSDAAddrFn, "lsda_addr");
232 Value *LSDAFieldPtr = Builder.CreateConstGEP2_32(FuncCtx, 0, 4, "lsda_gep");
233 Builder.CreateStore(LSDA, LSDAFieldPtr, /*isVolatile=*/true);
Bill Wendling2b6bd7b2011-09-28 03:14:05 +0000234
Bill Wendling631d1172011-10-03 21:15:28 +0000235 return FuncCtx;
Bill Wendlingcc8cf972011-09-28 21:56:53 +0000236}
237
Bill Wendlingd5d17002011-10-08 00:56:47 +0000238/// lowerIncomingArguments - To avoid having to handle incoming arguments
239/// specially, we lower each arg to a copy instruction in the entry block. This
240/// ensures that the argument value itself cannot be live out of the entry
241/// block.
Bill Wendlingeabae1d2012-03-13 20:04:21 +0000242void SjLjEHPrepare::lowerIncomingArguments(Function &F) {
Bill Wendlingd5d17002011-10-08 00:56:47 +0000243 BasicBlock::iterator AfterAllocaInsPt = F.begin()->begin();
244 while (isa<AllocaInst>(AfterAllocaInsPt) &&
245 isa<ConstantInt>(cast<AllocaInst>(AfterAllocaInsPt)->getArraySize()))
246 ++AfterAllocaInsPt;
247
248 for (Function::arg_iterator
249 AI = F.arg_begin(), AE = F.arg_end(); AI != AE; ++AI) {
250 Type *Ty = AI->getType();
251
252 // Aggregate types can't be cast, but are legal argument types, so we have
253 // to handle them differently. We use an extract/insert pair as a
254 // lightweight method to achieve the same goal.
255 if (isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<VectorType>(Ty)) {
256 Instruction *EI = ExtractValueInst::Create(AI, 0, "", AfterAllocaInsPt);
257 Instruction *NI = InsertValueInst::Create(AI, EI, 0);
258 NI->insertAfter(EI);
259 AI->replaceAllUsesWith(NI);
260
261 // Set the operand of the instructions back to the AllocaInst.
262 EI->setOperand(0, AI);
263 NI->setOperand(0, AI);
264 } else {
265 // This is always a no-op cast because we're casting AI to AI->getType()
266 // so src and destination types are identical. BitCast is the only
267 // possibility.
268 CastInst *NC =
269 new BitCastInst(AI, AI->getType(), AI->getName() + ".tmp",
270 AfterAllocaInsPt);
271 AI->replaceAllUsesWith(NC);
272
273 // Set the operand of the cast instruction back to the AllocaInst.
274 // Normally it's forbidden to replace a CastInst's operand because it
275 // could cause the opcode to reflect an illegal conversion. However, we're
276 // replacing it here with the same value it was constructed with. We do
277 // this because the above replaceAllUsesWith() clobbered the operand, but
278 // we want this one to remain.
279 NC->setOperand(0, AI);
280 }
281 }
282}
283
284/// lowerAcrossUnwindEdges - Find all variables which are alive across an unwind
285/// edge and spill them.
Bill Wendlingeabae1d2012-03-13 20:04:21 +0000286void SjLjEHPrepare::lowerAcrossUnwindEdges(Function &F,
287 ArrayRef<InvokeInst*> Invokes) {
Bill Wendlingd5d17002011-10-08 00:56:47 +0000288 // Finally, scan the code looking for instructions with bad live ranges.
289 for (Function::iterator
290 BB = F.begin(), BBE = F.end(); BB != BBE; ++BB) {
291 for (BasicBlock::iterator
292 II = BB->begin(), IIE = BB->end(); II != IIE; ++II) {
293 // Ignore obvious cases we don't have to handle. In particular, most
294 // instructions either have no uses or only have a single use inside the
295 // current block. Ignore them quickly.
296 Instruction *Inst = II;
297 if (Inst->use_empty()) continue;
298 if (Inst->hasOneUse() &&
299 cast<Instruction>(Inst->use_back())->getParent() == BB &&
300 !isa<PHINode>(Inst->use_back())) continue;
301
302 // If this is an alloca in the entry block, it's not a real register
303 // value.
304 if (AllocaInst *AI = dyn_cast<AllocaInst>(Inst))
305 if (isa<ConstantInt>(AI->getArraySize()) && BB == F.begin())
306 continue;
307
308 // Avoid iterator invalidation by copying users to a temporary vector.
309 SmallVector<Instruction*, 16> Users;
310 for (Value::use_iterator
311 UI = Inst->use_begin(), E = Inst->use_end(); UI != E; ++UI) {
312 Instruction *User = cast<Instruction>(*UI);
313 if (User->getParent() != BB || isa<PHINode>(User))
314 Users.push_back(User);
315 }
316
317 // Find all of the blocks that this value is live in.
Chad Rosierbace5da2012-03-16 01:04:00 +0000318 SmallPtrSet<BasicBlock*, 64> LiveBBs;
319 LiveBBs.insert(Inst->getParent());
Bill Wendlingd5d17002011-10-08 00:56:47 +0000320 while (!Users.empty()) {
Chad Rosierbace5da2012-03-16 01:04:00 +0000321 Instruction *U = Users.back();
322 Users.pop_back();
Bill Wendlingd5d17002011-10-08 00:56:47 +0000323
Chad Rosierbace5da2012-03-16 01:04:00 +0000324 if (!isa<PHINode>(U)) {
325 MarkBlocksLiveIn(U->getParent(), LiveBBs);
326 } else {
Bill Wendlingd5d17002011-10-08 00:56:47 +0000327 // Uses for a PHI node occur in their predecessor block.
Chad Rosierbace5da2012-03-16 01:04:00 +0000328 PHINode *PN = cast<PHINode>(U);
Bill Wendlingd5d17002011-10-08 00:56:47 +0000329 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
330 if (PN->getIncomingValue(i) == Inst)
Chad Rosierbace5da2012-03-16 01:04:00 +0000331 MarkBlocksLiveIn(PN->getIncomingBlock(i), LiveBBs);
Bill Wendlingd5d17002011-10-08 00:56:47 +0000332 }
333 }
334
Chad Rosierbace5da2012-03-16 01:04:00 +0000335 // Now that we know all of the blocks that this thing is live in, see if
336 // it includes any of the unwind locations.
337 bool NeedsSpill = false;
338 for (unsigned i = 0, e = Invokes.size(); i != e; ++i) {
339 BasicBlock *UnwindBlock = Invokes[i]->getUnwindDest();
340 if (UnwindBlock != BB && LiveBBs.count(UnwindBlock)) {
341 DEBUG(dbgs() << "SJLJ Spill: " << *Inst << " around "
342 << UnwindBlock->getName() << "\n");
343 NeedsSpill = true;
344 break;
Bill Wendling30442f92012-03-14 07:28:01 +0000345 }
Bill Wendling9eb5f172012-03-12 20:19:41 +0000346 }
Bill Wendling0ad56122011-10-21 22:08:56 +0000347
Chad Rosierbace5da2012-03-16 01:04:00 +0000348 // If we decided we need a spill, do it.
349 // FIXME: Spilling this way is overkill, as it forces all uses of
350 // the value to be reloaded from the stack slot, even those that aren't
351 // in the unwind blocks. We should be more selective.
352 if (NeedsSpill) {
353 DemoteRegToStack(*Inst, true);
354 ++NumSpilled;
355 }
Bill Wendling30442f92012-03-14 07:28:01 +0000356 }
357 }
358
Bill Wendling0ad56122011-10-21 22:08:56 +0000359 // Go through the landing pads and remove any PHIs there.
360 for (unsigned i = 0, e = Invokes.size(); i != e; ++i) {
361 BasicBlock *UnwindBlock = Invokes[i]->getUnwindDest();
362 LandingPadInst *LPI = UnwindBlock->getLandingPadInst();
363
364 // Place PHIs into a set to avoid invalidating the iterator.
365 SmallPtrSet<PHINode*, 8> PHIsToDemote;
366 for (BasicBlock::iterator
367 PN = UnwindBlock->begin(); isa<PHINode>(PN); ++PN)
368 PHIsToDemote.insert(cast<PHINode>(PN));
369 if (PHIsToDemote.empty()) continue;
370
371 // Demote the PHIs to the stack.
372 for (SmallPtrSet<PHINode*, 8>::iterator
373 I = PHIsToDemote.begin(), E = PHIsToDemote.end(); I != E; ++I)
374 DemotePHIToStack(*I);
375
376 // Move the landingpad instruction back to the top of the landing pad block.
377 LPI->moveBefore(UnwindBlock->begin());
378 }
Bill Wendlingd5d17002011-10-08 00:56:47 +0000379}
380
Bill Wendlingcc8cf972011-09-28 21:56:53 +0000381/// setupEntryBlockAndCallSites - Setup the entry block by creating and filling
382/// the function context and marking the call sites with the appropriate
383/// values. These values are used by the DWARF EH emitter.
Bill Wendlingeabae1d2012-03-13 20:04:21 +0000384bool SjLjEHPrepare::setupEntryBlockAndCallSites(Function &F) {
Bill Wendlinge36b47e2013-03-08 02:21:08 +0000385 SmallVector<ReturnInst*, 16> Returns;
386 SmallVector<InvokeInst*, 16> Invokes;
Bob Wilsonf1b41dd2011-11-16 07:57:21 +0000387 SmallSetVector<LandingPadInst*, 16> LPads;
Bill Wendlingcc8cf972011-09-28 21:56:53 +0000388
389 // Look through the terminators of the basic blocks to find invokes.
390 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
391 if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
Bill Wendlinge36b47e2013-03-08 02:21:08 +0000392 if (Function *Callee = II->getCalledFunction())
393 if (Callee->isIntrinsic() &&
394 Callee->getIntrinsicID() == Intrinsic::donothing) {
395 // Remove the NOP invoke.
396 BranchInst::Create(II->getNormalDest(), II);
397 II->eraseFromParent();
398 continue;
399 }
400
Bill Wendlingcc8cf972011-09-28 21:56:53 +0000401 Invokes.push_back(II);
Bob Wilsonf1b41dd2011-11-16 07:57:21 +0000402 LPads.insert(II->getUnwindDest()->getLandingPadInst());
Bill Wendlingcc8cf972011-09-28 21:56:53 +0000403 } else if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
404 Returns.push_back(RI);
405 }
406
407 if (Invokes.empty()) return false;
408
Bill Wendlingd2dae0c2011-10-24 17:12:36 +0000409 NumInvokes += Invokes.size();
410
Bill Wendlingd5d17002011-10-08 00:56:47 +0000411 lowerIncomingArguments(F);
412 lowerAcrossUnwindEdges(F, Invokes);
413
Bob Wilsonf1b41dd2011-11-16 07:57:21 +0000414 Value *FuncCtx =
415 setupFunctionContext(F, makeArrayRef(LPads.begin(), LPads.end()));
Bill Wendlingcc8cf972011-09-28 21:56:53 +0000416 BasicBlock *EntryBB = F.begin();
Benjamin Kramerf68b87f2012-09-03 12:27:43 +0000417 IRBuilder<> Builder(EntryBB->getTerminator());
Bill Wendling631d1172011-10-03 21:15:28 +0000418
419 // Get a reference to the jump buffer.
Benjamin Kramerf68b87f2012-09-03 12:27:43 +0000420 Value *JBufPtr = Builder.CreateConstGEP2_32(FuncCtx, 0, 5, "jbuf_gep");
Bill Wendling2b6bd7b2011-09-28 03:14:05 +0000421
Bill Wendling631d1172011-10-03 21:15:28 +0000422 // Save the frame pointer.
Benjamin Kramerf68b87f2012-09-03 12:27:43 +0000423 Value *FramePtr = Builder.CreateConstGEP2_32(JBufPtr, 0, 0, "jbuf_fp_gep");
Bill Wendling631d1172011-10-03 21:15:28 +0000424
Benjamin Kramerf68b87f2012-09-03 12:27:43 +0000425 Value *Val = Builder.CreateCall(FrameAddrFn, Builder.getInt32(0), "fp");
426 Builder.CreateStore(Val, FramePtr, /*isVolatile=*/true);
Bill Wendling631d1172011-10-03 21:15:28 +0000427
428 // Save the stack pointer.
Benjamin Kramerf68b87f2012-09-03 12:27:43 +0000429 Value *StackPtr = Builder.CreateConstGEP2_32(JBufPtr, 0, 2, "jbuf_sp_gep");
Bill Wendling631d1172011-10-03 21:15:28 +0000430
Benjamin Kramerf68b87f2012-09-03 12:27:43 +0000431 Val = Builder.CreateCall(StackAddrFn, "sp");
432 Builder.CreateStore(Val, StackPtr, /*isVolatile=*/true);
Bill Wendling2b6bd7b2011-09-28 03:14:05 +0000433
434 // Call the setjmp instrinsic. It fills in the rest of the jmpbuf.
Benjamin Kramerf68b87f2012-09-03 12:27:43 +0000435 Value *SetjmpArg = Builder.CreateBitCast(JBufPtr, Builder.getInt8PtrTy());
436 Builder.CreateCall(BuiltinSetjmpFn, SetjmpArg);
Bill Wendling2b6bd7b2011-09-28 03:14:05 +0000437
Bill Wendlingcc8cf972011-09-28 21:56:53 +0000438 // Store a pointer to the function context so that the back-end will know
439 // where to look for it.
Benjamin Kramerf68b87f2012-09-03 12:27:43 +0000440 Value *FuncCtxArg = Builder.CreateBitCast(FuncCtx, Builder.getInt8PtrTy());
441 Builder.CreateCall(FuncCtxFn, FuncCtxArg);
Bill Wendling2b6bd7b2011-09-28 03:14:05 +0000442
443 // At this point, we are all set up, update the invoke instructions to mark
Bill Wendling2130ab02011-10-05 22:04:08 +0000444 // their call_site values.
Bill Wendling2b6bd7b2011-09-28 03:14:05 +0000445 for (unsigned I = 0, E = Invokes.size(); I != E; ++I) {
Bill Wendling4cc46662012-01-27 02:02:24 +0000446 insertCallSiteStore(Invokes[I], I + 1);
Bill Wendling2b6bd7b2011-09-28 03:14:05 +0000447
448 ConstantInt *CallSiteNum =
449 ConstantInt::get(Type::getInt32Ty(F.getContext()), I + 1);
450
451 // Record the call site value for the back end so it stays associated with
452 // the invoke.
453 CallInst::Create(CallSiteFn, CallSiteNum, "", Invokes[I]);
454 }
455
456 // Mark call instructions that aren't nounwind as no-action (call_site ==
457 // -1). Skip the entry block, as prior to then, no function context has been
458 // created for this function and any unexpected exceptions thrown will go
459 // directly to the caller's context, which is what we want anyway, so no need
460 // to do anything here.
Bill Wendlingda7e6a92011-10-04 00:16:40 +0000461 for (Function::iterator BB = F.begin(), E = F.end(); ++BB != E;)
Bill Wendling2b6bd7b2011-09-28 03:14:05 +0000462 for (BasicBlock::iterator I = BB->begin(), end = BB->end(); I != end; ++I)
463 if (CallInst *CI = dyn_cast<CallInst>(I)) {
464 if (!CI->doesNotThrow())
Bill Wendling4cc46662012-01-27 02:02:24 +0000465 insertCallSiteStore(CI, -1);
Bill Wendling2b6bd7b2011-09-28 03:14:05 +0000466 } else if (ResumeInst *RI = dyn_cast<ResumeInst>(I)) {
Bill Wendling4cc46662012-01-27 02:02:24 +0000467 insertCallSiteStore(RI, -1);
Bill Wendling2b6bd7b2011-09-28 03:14:05 +0000468 }
Bill Wendling2b6bd7b2011-09-28 03:14:05 +0000469
Bill Wendlingcc8cf972011-09-28 21:56:53 +0000470 // Register the function context and make sure it's known to not throw
Bill Wendling631d1172011-10-03 21:15:28 +0000471 CallInst *Register = CallInst::Create(RegisterFn, FuncCtx, "",
Bill Wendlingcc8cf972011-09-28 21:56:53 +0000472 EntryBB->getTerminator());
473 Register->setDoesNotThrow();
474
Bob Wilson20c918d2011-11-16 07:12:00 +0000475 // Following any allocas not in the entry block, update the saved SP in the
476 // jmpbuf to the new value.
477 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
478 if (BB == F.begin())
479 continue;
480 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
481 if (CallInst *CI = dyn_cast<CallInst>(I)) {
482 if (CI->getCalledFunction() != StackRestoreFn)
483 continue;
484 } else if (!isa<AllocaInst>(I)) {
485 continue;
486 }
487 Instruction *StackAddr = CallInst::Create(StackAddrFn, "sp");
488 StackAddr->insertAfter(I);
489 Instruction *StoreStackAddr = new StoreInst(StackAddr, StackPtr, true);
490 StoreStackAddr->insertAfter(StackAddr);
491 }
492 }
493
Bill Wendlingcc8cf972011-09-28 21:56:53 +0000494 // Finally, for any returns from this function, if this function contains an
495 // invoke, add a call to unregister the function context.
496 for (unsigned I = 0, E = Returns.size(); I != E; ++I)
Bill Wendling631d1172011-10-03 21:15:28 +0000497 CallInst::Create(UnregisterFn, FuncCtx, "", Returns[I]);
Bill Wendlingcc8cf972011-09-28 21:56:53 +0000498
Bill Wendling2b6bd7b2011-09-28 03:14:05 +0000499 return true;
500}
501
Bill Wendlingeabae1d2012-03-13 20:04:21 +0000502bool SjLjEHPrepare::runOnFunction(Function &F) {
Bill Wendlingd2dae0c2011-10-24 17:12:36 +0000503 bool Res = setupEntryBlockAndCallSites(F);
Jim Grosbach8b818d72009-08-17 16:41:22 +0000504 return Res;
505}