blob: 1855984f6664e5718602d00fa9594479dc9f5879 [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"
Benjamin Kramerf7888542010-11-06 11:45:59 +000025#include "llvm/Target/TargetLowering.h"
Jim Grosbach8b818d72009-08-17 16:41:22 +000026#include "llvm/Transforms/Utils/BasicBlockUtils.h"
27#include "llvm/Transforms/Utils/Local.h"
Bill Wendlingd36b3e32011-08-22 18:44:49 +000028#include "llvm/Support/Debug.h"
29#include "llvm/ADT/SmallVector.h"
30#include "llvm/ADT/Statistic.h"
Benjamin Kramerf7888542010-11-06 11:45:59 +000031#include <set>
Jim Grosbach8b818d72009-08-17 16:41:22 +000032using namespace llvm;
33
34STATISTIC(NumInvokes, "Number of invokes replaced");
35STATISTIC(NumUnwinds, "Number of unwinds replaced");
36STATISTIC(NumSpilled, "Number of registers live across unwind edges");
37
38namespace {
Nick Lewycky6726b6d2009-10-25 06:33:48 +000039 class SjLjEHPass : public FunctionPass {
Jim Grosbach8b818d72009-08-17 16:41:22 +000040 const TargetLowering *TLI;
Chris Lattnerdb125cf2011-07-18 04:54:35 +000041 Type *FunctionContextTy;
Jim Grosbach8b818d72009-08-17 16:41:22 +000042 Constant *RegisterFn;
43 Constant *UnregisterFn;
Jim Grosbach8b818d72009-08-17 16:41:22 +000044 Constant *BuiltinSetjmpFn;
45 Constant *FrameAddrFn;
Jim Grosbach0798edd2010-05-27 23:49:24 +000046 Constant *StackAddrFn;
47 Constant *StackRestoreFn;
Jim Grosbach8b818d72009-08-17 16:41:22 +000048 Constant *LSDAAddrFn;
49 Value *PersonalityFn;
Duncan Sandsb01bbdc2009-10-14 16:11:37 +000050 Constant *SelectorFn;
Jim Grosbach8b818d72009-08-17 16:41:22 +000051 Constant *ExceptionFn;
Jim Grosbachca752c92010-01-28 01:45:32 +000052 Constant *CallSiteFn;
Jim Grosbache4ad3872010-10-19 23:27:08 +000053 Constant *DispatchSetupFn;
Jim Grosbach8b818d72009-08-17 16:41:22 +000054 Value *CallSite;
55 public:
56 static char ID; // Pass identification, replacement for typeid
57 explicit SjLjEHPass(const TargetLowering *tli = NULL)
Owen Anderson90c579d2010-08-06 18:33:48 +000058 : FunctionPass(ID), TLI(tli) { }
Jim Grosbach8b818d72009-08-17 16:41:22 +000059 bool doInitialization(Module &M);
60 bool runOnFunction(Function &F);
61
Bill Wendlingd36b3e32011-08-22 18:44:49 +000062 virtual void getAnalysisUsage(AnalysisUsage &AU) const {}
Jim Grosbach8b818d72009-08-17 16:41:22 +000063 const char *getPassName() const {
64 return "SJLJ Exception Handling preparation";
65 }
66
67 private:
Jim Grosbachb58a59b2010-03-04 22:07:46 +000068 void insertCallSiteStore(Instruction *I, int Number, Value *CallSite);
69 void markInvokeCallSite(InvokeInst *II, int InvokeNo, Value *CallSite,
Jim Grosbach0bb61c52009-08-31 01:35:03 +000070 SwitchInst *CatchSwitch);
Jim Grosbach288694f2010-06-15 18:53:34 +000071 void splitLiveRangesAcrossInvokes(SmallVector<InvokeInst*,16> &Invokes);
Jim Grosbach8b818d72009-08-17 16:41:22 +000072 bool insertSjLjEHSupport(Function &F);
73 };
74} // end anonymous namespace
75
76char SjLjEHPass::ID = 0;
77
78// Public Interface To the SjLjEHPass pass.
79FunctionPass *llvm::createSjLjEHPass(const TargetLowering *TLI) {
80 return new SjLjEHPass(TLI);
81}
Jim Grosbacha235d132009-08-23 18:13:48 +000082// doInitialization - Set up decalarations and types needed to process
83// exceptions.
Jim Grosbach8b818d72009-08-17 16:41:22 +000084bool SjLjEHPass::doInitialization(Module &M) {
85 // Build the function context structure.
86 // builtin_setjmp uses a five word jbuf
Jay Foad5fdd6c82011-07-12 14:06:48 +000087 Type *VoidPtrTy = Type::getInt8PtrTy(M.getContext());
88 Type *Int32Ty = Type::getInt32Ty(M.getContext());
Jim Grosbach8b818d72009-08-17 16:41:22 +000089 FunctionContextTy =
Chris Lattnerb2318662011-06-18 22:48:56 +000090 StructType::get(VoidPtrTy, // __prev
Jim Grosbach8b818d72009-08-17 16:41:22 +000091 Int32Ty, // call_site
92 ArrayType::get(Int32Ty, 4), // __data
93 VoidPtrTy, // __personality
94 VoidPtrTy, // __lsda
95 ArrayType::get(VoidPtrTy, 5), // __jbuf
96 NULL);
97 RegisterFn = M.getOrInsertFunction("_Unwind_SjLj_Register",
98 Type::getVoidTy(M.getContext()),
99 PointerType::getUnqual(FunctionContextTy),
100 (Type *)0);
101 UnregisterFn =
102 M.getOrInsertFunction("_Unwind_SjLj_Unregister",
103 Type::getVoidTy(M.getContext()),
104 PointerType::getUnqual(FunctionContextTy),
105 (Type *)0);
Jim Grosbach8b818d72009-08-17 16:41:22 +0000106 FrameAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::frameaddress);
Jim Grosbach0798edd2010-05-27 23:49:24 +0000107 StackAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::stacksave);
108 StackRestoreFn = Intrinsic::getDeclaration(&M, Intrinsic::stackrestore);
Jim Grosbach8b818d72009-08-17 16:41:22 +0000109 BuiltinSetjmpFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_setjmp);
110 LSDAAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_lsda);
Duncan Sandsb01bbdc2009-10-14 16:11:37 +0000111 SelectorFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_selector);
Jim Grosbach8b818d72009-08-17 16:41:22 +0000112 ExceptionFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_exception);
Jim Grosbachca752c92010-01-28 01:45:32 +0000113 CallSiteFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_callsite);
Jim Grosbache4ad3872010-10-19 23:27:08 +0000114 DispatchSetupFn
115 = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_dispatch_setup);
Jim Grosbacha235d132009-08-23 18:13:48 +0000116 PersonalityFn = 0;
Jim Grosbach8b818d72009-08-17 16:41:22 +0000117
118 return true;
119}
120
Jim Grosbachb58a59b2010-03-04 22:07:46 +0000121/// insertCallSiteStore - Insert a store of the call-site value to the
122/// function context
123void SjLjEHPass::insertCallSiteStore(Instruction *I, int Number,
124 Value *CallSite) {
125 ConstantInt *CallSiteNoC = ConstantInt::get(Type::getInt32Ty(I->getContext()),
126 Number);
127 // Insert a store of the call-site number
128 new StoreInst(CallSiteNoC, CallSite, true, I); // volatile
129}
130
Jim Grosbach8b818d72009-08-17 16:41:22 +0000131/// markInvokeCallSite - Insert code to mark the call_site for this invoke
Jim Grosbachb58a59b2010-03-04 22:07:46 +0000132void SjLjEHPass::markInvokeCallSite(InvokeInst *II, int InvokeNo,
Jim Grosbach0bb61c52009-08-31 01:35:03 +0000133 Value *CallSite,
134 SwitchInst *CatchSwitch) {
Jim Grosbach8b818d72009-08-17 16:41:22 +0000135 ConstantInt *CallSiteNoC= ConstantInt::get(Type::getInt32Ty(II->getContext()),
Jim Grosbachb58a59b2010-03-04 22:07:46 +0000136 InvokeNo);
Jim Grosbach0bb61c52009-08-31 01:35:03 +0000137 // The runtime comes back to the dispatcher with the call_site - 1 in
138 // the context. Odd, but there it is.
139 ConstantInt *SwitchValC = ConstantInt::get(Type::getInt32Ty(II->getContext()),
140 InvokeNo - 1);
Jim Grosbach8b818d72009-08-17 16:41:22 +0000141
142 // If the unwind edge has phi nodes, split the edge.
143 if (isa<PHINode>(II->getUnwindDest()->begin())) {
144 SplitCriticalEdge(II, 1, this);
145
146 // If there are any phi nodes left, they must have a single predecessor.
147 while (PHINode *PN = dyn_cast<PHINode>(II->getUnwindDest()->begin())) {
148 PN->replaceAllUsesWith(PN->getIncomingValue(0));
149 PN->eraseFromParent();
150 }
151 }
152
Jim Grosbachb58a59b2010-03-04 22:07:46 +0000153 // Insert the store of the call site value
154 insertCallSiteStore(II, InvokeNo, CallSite);
155
156 // Record the call site value for the back end so it stays associated with
157 // the invoke.
Jim Grosbachca752c92010-01-28 01:45:32 +0000158 CallInst::Create(CallSiteFn, CallSiteNoC, "", II);
Jim Grosbach8b818d72009-08-17 16:41:22 +0000159
Jim Grosbach0bb61c52009-08-31 01:35:03 +0000160 // Add a switch case to our unwind block.
161 CatchSwitch->addCase(SwitchValC, II->getUnwindDest());
Jim Grosbachca752c92010-01-28 01:45:32 +0000162 // We still want this to look like an invoke so we emit the LSDA properly,
163 // so we don't transform the invoke into a call here.
Jim Grosbach8b818d72009-08-17 16:41:22 +0000164}
165
166/// MarkBlocksLiveIn - Insert BB and all of its predescessors into LiveBBs until
167/// we reach blocks we've already seen.
168static void MarkBlocksLiveIn(BasicBlock *BB, std::set<BasicBlock*> &LiveBBs) {
169 if (!LiveBBs.insert(BB).second) return; // already been here.
170
171 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
172 MarkBlocksLiveIn(*PI, LiveBBs);
173}
174
Jim Grosbach606f3d62009-08-17 21:40:03 +0000175/// splitLiveRangesAcrossInvokes - Each value that is live across an unwind edge
176/// we spill into a stack location, guaranteeing that there is nothing live
177/// across the unwind edge. This process also splits all critical edges
178/// coming out of invoke's.
Jim Grosbach2f3257e2010-06-01 18:06:35 +0000179/// FIXME: Move this function to a common utility file (Local.cpp?) so
180/// both SjLj and LowerInvoke can use it.
Jim Grosbach8b818d72009-08-17 16:41:22 +0000181void SjLjEHPass::
Jim Grosbach288694f2010-06-15 18:53:34 +0000182splitLiveRangesAcrossInvokes(SmallVector<InvokeInst*,16> &Invokes) {
Jim Grosbach8b818d72009-08-17 16:41:22 +0000183 // First step, split all critical edges from invoke instructions.
184 for (unsigned i = 0, e = Invokes.size(); i != e; ++i) {
185 InvokeInst *II = Invokes[i];
186 SplitCriticalEdge(II, 0, this);
187 SplitCriticalEdge(II, 1, this);
188 assert(!isa<PHINode>(II->getNormalDest()) &&
189 !isa<PHINode>(II->getUnwindDest()) &&
Bill Wendlingd36b3e32011-08-22 18:44:49 +0000190 "Critical edge splitting left single entry phi nodes?");
Jim Grosbach8b818d72009-08-17 16:41:22 +0000191 }
192
193 Function *F = Invokes.back()->getParent()->getParent();
194
195 // To avoid having to handle incoming arguments specially, we lower each arg
196 // to a copy instruction in the entry block. This ensures that the argument
197 // value itself cannot be live across the entry block.
198 BasicBlock::iterator AfterAllocaInsertPt = F->begin()->begin();
199 while (isa<AllocaInst>(AfterAllocaInsertPt) &&
200 isa<ConstantInt>(cast<AllocaInst>(AfterAllocaInsertPt)->getArraySize()))
201 ++AfterAllocaInsertPt;
202 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
203 AI != E; ++AI) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000204 Type *Ty = AI->getType();
Jim Grosbache70fc8e2010-06-30 22:20:38 +0000205 // Aggregate types can't be cast, but are legal argument types, so we have
Jim Grosbachdc58b252010-06-01 18:04:09 +0000206 // to handle them differently. We use an extract/insert pair as a
207 // lightweight method to achieve the same goal.
Jim Grosbache70fc8e2010-06-30 22:20:38 +0000208 if (isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<VectorType>(Ty)) {
209 Instruction *EI = ExtractValueInst::Create(AI, 0, "",AfterAllocaInsertPt);
Jim Grosbachdc58b252010-06-01 18:04:09 +0000210 Instruction *NI = InsertValueInst::Create(AI, EI, 0);
211 NI->insertAfter(EI);
212 AI->replaceAllUsesWith(NI);
Jim Grosbache70fc8e2010-06-30 22:20:38 +0000213 // Set the operand of the instructions back to the AllocaInst.
Jim Grosbachdc58b252010-06-01 18:04:09 +0000214 EI->setOperand(0, AI);
215 NI->setOperand(0, AI);
216 } else {
217 // This is always a no-op cast because we're casting AI to AI->getType()
218 // so src and destination types are identical. BitCast is the only
219 // possibility.
220 CastInst *NC = new BitCastInst(
221 AI, AI->getType(), AI->getName()+".tmp", AfterAllocaInsertPt);
222 AI->replaceAllUsesWith(NC);
223 // Set the operand of the cast instruction back to the AllocaInst.
224 // Normally it's forbidden to replace a CastInst's operand because it
225 // could cause the opcode to reflect an illegal conversion. However,
226 // we're replacing it here with the same value it was constructed with.
227 // We do this because the above replaceAllUsesWith() clobbered the
228 // operand, but we want this one to remain.
229 NC->setOperand(0, AI);
230 }
Jim Grosbach8b818d72009-08-17 16:41:22 +0000231 }
232
233 // Finally, scan the code looking for instructions with bad live ranges.
234 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
235 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; ++II) {
236 // Ignore obvious cases we don't have to handle. In particular, most
237 // instructions either have no uses or only have a single use inside the
238 // current block. Ignore them quickly.
239 Instruction *Inst = II;
240 if (Inst->use_empty()) continue;
241 if (Inst->hasOneUse() &&
242 cast<Instruction>(Inst->use_back())->getParent() == BB &&
243 !isa<PHINode>(Inst->use_back())) continue;
244
245 // If this is an alloca in the entry block, it's not a real register
246 // value.
247 if (AllocaInst *AI = dyn_cast<AllocaInst>(Inst))
248 if (isa<ConstantInt>(AI->getArraySize()) && BB == F->begin())
249 continue;
250
251 // Avoid iterator invalidation by copying users to a temporary vector.
Jim Grosbach606f3d62009-08-17 21:40:03 +0000252 SmallVector<Instruction*,16> Users;
Jim Grosbach8b818d72009-08-17 16:41:22 +0000253 for (Value::use_iterator UI = Inst->use_begin(), E = Inst->use_end();
254 UI != E; ++UI) {
255 Instruction *User = cast<Instruction>(*UI);
256 if (User->getParent() != BB || isa<PHINode>(User))
257 Users.push_back(User);
258 }
259
Jim Grosbach8b818d72009-08-17 16:41:22 +0000260 // Find all of the blocks that this value is live in.
261 std::set<BasicBlock*> LiveBBs;
262 LiveBBs.insert(Inst->getParent());
263 while (!Users.empty()) {
264 Instruction *U = Users.back();
265 Users.pop_back();
266
267 if (!isa<PHINode>(U)) {
268 MarkBlocksLiveIn(U->getParent(), LiveBBs);
269 } else {
270 // Uses for a PHI node occur in their predecessor block.
271 PHINode *PN = cast<PHINode>(U);
272 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
273 if (PN->getIncomingValue(i) == Inst)
274 MarkBlocksLiveIn(PN->getIncomingBlock(i), LiveBBs);
275 }
276 }
277
278 // Now that we know all of the blocks that this thing is live in, see if
279 // it includes any of the unwind locations.
280 bool NeedsSpill = false;
281 for (unsigned i = 0, e = Invokes.size(); i != e; ++i) {
282 BasicBlock *UnwindBlock = Invokes[i]->getUnwindDest();
283 if (UnwindBlock != BB && LiveBBs.count(UnwindBlock)) {
284 NeedsSpill = true;
285 }
286 }
287
288 // If we decided we need a spill, do it.
Jim Grosbach956352e2010-06-16 18:45:08 +0000289 // FIXME: Spilling this way is overkill, as it forces all uses of
290 // the value to be reloaded from the stack slot, even those that aren't
291 // in the unwind blocks. We should be more selective.
Jim Grosbach8b818d72009-08-17 16:41:22 +0000292 if (NeedsSpill) {
293 ++NumSpilled;
294 DemoteRegToStack(*Inst, true);
295 }
296 }
297}
298
299bool SjLjEHPass::insertSjLjEHSupport(Function &F) {
Jim Grosbach606f3d62009-08-17 21:40:03 +0000300 SmallVector<ReturnInst*,16> Returns;
301 SmallVector<UnwindInst*,16> Unwinds;
302 SmallVector<InvokeInst*,16> Invokes;
Jim Grosbach8b818d72009-08-17 16:41:22 +0000303
304 // Look through the terminators of the basic blocks to find invokes, returns
Jim Grosbachb58a59b2010-03-04 22:07:46 +0000305 // and unwinds.
306 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
Jim Grosbach8b818d72009-08-17 16:41:22 +0000307 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
308 // Remember all return instructions in case we insert an invoke into this
309 // function.
310 Returns.push_back(RI);
311 } else if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
312 Invokes.push_back(II);
313 } else if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator())) {
314 Unwinds.push_back(UI);
315 }
Jim Grosbachb58a59b2010-03-04 22:07:46 +0000316 }
Bill Wendling8d90b712011-01-07 02:54:45 +0000317
318 NumInvokes += Invokes.size();
319 NumUnwinds += Unwinds.size();
320
321 // If we don't have any invokes, there's nothing to do.
322 if (Invokes.empty()) return false;
Jim Grosbach8b818d72009-08-17 16:41:22 +0000323
Jim Grosbach0798edd2010-05-27 23:49:24 +0000324 // Find the eh.selector.*, eh.exception and alloca calls.
325 //
326 // Remember any allocas() that aren't in the entry block, as the
327 // jmpbuf saved SP will need to be updated for them.
328 //
329 // We'll use the first eh.selector to determine the right personality
330 // function to use. For SJLJ, we always use the same personality for the
331 // whole function, not on a per-selector basis.
Jim Grosbacha235d132009-08-23 18:13:48 +0000332 // FIXME: That's a bit ugly. Better way?
333 SmallVector<CallInst*,16> EH_Selectors;
334 SmallVector<CallInst*,16> EH_Exceptions;
Jim Grosbach0798edd2010-05-27 23:49:24 +0000335 SmallVector<Instruction*,16> JmpbufUpdatePoints;
Bill Wendling8d90b712011-01-07 02:54:45 +0000336
Jim Grosbach0798edd2010-05-27 23:49:24 +0000337 // Note: Skip the entry block since there's nothing there that interests
338 // us. eh.selector and eh.exception shouldn't ever be there, and we
339 // want to disregard any allocas that are there.
340 for (Function::iterator BB = F.begin(), E = F.end(); ++BB != E;) {
Jim Grosbacha235d132009-08-23 18:13:48 +0000341 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
342 if (CallInst *CI = dyn_cast<CallInst>(I)) {
Duncan Sandsb01bbdc2009-10-14 16:11:37 +0000343 if (CI->getCalledFunction() == SelectorFn) {
Gabor Greif45c097f2010-06-25 09:36:23 +0000344 if (!PersonalityFn) PersonalityFn = CI->getArgOperand(1);
Jim Grosbacha235d132009-08-23 18:13:48 +0000345 EH_Selectors.push_back(CI);
346 } else if (CI->getCalledFunction() == ExceptionFn) {
347 EH_Exceptions.push_back(CI);
Jim Grosbach0798edd2010-05-27 23:49:24 +0000348 } else if (CI->getCalledFunction() == StackRestoreFn) {
349 JmpbufUpdatePoints.push_back(CI);
Jim Grosbacha235d132009-08-23 18:13:48 +0000350 }
Jim Grosbach0798edd2010-05-27 23:49:24 +0000351 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) {
352 JmpbufUpdatePoints.push_back(AI);
Jim Grosbacha235d132009-08-23 18:13:48 +0000353 }
354 }
355 }
Bill Wendling8d90b712011-01-07 02:54:45 +0000356
Jim Grosbacha235d132009-08-23 18:13:48 +0000357 // If we don't have any eh.selector calls, we can't determine the personality
358 // function. Without a personality function, we can't process exceptions.
359 if (!PersonalityFn) return false;
360
Bill Wendling8d90b712011-01-07 02:54:45 +0000361 // We have invokes, so we need to add register/unregister calls to get this
362 // function onto the global unwind stack.
363 //
364 // First thing we need to do is scan the whole function for values that are
365 // live across unwind edges. Each value that is live across an unwind edge we
366 // spill into a stack location, guaranteeing that there is nothing live across
367 // the unwind edge. This process also splits all critical edges coming out of
368 // invoke's.
369 splitLiveRangesAcrossInvokes(Invokes);
Jim Grosbach8b818d72009-08-17 16:41:22 +0000370
Bill Wendling8d90b712011-01-07 02:54:45 +0000371 BasicBlock *EntryBB = F.begin();
372 // Create an alloca for the incoming jump buffer ptr and the new jump buffer
373 // that needs to be restored on all exits from the function. This is an
374 // alloca because the value needs to be added to the global context list.
375 unsigned Align = 4; // FIXME: Should be a TLI check?
376 AllocaInst *FunctionContext =
377 new AllocaInst(FunctionContextTy, 0, Align,
378 "fcn_context", F.begin()->begin());
Jim Grosbach8b818d72009-08-17 16:41:22 +0000379
Bill Wendling8d90b712011-01-07 02:54:45 +0000380 Value *Idxs[2];
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000381 Type *Int32Ty = Type::getInt32Ty(F.getContext());
Bill Wendling8d90b712011-01-07 02:54:45 +0000382 Value *Zero = ConstantInt::get(Int32Ty, 0);
383 // We need to also keep around a reference to the call_site field
384 Idxs[0] = Zero;
385 Idxs[1] = ConstantInt::get(Int32Ty, 1);
Jay Foada9203102011-07-25 09:48:08 +0000386 CallSite = GetElementPtrInst::Create(FunctionContext, Idxs, "call_site",
Bill Wendling8d90b712011-01-07 02:54:45 +0000387 EntryBB->getTerminator());
Jim Grosbach8b818d72009-08-17 16:41:22 +0000388
Bill Wendling8d90b712011-01-07 02:54:45 +0000389 // The exception selector comes back in context->data[1]
390 Idxs[1] = ConstantInt::get(Int32Ty, 2);
Jay Foada9203102011-07-25 09:48:08 +0000391 Value *FCData = GetElementPtrInst::Create(FunctionContext, Idxs, "fc_data",
Bill Wendling8d90b712011-01-07 02:54:45 +0000392 EntryBB->getTerminator());
393 Idxs[1] = ConstantInt::get(Int32Ty, 1);
Jay Foada9203102011-07-25 09:48:08 +0000394 Value *SelectorAddr = GetElementPtrInst::Create(FCData, Idxs,
Bill Wendling8d90b712011-01-07 02:54:45 +0000395 "exc_selector_gep",
396 EntryBB->getTerminator());
397 // The exception value comes back in context->data[0]
398 Idxs[1] = Zero;
Jay Foada9203102011-07-25 09:48:08 +0000399 Value *ExceptionAddr = GetElementPtrInst::Create(FCData, Idxs,
Bill Wendling8d90b712011-01-07 02:54:45 +0000400 "exception_gep",
401 EntryBB->getTerminator());
Jim Grosbach8b818d72009-08-17 16:41:22 +0000402
Bill Wendling8d90b712011-01-07 02:54:45 +0000403 // The result of the eh.selector call will be replaced with a a reference to
404 // the selector value returned in the function context. We leave the selector
405 // itself so the EH analysis later can use it.
406 for (int i = 0, e = EH_Selectors.size(); i < e; ++i) {
407 CallInst *I = EH_Selectors[i];
408 Value *SelectorVal = new LoadInst(SelectorAddr, "select_val", true, I);
409 I->replaceAllUsesWith(SelectorVal);
Jim Grosbach8b818d72009-08-17 16:41:22 +0000410 }
411
Bill Wendling8d90b712011-01-07 02:54:45 +0000412 // eh.exception calls are replaced with references to the proper location in
413 // the context. Unlike eh.selector, the eh.exception calls are removed
414 // entirely.
415 for (int i = 0, e = EH_Exceptions.size(); i < e; ++i) {
416 CallInst *I = EH_Exceptions[i];
417 // Possible for there to be duplicates, so check to make sure the
418 // instruction hasn't already been removed.
419 if (!I->getParent()) continue;
420 Value *Val = new LoadInst(ExceptionAddr, "exception", true, I);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000421 Type *Ty = Type::getInt8PtrTy(F.getContext());
Bill Wendling8d90b712011-01-07 02:54:45 +0000422 Val = CastInst::Create(Instruction::IntToPtr, Val, Ty, "", I);
423
424 I->replaceAllUsesWith(Val);
425 I->eraseFromParent();
426 }
427
428 // The entry block changes to have the eh.sjlj.setjmp, with a conditional
429 // branch to a dispatch block for non-zero returns. If we return normally,
430 // we're not handling an exception and just register the function context and
431 // continue.
432
433 // Create the dispatch block. The dispatch block is basically a big switch
434 // statement that goes to all of the invoke landing pads.
435 BasicBlock *DispatchBlock =
436 BasicBlock::Create(F.getContext(), "eh.sjlj.setjmp.catch", &F);
437
Bill Wendling8d90b712011-01-07 02:54:45 +0000438 // Insert a load of the callsite in the dispatch block, and a switch on its
Bill Wendlingcc885952011-04-11 21:32:34 +0000439 // value. By default, we issue a trap statement.
440 BasicBlock *TrapBlock =
441 BasicBlock::Create(F.getContext(), "trapbb", &F);
442 CallInst::Create(Intrinsic::getDeclaration(F.getParent(), Intrinsic::trap),
443 "", TrapBlock);
444 new UnreachableInst(F.getContext(), TrapBlock);
Bill Wendling8d90b712011-01-07 02:54:45 +0000445
446 Value *DispatchLoad = new LoadInst(CallSite, "invoke.num", true,
447 DispatchBlock);
448 SwitchInst *DispatchSwitch =
Bill Wendlingcc885952011-04-11 21:32:34 +0000449 SwitchInst::Create(DispatchLoad, TrapBlock, Invokes.size(),
Bill Wendling8d90b712011-01-07 02:54:45 +0000450 DispatchBlock);
451 // Split the entry block to insert the conditional branch for the setjmp.
452 BasicBlock *ContBlock = EntryBB->splitBasicBlock(EntryBB->getTerminator(),
453 "eh.sjlj.setjmp.cont");
454
455 // Populate the Function Context
456 // 1. LSDA address
457 // 2. Personality function address
458 // 3. jmpbuf (save SP, FP and call eh.sjlj.setjmp)
459
460 // LSDA address
461 Idxs[0] = Zero;
462 Idxs[1] = ConstantInt::get(Int32Ty, 4);
463 Value *LSDAFieldPtr =
Jay Foada9203102011-07-25 09:48:08 +0000464 GetElementPtrInst::Create(FunctionContext, Idxs, "lsda_gep",
Bill Wendling8d90b712011-01-07 02:54:45 +0000465 EntryBB->getTerminator());
466 Value *LSDA = CallInst::Create(LSDAAddrFn, "lsda_addr",
467 EntryBB->getTerminator());
468 new StoreInst(LSDA, LSDAFieldPtr, true, EntryBB->getTerminator());
469
470 Idxs[1] = ConstantInt::get(Int32Ty, 3);
471 Value *PersonalityFieldPtr =
Jay Foada9203102011-07-25 09:48:08 +0000472 GetElementPtrInst::Create(FunctionContext, Idxs, "lsda_gep",
Bill Wendling8d90b712011-01-07 02:54:45 +0000473 EntryBB->getTerminator());
474 new StoreInst(PersonalityFn, PersonalityFieldPtr, true,
475 EntryBB->getTerminator());
476
477 // Save the frame pointer.
478 Idxs[1] = ConstantInt::get(Int32Ty, 5);
479 Value *JBufPtr
Jay Foada9203102011-07-25 09:48:08 +0000480 = GetElementPtrInst::Create(FunctionContext, Idxs, "jbuf_gep",
Bill Wendling8d90b712011-01-07 02:54:45 +0000481 EntryBB->getTerminator());
482 Idxs[1] = ConstantInt::get(Int32Ty, 0);
483 Value *FramePtr =
Jay Foada9203102011-07-25 09:48:08 +0000484 GetElementPtrInst::Create(JBufPtr, Idxs, "jbuf_fp_gep",
Bill Wendling8d90b712011-01-07 02:54:45 +0000485 EntryBB->getTerminator());
486
487 Value *Val = CallInst::Create(FrameAddrFn,
488 ConstantInt::get(Int32Ty, 0),
489 "fp",
490 EntryBB->getTerminator());
491 new StoreInst(Val, FramePtr, true, EntryBB->getTerminator());
492
493 // Save the stack pointer.
494 Idxs[1] = ConstantInt::get(Int32Ty, 2);
495 Value *StackPtr =
Jay Foada9203102011-07-25 09:48:08 +0000496 GetElementPtrInst::Create(JBufPtr, Idxs, "jbuf_sp_gep",
Bill Wendling8d90b712011-01-07 02:54:45 +0000497 EntryBB->getTerminator());
498
499 Val = CallInst::Create(StackAddrFn, "sp", EntryBB->getTerminator());
500 new StoreInst(Val, StackPtr, true, EntryBB->getTerminator());
501
502 // Call the setjmp instrinsic. It fills in the rest of the jmpbuf.
503 Value *SetjmpArg =
504 CastInst::Create(Instruction::BitCast, JBufPtr,
505 Type::getInt8PtrTy(F.getContext()), "",
506 EntryBB->getTerminator());
507 Value *DispatchVal = CallInst::Create(BuiltinSetjmpFn, SetjmpArg,
508 "dispatch",
509 EntryBB->getTerminator());
Bill Wendlingf05b1dc2011-04-05 01:37:43 +0000510
511 // Add a call to dispatch_setup after the setjmp call. This is expanded to any
512 // target-specific setup that needs to be done.
Bill Wendling61512ba2011-05-11 01:11:55 +0000513 CallInst::Create(DispatchSetupFn, DispatchVal, "", EntryBB->getTerminator());
Bill Wendlingf05b1dc2011-04-05 01:37:43 +0000514
Bill Wendling8d90b712011-01-07 02:54:45 +0000515 // check the return value of the setjmp. non-zero goes to dispatcher.
516 Value *IsNormal = new ICmpInst(EntryBB->getTerminator(),
517 ICmpInst::ICMP_EQ, DispatchVal, Zero,
518 "notunwind");
519 // Nuke the uncond branch.
520 EntryBB->getTerminator()->eraseFromParent();
521
522 // Put in a new condbranch in its place.
523 BranchInst::Create(ContBlock, DispatchBlock, IsNormal, EntryBB);
524
525 // Register the function context and make sure it's known to not throw
526 CallInst *Register =
527 CallInst::Create(RegisterFn, FunctionContext, "",
528 ContBlock->getTerminator());
529 Register->setDoesNotThrow();
530
531 // At this point, we are all set up, update the invoke instructions to mark
532 // their call_site values, and fill in the dispatch switch accordingly.
533 for (unsigned i = 0, e = Invokes.size(); i != e; ++i)
534 markInvokeCallSite(Invokes[i], i+1, CallSite, DispatchSwitch);
535
536 // Mark call instructions that aren't nounwind as no-action (call_site ==
537 // -1). Skip the entry block, as prior to then, no function context has been
538 // created for this function and any unexpected exceptions thrown will go
539 // directly to the caller's context, which is what we want anyway, so no need
540 // to do anything here.
541 for (Function::iterator BB = F.begin(), E = F.end(); ++BB != E;) {
542 for (BasicBlock::iterator I = BB->begin(), end = BB->end(); I != end; ++I)
543 if (CallInst *CI = dyn_cast<CallInst>(I)) {
544 // Ignore calls to the EH builtins (eh.selector, eh.exception)
545 Constant *Callee = CI->getCalledFunction();
546 if (Callee != SelectorFn && Callee != ExceptionFn
547 && !CI->doesNotThrow())
548 insertCallSiteStore(CI, -1, CallSite);
549 }
550 }
551
552 // Replace all unwinds with a branch to the unwind handler.
553 // ??? Should this ever happen with sjlj exceptions?
554 for (unsigned i = 0, e = Unwinds.size(); i != e; ++i) {
Bill Wendlingcc885952011-04-11 21:32:34 +0000555 BranchInst::Create(TrapBlock, Unwinds[i]);
Bill Wendling8d90b712011-01-07 02:54:45 +0000556 Unwinds[i]->eraseFromParent();
557 }
558
559 // Following any allocas not in the entry block, update the saved SP in the
560 // jmpbuf to the new value.
561 for (unsigned i = 0, e = JmpbufUpdatePoints.size(); i != e; ++i) {
562 Instruction *AI = JmpbufUpdatePoints[i];
563 Instruction *StackAddr = CallInst::Create(StackAddrFn, "sp");
564 StackAddr->insertAfter(AI);
565 Instruction *StoreStackAddr = new StoreInst(StackAddr, StackPtr, true);
566 StoreStackAddr->insertAfter(StackAddr);
567 }
568
569 // Finally, for any returns from this function, if this function contains an
570 // invoke, add a call to unregister the function context.
571 for (unsigned i = 0, e = Returns.size(); i != e; ++i)
572 CallInst::Create(UnregisterFn, FunctionContext, "", Returns[i]);
573
Jim Grosbach8b818d72009-08-17 16:41:22 +0000574 return true;
575}
576
577bool SjLjEHPass::runOnFunction(Function &F) {
578 bool Res = insertSjLjEHSupport(F);
579 return Res;
580}