blob: 9836623c5fc1d4aacbd97d0c3b4a32f706c726fb [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 =
94 StructType::get(M.getContext(),
95 VoidPtrTy, // __prev
96 Int32Ty, // call_site
97 ArrayType::get(Int32Ty, 4), // __data
98 VoidPtrTy, // __personality
99 VoidPtrTy, // __lsda
100 ArrayType::get(VoidPtrTy, 5), // __jbuf
101 NULL);
102 RegisterFn = M.getOrInsertFunction("_Unwind_SjLj_Register",
103 Type::getVoidTy(M.getContext()),
104 PointerType::getUnqual(FunctionContextTy),
105 (Type *)0);
106 UnregisterFn =
107 M.getOrInsertFunction("_Unwind_SjLj_Unregister",
108 Type::getVoidTy(M.getContext()),
109 PointerType::getUnqual(FunctionContextTy),
110 (Type *)0);
Jim Grosbach8b818d72009-08-17 16:41:22 +0000111 FrameAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::frameaddress);
Jim Grosbach0798edd2010-05-27 23:49:24 +0000112 StackAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::stacksave);
113 StackRestoreFn = Intrinsic::getDeclaration(&M, Intrinsic::stackrestore);
Jim Grosbach8b818d72009-08-17 16:41:22 +0000114 BuiltinSetjmpFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_setjmp);
115 LSDAAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_lsda);
Duncan Sandsb01bbdc2009-10-14 16:11:37 +0000116 SelectorFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_selector);
Jim Grosbach8b818d72009-08-17 16:41:22 +0000117 ExceptionFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_exception);
Jim Grosbachca752c92010-01-28 01:45:32 +0000118 CallSiteFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_callsite);
Jim Grosbache4ad3872010-10-19 23:27:08 +0000119 DispatchSetupFn
120 = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_dispatch_setup);
Jim Grosbacha235d132009-08-23 18:13:48 +0000121 PersonalityFn = 0;
Jim Grosbach8b818d72009-08-17 16:41:22 +0000122
123 return true;
124}
125
Jim Grosbachb58a59b2010-03-04 22:07:46 +0000126/// insertCallSiteStore - Insert a store of the call-site value to the
127/// function context
128void SjLjEHPass::insertCallSiteStore(Instruction *I, int Number,
129 Value *CallSite) {
130 ConstantInt *CallSiteNoC = ConstantInt::get(Type::getInt32Ty(I->getContext()),
131 Number);
132 // Insert a store of the call-site number
133 new StoreInst(CallSiteNoC, CallSite, true, I); // volatile
134}
135
Jim Grosbach8b818d72009-08-17 16:41:22 +0000136/// markInvokeCallSite - Insert code to mark the call_site for this invoke
Jim Grosbachb58a59b2010-03-04 22:07:46 +0000137void SjLjEHPass::markInvokeCallSite(InvokeInst *II, int InvokeNo,
Jim Grosbach0bb61c52009-08-31 01:35:03 +0000138 Value *CallSite,
139 SwitchInst *CatchSwitch) {
Jim Grosbach8b818d72009-08-17 16:41:22 +0000140 ConstantInt *CallSiteNoC= ConstantInt::get(Type::getInt32Ty(II->getContext()),
Jim Grosbachb58a59b2010-03-04 22:07:46 +0000141 InvokeNo);
Jim Grosbach0bb61c52009-08-31 01:35:03 +0000142 // The runtime comes back to the dispatcher with the call_site - 1 in
143 // the context. Odd, but there it is.
144 ConstantInt *SwitchValC = ConstantInt::get(Type::getInt32Ty(II->getContext()),
145 InvokeNo - 1);
Jim Grosbach8b818d72009-08-17 16:41:22 +0000146
147 // If the unwind edge has phi nodes, split the edge.
148 if (isa<PHINode>(II->getUnwindDest()->begin())) {
149 SplitCriticalEdge(II, 1, this);
150
151 // If there are any phi nodes left, they must have a single predecessor.
152 while (PHINode *PN = dyn_cast<PHINode>(II->getUnwindDest()->begin())) {
153 PN->replaceAllUsesWith(PN->getIncomingValue(0));
154 PN->eraseFromParent();
155 }
156 }
157
Jim Grosbachb58a59b2010-03-04 22:07:46 +0000158 // Insert the store of the call site value
159 insertCallSiteStore(II, InvokeNo, CallSite);
160
161 // Record the call site value for the back end so it stays associated with
162 // the invoke.
Jim Grosbachca752c92010-01-28 01:45:32 +0000163 CallInst::Create(CallSiteFn, CallSiteNoC, "", II);
Jim Grosbach8b818d72009-08-17 16:41:22 +0000164
Jim Grosbach0bb61c52009-08-31 01:35:03 +0000165 // Add a switch case to our unwind block.
166 CatchSwitch->addCase(SwitchValC, II->getUnwindDest());
Jim Grosbachca752c92010-01-28 01:45:32 +0000167 // We still want this to look like an invoke so we emit the LSDA properly,
168 // so we don't transform the invoke into a call here.
Jim Grosbach8b818d72009-08-17 16:41:22 +0000169}
170
171/// MarkBlocksLiveIn - Insert BB and all of its predescessors into LiveBBs until
172/// we reach blocks we've already seen.
173static void MarkBlocksLiveIn(BasicBlock *BB, std::set<BasicBlock*> &LiveBBs) {
174 if (!LiveBBs.insert(BB).second) return; // already been here.
175
176 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
177 MarkBlocksLiveIn(*PI, LiveBBs);
178}
179
Jim Grosbach606f3d62009-08-17 21:40:03 +0000180/// splitLiveRangesAcrossInvokes - Each value that is live across an unwind edge
181/// we spill into a stack location, guaranteeing that there is nothing live
182/// across the unwind edge. This process also splits all critical edges
183/// coming out of invoke's.
Jim Grosbach2f3257e2010-06-01 18:06:35 +0000184/// FIXME: Move this function to a common utility file (Local.cpp?) so
185/// both SjLj and LowerInvoke can use it.
Jim Grosbach8b818d72009-08-17 16:41:22 +0000186void SjLjEHPass::
Jim Grosbach288694f2010-06-15 18:53:34 +0000187splitLiveRangesAcrossInvokes(SmallVector<InvokeInst*,16> &Invokes) {
Jim Grosbach8b818d72009-08-17 16:41:22 +0000188 // First step, split all critical edges from invoke instructions.
189 for (unsigned i = 0, e = Invokes.size(); i != e; ++i) {
190 InvokeInst *II = Invokes[i];
191 SplitCriticalEdge(II, 0, this);
192 SplitCriticalEdge(II, 1, this);
193 assert(!isa<PHINode>(II->getNormalDest()) &&
194 !isa<PHINode>(II->getUnwindDest()) &&
195 "critical edge splitting left single entry phi nodes?");
196 }
197
198 Function *F = Invokes.back()->getParent()->getParent();
199
200 // To avoid having to handle incoming arguments specially, we lower each arg
201 // to a copy instruction in the entry block. This ensures that the argument
202 // value itself cannot be live across the entry block.
203 BasicBlock::iterator AfterAllocaInsertPt = F->begin()->begin();
204 while (isa<AllocaInst>(AfterAllocaInsertPt) &&
205 isa<ConstantInt>(cast<AllocaInst>(AfterAllocaInsertPt)->getArraySize()))
206 ++AfterAllocaInsertPt;
207 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
208 AI != E; ++AI) {
Jim Grosbachdc58b252010-06-01 18:04:09 +0000209 const Type *Ty = AI->getType();
Jim Grosbache70fc8e2010-06-30 22:20:38 +0000210 // Aggregate types can't be cast, but are legal argument types, so we have
Jim Grosbachdc58b252010-06-01 18:04:09 +0000211 // to handle them differently. We use an extract/insert pair as a
212 // lightweight method to achieve the same goal.
Jim Grosbache70fc8e2010-06-30 22:20:38 +0000213 if (isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<VectorType>(Ty)) {
214 Instruction *EI = ExtractValueInst::Create(AI, 0, "",AfterAllocaInsertPt);
Jim Grosbachdc58b252010-06-01 18:04:09 +0000215 Instruction *NI = InsertValueInst::Create(AI, EI, 0);
216 NI->insertAfter(EI);
217 AI->replaceAllUsesWith(NI);
Jim Grosbache70fc8e2010-06-30 22:20:38 +0000218 // Set the operand of the instructions back to the AllocaInst.
Jim Grosbachdc58b252010-06-01 18:04:09 +0000219 EI->setOperand(0, AI);
220 NI->setOperand(0, AI);
221 } else {
222 // This is always a no-op cast because we're casting AI to AI->getType()
223 // so src and destination types are identical. BitCast is the only
224 // possibility.
225 CastInst *NC = new BitCastInst(
226 AI, AI->getType(), AI->getName()+".tmp", AfterAllocaInsertPt);
227 AI->replaceAllUsesWith(NC);
228 // Set the operand of the cast instruction back to the AllocaInst.
229 // Normally it's forbidden to replace a CastInst's operand because it
230 // could cause the opcode to reflect an illegal conversion. However,
231 // we're replacing it here with the same value it was constructed with.
232 // We do this because the above replaceAllUsesWith() clobbered the
233 // operand, but we want this one to remain.
234 NC->setOperand(0, AI);
235 }
Jim Grosbach8b818d72009-08-17 16:41:22 +0000236 }
237
238 // Finally, scan the code looking for instructions with bad live ranges.
239 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
240 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; ++II) {
241 // Ignore obvious cases we don't have to handle. In particular, most
242 // instructions either have no uses or only have a single use inside the
243 // current block. Ignore them quickly.
244 Instruction *Inst = II;
245 if (Inst->use_empty()) continue;
246 if (Inst->hasOneUse() &&
247 cast<Instruction>(Inst->use_back())->getParent() == BB &&
248 !isa<PHINode>(Inst->use_back())) continue;
249
250 // If this is an alloca in the entry block, it's not a real register
251 // value.
252 if (AllocaInst *AI = dyn_cast<AllocaInst>(Inst))
253 if (isa<ConstantInt>(AI->getArraySize()) && BB == F->begin())
254 continue;
255
256 // Avoid iterator invalidation by copying users to a temporary vector.
Jim Grosbach606f3d62009-08-17 21:40:03 +0000257 SmallVector<Instruction*,16> Users;
Jim Grosbach8b818d72009-08-17 16:41:22 +0000258 for (Value::use_iterator UI = Inst->use_begin(), E = Inst->use_end();
259 UI != E; ++UI) {
260 Instruction *User = cast<Instruction>(*UI);
261 if (User->getParent() != BB || isa<PHINode>(User))
262 Users.push_back(User);
263 }
264
Jim Grosbach8b818d72009-08-17 16:41:22 +0000265 // Find all of the blocks that this value is live in.
266 std::set<BasicBlock*> LiveBBs;
267 LiveBBs.insert(Inst->getParent());
268 while (!Users.empty()) {
269 Instruction *U = Users.back();
270 Users.pop_back();
271
272 if (!isa<PHINode>(U)) {
273 MarkBlocksLiveIn(U->getParent(), LiveBBs);
274 } else {
275 // Uses for a PHI node occur in their predecessor block.
276 PHINode *PN = cast<PHINode>(U);
277 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
278 if (PN->getIncomingValue(i) == Inst)
279 MarkBlocksLiveIn(PN->getIncomingBlock(i), LiveBBs);
280 }
281 }
282
283 // Now that we know all of the blocks that this thing is live in, see if
284 // it includes any of the unwind locations.
285 bool NeedsSpill = false;
286 for (unsigned i = 0, e = Invokes.size(); i != e; ++i) {
287 BasicBlock *UnwindBlock = Invokes[i]->getUnwindDest();
288 if (UnwindBlock != BB && LiveBBs.count(UnwindBlock)) {
289 NeedsSpill = true;
290 }
291 }
292
293 // If we decided we need a spill, do it.
Jim Grosbach956352e2010-06-16 18:45:08 +0000294 // FIXME: Spilling this way is overkill, as it forces all uses of
295 // the value to be reloaded from the stack slot, even those that aren't
296 // in the unwind blocks. We should be more selective.
Jim Grosbach8b818d72009-08-17 16:41:22 +0000297 if (NeedsSpill) {
298 ++NumSpilled;
299 DemoteRegToStack(*Inst, true);
300 }
301 }
302}
303
304bool SjLjEHPass::insertSjLjEHSupport(Function &F) {
Jim Grosbach606f3d62009-08-17 21:40:03 +0000305 SmallVector<ReturnInst*,16> Returns;
306 SmallVector<UnwindInst*,16> Unwinds;
307 SmallVector<InvokeInst*,16> Invokes;
Jim Grosbach8b818d72009-08-17 16:41:22 +0000308
309 // Look through the terminators of the basic blocks to find invokes, returns
Jim Grosbachb58a59b2010-03-04 22:07:46 +0000310 // and unwinds.
311 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
Jim Grosbach8b818d72009-08-17 16:41:22 +0000312 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
313 // Remember all return instructions in case we insert an invoke into this
314 // function.
315 Returns.push_back(RI);
316 } else if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
317 Invokes.push_back(II);
318 } else if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator())) {
319 Unwinds.push_back(UI);
320 }
Jim Grosbachb58a59b2010-03-04 22:07:46 +0000321 }
Jim Grosbach8b818d72009-08-17 16:41:22 +0000322 // If we don't have any invokes or unwinds, there's nothing to do.
323 if (Unwinds.empty() && Invokes.empty()) return false;
324
Jim Grosbach0798edd2010-05-27 23:49:24 +0000325 // Find the eh.selector.*, eh.exception and alloca calls.
326 //
327 // Remember any allocas() that aren't in the entry block, as the
328 // jmpbuf saved SP will need to be updated for them.
329 //
330 // We'll use the first eh.selector to determine the right personality
331 // function to use. For SJLJ, we always use the same personality for the
332 // whole function, not on a per-selector basis.
Jim Grosbacha235d132009-08-23 18:13:48 +0000333 // FIXME: That's a bit ugly. Better way?
334 SmallVector<CallInst*,16> EH_Selectors;
335 SmallVector<CallInst*,16> EH_Exceptions;
Jim Grosbach0798edd2010-05-27 23:49:24 +0000336 SmallVector<Instruction*,16> JmpbufUpdatePoints;
337 // 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 }
356 // If we don't have any eh.selector calls, we can't determine the personality
357 // function. Without a personality function, we can't process exceptions.
358 if (!PersonalityFn) return false;
359
Jim Grosbach8b818d72009-08-17 16:41:22 +0000360 NumInvokes += Invokes.size();
361 NumUnwinds += Unwinds.size();
362
Jim Grosbach8b818d72009-08-17 16:41:22 +0000363 if (!Invokes.empty()) {
364 // We have invokes, so we need to add register/unregister calls to get
365 // this function onto the global unwind stack.
Jim Grosbach0bb61c52009-08-31 01:35:03 +0000366 //
367 // First thing we need to do is scan the whole function for values that are
368 // live across unwind edges. Each value that is live across an unwind edge
369 // we spill into a stack location, guaranteeing that there is nothing live
370 // across the unwind edge. This process also splits all critical edges
371 // coming out of invoke's.
Jim Grosbach288694f2010-06-15 18:53:34 +0000372 splitLiveRangesAcrossInvokes(Invokes);
Jim Grosbach8b818d72009-08-17 16:41:22 +0000373
374 BasicBlock *EntryBB = F.begin();
375 // Create an alloca for the incoming jump buffer ptr and the new jump buffer
376 // that needs to be restored on all exits from the function. This is an
377 // alloca because the value needs to be added to the global context list.
378 unsigned Align = 4; // FIXME: Should be a TLI check?
379 AllocaInst *FunctionContext =
380 new AllocaInst(FunctionContextTy, 0, Align,
381 "fcn_context", F.begin()->begin());
382
383 Value *Idxs[2];
384 const Type *Int32Ty = Type::getInt32Ty(F.getContext());
385 Value *Zero = ConstantInt::get(Int32Ty, 0);
386 // We need to also keep around a reference to the call_site field
387 Idxs[0] = Zero;
388 Idxs[1] = ConstantInt::get(Int32Ty, 1);
389 CallSite = GetElementPtrInst::Create(FunctionContext, Idxs, Idxs+2,
390 "call_site",
391 EntryBB->getTerminator());
392
393 // The exception selector comes back in context->data[1]
394 Idxs[1] = ConstantInt::get(Int32Ty, 2);
395 Value *FCData = GetElementPtrInst::Create(FunctionContext, Idxs, Idxs+2,
396 "fc_data",
397 EntryBB->getTerminator());
398 Idxs[1] = ConstantInt::get(Int32Ty, 1);
399 Value *SelectorAddr = GetElementPtrInst::Create(FCData, Idxs, Idxs+2,
400 "exc_selector_gep",
401 EntryBB->getTerminator());
402 // The exception value comes back in context->data[0]
403 Idxs[1] = Zero;
404 Value *ExceptionAddr = GetElementPtrInst::Create(FCData, Idxs, Idxs+2,
405 "exception_gep",
406 EntryBB->getTerminator());
407
Jim Grosbach8b818d72009-08-17 16:41:22 +0000408 // The result of the eh.selector call will be replaced with a
409 // a reference to the selector value returned in the function
410 // context. We leave the selector itself so the EH analysis later
411 // 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);
416 }
417 // eh.exception calls are replaced with references to the proper
418 // location in the context. Unlike eh.selector, the eh.exception
419 // calls are removed entirely.
420 for (int i = 0, e = EH_Exceptions.size(); i < e; ++i) {
421 CallInst *I = EH_Exceptions[i];
422 // Possible for there to be duplicates, so check to make sure
423 // the instruction hasn't already been removed.
424 if (!I->getParent()) continue;
425 Value *Val = new LoadInst(ExceptionAddr, "exception", true, I);
Duncan Sandsac53a0b2009-10-06 15:40:36 +0000426 const Type *Ty = Type::getInt8PtrTy(F.getContext());
Jim Grosbach606f3d62009-08-17 21:40:03 +0000427 Val = CastInst::Create(Instruction::IntToPtr, Val, Ty, "", I);
Jim Grosbach8b818d72009-08-17 16:41:22 +0000428
429 I->replaceAllUsesWith(Val);
430 I->eraseFromParent();
431 }
432
Jim Grosbach8b818d72009-08-17 16:41:22 +0000433 // The entry block changes to have the eh.sjlj.setjmp, with a conditional
434 // branch to a dispatch block for non-zero returns. If we return normally,
435 // we're not handling an exception and just register the function context
436 // and continue.
437
438 // Create the dispatch block. The dispatch block is basically a big switch
439 // statement that goes to all of the invoke landing pads.
440 BasicBlock *DispatchBlock =
441 BasicBlock::Create(F.getContext(), "eh.sjlj.setjmp.catch", &F);
442
Jim Grosbache4ad3872010-10-19 23:27:08 +0000443 // Add a call to dispatch_setup at the start of the dispatch block. This
444 // is expanded to any target-specific setup that needs to be done.
445 Value *SetupArg =
446 CastInst::Create(Instruction::BitCast, FunctionContext,
447 Type::getInt8PtrTy(F.getContext()), "",
448 DispatchBlock);
449 CallInst::Create(DispatchSetupFn, SetupArg, "", DispatchBlock);
450
451 // Insert a load of the callsite in the dispatch block, and a switch on
452 // its value. By default, we go to a block that just does an unwind
453 // (which is the correct action for a standard call).
Jim Grosbach03825f82010-01-15 00:32:47 +0000454 BasicBlock *UnwindBlock =
455 BasicBlock::Create(F.getContext(), "unwindbb", &F);
Jim Grosbach8b818d72009-08-17 16:41:22 +0000456 Unwinds.push_back(new UnwindInst(F.getContext(), UnwindBlock));
457
458 Value *DispatchLoad = new LoadInst(CallSite, "invoke.num", true,
459 DispatchBlock);
460 SwitchInst *DispatchSwitch =
Jim Grosbach03825f82010-01-15 00:32:47 +0000461 SwitchInst::Create(DispatchLoad, UnwindBlock, Invokes.size(),
462 DispatchBlock);
Jim Grosbach8b818d72009-08-17 16:41:22 +0000463 // Split the entry block to insert the conditional branch for the setjmp.
464 BasicBlock *ContBlock = EntryBB->splitBasicBlock(EntryBB->getTerminator(),
465 "eh.sjlj.setjmp.cont");
466
467 // Populate the Function Context
468 // 1. LSDA address
469 // 2. Personality function address
Jim Grosbach0798edd2010-05-27 23:49:24 +0000470 // 3. jmpbuf (save SP, FP and call eh.sjlj.setjmp)
Jim Grosbach8b818d72009-08-17 16:41:22 +0000471
472 // LSDA address
473 Idxs[0] = Zero;
474 Idxs[1] = ConstantInt::get(Int32Ty, 4);
475 Value *LSDAFieldPtr =
476 GetElementPtrInst::Create(FunctionContext, Idxs, Idxs+2,
477 "lsda_gep",
478 EntryBB->getTerminator());
479 Value *LSDA = CallInst::Create(LSDAAddrFn, "lsda_addr",
480 EntryBB->getTerminator());
481 new StoreInst(LSDA, LSDAFieldPtr, true, EntryBB->getTerminator());
482
483 Idxs[1] = ConstantInt::get(Int32Ty, 3);
484 Value *PersonalityFieldPtr =
485 GetElementPtrInst::Create(FunctionContext, Idxs, Idxs+2,
486 "lsda_gep",
487 EntryBB->getTerminator());
488 new StoreInst(PersonalityFn, PersonalityFieldPtr, true,
489 EntryBB->getTerminator());
490
Jim Grosbach0798edd2010-05-27 23:49:24 +0000491 // Save the frame pointer.
Jim Grosbach8b818d72009-08-17 16:41:22 +0000492 Idxs[1] = ConstantInt::get(Int32Ty, 5);
Jim Grosbach0798edd2010-05-27 23:49:24 +0000493 Value *JBufPtr
Jim Grosbach8b818d72009-08-17 16:41:22 +0000494 = GetElementPtrInst::Create(FunctionContext, Idxs, Idxs+2,
495 "jbuf_gep",
496 EntryBB->getTerminator());
497 Idxs[1] = ConstantInt::get(Int32Ty, 0);
Jim Grosbach0798edd2010-05-27 23:49:24 +0000498 Value *FramePtr =
499 GetElementPtrInst::Create(JBufPtr, Idxs, Idxs+2, "jbuf_fp_gep",
Jim Grosbach8b818d72009-08-17 16:41:22 +0000500 EntryBB->getTerminator());
501
502 Value *Val = CallInst::Create(FrameAddrFn,
503 ConstantInt::get(Int32Ty, 0),
504 "fp",
505 EntryBB->getTerminator());
Jim Grosbach0798edd2010-05-27 23:49:24 +0000506 new StoreInst(Val, FramePtr, true, EntryBB->getTerminator());
507
508 // Save the stack pointer.
509 Idxs[1] = ConstantInt::get(Int32Ty, 2);
510 Value *StackPtr =
511 GetElementPtrInst::Create(JBufPtr, Idxs, Idxs+2, "jbuf_sp_gep",
512 EntryBB->getTerminator());
513
514 Val = CallInst::Create(StackAddrFn, "sp", EntryBB->getTerminator());
515 new StoreInst(Val, StackPtr, true, EntryBB->getTerminator());
516
517 // Call the setjmp instrinsic. It fills in the rest of the jmpbuf.
Jim Grosbach8b818d72009-08-17 16:41:22 +0000518 Value *SetjmpArg =
Jim Grosbach0798edd2010-05-27 23:49:24 +0000519 CastInst::Create(Instruction::BitCast, JBufPtr,
Duncan Sandsac53a0b2009-10-06 15:40:36 +0000520 Type::getInt8PtrTy(F.getContext()), "",
521 EntryBB->getTerminator());
Jim Grosbach8b818d72009-08-17 16:41:22 +0000522 Value *DispatchVal = CallInst::Create(BuiltinSetjmpFn, SetjmpArg,
523 "dispatch",
524 EntryBB->getTerminator());
Jim Grosbach0798edd2010-05-27 23:49:24 +0000525 // check the return value of the setjmp. non-zero goes to dispatcher.
Jim Grosbach8b818d72009-08-17 16:41:22 +0000526 Value *IsNormal = new ICmpInst(EntryBB->getTerminator(),
527 ICmpInst::ICMP_EQ, DispatchVal, Zero,
528 "notunwind");
529 // Nuke the uncond branch.
530 EntryBB->getTerminator()->eraseFromParent();
531
532 // Put in a new condbranch in its place.
533 BranchInst::Create(ContBlock, DispatchBlock, IsNormal, EntryBB);
534
535 // Register the function context and make sure it's known to not throw
536 CallInst *Register =
537 CallInst::Create(RegisterFn, FunctionContext, "",
538 ContBlock->getTerminator());
539 Register->setDoesNotThrow();
540
Jim Grosbach0bb61c52009-08-31 01:35:03 +0000541 // At this point, we are all set up, update the invoke instructions
Jim Grosbach8b818d72009-08-17 16:41:22 +0000542 // to mark their call_site values, and fill in the dispatch switch
543 // accordingly.
Jim Grosbachf38a33c2010-01-21 20:10:22 +0000544 for (unsigned i = 0, e = Invokes.size(); i != e; ++i)
Jim Grosbach0bb61c52009-08-31 01:35:03 +0000545 markInvokeCallSite(Invokes[i], i+1, CallSite, DispatchSwitch);
Jim Grosbach8b818d72009-08-17 16:41:22 +0000546
Jim Grosbachb58a59b2010-03-04 22:07:46 +0000547 // Mark call instructions that aren't nounwind as no-action
548 // (call_site == -1). Skip the entry block, as prior to then, no function
549 // context has been created for this function and any unexpected exceptions
550 // thrown will go directly to the caller's context, which is what we want
551 // anyway, so no need to do anything here.
552 for (Function::iterator BB = F.begin(), E = F.end(); ++BB != E;) {
553 for (BasicBlock::iterator I = BB->begin(), end = BB->end(); I != end; ++I)
554 if (CallInst *CI = dyn_cast<CallInst>(I)) {
555 // Ignore calls to the EH builtins (eh.selector, eh.exception)
556 Constant *Callee = CI->getCalledFunction();
557 if (Callee != SelectorFn && Callee != ExceptionFn
558 && !CI->doesNotThrow())
559 insertCallSiteStore(CI, -1, CallSite);
Jim Grosbach8b818d72009-08-17 16:41:22 +0000560 }
Jim Grosbachb58a59b2010-03-04 22:07:46 +0000561 }
Jim Grosbach8b818d72009-08-17 16:41:22 +0000562
563 // Replace all unwinds with a branch to the unwind handler.
564 // ??? Should this ever happen with sjlj exceptions?
565 for (unsigned i = 0, e = Unwinds.size(); i != e; ++i) {
566 BranchInst::Create(UnwindBlock, Unwinds[i]);
567 Unwinds[i]->eraseFromParent();
568 }
569
Jim Grosbach0798edd2010-05-27 23:49:24 +0000570 // Following any allocas not in the entry block, update the saved SP
571 // in the jmpbuf to the new value.
572 for (unsigned i = 0, e = JmpbufUpdatePoints.size(); i != e; ++i) {
573 Instruction *AI = JmpbufUpdatePoints[i];
574 Instruction *StackAddr = CallInst::Create(StackAddrFn, "sp");
575 StackAddr->insertAfter(AI);
576 Instruction *StoreStackAddr = new StoreInst(StackAddr, StackPtr, true);
577 StoreStackAddr->insertAfter(StackAddr);
578 }
579
Jim Grosbach8b818d72009-08-17 16:41:22 +0000580 // Finally, for any returns from this function, if this function contains an
581 // invoke, add a call to unregister the function context.
582 for (unsigned i = 0, e = Returns.size(); i != e; ++i)
583 CallInst::Create(UnregisterFn, FunctionContext, "", Returns[i]);
584 }
585
586 return true;
587}
588
589bool SjLjEHPass::runOnFunction(Function &F) {
590 bool Res = insertSjLjEHSupport(F);
591 return Res;
592}