blob: e94d4d35381240100245596e444e907e15389b46 [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"
25#include "llvm/Transforms/Utils/BasicBlockUtils.h"
26#include "llvm/Transforms/Utils/Local.h"
27#include "llvm/ADT/Statistic.h"
Jim Grosbach606f3d62009-08-17 21:40:03 +000028#include "llvm/ADT/SmallVector.h"
Jim Grosbach8b818d72009-08-17 16:41:22 +000029#include "llvm/Support/CommandLine.h"
Jim Grosbach8b818d72009-08-17 16:41:22 +000030#include "llvm/Support/Debug.h"
31#include "llvm/Support/raw_ostream.h"
32#include "llvm/Target/TargetLowering.h"
Jim Grosbach8b818d72009-08-17 16:41:22 +000033using namespace llvm;
34
35STATISTIC(NumInvokes, "Number of invokes replaced");
36STATISTIC(NumUnwinds, "Number of unwinds replaced");
37STATISTIC(NumSpilled, "Number of registers live across unwind edges");
38
39namespace {
Nick Lewycky6726b6d2009-10-25 06:33:48 +000040 class SjLjEHPass : public FunctionPass {
Jim Grosbach8b818d72009-08-17 16:41:22 +000041
42 const TargetLowering *TLI;
43
44 const Type *FunctionContextTy;
45 Constant *RegisterFn;
46 Constant *UnregisterFn;
Jim Grosbach8b818d72009-08-17 16:41:22 +000047 Constant *BuiltinSetjmpFn;
48 Constant *FrameAddrFn;
Jim Grosbach0798edd2010-05-27 23:49:24 +000049 Constant *StackAddrFn;
50 Constant *StackRestoreFn;
Jim Grosbach8b818d72009-08-17 16:41:22 +000051 Constant *LSDAAddrFn;
52 Value *PersonalityFn;
Duncan Sandsb01bbdc2009-10-14 16:11:37 +000053 Constant *SelectorFn;
Jim Grosbach8b818d72009-08-17 16:41:22 +000054 Constant *ExceptionFn;
Jim Grosbachca752c92010-01-28 01:45:32 +000055 Constant *CallSiteFn;
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)
61 : FunctionPass(&ID), TLI(tli) { }
62 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 Grosbach606f3d62009-08-17 21:40:03 +000074 void splitLiveRangesLiveAcrossInvokes(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 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 Grosbach8b818d72009-08-17 16:41:22 +0000182void SjLjEHPass::
Jim Grosbach606f3d62009-08-17 21:40:03 +0000183splitLiveRangesLiveAcrossInvokes(SmallVector<InvokeInst*,16> &Invokes) {
Jim Grosbach8b818d72009-08-17 16:41:22 +0000184 // First step, split all critical edges from invoke instructions.
185 for (unsigned i = 0, e = Invokes.size(); i != e; ++i) {
186 InvokeInst *II = Invokes[i];
187 SplitCriticalEdge(II, 0, this);
188 SplitCriticalEdge(II, 1, this);
189 assert(!isa<PHINode>(II->getNormalDest()) &&
190 !isa<PHINode>(II->getUnwindDest()) &&
191 "critical edge splitting left single entry phi nodes?");
192 }
193
194 Function *F = Invokes.back()->getParent()->getParent();
195
196 // To avoid having to handle incoming arguments specially, we lower each arg
197 // to a copy instruction in the entry block. This ensures that the argument
198 // value itself cannot be live across the entry block.
199 BasicBlock::iterator AfterAllocaInsertPt = F->begin()->begin();
200 while (isa<AllocaInst>(AfterAllocaInsertPt) &&
201 isa<ConstantInt>(cast<AllocaInst>(AfterAllocaInsertPt)->getArraySize()))
202 ++AfterAllocaInsertPt;
203 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
204 AI != E; ++AI) {
Jim Grosbachdc58b252010-06-01 18:04:09 +0000205 const Type *Ty = AI->getType();
206 // StructType can't be cast, but is a legal argument type, so we have
207 // to handle them differently. We use an extract/insert pair as a
208 // lightweight method to achieve the same goal.
209 if (isa<StructType>(Ty)) {
210 Instruction *EI = ExtractValueInst::Create(AI, 0, "", AfterAllocaInsertPt);
211 Instruction *NI = InsertValueInst::Create(AI, EI, 0);
212 NI->insertAfter(EI);
213 AI->replaceAllUsesWith(NI);
214 // Set the struct operand of the instructions back to the AllocaInst.
215 EI->setOperand(0, AI);
216 NI->setOperand(0, AI);
217 } else {
218 // This is always a no-op cast because we're casting AI to AI->getType()
219 // so src and destination types are identical. BitCast is the only
220 // possibility.
221 CastInst *NC = new BitCastInst(
222 AI, AI->getType(), AI->getName()+".tmp", AfterAllocaInsertPt);
223 AI->replaceAllUsesWith(NC);
224 // Set the operand of the cast instruction back to the AllocaInst.
225 // Normally it's forbidden to replace a CastInst's operand because it
226 // could cause the opcode to reflect an illegal conversion. However,
227 // we're replacing it here with the same value it was constructed with.
228 // We do this because the above replaceAllUsesWith() clobbered the
229 // operand, but we want this one to remain.
230 NC->setOperand(0, AI);
231 }
Jim Grosbach8b818d72009-08-17 16:41:22 +0000232 }
233
234 // Finally, scan the code looking for instructions with bad live ranges.
235 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
236 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; ++II) {
237 // Ignore obvious cases we don't have to handle. In particular, most
238 // instructions either have no uses or only have a single use inside the
239 // current block. Ignore them quickly.
240 Instruction *Inst = II;
241 if (Inst->use_empty()) continue;
242 if (Inst->hasOneUse() &&
243 cast<Instruction>(Inst->use_back())->getParent() == BB &&
244 !isa<PHINode>(Inst->use_back())) continue;
245
246 // If this is an alloca in the entry block, it's not a real register
247 // value.
248 if (AllocaInst *AI = dyn_cast<AllocaInst>(Inst))
249 if (isa<ConstantInt>(AI->getArraySize()) && BB == F->begin())
250 continue;
251
252 // Avoid iterator invalidation by copying users to a temporary vector.
Jim Grosbach606f3d62009-08-17 21:40:03 +0000253 SmallVector<Instruction*,16> Users;
Jim Grosbach8b818d72009-08-17 16:41:22 +0000254 for (Value::use_iterator UI = Inst->use_begin(), E = Inst->use_end();
255 UI != E; ++UI) {
256 Instruction *User = cast<Instruction>(*UI);
257 if (User->getParent() != BB || isa<PHINode>(User))
258 Users.push_back(User);
259 }
260
Jim Grosbach8b818d72009-08-17 16:41:22 +0000261 // Find all of the blocks that this value is live in.
262 std::set<BasicBlock*> LiveBBs;
263 LiveBBs.insert(Inst->getParent());
264 while (!Users.empty()) {
265 Instruction *U = Users.back();
266 Users.pop_back();
267
268 if (!isa<PHINode>(U)) {
269 MarkBlocksLiveIn(U->getParent(), LiveBBs);
270 } else {
271 // Uses for a PHI node occur in their predecessor block.
272 PHINode *PN = cast<PHINode>(U);
273 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
274 if (PN->getIncomingValue(i) == Inst)
275 MarkBlocksLiveIn(PN->getIncomingBlock(i), LiveBBs);
276 }
277 }
278
279 // Now that we know all of the blocks that this thing is live in, see if
280 // it includes any of the unwind locations.
281 bool NeedsSpill = false;
282 for (unsigned i = 0, e = Invokes.size(); i != e; ++i) {
283 BasicBlock *UnwindBlock = Invokes[i]->getUnwindDest();
284 if (UnwindBlock != BB && LiveBBs.count(UnwindBlock)) {
285 NeedsSpill = true;
286 }
287 }
288
289 // If we decided we need a spill, do it.
290 if (NeedsSpill) {
291 ++NumSpilled;
292 DemoteRegToStack(*Inst, true);
293 }
294 }
295}
296
297bool SjLjEHPass::insertSjLjEHSupport(Function &F) {
Jim Grosbach606f3d62009-08-17 21:40:03 +0000298 SmallVector<ReturnInst*,16> Returns;
299 SmallVector<UnwindInst*,16> Unwinds;
300 SmallVector<InvokeInst*,16> Invokes;
Jim Grosbach8b818d72009-08-17 16:41:22 +0000301
302 // Look through the terminators of the basic blocks to find invokes, returns
Jim Grosbachb58a59b2010-03-04 22:07:46 +0000303 // and unwinds.
304 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
Jim Grosbach8b818d72009-08-17 16:41:22 +0000305 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
306 // Remember all return instructions in case we insert an invoke into this
307 // function.
308 Returns.push_back(RI);
309 } else if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
310 Invokes.push_back(II);
311 } else if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator())) {
312 Unwinds.push_back(UI);
313 }
Jim Grosbachb58a59b2010-03-04 22:07:46 +0000314 }
Jim Grosbach8b818d72009-08-17 16:41:22 +0000315 // If we don't have any invokes or unwinds, there's nothing to do.
316 if (Unwinds.empty() && Invokes.empty()) return false;
317
Jim Grosbach0798edd2010-05-27 23:49:24 +0000318 // Find the eh.selector.*, eh.exception and alloca calls.
319 //
320 // Remember any allocas() that aren't in the entry block, as the
321 // jmpbuf saved SP will need to be updated for them.
322 //
323 // We'll use the first eh.selector to determine the right personality
324 // function to use. For SJLJ, we always use the same personality for the
325 // whole function, not on a per-selector basis.
Jim Grosbacha235d132009-08-23 18:13:48 +0000326 // FIXME: That's a bit ugly. Better way?
327 SmallVector<CallInst*,16> EH_Selectors;
328 SmallVector<CallInst*,16> EH_Exceptions;
Jim Grosbach0798edd2010-05-27 23:49:24 +0000329 SmallVector<Instruction*,16> JmpbufUpdatePoints;
330 // Note: Skip the entry block since there's nothing there that interests
331 // us. eh.selector and eh.exception shouldn't ever be there, and we
332 // want to disregard any allocas that are there.
333 for (Function::iterator BB = F.begin(), E = F.end(); ++BB != E;) {
Jim Grosbacha235d132009-08-23 18:13:48 +0000334 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
335 if (CallInst *CI = dyn_cast<CallInst>(I)) {
Duncan Sandsb01bbdc2009-10-14 16:11:37 +0000336 if (CI->getCalledFunction() == SelectorFn) {
Eric Christopher551754c2010-04-16 23:37:20 +0000337 if (!PersonalityFn) PersonalityFn = CI->getOperand(2);
Jim Grosbacha235d132009-08-23 18:13:48 +0000338 EH_Selectors.push_back(CI);
339 } else if (CI->getCalledFunction() == ExceptionFn) {
340 EH_Exceptions.push_back(CI);
Jim Grosbach0798edd2010-05-27 23:49:24 +0000341 } else if (CI->getCalledFunction() == StackRestoreFn) {
342 JmpbufUpdatePoints.push_back(CI);
Jim Grosbacha235d132009-08-23 18:13:48 +0000343 }
Jim Grosbach0798edd2010-05-27 23:49:24 +0000344 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) {
345 JmpbufUpdatePoints.push_back(AI);
Jim Grosbacha235d132009-08-23 18:13:48 +0000346 }
347 }
348 }
349 // If we don't have any eh.selector calls, we can't determine the personality
350 // function. Without a personality function, we can't process exceptions.
351 if (!PersonalityFn) return false;
352
Jim Grosbach8b818d72009-08-17 16:41:22 +0000353 NumInvokes += Invokes.size();
354 NumUnwinds += Unwinds.size();
355
Jim Grosbach8b818d72009-08-17 16:41:22 +0000356 if (!Invokes.empty()) {
357 // We have invokes, so we need to add register/unregister calls to get
358 // this function onto the global unwind stack.
Jim Grosbach0bb61c52009-08-31 01:35:03 +0000359 //
360 // First thing we need to do is scan the whole function for values that are
361 // live across unwind edges. Each value that is live across an unwind edge
362 // we spill into a stack location, guaranteeing that there is nothing live
363 // across the unwind edge. This process also splits all critical edges
364 // coming out of invoke's.
365 splitLiveRangesLiveAcrossInvokes(Invokes);
Jim Grosbach8b818d72009-08-17 16:41:22 +0000366
367 BasicBlock *EntryBB = F.begin();
368 // Create an alloca for the incoming jump buffer ptr and the new jump buffer
369 // that needs to be restored on all exits from the function. This is an
370 // alloca because the value needs to be added to the global context list.
371 unsigned Align = 4; // FIXME: Should be a TLI check?
372 AllocaInst *FunctionContext =
373 new AllocaInst(FunctionContextTy, 0, Align,
374 "fcn_context", F.begin()->begin());
375
376 Value *Idxs[2];
377 const Type *Int32Ty = Type::getInt32Ty(F.getContext());
378 Value *Zero = ConstantInt::get(Int32Ty, 0);
379 // We need to also keep around a reference to the call_site field
380 Idxs[0] = Zero;
381 Idxs[1] = ConstantInt::get(Int32Ty, 1);
382 CallSite = GetElementPtrInst::Create(FunctionContext, Idxs, Idxs+2,
383 "call_site",
384 EntryBB->getTerminator());
385
386 // The exception selector comes back in context->data[1]
387 Idxs[1] = ConstantInt::get(Int32Ty, 2);
388 Value *FCData = GetElementPtrInst::Create(FunctionContext, Idxs, Idxs+2,
389 "fc_data",
390 EntryBB->getTerminator());
391 Idxs[1] = ConstantInt::get(Int32Ty, 1);
392 Value *SelectorAddr = GetElementPtrInst::Create(FCData, Idxs, Idxs+2,
393 "exc_selector_gep",
394 EntryBB->getTerminator());
395 // The exception value comes back in context->data[0]
396 Idxs[1] = Zero;
397 Value *ExceptionAddr = GetElementPtrInst::Create(FCData, Idxs, Idxs+2,
398 "exception_gep",
399 EntryBB->getTerminator());
400
Jim Grosbach8b818d72009-08-17 16:41:22 +0000401 // The result of the eh.selector call will be replaced with a
402 // a reference to the selector value returned in the function
403 // context. We leave the selector itself so the EH analysis later
404 // can use it.
405 for (int i = 0, e = EH_Selectors.size(); i < e; ++i) {
406 CallInst *I = EH_Selectors[i];
407 Value *SelectorVal = new LoadInst(SelectorAddr, "select_val", true, I);
408 I->replaceAllUsesWith(SelectorVal);
409 }
410 // eh.exception calls are replaced with references to the proper
411 // location in the context. Unlike eh.selector, the eh.exception
412 // calls are removed entirely.
413 for (int i = 0, e = EH_Exceptions.size(); i < e; ++i) {
414 CallInst *I = EH_Exceptions[i];
415 // Possible for there to be duplicates, so check to make sure
416 // the instruction hasn't already been removed.
417 if (!I->getParent()) continue;
418 Value *Val = new LoadInst(ExceptionAddr, "exception", true, I);
Duncan Sandsac53a0b2009-10-06 15:40:36 +0000419 const Type *Ty = Type::getInt8PtrTy(F.getContext());
Jim Grosbach606f3d62009-08-17 21:40:03 +0000420 Val = CastInst::Create(Instruction::IntToPtr, Val, Ty, "", I);
Jim Grosbach8b818d72009-08-17 16:41:22 +0000421
422 I->replaceAllUsesWith(Val);
423 I->eraseFromParent();
424 }
425
Jim Grosbach8b818d72009-08-17 16:41:22 +0000426 // The entry block changes to have the eh.sjlj.setjmp, with a conditional
427 // branch to a dispatch block for non-zero returns. If we return normally,
428 // we're not handling an exception and just register the function context
429 // and continue.
430
431 // Create the dispatch block. The dispatch block is basically a big switch
432 // statement that goes to all of the invoke landing pads.
433 BasicBlock *DispatchBlock =
434 BasicBlock::Create(F.getContext(), "eh.sjlj.setjmp.catch", &F);
435
436 // Insert a load in the Catch block, and a switch on its value. By default,
437 // we go to a block that just does an unwind (which is the correct action
438 // for a standard call).
Jim Grosbach03825f82010-01-15 00:32:47 +0000439 BasicBlock *UnwindBlock =
440 BasicBlock::Create(F.getContext(), "unwindbb", &F);
Jim Grosbach8b818d72009-08-17 16:41:22 +0000441 Unwinds.push_back(new UnwindInst(F.getContext(), UnwindBlock));
442
443 Value *DispatchLoad = new LoadInst(CallSite, "invoke.num", true,
444 DispatchBlock);
445 SwitchInst *DispatchSwitch =
Jim Grosbach03825f82010-01-15 00:32:47 +0000446 SwitchInst::Create(DispatchLoad, UnwindBlock, Invokes.size(),
447 DispatchBlock);
Jim Grosbach8b818d72009-08-17 16:41:22 +0000448 // Split the entry block to insert the conditional branch for the setjmp.
449 BasicBlock *ContBlock = EntryBB->splitBasicBlock(EntryBB->getTerminator(),
450 "eh.sjlj.setjmp.cont");
451
452 // Populate the Function Context
453 // 1. LSDA address
454 // 2. Personality function address
Jim Grosbach0798edd2010-05-27 23:49:24 +0000455 // 3. jmpbuf (save SP, FP and call eh.sjlj.setjmp)
Jim Grosbach8b818d72009-08-17 16:41:22 +0000456
457 // LSDA address
458 Idxs[0] = Zero;
459 Idxs[1] = ConstantInt::get(Int32Ty, 4);
460 Value *LSDAFieldPtr =
461 GetElementPtrInst::Create(FunctionContext, Idxs, Idxs+2,
462 "lsda_gep",
463 EntryBB->getTerminator());
464 Value *LSDA = CallInst::Create(LSDAAddrFn, "lsda_addr",
465 EntryBB->getTerminator());
466 new StoreInst(LSDA, LSDAFieldPtr, true, EntryBB->getTerminator());
467
468 Idxs[1] = ConstantInt::get(Int32Ty, 3);
469 Value *PersonalityFieldPtr =
470 GetElementPtrInst::Create(FunctionContext, Idxs, Idxs+2,
471 "lsda_gep",
472 EntryBB->getTerminator());
473 new StoreInst(PersonalityFn, PersonalityFieldPtr, true,
474 EntryBB->getTerminator());
475
Jim Grosbach0798edd2010-05-27 23:49:24 +0000476 // Save the frame pointer.
Jim Grosbach8b818d72009-08-17 16:41:22 +0000477 Idxs[1] = ConstantInt::get(Int32Ty, 5);
Jim Grosbach0798edd2010-05-27 23:49:24 +0000478 Value *JBufPtr
Jim Grosbach8b818d72009-08-17 16:41:22 +0000479 = GetElementPtrInst::Create(FunctionContext, Idxs, Idxs+2,
480 "jbuf_gep",
481 EntryBB->getTerminator());
482 Idxs[1] = ConstantInt::get(Int32Ty, 0);
Jim Grosbach0798edd2010-05-27 23:49:24 +0000483 Value *FramePtr =
484 GetElementPtrInst::Create(JBufPtr, Idxs, Idxs+2, "jbuf_fp_gep",
Jim Grosbach8b818d72009-08-17 16:41:22 +0000485 EntryBB->getTerminator());
486
487 Value *Val = CallInst::Create(FrameAddrFn,
488 ConstantInt::get(Int32Ty, 0),
489 "fp",
490 EntryBB->getTerminator());
Jim Grosbach0798edd2010-05-27 23:49:24 +0000491 new StoreInst(Val, FramePtr, true, EntryBB->getTerminator());
492
493 // Save the stack pointer.
494 Idxs[1] = ConstantInt::get(Int32Ty, 2);
495 Value *StackPtr =
496 GetElementPtrInst::Create(JBufPtr, Idxs, Idxs+2, "jbuf_sp_gep",
497 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.
Jim Grosbach8b818d72009-08-17 16:41:22 +0000503 Value *SetjmpArg =
Jim Grosbach0798edd2010-05-27 23:49:24 +0000504 CastInst::Create(Instruction::BitCast, JBufPtr,
Duncan Sandsac53a0b2009-10-06 15:40:36 +0000505 Type::getInt8PtrTy(F.getContext()), "",
506 EntryBB->getTerminator());
Jim Grosbach8b818d72009-08-17 16:41:22 +0000507 Value *DispatchVal = CallInst::Create(BuiltinSetjmpFn, SetjmpArg,
508 "dispatch",
509 EntryBB->getTerminator());
Jim Grosbach0798edd2010-05-27 23:49:24 +0000510 // check the return value of the setjmp. non-zero goes to dispatcher.
Jim Grosbach8b818d72009-08-17 16:41:22 +0000511 Value *IsNormal = new ICmpInst(EntryBB->getTerminator(),
512 ICmpInst::ICMP_EQ, DispatchVal, Zero,
513 "notunwind");
514 // Nuke the uncond branch.
515 EntryBB->getTerminator()->eraseFromParent();
516
517 // Put in a new condbranch in its place.
518 BranchInst::Create(ContBlock, DispatchBlock, IsNormal, EntryBB);
519
520 // Register the function context and make sure it's known to not throw
521 CallInst *Register =
522 CallInst::Create(RegisterFn, FunctionContext, "",
523 ContBlock->getTerminator());
524 Register->setDoesNotThrow();
525
Jim Grosbach0bb61c52009-08-31 01:35:03 +0000526 // At this point, we are all set up, update the invoke instructions
Jim Grosbach8b818d72009-08-17 16:41:22 +0000527 // to mark their call_site values, and fill in the dispatch switch
528 // accordingly.
Jim Grosbachf38a33c2010-01-21 20:10:22 +0000529 for (unsigned i = 0, e = Invokes.size(); i != e; ++i)
Jim Grosbach0bb61c52009-08-31 01:35:03 +0000530 markInvokeCallSite(Invokes[i], i+1, CallSite, DispatchSwitch);
Jim Grosbach8b818d72009-08-17 16:41:22 +0000531
Jim Grosbachb58a59b2010-03-04 22:07:46 +0000532 // Mark call instructions that aren't nounwind as no-action
533 // (call_site == -1). Skip the entry block, as prior to then, no function
534 // context has been created for this function and any unexpected exceptions
535 // thrown will go directly to the caller's context, which is what we want
536 // anyway, so no need to do anything here.
537 for (Function::iterator BB = F.begin(), E = F.end(); ++BB != E;) {
538 for (BasicBlock::iterator I = BB->begin(), end = BB->end(); I != end; ++I)
539 if (CallInst *CI = dyn_cast<CallInst>(I)) {
540 // Ignore calls to the EH builtins (eh.selector, eh.exception)
541 Constant *Callee = CI->getCalledFunction();
542 if (Callee != SelectorFn && Callee != ExceptionFn
543 && !CI->doesNotThrow())
544 insertCallSiteStore(CI, -1, CallSite);
Jim Grosbach8b818d72009-08-17 16:41:22 +0000545 }
Jim Grosbachb58a59b2010-03-04 22:07:46 +0000546 }
Jim Grosbach8b818d72009-08-17 16:41:22 +0000547
548 // Replace all unwinds with a branch to the unwind handler.
549 // ??? Should this ever happen with sjlj exceptions?
550 for (unsigned i = 0, e = Unwinds.size(); i != e; ++i) {
551 BranchInst::Create(UnwindBlock, Unwinds[i]);
552 Unwinds[i]->eraseFromParent();
553 }
554
Jim Grosbach0798edd2010-05-27 23:49:24 +0000555 // Following any allocas not in the entry block, update the saved SP
556 // in the jmpbuf to the new value.
557 for (unsigned i = 0, e = JmpbufUpdatePoints.size(); i != e; ++i) {
558 Instruction *AI = JmpbufUpdatePoints[i];
559 Instruction *StackAddr = CallInst::Create(StackAddrFn, "sp");
560 StackAddr->insertAfter(AI);
561 Instruction *StoreStackAddr = new StoreInst(StackAddr, StackPtr, true);
562 StoreStackAddr->insertAfter(StackAddr);
563 }
564
Jim Grosbach8b818d72009-08-17 16:41:22 +0000565 // Finally, for any returns from this function, if this function contains an
566 // invoke, add a call to unregister the function context.
567 for (unsigned i = 0, e = Returns.size(); i != e; ++i)
568 CallInst::Create(UnregisterFn, FunctionContext, "", Returns[i]);
569 }
570
571 return true;
572}
573
574bool SjLjEHPass::runOnFunction(Function &F) {
575 bool Res = insertSjLjEHSupport(F);
576 return Res;
577}