blob: 510c92f301225c066dd42e8df6604d5c19a209cf [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
Chris Lattnerdb125cf2011-07-18 04:54:35 +000043 Type *FunctionContextTy;
Jim Grosbach8b818d72009-08-17 16:41:22 +000044 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
Jay Foad5fdd6c82011-07-12 14:06:48 +000090 Type *VoidPtrTy = Type::getInt8PtrTy(M.getContext());
91 Type *Int32Ty = Type::getInt32Ty(M.getContext());
Jim Grosbach8b818d72009-08-17 16:41:22 +000092 FunctionContextTy =
Chris Lattnerb2318662011-06-18 22:48:56 +000093 StructType::get(VoidPtrTy, // __prev
Jim Grosbach8b818d72009-08-17 16:41:22 +000094 Int32Ty, // call_site
95 ArrayType::get(Int32Ty, 4), // __data
96 VoidPtrTy, // __personality
97 VoidPtrTy, // __lsda
98 ArrayType::get(VoidPtrTy, 5), // __jbuf
99 NULL);
100 RegisterFn = M.getOrInsertFunction("_Unwind_SjLj_Register",
101 Type::getVoidTy(M.getContext()),
102 PointerType::getUnqual(FunctionContextTy),
103 (Type *)0);
104 UnregisterFn =
105 M.getOrInsertFunction("_Unwind_SjLj_Unregister",
106 Type::getVoidTy(M.getContext()),
107 PointerType::getUnqual(FunctionContextTy),
108 (Type *)0);
Jim Grosbach8b818d72009-08-17 16:41:22 +0000109 FrameAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::frameaddress);
Jim Grosbach0798edd2010-05-27 23:49:24 +0000110 StackAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::stacksave);
111 StackRestoreFn = Intrinsic::getDeclaration(&M, Intrinsic::stackrestore);
Jim Grosbach8b818d72009-08-17 16:41:22 +0000112 BuiltinSetjmpFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_setjmp);
113 LSDAAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_lsda);
Duncan Sandsb01bbdc2009-10-14 16:11:37 +0000114 SelectorFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_selector);
Jim Grosbach8b818d72009-08-17 16:41:22 +0000115 ExceptionFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_exception);
Jim Grosbachca752c92010-01-28 01:45:32 +0000116 CallSiteFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_callsite);
Jim Grosbache4ad3872010-10-19 23:27:08 +0000117 DispatchSetupFn
118 = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_dispatch_setup);
Jim Grosbacha235d132009-08-23 18:13:48 +0000119 PersonalityFn = 0;
Jim Grosbach8b818d72009-08-17 16:41:22 +0000120
121 return true;
122}
123
Jim Grosbachb58a59b2010-03-04 22:07:46 +0000124/// insertCallSiteStore - Insert a store of the call-site value to the
125/// function context
126void SjLjEHPass::insertCallSiteStore(Instruction *I, int Number,
127 Value *CallSite) {
128 ConstantInt *CallSiteNoC = ConstantInt::get(Type::getInt32Ty(I->getContext()),
129 Number);
130 // Insert a store of the call-site number
131 new StoreInst(CallSiteNoC, CallSite, true, I); // volatile
132}
133
Jim Grosbach8b818d72009-08-17 16:41:22 +0000134/// markInvokeCallSite - Insert code to mark the call_site for this invoke
Jim Grosbachb58a59b2010-03-04 22:07:46 +0000135void SjLjEHPass::markInvokeCallSite(InvokeInst *II, int InvokeNo,
Jim Grosbach0bb61c52009-08-31 01:35:03 +0000136 Value *CallSite,
137 SwitchInst *CatchSwitch) {
Jim Grosbach8b818d72009-08-17 16:41:22 +0000138 ConstantInt *CallSiteNoC= ConstantInt::get(Type::getInt32Ty(II->getContext()),
Jim Grosbachb58a59b2010-03-04 22:07:46 +0000139 InvokeNo);
Jim Grosbach0bb61c52009-08-31 01:35:03 +0000140 // The runtime comes back to the dispatcher with the call_site - 1 in
141 // the context. Odd, but there it is.
142 ConstantInt *SwitchValC = ConstantInt::get(Type::getInt32Ty(II->getContext()),
143 InvokeNo - 1);
Jim Grosbach8b818d72009-08-17 16:41:22 +0000144
145 // If the unwind edge has phi nodes, split the edge.
146 if (isa<PHINode>(II->getUnwindDest()->begin())) {
147 SplitCriticalEdge(II, 1, this);
148
149 // If there are any phi nodes left, they must have a single predecessor.
150 while (PHINode *PN = dyn_cast<PHINode>(II->getUnwindDest()->begin())) {
151 PN->replaceAllUsesWith(PN->getIncomingValue(0));
152 PN->eraseFromParent();
153 }
154 }
155
Jim Grosbachb58a59b2010-03-04 22:07:46 +0000156 // Insert the store of the call site value
157 insertCallSiteStore(II, InvokeNo, CallSite);
158
159 // Record the call site value for the back end so it stays associated with
160 // the invoke.
Jim Grosbachca752c92010-01-28 01:45:32 +0000161 CallInst::Create(CallSiteFn, CallSiteNoC, "", II);
Jim Grosbach8b818d72009-08-17 16:41:22 +0000162
Jim Grosbach0bb61c52009-08-31 01:35:03 +0000163 // Add a switch case to our unwind block.
164 CatchSwitch->addCase(SwitchValC, II->getUnwindDest());
Jim Grosbachca752c92010-01-28 01:45:32 +0000165 // We still want this to look like an invoke so we emit the LSDA properly,
166 // so we don't transform the invoke into a call here.
Jim Grosbach8b818d72009-08-17 16:41:22 +0000167}
168
169/// MarkBlocksLiveIn - Insert BB and all of its predescessors into LiveBBs until
170/// we reach blocks we've already seen.
171static void MarkBlocksLiveIn(BasicBlock *BB, std::set<BasicBlock*> &LiveBBs) {
172 if (!LiveBBs.insert(BB).second) return; // already been here.
173
174 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
175 MarkBlocksLiveIn(*PI, LiveBBs);
176}
177
Jim Grosbach606f3d62009-08-17 21:40:03 +0000178/// splitLiveRangesAcrossInvokes - Each value that is live across an unwind edge
179/// we spill into a stack location, guaranteeing that there is nothing live
180/// across the unwind edge. This process also splits all critical edges
181/// coming out of invoke's.
Jim Grosbach2f3257e2010-06-01 18:06:35 +0000182/// FIXME: Move this function to a common utility file (Local.cpp?) so
183/// both SjLj and LowerInvoke can use it.
Jim Grosbach8b818d72009-08-17 16:41:22 +0000184void SjLjEHPass::
Jim Grosbach288694f2010-06-15 18:53:34 +0000185splitLiveRangesAcrossInvokes(SmallVector<InvokeInst*,16> &Invokes) {
Jim Grosbach8b818d72009-08-17 16:41:22 +0000186 // First step, split all critical edges from invoke instructions.
187 for (unsigned i = 0, e = Invokes.size(); i != e; ++i) {
188 InvokeInst *II = Invokes[i];
189 SplitCriticalEdge(II, 0, this);
190 SplitCriticalEdge(II, 1, this);
191 assert(!isa<PHINode>(II->getNormalDest()) &&
192 !isa<PHINode>(II->getUnwindDest()) &&
193 "critical edge splitting left single entry phi nodes?");
194 }
195
196 Function *F = Invokes.back()->getParent()->getParent();
197
198 // To avoid having to handle incoming arguments specially, we lower each arg
199 // to a copy instruction in the entry block. This ensures that the argument
200 // value itself cannot be live across the entry block.
201 BasicBlock::iterator AfterAllocaInsertPt = F->begin()->begin();
202 while (isa<AllocaInst>(AfterAllocaInsertPt) &&
203 isa<ConstantInt>(cast<AllocaInst>(AfterAllocaInsertPt)->getArraySize()))
204 ++AfterAllocaInsertPt;
205 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
206 AI != E; ++AI) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000207 Type *Ty = AI->getType();
Jim Grosbache70fc8e2010-06-30 22:20:38 +0000208 // Aggregate types can't be cast, but are legal argument types, so we have
Jim Grosbachdc58b252010-06-01 18:04:09 +0000209 // to handle them differently. We use an extract/insert pair as a
210 // lightweight method to achieve the same goal.
Jim Grosbache70fc8e2010-06-30 22:20:38 +0000211 if (isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<VectorType>(Ty)) {
212 Instruction *EI = ExtractValueInst::Create(AI, 0, "",AfterAllocaInsertPt);
Jim Grosbachdc58b252010-06-01 18:04:09 +0000213 Instruction *NI = InsertValueInst::Create(AI, EI, 0);
214 NI->insertAfter(EI);
215 AI->replaceAllUsesWith(NI);
Jim Grosbache70fc8e2010-06-30 22:20:38 +0000216 // Set the operand of the instructions back to the AllocaInst.
Jim Grosbachdc58b252010-06-01 18:04:09 +0000217 EI->setOperand(0, AI);
218 NI->setOperand(0, AI);
219 } else {
220 // This is always a no-op cast because we're casting AI to AI->getType()
221 // so src and destination types are identical. BitCast is the only
222 // possibility.
223 CastInst *NC = new BitCastInst(
224 AI, AI->getType(), AI->getName()+".tmp", AfterAllocaInsertPt);
225 AI->replaceAllUsesWith(NC);
226 // Set the operand of the cast instruction back to the AllocaInst.
227 // Normally it's forbidden to replace a CastInst's operand because it
228 // could cause the opcode to reflect an illegal conversion. However,
229 // we're replacing it here with the same value it was constructed with.
230 // We do this because the above replaceAllUsesWith() clobbered the
231 // operand, but we want this one to remain.
232 NC->setOperand(0, AI);
233 }
Jim Grosbach8b818d72009-08-17 16:41:22 +0000234 }
235
236 // Finally, scan the code looking for instructions with bad live ranges.
237 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
238 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; ++II) {
239 // Ignore obvious cases we don't have to handle. In particular, most
240 // instructions either have no uses or only have a single use inside the
241 // current block. Ignore them quickly.
242 Instruction *Inst = II;
243 if (Inst->use_empty()) continue;
244 if (Inst->hasOneUse() &&
245 cast<Instruction>(Inst->use_back())->getParent() == BB &&
246 !isa<PHINode>(Inst->use_back())) continue;
247
248 // If this is an alloca in the entry block, it's not a real register
249 // value.
250 if (AllocaInst *AI = dyn_cast<AllocaInst>(Inst))
251 if (isa<ConstantInt>(AI->getArraySize()) && BB == F->begin())
252 continue;
253
254 // Avoid iterator invalidation by copying users to a temporary vector.
Jim Grosbach606f3d62009-08-17 21:40:03 +0000255 SmallVector<Instruction*,16> Users;
Jim Grosbach8b818d72009-08-17 16:41:22 +0000256 for (Value::use_iterator UI = Inst->use_begin(), E = Inst->use_end();
257 UI != E; ++UI) {
258 Instruction *User = cast<Instruction>(*UI);
259 if (User->getParent() != BB || isa<PHINode>(User))
260 Users.push_back(User);
261 }
262
Jim Grosbach8b818d72009-08-17 16:41:22 +0000263 // Find all of the blocks that this value is live in.
264 std::set<BasicBlock*> LiveBBs;
265 LiveBBs.insert(Inst->getParent());
266 while (!Users.empty()) {
267 Instruction *U = Users.back();
268 Users.pop_back();
269
270 if (!isa<PHINode>(U)) {
271 MarkBlocksLiveIn(U->getParent(), LiveBBs);
272 } else {
273 // Uses for a PHI node occur in their predecessor block.
274 PHINode *PN = cast<PHINode>(U);
275 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
276 if (PN->getIncomingValue(i) == Inst)
277 MarkBlocksLiveIn(PN->getIncomingBlock(i), LiveBBs);
278 }
279 }
280
281 // Now that we know all of the blocks that this thing is live in, see if
282 // it includes any of the unwind locations.
283 bool NeedsSpill = false;
284 for (unsigned i = 0, e = Invokes.size(); i != e; ++i) {
285 BasicBlock *UnwindBlock = Invokes[i]->getUnwindDest();
286 if (UnwindBlock != BB && LiveBBs.count(UnwindBlock)) {
287 NeedsSpill = true;
288 }
289 }
290
291 // If we decided we need a spill, do it.
Jim Grosbach956352e2010-06-16 18:45:08 +0000292 // FIXME: Spilling this way is overkill, as it forces all uses of
293 // the value to be reloaded from the stack slot, even those that aren't
294 // in the unwind blocks. We should be more selective.
Jim Grosbach8b818d72009-08-17 16:41:22 +0000295 if (NeedsSpill) {
296 ++NumSpilled;
297 DemoteRegToStack(*Inst, true);
298 }
299 }
300}
301
302bool SjLjEHPass::insertSjLjEHSupport(Function &F) {
Jim Grosbach606f3d62009-08-17 21:40:03 +0000303 SmallVector<ReturnInst*,16> Returns;
304 SmallVector<UnwindInst*,16> Unwinds;
305 SmallVector<InvokeInst*,16> Invokes;
Jim Grosbach8b818d72009-08-17 16:41:22 +0000306
307 // Look through the terminators of the basic blocks to find invokes, returns
Jim Grosbachb58a59b2010-03-04 22:07:46 +0000308 // and unwinds.
309 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
Jim Grosbach8b818d72009-08-17 16:41:22 +0000310 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
311 // Remember all return instructions in case we insert an invoke into this
312 // function.
313 Returns.push_back(RI);
314 } else if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
315 Invokes.push_back(II);
316 } else if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator())) {
317 Unwinds.push_back(UI);
318 }
Jim Grosbachb58a59b2010-03-04 22:07:46 +0000319 }
Bill Wendling8d90b712011-01-07 02:54:45 +0000320
321 NumInvokes += Invokes.size();
322 NumUnwinds += Unwinds.size();
323
324 // If we don't have any invokes, there's nothing to do.
325 if (Invokes.empty()) return false;
Jim Grosbach8b818d72009-08-17 16:41:22 +0000326
Jim Grosbach0798edd2010-05-27 23:49:24 +0000327 // Find the eh.selector.*, eh.exception and alloca calls.
328 //
329 // Remember any allocas() that aren't in the entry block, as the
330 // jmpbuf saved SP will need to be updated for them.
331 //
332 // We'll use the first eh.selector to determine the right personality
333 // function to use. For SJLJ, we always use the same personality for the
334 // whole function, not on a per-selector basis.
Jim Grosbacha235d132009-08-23 18:13:48 +0000335 // FIXME: That's a bit ugly. Better way?
336 SmallVector<CallInst*,16> EH_Selectors;
337 SmallVector<CallInst*,16> EH_Exceptions;
Jim Grosbach0798edd2010-05-27 23:49:24 +0000338 SmallVector<Instruction*,16> JmpbufUpdatePoints;
Bill Wendling8d90b712011-01-07 02:54:45 +0000339
Jim Grosbach0798edd2010-05-27 23:49:24 +0000340 // Note: Skip the entry block since there's nothing there that interests
341 // us. eh.selector and eh.exception shouldn't ever be there, and we
342 // want to disregard any allocas that are there.
343 for (Function::iterator BB = F.begin(), E = F.end(); ++BB != E;) {
Jim Grosbacha235d132009-08-23 18:13:48 +0000344 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
345 if (CallInst *CI = dyn_cast<CallInst>(I)) {
Duncan Sandsb01bbdc2009-10-14 16:11:37 +0000346 if (CI->getCalledFunction() == SelectorFn) {
Gabor Greif45c097f2010-06-25 09:36:23 +0000347 if (!PersonalityFn) PersonalityFn = CI->getArgOperand(1);
Jim Grosbacha235d132009-08-23 18:13:48 +0000348 EH_Selectors.push_back(CI);
349 } else if (CI->getCalledFunction() == ExceptionFn) {
350 EH_Exceptions.push_back(CI);
Jim Grosbach0798edd2010-05-27 23:49:24 +0000351 } else if (CI->getCalledFunction() == StackRestoreFn) {
352 JmpbufUpdatePoints.push_back(CI);
Jim Grosbacha235d132009-08-23 18:13:48 +0000353 }
Jim Grosbach0798edd2010-05-27 23:49:24 +0000354 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) {
355 JmpbufUpdatePoints.push_back(AI);
Jim Grosbacha235d132009-08-23 18:13:48 +0000356 }
357 }
358 }
Bill Wendling8d90b712011-01-07 02:54:45 +0000359
Jim Grosbacha235d132009-08-23 18:13:48 +0000360 // If we don't have any eh.selector calls, we can't determine the personality
361 // function. Without a personality function, we can't process exceptions.
362 if (!PersonalityFn) return false;
363
Bill Wendling8d90b712011-01-07 02:54:45 +0000364 // We have invokes, so we need to add register/unregister calls to get this
365 // function onto the global unwind stack.
366 //
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 we
369 // spill into a stack location, guaranteeing that there is nothing live across
370 // the unwind edge. This process also splits all critical edges coming out of
371 // invoke's.
372 splitLiveRangesAcrossInvokes(Invokes);
Jim Grosbach8b818d72009-08-17 16:41:22 +0000373
Bill Wendling8d90b712011-01-07 02:54:45 +0000374 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());
Jim Grosbach8b818d72009-08-17 16:41:22 +0000382
Bill Wendling8d90b712011-01-07 02:54:45 +0000383 Value *Idxs[2];
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000384 Type *Int32Ty = Type::getInt32Ty(F.getContext());
Bill Wendling8d90b712011-01-07 02:54:45 +0000385 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);
Jay Foada9203102011-07-25 09:48:08 +0000389 CallSite = GetElementPtrInst::Create(FunctionContext, Idxs, "call_site",
Bill Wendling8d90b712011-01-07 02:54:45 +0000390 EntryBB->getTerminator());
Jim Grosbach8b818d72009-08-17 16:41:22 +0000391
Bill Wendling8d90b712011-01-07 02:54:45 +0000392 // The exception selector comes back in context->data[1]
393 Idxs[1] = ConstantInt::get(Int32Ty, 2);
Jay Foada9203102011-07-25 09:48:08 +0000394 Value *FCData = GetElementPtrInst::Create(FunctionContext, Idxs, "fc_data",
Bill Wendling8d90b712011-01-07 02:54:45 +0000395 EntryBB->getTerminator());
396 Idxs[1] = ConstantInt::get(Int32Ty, 1);
Jay Foada9203102011-07-25 09:48:08 +0000397 Value *SelectorAddr = GetElementPtrInst::Create(FCData, Idxs,
Bill Wendling8d90b712011-01-07 02:54:45 +0000398 "exc_selector_gep",
399 EntryBB->getTerminator());
400 // The exception value comes back in context->data[0]
401 Idxs[1] = Zero;
Jay Foada9203102011-07-25 09:48:08 +0000402 Value *ExceptionAddr = GetElementPtrInst::Create(FCData, Idxs,
Bill Wendling8d90b712011-01-07 02:54:45 +0000403 "exception_gep",
404 EntryBB->getTerminator());
Jim Grosbach8b818d72009-08-17 16:41:22 +0000405
Bill Wendling8d90b712011-01-07 02:54:45 +0000406 // The result of the eh.selector call will be replaced with a a reference to
407 // the selector value returned in the function context. We leave the selector
408 // itself so the EH analysis later can use it.
409 for (int i = 0, e = EH_Selectors.size(); i < e; ++i) {
410 CallInst *I = EH_Selectors[i];
411 Value *SelectorVal = new LoadInst(SelectorAddr, "select_val", true, I);
412 I->replaceAllUsesWith(SelectorVal);
Jim Grosbach8b818d72009-08-17 16:41:22 +0000413 }
414
Bill Wendling8d90b712011-01-07 02:54:45 +0000415 // eh.exception calls are replaced with references to the proper location in
416 // the context. Unlike eh.selector, the eh.exception calls are removed
417 // entirely.
418 for (int i = 0, e = EH_Exceptions.size(); i < e; ++i) {
419 CallInst *I = EH_Exceptions[i];
420 // Possible for there to be duplicates, so check to make sure the
421 // instruction hasn't already been removed.
422 if (!I->getParent()) continue;
423 Value *Val = new LoadInst(ExceptionAddr, "exception", true, I);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000424 Type *Ty = Type::getInt8PtrTy(F.getContext());
Bill Wendling8d90b712011-01-07 02:54:45 +0000425 Val = CastInst::Create(Instruction::IntToPtr, Val, Ty, "", I);
426
427 I->replaceAllUsesWith(Val);
428 I->eraseFromParent();
429 }
430
431 // The entry block changes to have the eh.sjlj.setjmp, with a conditional
432 // branch to a dispatch block for non-zero returns. If we return normally,
433 // we're not handling an exception and just register the function context and
434 // continue.
435
436 // Create the dispatch block. The dispatch block is basically a big switch
437 // statement that goes to all of the invoke landing pads.
438 BasicBlock *DispatchBlock =
439 BasicBlock::Create(F.getContext(), "eh.sjlj.setjmp.catch", &F);
440
Bill Wendling8d90b712011-01-07 02:54:45 +0000441 // Insert a load of the callsite in the dispatch block, and a switch on its
Bill Wendlingcc885952011-04-11 21:32:34 +0000442 // value. By default, we issue a trap statement.
443 BasicBlock *TrapBlock =
444 BasicBlock::Create(F.getContext(), "trapbb", &F);
445 CallInst::Create(Intrinsic::getDeclaration(F.getParent(), Intrinsic::trap),
446 "", TrapBlock);
447 new UnreachableInst(F.getContext(), TrapBlock);
Bill Wendling8d90b712011-01-07 02:54:45 +0000448
449 Value *DispatchLoad = new LoadInst(CallSite, "invoke.num", true,
450 DispatchBlock);
451 SwitchInst *DispatchSwitch =
Bill Wendlingcc885952011-04-11 21:32:34 +0000452 SwitchInst::Create(DispatchLoad, TrapBlock, Invokes.size(),
Bill Wendling8d90b712011-01-07 02:54:45 +0000453 DispatchBlock);
454 // Split the entry block to insert the conditional branch for the setjmp.
455 BasicBlock *ContBlock = EntryBB->splitBasicBlock(EntryBB->getTerminator(),
456 "eh.sjlj.setjmp.cont");
457
458 // Populate the Function Context
459 // 1. LSDA address
460 // 2. Personality function address
461 // 3. jmpbuf (save SP, FP and call eh.sjlj.setjmp)
462
463 // LSDA address
464 Idxs[0] = Zero;
465 Idxs[1] = ConstantInt::get(Int32Ty, 4);
466 Value *LSDAFieldPtr =
Jay Foada9203102011-07-25 09:48:08 +0000467 GetElementPtrInst::Create(FunctionContext, Idxs, "lsda_gep",
Bill Wendling8d90b712011-01-07 02:54:45 +0000468 EntryBB->getTerminator());
469 Value *LSDA = CallInst::Create(LSDAAddrFn, "lsda_addr",
470 EntryBB->getTerminator());
471 new StoreInst(LSDA, LSDAFieldPtr, true, EntryBB->getTerminator());
472
473 Idxs[1] = ConstantInt::get(Int32Ty, 3);
474 Value *PersonalityFieldPtr =
Jay Foada9203102011-07-25 09:48:08 +0000475 GetElementPtrInst::Create(FunctionContext, Idxs, "lsda_gep",
Bill Wendling8d90b712011-01-07 02:54:45 +0000476 EntryBB->getTerminator());
477 new StoreInst(PersonalityFn, PersonalityFieldPtr, true,
478 EntryBB->getTerminator());
479
480 // Save the frame pointer.
481 Idxs[1] = ConstantInt::get(Int32Ty, 5);
482 Value *JBufPtr
Jay Foada9203102011-07-25 09:48:08 +0000483 = GetElementPtrInst::Create(FunctionContext, Idxs, "jbuf_gep",
Bill Wendling8d90b712011-01-07 02:54:45 +0000484 EntryBB->getTerminator());
485 Idxs[1] = ConstantInt::get(Int32Ty, 0);
486 Value *FramePtr =
Jay Foada9203102011-07-25 09:48:08 +0000487 GetElementPtrInst::Create(JBufPtr, Idxs, "jbuf_fp_gep",
Bill Wendling8d90b712011-01-07 02:54:45 +0000488 EntryBB->getTerminator());
489
490 Value *Val = CallInst::Create(FrameAddrFn,
491 ConstantInt::get(Int32Ty, 0),
492 "fp",
493 EntryBB->getTerminator());
494 new StoreInst(Val, FramePtr, true, EntryBB->getTerminator());
495
496 // Save the stack pointer.
497 Idxs[1] = ConstantInt::get(Int32Ty, 2);
498 Value *StackPtr =
Jay Foada9203102011-07-25 09:48:08 +0000499 GetElementPtrInst::Create(JBufPtr, Idxs, "jbuf_sp_gep",
Bill Wendling8d90b712011-01-07 02:54:45 +0000500 EntryBB->getTerminator());
501
502 Val = CallInst::Create(StackAddrFn, "sp", EntryBB->getTerminator());
503 new StoreInst(Val, StackPtr, true, EntryBB->getTerminator());
504
505 // Call the setjmp instrinsic. It fills in the rest of the jmpbuf.
506 Value *SetjmpArg =
507 CastInst::Create(Instruction::BitCast, JBufPtr,
508 Type::getInt8PtrTy(F.getContext()), "",
509 EntryBB->getTerminator());
510 Value *DispatchVal = CallInst::Create(BuiltinSetjmpFn, SetjmpArg,
511 "dispatch",
512 EntryBB->getTerminator());
Bill Wendlingf05b1dc2011-04-05 01:37:43 +0000513
514 // Add a call to dispatch_setup after the setjmp call. This is expanded to any
515 // target-specific setup that needs to be done.
Bill Wendling61512ba2011-05-11 01:11:55 +0000516 CallInst::Create(DispatchSetupFn, DispatchVal, "", EntryBB->getTerminator());
Bill Wendlingf05b1dc2011-04-05 01:37:43 +0000517
Bill Wendling8d90b712011-01-07 02:54:45 +0000518 // check the return value of the setjmp. non-zero goes to dispatcher.
519 Value *IsNormal = new ICmpInst(EntryBB->getTerminator(),
520 ICmpInst::ICMP_EQ, DispatchVal, Zero,
521 "notunwind");
522 // Nuke the uncond branch.
523 EntryBB->getTerminator()->eraseFromParent();
524
525 // Put in a new condbranch in its place.
526 BranchInst::Create(ContBlock, DispatchBlock, IsNormal, EntryBB);
527
528 // Register the function context and make sure it's known to not throw
529 CallInst *Register =
530 CallInst::Create(RegisterFn, FunctionContext, "",
531 ContBlock->getTerminator());
532 Register->setDoesNotThrow();
533
534 // At this point, we are all set up, update the invoke instructions to mark
535 // their call_site values, and fill in the dispatch switch accordingly.
536 for (unsigned i = 0, e = Invokes.size(); i != e; ++i)
537 markInvokeCallSite(Invokes[i], i+1, CallSite, DispatchSwitch);
538
539 // Mark call instructions that aren't nounwind as no-action (call_site ==
540 // -1). Skip the entry block, as prior to then, no function context has been
541 // created for this function and any unexpected exceptions thrown will go
542 // directly to the caller's context, which is what we want anyway, so no need
543 // to do anything here.
544 for (Function::iterator BB = F.begin(), E = F.end(); ++BB != E;) {
545 for (BasicBlock::iterator I = BB->begin(), end = BB->end(); I != end; ++I)
546 if (CallInst *CI = dyn_cast<CallInst>(I)) {
547 // Ignore calls to the EH builtins (eh.selector, eh.exception)
548 Constant *Callee = CI->getCalledFunction();
549 if (Callee != SelectorFn && Callee != ExceptionFn
550 && !CI->doesNotThrow())
551 insertCallSiteStore(CI, -1, CallSite);
552 }
553 }
554
555 // Replace all unwinds with a branch to the unwind handler.
556 // ??? Should this ever happen with sjlj exceptions?
557 for (unsigned i = 0, e = Unwinds.size(); i != e; ++i) {
Bill Wendlingcc885952011-04-11 21:32:34 +0000558 BranchInst::Create(TrapBlock, Unwinds[i]);
Bill Wendling8d90b712011-01-07 02:54:45 +0000559 Unwinds[i]->eraseFromParent();
560 }
561
562 // Following any allocas not in the entry block, update the saved SP in the
563 // jmpbuf to the new value.
564 for (unsigned i = 0, e = JmpbufUpdatePoints.size(); i != e; ++i) {
565 Instruction *AI = JmpbufUpdatePoints[i];
566 Instruction *StackAddr = CallInst::Create(StackAddrFn, "sp");
567 StackAddr->insertAfter(AI);
568 Instruction *StoreStackAddr = new StoreInst(StackAddr, StackPtr, true);
569 StoreStackAddr->insertAfter(StackAddr);
570 }
571
572 // Finally, for any returns from this function, if this function contains an
573 // invoke, add a call to unregister the function context.
574 for (unsigned i = 0, e = Returns.size(); i != e; ++i)
575 CallInst::Create(UnregisterFn, FunctionContext, "", Returns[i]);
576
Jim Grosbach8b818d72009-08-17 16:41:22 +0000577 return true;
578}
579
580bool SjLjEHPass::runOnFunction(Function &F) {
581 bool Res = insertSjLjEHSupport(F);
582 return Res;
583}