blob: 5d60bc9b751abc76f8c3fbd2a64329c16187b441 [file] [log] [blame]
Jim Grosbach8b818d72009-08-17 16:41:22 +00001//===- SjLjEHPass.cpp - Eliminate Invoke & Unwind instructions -----------===//
2//
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"
16#include "llvm/Transforms/Scalar.h"
17#include "llvm/Constants.h"
18#include "llvm/DerivedTypes.h"
19#include "llvm/Instructions.h"
20#include "llvm/Intrinsics.h"
21#include "llvm/LLVMContext.h"
22#include "llvm/Module.h"
23#include "llvm/Pass.h"
24#include "llvm/CodeGen/Passes.h"
Bill Wendling2b6bd7b2011-09-28 03:14:05 +000025#include "llvm/Target/TargetData.h"
Benjamin Kramerf7888542010-11-06 11:45:59 +000026#include "llvm/Target/TargetLowering.h"
Jim Grosbach8b818d72009-08-17 16:41:22 +000027#include "llvm/Transforms/Utils/BasicBlockUtils.h"
28#include "llvm/Transforms/Utils/Local.h"
Bill Wendling2b6bd7b2011-09-28 03:14:05 +000029#include "llvm/Support/CommandLine.h"
Bill Wendlingd36b3e32011-08-22 18:44:49 +000030#include "llvm/Support/Debug.h"
Bill Wendling2b6bd7b2011-09-28 03:14:05 +000031#include "llvm/Support/IRBuilder.h"
Bill Wendlingaef508d2011-08-22 23:38:40 +000032#include "llvm/ADT/DenseMap.h"
Bill Wendlingd2dae0c2011-10-24 17:12:36 +000033#include "llvm/ADT/SmallPtrSet.h"
Bill Wendlingd36b3e32011-08-22 18:44:49 +000034#include "llvm/ADT/SmallVector.h"
35#include "llvm/ADT/Statistic.h"
Benjamin Kramerf7888542010-11-06 11:45:59 +000036#include <set>
Jim Grosbach8b818d72009-08-17 16:41:22 +000037using namespace llvm;
38
39STATISTIC(NumInvokes, "Number of invokes replaced");
Jim Grosbach8b818d72009-08-17 16:41:22 +000040STATISTIC(NumSpilled, "Number of registers live across unwind edges");
41
42namespace {
Nick Lewycky6726b6d2009-10-25 06:33:48 +000043 class SjLjEHPass : public FunctionPass {
Jim Grosbach8b818d72009-08-17 16:41:22 +000044 const TargetLowering *TLI;
Chris Lattnerdb125cf2011-07-18 04:54:35 +000045 Type *FunctionContextTy;
Jim Grosbach8b818d72009-08-17 16:41:22 +000046 Constant *RegisterFn;
47 Constant *UnregisterFn;
Jim Grosbach8b818d72009-08-17 16:41:22 +000048 Constant *BuiltinSetjmpFn;
49 Constant *FrameAddrFn;
Jim Grosbach0798edd2010-05-27 23:49:24 +000050 Constant *StackAddrFn;
Bob Wilson20c918d2011-11-16 07:12:00 +000051 Constant *StackRestoreFn;
Jim Grosbach8b818d72009-08-17 16:41:22 +000052 Constant *LSDAAddrFn;
53 Value *PersonalityFn;
Jim Grosbachca752c92010-01-28 01:45:32 +000054 Constant *CallSiteFn;
Bill Wendlingcc8cf972011-09-28 21:56:53 +000055 Constant *FuncCtxFn;
Jim Grosbach8b818d72009-08-17 16:41:22 +000056 Value *CallSite;
57 public:
58 static char ID; // Pass identification, replacement for typeid
59 explicit SjLjEHPass(const TargetLowering *tli = NULL)
Owen Anderson90c579d2010-08-06 18:33:48 +000060 : FunctionPass(ID), TLI(tli) { }
Jim Grosbach8b818d72009-08-17 16:41:22 +000061 bool doInitialization(Module &M);
62 bool runOnFunction(Function &F);
63
Bill Wendlingd36b3e32011-08-22 18:44:49 +000064 virtual void getAnalysisUsage(AnalysisUsage &AU) const {}
Jim Grosbach8b818d72009-08-17 16:41:22 +000065 const char *getPassName() const {
66 return "SJLJ Exception Handling preparation";
67 }
68
69 private:
Bill Wendling2b6bd7b2011-09-28 03:14:05 +000070 bool setupEntryBlockAndCallSites(Function &F);
Bill Wendling631d1172011-10-03 21:15:28 +000071 Value *setupFunctionContext(Function &F, ArrayRef<LandingPadInst*> LPads);
Bill Wendlingd5d17002011-10-08 00:56:47 +000072 void lowerIncomingArguments(Function &F);
73 void lowerAcrossUnwindEdges(Function &F, ArrayRef<InvokeInst*> Invokes);
Jim Grosbachb58a59b2010-03-04 22:07:46 +000074 void insertCallSiteStore(Instruction *I, int Number, Value *CallSite);
Jim Grosbach8b818d72009-08-17 16:41:22 +000075 };
76} // end anonymous namespace
77
78char SjLjEHPass::ID = 0;
79
80// Public Interface To the SjLjEHPass pass.
81FunctionPass *llvm::createSjLjEHPass(const TargetLowering *TLI) {
82 return new SjLjEHPass(TLI);
83}
Jim Grosbacha235d132009-08-23 18:13:48 +000084// doInitialization - Set up decalarations and types needed to process
85// exceptions.
Jim Grosbach8b818d72009-08-17 16:41:22 +000086bool SjLjEHPass::doInitialization(Module &M) {
87 // Build the function context structure.
88 // builtin_setjmp uses a five word jbuf
Jay Foad5fdd6c82011-07-12 14:06:48 +000089 Type *VoidPtrTy = Type::getInt8PtrTy(M.getContext());
90 Type *Int32Ty = Type::getInt32Ty(M.getContext());
Jim Grosbach8b818d72009-08-17 16:41:22 +000091 FunctionContextTy =
Chris Lattnerb2318662011-06-18 22:48:56 +000092 StructType::get(VoidPtrTy, // __prev
Jim Grosbach8b818d72009-08-17 16:41:22 +000093 Int32Ty, // call_site
94 ArrayType::get(Int32Ty, 4), // __data
95 VoidPtrTy, // __personality
96 VoidPtrTy, // __lsda
97 ArrayType::get(VoidPtrTy, 5), // __jbuf
98 NULL);
99 RegisterFn = M.getOrInsertFunction("_Unwind_SjLj_Register",
100 Type::getVoidTy(M.getContext()),
101 PointerType::getUnqual(FunctionContextTy),
102 (Type *)0);
103 UnregisterFn =
104 M.getOrInsertFunction("_Unwind_SjLj_Unregister",
105 Type::getVoidTy(M.getContext()),
106 PointerType::getUnqual(FunctionContextTy),
107 (Type *)0);
Jim Grosbach8b818d72009-08-17 16:41:22 +0000108 FrameAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::frameaddress);
Jim Grosbach0798edd2010-05-27 23:49:24 +0000109 StackAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::stacksave);
Bob Wilson20c918d2011-11-16 07:12:00 +0000110 StackRestoreFn = Intrinsic::getDeclaration(&M, Intrinsic::stackrestore);
Jim Grosbach8b818d72009-08-17 16:41:22 +0000111 BuiltinSetjmpFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_setjmp);
112 LSDAAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_lsda);
Jim Grosbachca752c92010-01-28 01:45:32 +0000113 CallSiteFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_callsite);
Bill Wendlingcc8cf972011-09-28 21:56:53 +0000114 FuncCtxFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_functioncontext);
Jim Grosbacha235d132009-08-23 18:13:48 +0000115 PersonalityFn = 0;
Jim Grosbach8b818d72009-08-17 16:41:22 +0000116
117 return true;
118}
119
Jim Grosbachb58a59b2010-03-04 22:07:46 +0000120/// insertCallSiteStore - Insert a store of the call-site value to the
121/// function context
122void SjLjEHPass::insertCallSiteStore(Instruction *I, int Number,
123 Value *CallSite) {
124 ConstantInt *CallSiteNoC = ConstantInt::get(Type::getInt32Ty(I->getContext()),
125 Number);
126 // Insert a store of the call-site number
127 new StoreInst(CallSiteNoC, CallSite, true, I); // volatile
128}
129
Jim Grosbach8b818d72009-08-17 16:41:22 +0000130/// MarkBlocksLiveIn - Insert BB and all of its predescessors into LiveBBs until
131/// we reach blocks we've already seen.
Bill Wendlingd2dae0c2011-10-24 17:12:36 +0000132static void MarkBlocksLiveIn(BasicBlock *BB,
133 SmallPtrSet<BasicBlock*, 64> &LiveBBs) {
134 if (!LiveBBs.insert(BB)) return; // already been here.
Jim Grosbach8b818d72009-08-17 16:41:22 +0000135
136 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
137 MarkBlocksLiveIn(*PI, LiveBBs);
138}
139
Bill Wendling2b6bd7b2011-09-28 03:14:05 +0000140/// setupFunctionContext - Allocate the function context on the stack and fill
141/// it with all of the data that we know at this point.
Bill Wendling631d1172011-10-03 21:15:28 +0000142Value *SjLjEHPass::
Bill Wendlingcc8cf972011-09-28 21:56:53 +0000143setupFunctionContext(Function &F, ArrayRef<LandingPadInst*> LPads) {
Bill Wendling2b6bd7b2011-09-28 03:14:05 +0000144 BasicBlock *EntryBB = F.begin();
145
146 // Create an alloca for the incoming jump buffer ptr and the new jump buffer
147 // that needs to be restored on all exits from the function. This is an alloca
148 // because the value needs to be added to the global context list.
149 unsigned Align =
150 TLI->getTargetData()->getPrefTypeAlignment(FunctionContextTy);
151 AllocaInst *FuncCtx =
152 new AllocaInst(FunctionContextTy, 0, Align, "fn_context", EntryBB->begin());
153
154 // Fill in the function context structure.
155 Value *Idxs[2];
156 Type *Int32Ty = Type::getInt32Ty(F.getContext());
157 Value *Zero = ConstantInt::get(Int32Ty, 0);
158 Value *One = ConstantInt::get(Int32Ty, 1);
159
160 // Keep around a reference to the call_site field.
161 Idxs[0] = Zero;
162 Idxs[1] = One;
163 CallSite = GetElementPtrInst::Create(FuncCtx, Idxs, "call_site",
164 EntryBB->getTerminator());
165
166 // Reference the __data field.
167 Idxs[1] = ConstantInt::get(Int32Ty, 2);
168 Value *FCData = GetElementPtrInst::Create(FuncCtx, Idxs, "__data",
169 EntryBB->getTerminator());
170
171 // The exception value comes back in context->__data[0].
172 Idxs[1] = Zero;
173 Value *ExceptionAddr = GetElementPtrInst::Create(FCData, Idxs,
174 "exception_gep",
175 EntryBB->getTerminator());
176
177 // The exception selector comes back in context->__data[1].
178 Idxs[1] = One;
179 Value *SelectorAddr = GetElementPtrInst::Create(FCData, Idxs,
180 "exn_selector_gep",
181 EntryBB->getTerminator());
182
183 for (unsigned I = 0, E = LPads.size(); I != E; ++I) {
184 LandingPadInst *LPI = LPads[I];
185 IRBuilder<> Builder(LPI->getParent()->getFirstInsertionPt());
186
187 Value *ExnVal = Builder.CreateLoad(ExceptionAddr, true, "exn_val");
188 ExnVal = Builder.CreateIntToPtr(ExnVal, Type::getInt8PtrTy(F.getContext()));
189 Value *SelVal = Builder.CreateLoad(SelectorAddr, true, "exn_selector_val");
190
191 Type *LPadType = LPI->getType();
192 Value *LPadVal = UndefValue::get(LPadType);
193 LPadVal = Builder.CreateInsertValue(LPadVal, ExnVal, 0, "lpad.val");
194 LPadVal = Builder.CreateInsertValue(LPadVal, SelVal, 1, "lpad.val");
195
196 LPI->replaceAllUsesWith(LPadVal);
197 }
198
199 // Personality function
200 Idxs[1] = ConstantInt::get(Int32Ty, 3);
201 if (!PersonalityFn)
202 PersonalityFn = LPads[0]->getPersonalityFn();
203 Value *PersonalityFieldPtr =
204 GetElementPtrInst::Create(FuncCtx, Idxs, "pers_fn_gep",
205 EntryBB->getTerminator());
206 new StoreInst(PersonalityFn, PersonalityFieldPtr, true,
207 EntryBB->getTerminator());
208
209 // LSDA address
210 Idxs[1] = ConstantInt::get(Int32Ty, 4);
Bill Wendlingda7e6a92011-10-04 00:16:40 +0000211 Value *LSDAFieldPtr = GetElementPtrInst::Create(FuncCtx, Idxs, "lsda_gep",
212 EntryBB->getTerminator());
Bill Wendling2b6bd7b2011-09-28 03:14:05 +0000213 Value *LSDA = CallInst::Create(LSDAAddrFn, "lsda_addr",
214 EntryBB->getTerminator());
215 new StoreInst(LSDA, LSDAFieldPtr, true, EntryBB->getTerminator());
216
Bill Wendling631d1172011-10-03 21:15:28 +0000217 return FuncCtx;
Bill Wendlingcc8cf972011-09-28 21:56:53 +0000218}
219
Bill Wendlingd5d17002011-10-08 00:56:47 +0000220/// lowerIncomingArguments - To avoid having to handle incoming arguments
221/// specially, we lower each arg to a copy instruction in the entry block. This
222/// ensures that the argument value itself cannot be live out of the entry
223/// block.
224void SjLjEHPass::lowerIncomingArguments(Function &F) {
225 BasicBlock::iterator AfterAllocaInsPt = F.begin()->begin();
226 while (isa<AllocaInst>(AfterAllocaInsPt) &&
227 isa<ConstantInt>(cast<AllocaInst>(AfterAllocaInsPt)->getArraySize()))
228 ++AfterAllocaInsPt;
229
230 for (Function::arg_iterator
231 AI = F.arg_begin(), AE = F.arg_end(); AI != AE; ++AI) {
232 Type *Ty = AI->getType();
233
234 // Aggregate types can't be cast, but are legal argument types, so we have
235 // to handle them differently. We use an extract/insert pair as a
236 // lightweight method to achieve the same goal.
237 if (isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<VectorType>(Ty)) {
238 Instruction *EI = ExtractValueInst::Create(AI, 0, "", AfterAllocaInsPt);
239 Instruction *NI = InsertValueInst::Create(AI, EI, 0);
240 NI->insertAfter(EI);
241 AI->replaceAllUsesWith(NI);
242
243 // Set the operand of the instructions back to the AllocaInst.
244 EI->setOperand(0, AI);
245 NI->setOperand(0, AI);
246 } else {
247 // This is always a no-op cast because we're casting AI to AI->getType()
248 // so src and destination types are identical. BitCast is the only
249 // possibility.
250 CastInst *NC =
251 new BitCastInst(AI, AI->getType(), AI->getName() + ".tmp",
252 AfterAllocaInsPt);
253 AI->replaceAllUsesWith(NC);
254
255 // Set the operand of the cast instruction back to the AllocaInst.
256 // Normally it's forbidden to replace a CastInst's operand because it
257 // could cause the opcode to reflect an illegal conversion. However, we're
258 // replacing it here with the same value it was constructed with. We do
259 // this because the above replaceAllUsesWith() clobbered the operand, but
260 // we want this one to remain.
261 NC->setOperand(0, AI);
262 }
263 }
264}
265
266/// lowerAcrossUnwindEdges - Find all variables which are alive across an unwind
267/// edge and spill them.
268void SjLjEHPass::lowerAcrossUnwindEdges(Function &F,
269 ArrayRef<InvokeInst*> Invokes) {
270 // Finally, scan the code looking for instructions with bad live ranges.
271 for (Function::iterator
272 BB = F.begin(), BBE = F.end(); BB != BBE; ++BB) {
273 for (BasicBlock::iterator
274 II = BB->begin(), IIE = BB->end(); II != IIE; ++II) {
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()) continue;
280 if (Inst->hasOneUse() &&
281 cast<Instruction>(Inst->use_back())->getParent() == BB &&
282 !isa<PHINode>(Inst->use_back())) continue;
283
284 // If this is an alloca in the entry block, it's not a real register
285 // value.
286 if (AllocaInst *AI = dyn_cast<AllocaInst>(Inst))
287 if (isa<ConstantInt>(AI->getArraySize()) && BB == F.begin())
288 continue;
289
290 // Avoid iterator invalidation by copying users to a temporary vector.
291 SmallVector<Instruction*, 16> Users;
292 for (Value::use_iterator
293 UI = Inst->use_begin(), E = Inst->use_end(); UI != E; ++UI) {
294 Instruction *User = cast<Instruction>(*UI);
295 if (User->getParent() != BB || isa<PHINode>(User))
296 Users.push_back(User);
297 }
298
299 // Find all of the blocks that this value is live in.
Bill Wendlingd2dae0c2011-10-24 17:12:36 +0000300 SmallPtrSet<BasicBlock*, 64> LiveBBs;
Bill Wendlingd5d17002011-10-08 00:56:47 +0000301 LiveBBs.insert(Inst->getParent());
302 while (!Users.empty()) {
303 Instruction *U = Users.back();
304 Users.pop_back();
305
306 if (!isa<PHINode>(U)) {
307 MarkBlocksLiveIn(U->getParent(), LiveBBs);
308 } else {
309 // Uses for a PHI node occur in their predecessor block.
310 PHINode *PN = cast<PHINode>(U);
311 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
312 if (PN->getIncomingValue(i) == Inst)
313 MarkBlocksLiveIn(PN->getIncomingBlock(i), LiveBBs);
314 }
315 }
316
317 // Now that we know all of the blocks that this thing is live in, see if
318 // it includes any of the unwind locations.
319 bool NeedsSpill = false;
320 for (unsigned i = 0, e = Invokes.size(); i != e; ++i) {
321 BasicBlock *UnwindBlock = Invokes[i]->getUnwindDest();
322 if (UnwindBlock != BB && LiveBBs.count(UnwindBlock)) {
323 NeedsSpill = true;
Bill Wendlingd2dae0c2011-10-24 17:12:36 +0000324 break;
Bill Wendlingd5d17002011-10-08 00:56:47 +0000325 }
326 }
327
328 // If we decided we need a spill, do it.
329 // FIXME: Spilling this way is overkill, as it forces all uses of
330 // the value to be reloaded from the stack slot, even those that aren't
331 // in the unwind blocks. We should be more selective.
332 if (NeedsSpill) {
Bill Wendlingd5d17002011-10-08 00:56:47 +0000333 DemoteRegToStack(*Inst, true);
Bill Wendlingd2dae0c2011-10-24 17:12:36 +0000334 ++NumSpilled;
Bill Wendlingd5d17002011-10-08 00:56:47 +0000335 }
336 }
337 }
Bill Wendling0ad56122011-10-21 22:08:56 +0000338
339 // Go through the landing pads and remove any PHIs there.
340 for (unsigned i = 0, e = Invokes.size(); i != e; ++i) {
341 BasicBlock *UnwindBlock = Invokes[i]->getUnwindDest();
342 LandingPadInst *LPI = UnwindBlock->getLandingPadInst();
343
344 // Place PHIs into a set to avoid invalidating the iterator.
345 SmallPtrSet<PHINode*, 8> PHIsToDemote;
346 for (BasicBlock::iterator
347 PN = UnwindBlock->begin(); isa<PHINode>(PN); ++PN)
348 PHIsToDemote.insert(cast<PHINode>(PN));
349 if (PHIsToDemote.empty()) continue;
350
351 // Demote the PHIs to the stack.
352 for (SmallPtrSet<PHINode*, 8>::iterator
353 I = PHIsToDemote.begin(), E = PHIsToDemote.end(); I != E; ++I)
354 DemotePHIToStack(*I);
355
356 // Move the landingpad instruction back to the top of the landing pad block.
357 LPI->moveBefore(UnwindBlock->begin());
358 }
Bill Wendlingd5d17002011-10-08 00:56:47 +0000359}
360
Bill Wendlingcc8cf972011-09-28 21:56:53 +0000361/// setupEntryBlockAndCallSites - Setup the entry block by creating and filling
362/// the function context and marking the call sites with the appropriate
363/// values. These values are used by the DWARF EH emitter.
364bool SjLjEHPass::setupEntryBlockAndCallSites(Function &F) {
365 SmallVector<ReturnInst*, 16> Returns;
366 SmallVector<InvokeInst*, 16> Invokes;
367 SmallVector<LandingPadInst*, 16> LPads;
368
369 // Look through the terminators of the basic blocks to find invokes.
370 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
371 if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
372 Invokes.push_back(II);
373 LPads.push_back(II->getUnwindDest()->getLandingPadInst());
374 } else if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
375 Returns.push_back(RI);
376 }
377
378 if (Invokes.empty()) return false;
379
Bill Wendlingd2dae0c2011-10-24 17:12:36 +0000380 NumInvokes += Invokes.size();
381
Bill Wendlingd5d17002011-10-08 00:56:47 +0000382 lowerIncomingArguments(F);
383 lowerAcrossUnwindEdges(F, Invokes);
384
Bill Wendling631d1172011-10-03 21:15:28 +0000385 Value *FuncCtx = setupFunctionContext(F, LPads);
Bill Wendlingcc8cf972011-09-28 21:56:53 +0000386 BasicBlock *EntryBB = F.begin();
Bill Wendlingcc8cf972011-09-28 21:56:53 +0000387 Type *Int32Ty = Type::getInt32Ty(F.getContext());
Bill Wendling631d1172011-10-03 21:15:28 +0000388
Bill Wendlingcc8cf972011-09-28 21:56:53 +0000389 Value *Idxs[2] = {
Bill Wendling631d1172011-10-03 21:15:28 +0000390 ConstantInt::get(Int32Ty, 0), 0
Bill Wendlingcc8cf972011-09-28 21:56:53 +0000391 };
Bill Wendling631d1172011-10-03 21:15:28 +0000392
393 // Get a reference to the jump buffer.
394 Idxs[1] = ConstantInt::get(Int32Ty, 5);
Bill Wendlingda7e6a92011-10-04 00:16:40 +0000395 Value *JBufPtr = GetElementPtrInst::Create(FuncCtx, Idxs, "jbuf_gep",
396 EntryBB->getTerminator());
Bill Wendling2b6bd7b2011-09-28 03:14:05 +0000397
Bill Wendling631d1172011-10-03 21:15:28 +0000398 // Save the frame pointer.
399 Idxs[1] = ConstantInt::get(Int32Ty, 0);
Bill Wendlingda7e6a92011-10-04 00:16:40 +0000400 Value *FramePtr = GetElementPtrInst::Create(JBufPtr, Idxs, "jbuf_fp_gep",
401 EntryBB->getTerminator());
Bill Wendling631d1172011-10-03 21:15:28 +0000402
403 Value *Val = CallInst::Create(FrameAddrFn,
404 ConstantInt::get(Int32Ty, 0),
405 "fp",
406 EntryBB->getTerminator());
407 new StoreInst(Val, FramePtr, true, EntryBB->getTerminator());
408
409 // Save the stack pointer.
410 Idxs[1] = ConstantInt::get(Int32Ty, 2);
Bill Wendlingda7e6a92011-10-04 00:16:40 +0000411 Value *StackPtr = GetElementPtrInst::Create(JBufPtr, Idxs, "jbuf_sp_gep",
412 EntryBB->getTerminator());
Bill Wendling631d1172011-10-03 21:15:28 +0000413
414 Val = CallInst::Create(StackAddrFn, "sp", EntryBB->getTerminator());
Bill Wendling2b6bd7b2011-09-28 03:14:05 +0000415 new StoreInst(Val, StackPtr, true, EntryBB->getTerminator());
416
417 // Call the setjmp instrinsic. It fills in the rest of the jmpbuf.
Bill Wendlingda7e6a92011-10-04 00:16:40 +0000418 Value *SetjmpArg = CastInst::Create(Instruction::BitCast, JBufPtr,
419 Type::getInt8PtrTy(F.getContext()), "",
420 EntryBB->getTerminator());
Bill Wendlingf8520d52011-10-03 22:42:40 +0000421 CallInst::Create(BuiltinSetjmpFn, SetjmpArg, "", EntryBB->getTerminator());
Bill Wendling2b6bd7b2011-09-28 03:14:05 +0000422
Bill Wendlingcc8cf972011-09-28 21:56:53 +0000423 // Store a pointer to the function context so that the back-end will know
424 // where to look for it.
Bill Wendlingda7e6a92011-10-04 00:16:40 +0000425 Value *FuncCtxArg = CastInst::Create(Instruction::BitCast, FuncCtx,
426 Type::getInt8PtrTy(F.getContext()), "",
427 EntryBB->getTerminator());
Bill Wendlingcc8cf972011-09-28 21:56:53 +0000428 CallInst::Create(FuncCtxFn, FuncCtxArg, "", EntryBB->getTerminator());
Bill Wendling2b6bd7b2011-09-28 03:14:05 +0000429
430 // At this point, we are all set up, update the invoke instructions to mark
Bill Wendling2130ab02011-10-05 22:04:08 +0000431 // their call_site values.
Bill Wendling2b6bd7b2011-09-28 03:14:05 +0000432 for (unsigned I = 0, E = Invokes.size(); I != E; ++I) {
433 insertCallSiteStore(Invokes[I], I + 1, CallSite);
434
435 ConstantInt *CallSiteNum =
436 ConstantInt::get(Type::getInt32Ty(F.getContext()), I + 1);
437
438 // Record the call site value for the back end so it stays associated with
439 // the invoke.
440 CallInst::Create(CallSiteFn, CallSiteNum, "", Invokes[I]);
441 }
442
443 // Mark call instructions that aren't nounwind as no-action (call_site ==
444 // -1). Skip the entry block, as prior to then, no function context has been
445 // created for this function and any unexpected exceptions thrown will go
446 // directly to the caller's context, which is what we want anyway, so no need
447 // to do anything here.
Bill Wendlingda7e6a92011-10-04 00:16:40 +0000448 for (Function::iterator BB = F.begin(), E = F.end(); ++BB != E;)
Bill Wendling2b6bd7b2011-09-28 03:14:05 +0000449 for (BasicBlock::iterator I = BB->begin(), end = BB->end(); I != end; ++I)
450 if (CallInst *CI = dyn_cast<CallInst>(I)) {
451 if (!CI->doesNotThrow())
452 insertCallSiteStore(CI, -1, CallSite);
453 } else if (ResumeInst *RI = dyn_cast<ResumeInst>(I)) {
454 insertCallSiteStore(RI, -1, CallSite);
455 }
Bill Wendling2b6bd7b2011-09-28 03:14:05 +0000456
Bill Wendlingcc8cf972011-09-28 21:56:53 +0000457 // Register the function context and make sure it's known to not throw
Bill Wendling631d1172011-10-03 21:15:28 +0000458 CallInst *Register = CallInst::Create(RegisterFn, FuncCtx, "",
Bill Wendlingcc8cf972011-09-28 21:56:53 +0000459 EntryBB->getTerminator());
460 Register->setDoesNotThrow();
461
Bob Wilson20c918d2011-11-16 07:12:00 +0000462 // Following any allocas not in the entry block, update the saved SP in the
463 // jmpbuf to the new value.
464 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
465 if (BB == F.begin())
466 continue;
467 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
468 if (CallInst *CI = dyn_cast<CallInst>(I)) {
469 if (CI->getCalledFunction() != StackRestoreFn)
470 continue;
471 } else if (!isa<AllocaInst>(I)) {
472 continue;
473 }
474 Instruction *StackAddr = CallInst::Create(StackAddrFn, "sp");
475 StackAddr->insertAfter(I);
476 Instruction *StoreStackAddr = new StoreInst(StackAddr, StackPtr, true);
477 StoreStackAddr->insertAfter(StackAddr);
478 }
479 }
480
Bill Wendlingcc8cf972011-09-28 21:56:53 +0000481 // Finally, for any returns from this function, if this function contains an
482 // invoke, add a call to unregister the function context.
483 for (unsigned I = 0, E = Returns.size(); I != E; ++I)
Bill Wendling631d1172011-10-03 21:15:28 +0000484 CallInst::Create(UnregisterFn, FuncCtx, "", Returns[I]);
Bill Wendlingcc8cf972011-09-28 21:56:53 +0000485
Bill Wendling2b6bd7b2011-09-28 03:14:05 +0000486 return true;
487}
488
Jim Grosbach8b818d72009-08-17 16:41:22 +0000489bool SjLjEHPass::runOnFunction(Function &F) {
Bill Wendlingd2dae0c2011-10-24 17:12:36 +0000490 bool Res = setupEntryBlockAndCallSites(F);
Jim Grosbach8b818d72009-08-17 16:41:22 +0000491 return Res;
492}