blob: c2565afe0163af03912192c83de4fb7d7595d699 [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"
Benjamin Kramerf7888542010-11-06 11:45:59 +000024#include "llvm/ADT/SmallVector.h"
25#include "llvm/ADT/Statistic.h"
Jim Grosbach8b818d72009-08-17 16:41:22 +000026#include "llvm/CodeGen/Passes.h"
Benjamin Kramerf7888542010-11-06 11:45:59 +000027#include "llvm/Support/Debug.h"
28#include "llvm/Target/TargetLowering.h"
Jim Grosbach8b818d72009-08-17 16:41:22 +000029#include "llvm/Transforms/Utils/BasicBlockUtils.h"
30#include "llvm/Transforms/Utils/Local.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
41 const TargetLowering *TLI;
42
43 const Type *FunctionContextTy;
44 Constant *RegisterFn;
45 Constant *UnregisterFn;
Jim Grosbach8b818d72009-08-17 16:41:22 +000046 Constant *BuiltinSetjmpFn;
47 Constant *FrameAddrFn;
Jim Grosbach0798edd2010-05-27 23:49:24 +000048 Constant *StackAddrFn;
49 Constant *StackRestoreFn;
Jim Grosbach8b818d72009-08-17 16:41:22 +000050 Constant *LSDAAddrFn;
51 Value *PersonalityFn;
Duncan Sandsb01bbdc2009-10-14 16:11:37 +000052 Constant *SelectorFn;
Jim Grosbach8b818d72009-08-17 16:41:22 +000053 Constant *ExceptionFn;
Jim Grosbachca752c92010-01-28 01:45:32 +000054 Constant *CallSiteFn;
Jim Grosbache4ad3872010-10-19 23:27:08 +000055 Constant *DispatchSetupFn;
Jim Grosbach8b818d72009-08-17 16:41:22 +000056
57 Value *CallSite;
58 public:
59 static char ID; // Pass identification, replacement for typeid
60 explicit SjLjEHPass(const TargetLowering *tli = NULL)
Owen Anderson90c579d2010-08-06 18:33:48 +000061 : FunctionPass(ID), TLI(tli) { }
Jim Grosbach8b818d72009-08-17 16:41:22 +000062 bool doInitialization(Module &M);
63 bool runOnFunction(Function &F);
64
65 virtual void getAnalysisUsage(AnalysisUsage &AU) const { }
66 const char *getPassName() const {
67 return "SJLJ Exception Handling preparation";
68 }
69
70 private:
Jim Grosbachb58a59b2010-03-04 22:07:46 +000071 void insertCallSiteStore(Instruction *I, int Number, Value *CallSite);
72 void markInvokeCallSite(InvokeInst *II, int InvokeNo, Value *CallSite,
Jim Grosbach0bb61c52009-08-31 01:35:03 +000073 SwitchInst *CatchSwitch);
Jim Grosbach288694f2010-06-15 18:53:34 +000074 void splitLiveRangesAcrossInvokes(SmallVector<InvokeInst*,16> &Invokes);
Jim Grosbach8b818d72009-08-17 16:41:22 +000075 bool insertSjLjEHSupport(Function &F);
76 };
77} // end anonymous namespace
78
79char SjLjEHPass::ID = 0;
80
81// Public Interface To the SjLjEHPass pass.
82FunctionPass *llvm::createSjLjEHPass(const TargetLowering *TLI) {
83 return new SjLjEHPass(TLI);
84}
Jim Grosbacha235d132009-08-23 18:13:48 +000085// doInitialization - Set up decalarations and types needed to process
86// exceptions.
Jim Grosbach8b818d72009-08-17 16:41:22 +000087bool SjLjEHPass::doInitialization(Module &M) {
88 // Build the function context structure.
89 // builtin_setjmp uses a five word jbuf
90 const Type *VoidPtrTy =
Duncan Sandsac53a0b2009-10-06 15:40:36 +000091 Type::getInt8PtrTy(M.getContext());
Jim Grosbach8b818d72009-08-17 16:41:22 +000092 const Type *Int32Ty = Type::getInt32Ty(M.getContext());
93 FunctionContextTy =
Chris Lattnerb2318662011-06-18 22:48:56 +000094 StructType::get(VoidPtrTy, // __prev
Jim Grosbach8b818d72009-08-17 16:41:22 +000095 Int32Ty, // call_site
96 ArrayType::get(Int32Ty, 4), // __data
97 VoidPtrTy, // __personality
98 VoidPtrTy, // __lsda
99 ArrayType::get(VoidPtrTy, 5), // __jbuf
100 NULL);
101 RegisterFn = M.getOrInsertFunction("_Unwind_SjLj_Register",
102 Type::getVoidTy(M.getContext()),
103 PointerType::getUnqual(FunctionContextTy),
104 (Type *)0);
105 UnregisterFn =
106 M.getOrInsertFunction("_Unwind_SjLj_Unregister",
107 Type::getVoidTy(M.getContext()),
108 PointerType::getUnqual(FunctionContextTy),
109 (Type *)0);
Jim Grosbach8b818d72009-08-17 16:41:22 +0000110 FrameAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::frameaddress);
Jim Grosbach0798edd2010-05-27 23:49:24 +0000111 StackAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::stacksave);
112 StackRestoreFn = Intrinsic::getDeclaration(&M, Intrinsic::stackrestore);
Jim Grosbach8b818d72009-08-17 16:41:22 +0000113 BuiltinSetjmpFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_setjmp);
114 LSDAAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_lsda);
Duncan Sandsb01bbdc2009-10-14 16:11:37 +0000115 SelectorFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_selector);
Jim Grosbach8b818d72009-08-17 16:41:22 +0000116 ExceptionFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_exception);
Jim Grosbachca752c92010-01-28 01:45:32 +0000117 CallSiteFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_callsite);
Jim Grosbache4ad3872010-10-19 23:27:08 +0000118 DispatchSetupFn
119 = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_dispatch_setup);
Jim Grosbacha235d132009-08-23 18:13:48 +0000120 PersonalityFn = 0;
Jim Grosbach8b818d72009-08-17 16:41:22 +0000121
122 return true;
123}
124
Jim Grosbachb58a59b2010-03-04 22:07:46 +0000125/// insertCallSiteStore - Insert a store of the call-site value to the
126/// function context
127void SjLjEHPass::insertCallSiteStore(Instruction *I, int Number,
128 Value *CallSite) {
129 ConstantInt *CallSiteNoC = ConstantInt::get(Type::getInt32Ty(I->getContext()),
130 Number);
131 // Insert a store of the call-site number
132 new StoreInst(CallSiteNoC, CallSite, true, I); // volatile
133}
134
Jim Grosbach8b818d72009-08-17 16:41:22 +0000135/// markInvokeCallSite - Insert code to mark the call_site for this invoke
Jim Grosbachb58a59b2010-03-04 22:07:46 +0000136void SjLjEHPass::markInvokeCallSite(InvokeInst *II, int InvokeNo,
Jim Grosbach0bb61c52009-08-31 01:35:03 +0000137 Value *CallSite,
138 SwitchInst *CatchSwitch) {
Jim Grosbach8b818d72009-08-17 16:41:22 +0000139 ConstantInt *CallSiteNoC= ConstantInt::get(Type::getInt32Ty(II->getContext()),
Jim Grosbachb58a59b2010-03-04 22:07:46 +0000140 InvokeNo);
Jim Grosbach0bb61c52009-08-31 01:35:03 +0000141 // The runtime comes back to the dispatcher with the call_site - 1 in
142 // the context. Odd, but there it is.
143 ConstantInt *SwitchValC = ConstantInt::get(Type::getInt32Ty(II->getContext()),
144 InvokeNo - 1);
Jim Grosbach8b818d72009-08-17 16:41:22 +0000145
146 // If the unwind edge has phi nodes, split the edge.
147 if (isa<PHINode>(II->getUnwindDest()->begin())) {
148 SplitCriticalEdge(II, 1, this);
149
150 // If there are any phi nodes left, they must have a single predecessor.
151 while (PHINode *PN = dyn_cast<PHINode>(II->getUnwindDest()->begin())) {
152 PN->replaceAllUsesWith(PN->getIncomingValue(0));
153 PN->eraseFromParent();
154 }
155 }
156
Jim Grosbachb58a59b2010-03-04 22:07:46 +0000157 // Insert the store of the call site value
158 insertCallSiteStore(II, InvokeNo, CallSite);
159
160 // Record the call site value for the back end so it stays associated with
161 // the invoke.
Jim Grosbachca752c92010-01-28 01:45:32 +0000162 CallInst::Create(CallSiteFn, CallSiteNoC, "", II);
Jim Grosbach8b818d72009-08-17 16:41:22 +0000163
Jim Grosbach0bb61c52009-08-31 01:35:03 +0000164 // Add a switch case to our unwind block.
165 CatchSwitch->addCase(SwitchValC, II->getUnwindDest());
Jim Grosbachca752c92010-01-28 01:45:32 +0000166 // We still want this to look like an invoke so we emit the LSDA properly,
167 // so we don't transform the invoke into a call here.
Jim Grosbach8b818d72009-08-17 16:41:22 +0000168}
169
170/// MarkBlocksLiveIn - Insert BB and all of its predescessors into LiveBBs until
171/// we reach blocks we've already seen.
172static void MarkBlocksLiveIn(BasicBlock *BB, std::set<BasicBlock*> &LiveBBs) {
173 if (!LiveBBs.insert(BB).second) return; // already been here.
174
175 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
176 MarkBlocksLiveIn(*PI, LiveBBs);
177}
178
Jim Grosbach606f3d62009-08-17 21:40:03 +0000179/// splitLiveRangesAcrossInvokes - Each value that is live across an unwind edge
180/// we spill into a stack location, guaranteeing that there is nothing live
181/// across the unwind edge. This process also splits all critical edges
182/// coming out of invoke's.
Jim Grosbach2f3257e2010-06-01 18:06:35 +0000183/// FIXME: Move this function to a common utility file (Local.cpp?) so
184/// both SjLj and LowerInvoke can use it.
Jim Grosbach8b818d72009-08-17 16:41:22 +0000185void SjLjEHPass::
Jim Grosbach288694f2010-06-15 18:53:34 +0000186splitLiveRangesAcrossInvokes(SmallVector<InvokeInst*,16> &Invokes) {
Jim Grosbach8b818d72009-08-17 16:41:22 +0000187 // First step, split all critical edges from invoke instructions.
188 for (unsigned i = 0, e = Invokes.size(); i != e; ++i) {
189 InvokeInst *II = Invokes[i];
190 SplitCriticalEdge(II, 0, this);
191 SplitCriticalEdge(II, 1, this);
192 assert(!isa<PHINode>(II->getNormalDest()) &&
193 !isa<PHINode>(II->getUnwindDest()) &&
194 "critical edge splitting left single entry phi nodes?");
195 }
196
197 Function *F = Invokes.back()->getParent()->getParent();
198
199 // To avoid having to handle incoming arguments specially, we lower each arg
200 // to a copy instruction in the entry block. This ensures that the argument
201 // value itself cannot be live across the entry block.
202 BasicBlock::iterator AfterAllocaInsertPt = F->begin()->begin();
203 while (isa<AllocaInst>(AfterAllocaInsertPt) &&
204 isa<ConstantInt>(cast<AllocaInst>(AfterAllocaInsertPt)->getArraySize()))
205 ++AfterAllocaInsertPt;
206 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
207 AI != E; ++AI) {
Jim Grosbachdc58b252010-06-01 18:04:09 +0000208 const Type *Ty = AI->getType();
Jim Grosbache70fc8e2010-06-30 22:20:38 +0000209 // Aggregate types can't be cast, but are legal argument types, so we have
Jim Grosbachdc58b252010-06-01 18:04:09 +0000210 // to handle them differently. We use an extract/insert pair as a
211 // lightweight method to achieve the same goal.
Jim Grosbache70fc8e2010-06-30 22:20:38 +0000212 if (isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<VectorType>(Ty)) {
213 Instruction *EI = ExtractValueInst::Create(AI, 0, "",AfterAllocaInsertPt);
Jim Grosbachdc58b252010-06-01 18:04:09 +0000214 Instruction *NI = InsertValueInst::Create(AI, EI, 0);
215 NI->insertAfter(EI);
216 AI->replaceAllUsesWith(NI);
Jim Grosbache70fc8e2010-06-30 22:20:38 +0000217 // Set the operand of the instructions back to the AllocaInst.
Jim Grosbachdc58b252010-06-01 18:04:09 +0000218 EI->setOperand(0, AI);
219 NI->setOperand(0, AI);
220 } else {
221 // This is always a no-op cast because we're casting AI to AI->getType()
222 // so src and destination types are identical. BitCast is the only
223 // possibility.
224 CastInst *NC = new BitCastInst(
225 AI, AI->getType(), AI->getName()+".tmp", AfterAllocaInsertPt);
226 AI->replaceAllUsesWith(NC);
227 // Set the operand of the cast instruction back to the AllocaInst.
228 // Normally it's forbidden to replace a CastInst's operand because it
229 // could cause the opcode to reflect an illegal conversion. However,
230 // we're replacing it here with the same value it was constructed with.
231 // We do this because the above replaceAllUsesWith() clobbered the
232 // operand, but we want this one to remain.
233 NC->setOperand(0, AI);
234 }
Jim Grosbach8b818d72009-08-17 16:41:22 +0000235 }
236
237 // Finally, scan the code looking for instructions with bad live ranges.
238 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
239 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; ++II) {
240 // Ignore obvious cases we don't have to handle. In particular, most
241 // instructions either have no uses or only have a single use inside the
242 // current block. Ignore them quickly.
243 Instruction *Inst = II;
244 if (Inst->use_empty()) continue;
245 if (Inst->hasOneUse() &&
246 cast<Instruction>(Inst->use_back())->getParent() == BB &&
247 !isa<PHINode>(Inst->use_back())) continue;
248
249 // If this is an alloca in the entry block, it's not a real register
250 // value.
251 if (AllocaInst *AI = dyn_cast<AllocaInst>(Inst))
252 if (isa<ConstantInt>(AI->getArraySize()) && BB == F->begin())
253 continue;
254
255 // Avoid iterator invalidation by copying users to a temporary vector.
Jim Grosbach606f3d62009-08-17 21:40:03 +0000256 SmallVector<Instruction*,16> Users;
Jim Grosbach8b818d72009-08-17 16:41:22 +0000257 for (Value::use_iterator UI = Inst->use_begin(), E = Inst->use_end();
258 UI != E; ++UI) {
259 Instruction *User = cast<Instruction>(*UI);
260 if (User->getParent() != BB || isa<PHINode>(User))
261 Users.push_back(User);
262 }
263
Jim Grosbach8b818d72009-08-17 16:41:22 +0000264 // Find all of the blocks that this value is live in.
265 std::set<BasicBlock*> LiveBBs;
266 LiveBBs.insert(Inst->getParent());
267 while (!Users.empty()) {
268 Instruction *U = Users.back();
269 Users.pop_back();
270
271 if (!isa<PHINode>(U)) {
272 MarkBlocksLiveIn(U->getParent(), LiveBBs);
273 } else {
274 // Uses for a PHI node occur in their predecessor block.
275 PHINode *PN = cast<PHINode>(U);
276 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
277 if (PN->getIncomingValue(i) == Inst)
278 MarkBlocksLiveIn(PN->getIncomingBlock(i), LiveBBs);
279 }
280 }
281
282 // Now that we know all of the blocks that this thing is live in, see if
283 // it includes any of the unwind locations.
284 bool NeedsSpill = false;
285 for (unsigned i = 0, e = Invokes.size(); i != e; ++i) {
286 BasicBlock *UnwindBlock = Invokes[i]->getUnwindDest();
287 if (UnwindBlock != BB && LiveBBs.count(UnwindBlock)) {
288 NeedsSpill = true;
289 }
290 }
291
292 // If we decided we need a spill, do it.
Jim Grosbach956352e2010-06-16 18:45:08 +0000293 // FIXME: Spilling this way is overkill, as it forces all uses of
294 // the value to be reloaded from the stack slot, even those that aren't
295 // in the unwind blocks. We should be more selective.
Jim Grosbach8b818d72009-08-17 16:41:22 +0000296 if (NeedsSpill) {
297 ++NumSpilled;
298 DemoteRegToStack(*Inst, true);
299 }
300 }
301}
302
303bool SjLjEHPass::insertSjLjEHSupport(Function &F) {
Jim Grosbach606f3d62009-08-17 21:40:03 +0000304 SmallVector<ReturnInst*,16> Returns;
305 SmallVector<UnwindInst*,16> Unwinds;
306 SmallVector<InvokeInst*,16> Invokes;
Jim Grosbach8b818d72009-08-17 16:41:22 +0000307
308 // Look through the terminators of the basic blocks to find invokes, returns
Jim Grosbachb58a59b2010-03-04 22:07:46 +0000309 // and unwinds.
310 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
Jim Grosbach8b818d72009-08-17 16:41:22 +0000311 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
312 // Remember all return instructions in case we insert an invoke into this
313 // function.
314 Returns.push_back(RI);
315 } else if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
316 Invokes.push_back(II);
317 } else if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator())) {
318 Unwinds.push_back(UI);
319 }
Jim Grosbachb58a59b2010-03-04 22:07:46 +0000320 }
Bill Wendling8d90b712011-01-07 02:54:45 +0000321
322 NumInvokes += Invokes.size();
323 NumUnwinds += Unwinds.size();
324
325 // If we don't have any invokes, there's nothing to do.
326 if (Invokes.empty()) return false;
Jim Grosbach8b818d72009-08-17 16:41:22 +0000327
Jim Grosbach0798edd2010-05-27 23:49:24 +0000328 // Find the eh.selector.*, eh.exception and alloca calls.
329 //
330 // Remember any allocas() that aren't in the entry block, as the
331 // jmpbuf saved SP will need to be updated for them.
332 //
333 // We'll use the first eh.selector to determine the right personality
334 // function to use. For SJLJ, we always use the same personality for the
335 // whole function, not on a per-selector basis.
Jim Grosbacha235d132009-08-23 18:13:48 +0000336 // FIXME: That's a bit ugly. Better way?
337 SmallVector<CallInst*,16> EH_Selectors;
338 SmallVector<CallInst*,16> EH_Exceptions;
Jim Grosbach0798edd2010-05-27 23:49:24 +0000339 SmallVector<Instruction*,16> JmpbufUpdatePoints;
Bill Wendling8d90b712011-01-07 02:54:45 +0000340
Jim Grosbach0798edd2010-05-27 23:49:24 +0000341 // Note: Skip the entry block since there's nothing there that interests
342 // us. eh.selector and eh.exception shouldn't ever be there, and we
343 // want to disregard any allocas that are there.
344 for (Function::iterator BB = F.begin(), E = F.end(); ++BB != E;) {
Jim Grosbacha235d132009-08-23 18:13:48 +0000345 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
346 if (CallInst *CI = dyn_cast<CallInst>(I)) {
Duncan Sandsb01bbdc2009-10-14 16:11:37 +0000347 if (CI->getCalledFunction() == SelectorFn) {
Gabor Greif45c097f2010-06-25 09:36:23 +0000348 if (!PersonalityFn) PersonalityFn = CI->getArgOperand(1);
Jim Grosbacha235d132009-08-23 18:13:48 +0000349 EH_Selectors.push_back(CI);
350 } else if (CI->getCalledFunction() == ExceptionFn) {
351 EH_Exceptions.push_back(CI);
Jim Grosbach0798edd2010-05-27 23:49:24 +0000352 } else if (CI->getCalledFunction() == StackRestoreFn) {
353 JmpbufUpdatePoints.push_back(CI);
Jim Grosbacha235d132009-08-23 18:13:48 +0000354 }
Jim Grosbach0798edd2010-05-27 23:49:24 +0000355 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) {
356 JmpbufUpdatePoints.push_back(AI);
Jim Grosbacha235d132009-08-23 18:13:48 +0000357 }
358 }
359 }
Bill Wendling8d90b712011-01-07 02:54:45 +0000360
Jim Grosbacha235d132009-08-23 18:13:48 +0000361 // If we don't have any eh.selector calls, we can't determine the personality
362 // function. Without a personality function, we can't process exceptions.
363 if (!PersonalityFn) return false;
364
Bill Wendling8d90b712011-01-07 02:54:45 +0000365 // We have invokes, so we need to add register/unregister calls to get this
366 // function onto the global unwind stack.
367 //
368 // First thing we need to do is scan the whole function for values that are
369 // live across unwind edges. Each value that is live across an unwind edge we
370 // spill into a stack location, guaranteeing that there is nothing live across
371 // the unwind edge. This process also splits all critical edges coming out of
372 // invoke's.
373 splitLiveRangesAcrossInvokes(Invokes);
Jim Grosbach8b818d72009-08-17 16:41:22 +0000374
Bill Wendling8d90b712011-01-07 02:54:45 +0000375 BasicBlock *EntryBB = F.begin();
376 // Create an alloca for the incoming jump buffer ptr and the new jump buffer
377 // that needs to be restored on all exits from the function. This is an
378 // alloca because the value needs to be added to the global context list.
379 unsigned Align = 4; // FIXME: Should be a TLI check?
380 AllocaInst *FunctionContext =
381 new AllocaInst(FunctionContextTy, 0, Align,
382 "fcn_context", F.begin()->begin());
Jim Grosbach8b818d72009-08-17 16:41:22 +0000383
Bill Wendling8d90b712011-01-07 02:54:45 +0000384 Value *Idxs[2];
385 const Type *Int32Ty = Type::getInt32Ty(F.getContext());
386 Value *Zero = ConstantInt::get(Int32Ty, 0);
387 // We need to also keep around a reference to the call_site field
388 Idxs[0] = Zero;
389 Idxs[1] = ConstantInt::get(Int32Ty, 1);
390 CallSite = GetElementPtrInst::Create(FunctionContext, Idxs, Idxs+2,
391 "call_site",
392 EntryBB->getTerminator());
Jim Grosbach8b818d72009-08-17 16:41:22 +0000393
Bill Wendling8d90b712011-01-07 02:54:45 +0000394 // The exception selector comes back in context->data[1]
395 Idxs[1] = ConstantInt::get(Int32Ty, 2);
396 Value *FCData = GetElementPtrInst::Create(FunctionContext, Idxs, Idxs+2,
397 "fc_data",
398 EntryBB->getTerminator());
399 Idxs[1] = ConstantInt::get(Int32Ty, 1);
400 Value *SelectorAddr = GetElementPtrInst::Create(FCData, Idxs, Idxs+2,
401 "exc_selector_gep",
402 EntryBB->getTerminator());
403 // The exception value comes back in context->data[0]
404 Idxs[1] = Zero;
405 Value *ExceptionAddr = GetElementPtrInst::Create(FCData, Idxs, Idxs+2,
406 "exception_gep",
407 EntryBB->getTerminator());
Jim Grosbach8b818d72009-08-17 16:41:22 +0000408
Bill Wendling8d90b712011-01-07 02:54:45 +0000409 // The result of the eh.selector call will be replaced with a a reference to
410 // the selector value returned in the function context. We leave the selector
411 // itself so the EH analysis later can use it.
412 for (int i = 0, e = EH_Selectors.size(); i < e; ++i) {
413 CallInst *I = EH_Selectors[i];
414 Value *SelectorVal = new LoadInst(SelectorAddr, "select_val", true, I);
415 I->replaceAllUsesWith(SelectorVal);
Jim Grosbach8b818d72009-08-17 16:41:22 +0000416 }
417
Bill Wendling8d90b712011-01-07 02:54:45 +0000418 // eh.exception calls are replaced with references to the proper location in
419 // the context. Unlike eh.selector, the eh.exception calls are removed
420 // entirely.
421 for (int i = 0, e = EH_Exceptions.size(); i < e; ++i) {
422 CallInst *I = EH_Exceptions[i];
423 // Possible for there to be duplicates, so check to make sure the
424 // instruction hasn't already been removed.
425 if (!I->getParent()) continue;
426 Value *Val = new LoadInst(ExceptionAddr, "exception", true, I);
427 const Type *Ty = Type::getInt8PtrTy(F.getContext());
428 Val = CastInst::Create(Instruction::IntToPtr, Val, Ty, "", I);
429
430 I->replaceAllUsesWith(Val);
431 I->eraseFromParent();
432 }
433
434 // The entry block changes to have the eh.sjlj.setjmp, with a conditional
435 // branch to a dispatch block for non-zero returns. If we return normally,
436 // we're not handling an exception and just register the function context and
437 // continue.
438
439 // Create the dispatch block. The dispatch block is basically a big switch
440 // statement that goes to all of the invoke landing pads.
441 BasicBlock *DispatchBlock =
442 BasicBlock::Create(F.getContext(), "eh.sjlj.setjmp.catch", &F);
443
Bill Wendling8d90b712011-01-07 02:54:45 +0000444 // Insert a load of the callsite in the dispatch block, and a switch on its
Bill Wendlingcc885952011-04-11 21:32:34 +0000445 // value. By default, we issue a trap statement.
446 BasicBlock *TrapBlock =
447 BasicBlock::Create(F.getContext(), "trapbb", &F);
448 CallInst::Create(Intrinsic::getDeclaration(F.getParent(), Intrinsic::trap),
449 "", TrapBlock);
450 new UnreachableInst(F.getContext(), TrapBlock);
Bill Wendling8d90b712011-01-07 02:54:45 +0000451
452 Value *DispatchLoad = new LoadInst(CallSite, "invoke.num", true,
453 DispatchBlock);
454 SwitchInst *DispatchSwitch =
Bill Wendlingcc885952011-04-11 21:32:34 +0000455 SwitchInst::Create(DispatchLoad, TrapBlock, Invokes.size(),
Bill Wendling8d90b712011-01-07 02:54:45 +0000456 DispatchBlock);
457 // Split the entry block to insert the conditional branch for the setjmp.
458 BasicBlock *ContBlock = EntryBB->splitBasicBlock(EntryBB->getTerminator(),
459 "eh.sjlj.setjmp.cont");
460
461 // Populate the Function Context
462 // 1. LSDA address
463 // 2. Personality function address
464 // 3. jmpbuf (save SP, FP and call eh.sjlj.setjmp)
465
466 // LSDA address
467 Idxs[0] = Zero;
468 Idxs[1] = ConstantInt::get(Int32Ty, 4);
469 Value *LSDAFieldPtr =
470 GetElementPtrInst::Create(FunctionContext, Idxs, Idxs+2,
471 "lsda_gep",
472 EntryBB->getTerminator());
473 Value *LSDA = CallInst::Create(LSDAAddrFn, "lsda_addr",
474 EntryBB->getTerminator());
475 new StoreInst(LSDA, LSDAFieldPtr, true, EntryBB->getTerminator());
476
477 Idxs[1] = ConstantInt::get(Int32Ty, 3);
478 Value *PersonalityFieldPtr =
479 GetElementPtrInst::Create(FunctionContext, Idxs, Idxs+2,
480 "lsda_gep",
481 EntryBB->getTerminator());
482 new StoreInst(PersonalityFn, PersonalityFieldPtr, true,
483 EntryBB->getTerminator());
484
485 // Save the frame pointer.
486 Idxs[1] = ConstantInt::get(Int32Ty, 5);
487 Value *JBufPtr
488 = GetElementPtrInst::Create(FunctionContext, Idxs, Idxs+2,
489 "jbuf_gep",
490 EntryBB->getTerminator());
491 Idxs[1] = ConstantInt::get(Int32Ty, 0);
492 Value *FramePtr =
493 GetElementPtrInst::Create(JBufPtr, Idxs, Idxs+2, "jbuf_fp_gep",
494 EntryBB->getTerminator());
495
496 Value *Val = CallInst::Create(FrameAddrFn,
497 ConstantInt::get(Int32Ty, 0),
498 "fp",
499 EntryBB->getTerminator());
500 new StoreInst(Val, FramePtr, true, EntryBB->getTerminator());
501
502 // Save the stack pointer.
503 Idxs[1] = ConstantInt::get(Int32Ty, 2);
504 Value *StackPtr =
505 GetElementPtrInst::Create(JBufPtr, Idxs, Idxs+2, "jbuf_sp_gep",
506 EntryBB->getTerminator());
507
508 Val = CallInst::Create(StackAddrFn, "sp", EntryBB->getTerminator());
509 new StoreInst(Val, StackPtr, true, EntryBB->getTerminator());
510
511 // Call the setjmp instrinsic. It fills in the rest of the jmpbuf.
512 Value *SetjmpArg =
513 CastInst::Create(Instruction::BitCast, JBufPtr,
514 Type::getInt8PtrTy(F.getContext()), "",
515 EntryBB->getTerminator());
516 Value *DispatchVal = CallInst::Create(BuiltinSetjmpFn, SetjmpArg,
517 "dispatch",
518 EntryBB->getTerminator());
Bill Wendlingf05b1dc2011-04-05 01:37:43 +0000519
520 // Add a call to dispatch_setup after the setjmp call. This is expanded to any
521 // target-specific setup that needs to be done.
Bill Wendling61512ba2011-05-11 01:11:55 +0000522 CallInst::Create(DispatchSetupFn, DispatchVal, "", EntryBB->getTerminator());
Bill Wendlingf05b1dc2011-04-05 01:37:43 +0000523
Bill Wendling8d90b712011-01-07 02:54:45 +0000524 // check the return value of the setjmp. non-zero goes to dispatcher.
525 Value *IsNormal = new ICmpInst(EntryBB->getTerminator(),
526 ICmpInst::ICMP_EQ, DispatchVal, Zero,
527 "notunwind");
528 // Nuke the uncond branch.
529 EntryBB->getTerminator()->eraseFromParent();
530
531 // Put in a new condbranch in its place.
532 BranchInst::Create(ContBlock, DispatchBlock, IsNormal, EntryBB);
533
534 // Register the function context and make sure it's known to not throw
535 CallInst *Register =
536 CallInst::Create(RegisterFn, FunctionContext, "",
537 ContBlock->getTerminator());
538 Register->setDoesNotThrow();
539
540 // At this point, we are all set up, update the invoke instructions to mark
541 // their call_site values, and fill in the dispatch switch accordingly.
542 for (unsigned i = 0, e = Invokes.size(); i != e; ++i)
543 markInvokeCallSite(Invokes[i], i+1, CallSite, DispatchSwitch);
544
545 // Mark call instructions that aren't nounwind as no-action (call_site ==
546 // -1). Skip the entry block, as prior to then, no function context has been
547 // created for this function and any unexpected exceptions thrown will go
548 // directly to the caller's context, which is what we want anyway, so no need
549 // to do anything here.
550 for (Function::iterator BB = F.begin(), E = F.end(); ++BB != E;) {
551 for (BasicBlock::iterator I = BB->begin(), end = BB->end(); I != end; ++I)
552 if (CallInst *CI = dyn_cast<CallInst>(I)) {
553 // Ignore calls to the EH builtins (eh.selector, eh.exception)
554 Constant *Callee = CI->getCalledFunction();
555 if (Callee != SelectorFn && Callee != ExceptionFn
556 && !CI->doesNotThrow())
557 insertCallSiteStore(CI, -1, CallSite);
558 }
559 }
560
561 // Replace all unwinds with a branch to the unwind handler.
562 // ??? Should this ever happen with sjlj exceptions?
563 for (unsigned i = 0, e = Unwinds.size(); i != e; ++i) {
Bill Wendlingcc885952011-04-11 21:32:34 +0000564 BranchInst::Create(TrapBlock, Unwinds[i]);
Bill Wendling8d90b712011-01-07 02:54:45 +0000565 Unwinds[i]->eraseFromParent();
566 }
567
568 // Following any allocas not in the entry block, update the saved SP in the
569 // jmpbuf to the new value.
570 for (unsigned i = 0, e = JmpbufUpdatePoints.size(); i != e; ++i) {
571 Instruction *AI = JmpbufUpdatePoints[i];
572 Instruction *StackAddr = CallInst::Create(StackAddrFn, "sp");
573 StackAddr->insertAfter(AI);
574 Instruction *StoreStackAddr = new StoreInst(StackAddr, StackPtr, true);
575 StoreStackAddr->insertAfter(StackAddr);
576 }
577
578 // Finally, for any returns from this function, if this function contains an
579 // invoke, add a call to unregister the function context.
580 for (unsigned i = 0, e = Returns.size(); i != e; ++i)
581 CallInst::Create(UnregisterFn, FunctionContext, "", Returns[i]);
582
Jim Grosbach8b818d72009-08-17 16:41:22 +0000583 return true;
584}
585
586bool SjLjEHPass::runOnFunction(Function &F) {
587 bool Res = insertSjLjEHSupport(F);
588 return Res;
589}