blob: ebed3d2b882de9c9eadc6e338aa1e6cc2c8c65c8 [file] [log] [blame]
Jim Grosbach8b818d72009-08-17 16:41:22 +00001//===- SjLjEHPass.cpp - Eliminate Invoke & Unwind instructions -----------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This transformation is designed for use by code generators which use SjLj
11// based exception handling.
12//
13//===----------------------------------------------------------------------===//
14
15#define DEBUG_TYPE "sjljehprepare"
16#include "llvm/Transforms/Scalar.h"
17#include "llvm/Constants.h"
18#include "llvm/DerivedTypes.h"
19#include "llvm/Instructions.h"
20#include "llvm/Intrinsics.h"
21#include "llvm/LLVMContext.h"
22#include "llvm/Module.h"
23#include "llvm/Pass.h"
24#include "llvm/CodeGen/Passes.h"
Benjamin Kramerf7888542010-11-06 11:45:59 +000025#include "llvm/Target/TargetLowering.h"
Jim Grosbach8b818d72009-08-17 16:41:22 +000026#include "llvm/Transforms/Utils/BasicBlockUtils.h"
27#include "llvm/Transforms/Utils/Local.h"
Bill Wendlingd36b3e32011-08-22 18:44:49 +000028#include "llvm/Support/Debug.h"
Bill Wendlingaef508d2011-08-22 23:38:40 +000029#include "llvm/ADT/DenseMap.h"
Bill Wendlingd36b3e32011-08-22 18:44:49 +000030#include "llvm/ADT/SmallVector.h"
31#include "llvm/ADT/Statistic.h"
Benjamin Kramerf7888542010-11-06 11:45:59 +000032#include <set>
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 const TargetLowering *TLI;
Chris Lattnerdb125cf2011-07-18 04:54:35 +000042 Type *FunctionContextTy;
Jim Grosbach8b818d72009-08-17 16:41:22 +000043 Constant *RegisterFn;
44 Constant *UnregisterFn;
Jim Grosbach8b818d72009-08-17 16:41:22 +000045 Constant *BuiltinSetjmpFn;
46 Constant *FrameAddrFn;
Jim Grosbach0798edd2010-05-27 23:49:24 +000047 Constant *StackAddrFn;
48 Constant *StackRestoreFn;
Jim Grosbach8b818d72009-08-17 16:41:22 +000049 Constant *LSDAAddrFn;
50 Value *PersonalityFn;
Duncan Sandsb01bbdc2009-10-14 16:11:37 +000051 Constant *SelectorFn;
Jim Grosbach8b818d72009-08-17 16:41:22 +000052 Constant *ExceptionFn;
Jim Grosbachca752c92010-01-28 01:45:32 +000053 Constant *CallSiteFn;
Jim Grosbache4ad3872010-10-19 23:27:08 +000054 Constant *DispatchSetupFn;
Jim Grosbach8b818d72009-08-17 16:41:22 +000055 Value *CallSite;
Bill Wendlingaef508d2011-08-22 23:38:40 +000056 DenseMap<InvokeInst*, BasicBlock*> LPadSuccMap;
Jim Grosbach8b818d72009-08-17 16:41:22 +000057 public:
58 static char ID; // Pass identification, replacement for typeid
59 explicit SjLjEHPass(const TargetLowering *tli = NULL)
Owen Anderson90c579d2010-08-06 18:33:48 +000060 : FunctionPass(ID), TLI(tli) { }
Jim Grosbach8b818d72009-08-17 16:41:22 +000061 bool doInitialization(Module &M);
62 bool runOnFunction(Function &F);
63
Bill Wendlingd36b3e32011-08-22 18:44:49 +000064 virtual void getAnalysisUsage(AnalysisUsage &AU) const {}
Jim Grosbach8b818d72009-08-17 16:41:22 +000065 const char *getPassName() const {
66 return "SJLJ Exception Handling preparation";
67 }
68
69 private:
Jim Grosbachb58a59b2010-03-04 22:07:46 +000070 void insertCallSiteStore(Instruction *I, int Number, Value *CallSite);
71 void markInvokeCallSite(InvokeInst *II, int InvokeNo, Value *CallSite,
Jim Grosbach0bb61c52009-08-31 01:35:03 +000072 SwitchInst *CatchSwitch);
Jim Grosbach288694f2010-06-15 18:53:34 +000073 void splitLiveRangesAcrossInvokes(SmallVector<InvokeInst*,16> &Invokes);
Jim Grosbach8b818d72009-08-17 16:41:22 +000074 bool insertSjLjEHSupport(Function &F);
75 };
76} // end anonymous namespace
77
78char SjLjEHPass::ID = 0;
79
80// Public Interface To the SjLjEHPass pass.
81FunctionPass *llvm::createSjLjEHPass(const TargetLowering *TLI) {
82 return new SjLjEHPass(TLI);
83}
Jim Grosbacha235d132009-08-23 18:13:48 +000084// doInitialization - Set up decalarations and types needed to process
85// exceptions.
Jim Grosbach8b818d72009-08-17 16:41:22 +000086bool SjLjEHPass::doInitialization(Module &M) {
87 // Build the function context structure.
88 // builtin_setjmp uses a five word jbuf
Jay Foad5fdd6c82011-07-12 14:06:48 +000089 Type *VoidPtrTy = Type::getInt8PtrTy(M.getContext());
90 Type *Int32Ty = Type::getInt32Ty(M.getContext());
Jim Grosbach8b818d72009-08-17 16:41:22 +000091 FunctionContextTy =
Chris Lattnerb2318662011-06-18 22:48:56 +000092 StructType::get(VoidPtrTy, // __prev
Jim Grosbach8b818d72009-08-17 16:41:22 +000093 Int32Ty, // call_site
94 ArrayType::get(Int32Ty, 4), // __data
95 VoidPtrTy, // __personality
96 VoidPtrTy, // __lsda
97 ArrayType::get(VoidPtrTy, 5), // __jbuf
98 NULL);
99 RegisterFn = M.getOrInsertFunction("_Unwind_SjLj_Register",
100 Type::getVoidTy(M.getContext()),
101 PointerType::getUnqual(FunctionContextTy),
102 (Type *)0);
103 UnregisterFn =
104 M.getOrInsertFunction("_Unwind_SjLj_Unregister",
105 Type::getVoidTy(M.getContext()),
106 PointerType::getUnqual(FunctionContextTy),
107 (Type *)0);
Jim Grosbach8b818d72009-08-17 16:41:22 +0000108 FrameAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::frameaddress);
Jim Grosbach0798edd2010-05-27 23:49:24 +0000109 StackAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::stacksave);
110 StackRestoreFn = Intrinsic::getDeclaration(&M, Intrinsic::stackrestore);
Jim Grosbach8b818d72009-08-17 16:41:22 +0000111 BuiltinSetjmpFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_setjmp);
112 LSDAAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_lsda);
Duncan Sandsb01bbdc2009-10-14 16:11:37 +0000113 SelectorFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_selector);
Jim Grosbach8b818d72009-08-17 16:41:22 +0000114 ExceptionFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_exception);
Jim Grosbachca752c92010-01-28 01:45:32 +0000115 CallSiteFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_callsite);
Jim Grosbache4ad3872010-10-19 23:27:08 +0000116 DispatchSetupFn
117 = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_dispatch_setup);
Jim Grosbacha235d132009-08-23 18:13:48 +0000118 PersonalityFn = 0;
Jim Grosbach8b818d72009-08-17 16:41:22 +0000119
120 return true;
121}
122
Jim Grosbachb58a59b2010-03-04 22:07:46 +0000123/// insertCallSiteStore - Insert a store of the call-site value to the
124/// function context
125void SjLjEHPass::insertCallSiteStore(Instruction *I, int Number,
126 Value *CallSite) {
127 ConstantInt *CallSiteNoC = ConstantInt::get(Type::getInt32Ty(I->getContext()),
128 Number);
129 // Insert a store of the call-site number
130 new StoreInst(CallSiteNoC, CallSite, true, I); // volatile
131}
132
Jim Grosbach8b818d72009-08-17 16:41:22 +0000133/// markInvokeCallSite - Insert code to mark the call_site for this invoke
Jim Grosbachb58a59b2010-03-04 22:07:46 +0000134void SjLjEHPass::markInvokeCallSite(InvokeInst *II, int InvokeNo,
Jim Grosbach0bb61c52009-08-31 01:35:03 +0000135 Value *CallSite,
136 SwitchInst *CatchSwitch) {
Jim Grosbach8b818d72009-08-17 16:41:22 +0000137 ConstantInt *CallSiteNoC= ConstantInt::get(Type::getInt32Ty(II->getContext()),
Jim Grosbachb58a59b2010-03-04 22:07:46 +0000138 InvokeNo);
Jim Grosbach0bb61c52009-08-31 01:35:03 +0000139 // The runtime comes back to the dispatcher with the call_site - 1 in
140 // the context. Odd, but there it is.
141 ConstantInt *SwitchValC = ConstantInt::get(Type::getInt32Ty(II->getContext()),
142 InvokeNo - 1);
Jim Grosbach8b818d72009-08-17 16:41:22 +0000143
144 // If the unwind edge has phi nodes, split the edge.
145 if (isa<PHINode>(II->getUnwindDest()->begin())) {
146 SplitCriticalEdge(II, 1, this);
147
148 // If there are any phi nodes left, they must have a single predecessor.
149 while (PHINode *PN = dyn_cast<PHINode>(II->getUnwindDest()->begin())) {
150 PN->replaceAllUsesWith(PN->getIncomingValue(0));
151 PN->eraseFromParent();
152 }
153 }
154
Jim Grosbachb58a59b2010-03-04 22:07:46 +0000155 // Insert the store of the call site value
156 insertCallSiteStore(II, InvokeNo, CallSite);
157
158 // Record the call site value for the back end so it stays associated with
159 // the invoke.
Jim Grosbachca752c92010-01-28 01:45:32 +0000160 CallInst::Create(CallSiteFn, CallSiteNoC, "", II);
Jim Grosbach8b818d72009-08-17 16:41:22 +0000161
Jim Grosbach0bb61c52009-08-31 01:35:03 +0000162 // Add a switch case to our unwind block.
Bill Wendlingaef508d2011-08-22 23:38:40 +0000163 if (BasicBlock *SuccBB = LPadSuccMap[II]) {
164 CatchSwitch->addCase(SwitchValC, SuccBB);
165 } else {
166 CatchSwitch->addCase(SwitchValC, II->getUnwindDest());
167 }
168
Jim Grosbachca752c92010-01-28 01:45:32 +0000169 // We still want this to look like an invoke so we emit the LSDA properly,
170 // so we don't transform the invoke into a call here.
Jim Grosbach8b818d72009-08-17 16:41:22 +0000171}
172
173/// MarkBlocksLiveIn - Insert BB and all of its predescessors into LiveBBs until
174/// we reach blocks we've already seen.
175static void MarkBlocksLiveIn(BasicBlock *BB, std::set<BasicBlock*> &LiveBBs) {
176 if (!LiveBBs.insert(BB).second) return; // already been here.
177
178 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
179 MarkBlocksLiveIn(*PI, LiveBBs);
180}
181
Jim Grosbach606f3d62009-08-17 21:40:03 +0000182/// splitLiveRangesAcrossInvokes - Each value that is live across an unwind edge
183/// we spill into a stack location, guaranteeing that there is nothing live
184/// across the unwind edge. This process also splits all critical edges
185/// coming out of invoke's.
Jim Grosbach2f3257e2010-06-01 18:06:35 +0000186/// FIXME: Move this function to a common utility file (Local.cpp?) so
187/// both SjLj and LowerInvoke can use it.
Jim Grosbach8b818d72009-08-17 16:41:22 +0000188void SjLjEHPass::
Jim Grosbach288694f2010-06-15 18:53:34 +0000189splitLiveRangesAcrossInvokes(SmallVector<InvokeInst*,16> &Invokes) {
Jim Grosbach8b818d72009-08-17 16:41:22 +0000190 // First step, split all critical edges from invoke instructions.
191 for (unsigned i = 0, e = Invokes.size(); i != e; ++i) {
192 InvokeInst *II = Invokes[i];
193 SplitCriticalEdge(II, 0, this);
Bill Wendlingaef508d2011-08-22 23:38:40 +0000194
195 // FIXME: New EH - This if-condition will be always true in the new scheme.
196 if (II->getUnwindDest()->isLandingPad()) {
197 SmallVector<BasicBlock*, 2> NewBBs;
198 SplitLandingPadPredecessors(II->getUnwindDest(), II->getParent(),
199 ".1", ".2", this, NewBBs);
200 LPadSuccMap[II] = *succ_begin(NewBBs[0]);
201 } else {
202 SplitCriticalEdge(II, 1, this);
203 }
204
Jim Grosbach8b818d72009-08-17 16:41:22 +0000205 assert(!isa<PHINode>(II->getNormalDest()) &&
206 !isa<PHINode>(II->getUnwindDest()) &&
Bill Wendlingd36b3e32011-08-22 18:44:49 +0000207 "Critical edge splitting left single entry phi nodes?");
Jim Grosbach8b818d72009-08-17 16:41:22 +0000208 }
209
210 Function *F = Invokes.back()->getParent()->getParent();
211
212 // To avoid having to handle incoming arguments specially, we lower each arg
213 // to a copy instruction in the entry block. This ensures that the argument
214 // value itself cannot be live across the entry block.
215 BasicBlock::iterator AfterAllocaInsertPt = F->begin()->begin();
216 while (isa<AllocaInst>(AfterAllocaInsertPt) &&
217 isa<ConstantInt>(cast<AllocaInst>(AfterAllocaInsertPt)->getArraySize()))
218 ++AfterAllocaInsertPt;
219 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
220 AI != E; ++AI) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000221 Type *Ty = AI->getType();
Jim Grosbache70fc8e2010-06-30 22:20:38 +0000222 // Aggregate types can't be cast, but are legal argument types, so we have
Jim Grosbachdc58b252010-06-01 18:04:09 +0000223 // to handle them differently. We use an extract/insert pair as a
224 // lightweight method to achieve the same goal.
Jim Grosbache70fc8e2010-06-30 22:20:38 +0000225 if (isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<VectorType>(Ty)) {
226 Instruction *EI = ExtractValueInst::Create(AI, 0, "",AfterAllocaInsertPt);
Jim Grosbachdc58b252010-06-01 18:04:09 +0000227 Instruction *NI = InsertValueInst::Create(AI, EI, 0);
228 NI->insertAfter(EI);
229 AI->replaceAllUsesWith(NI);
Jim Grosbache70fc8e2010-06-30 22:20:38 +0000230 // Set the operand of the instructions back to the AllocaInst.
Jim Grosbachdc58b252010-06-01 18:04:09 +0000231 EI->setOperand(0, AI);
232 NI->setOperand(0, AI);
233 } else {
234 // This is always a no-op cast because we're casting AI to AI->getType()
235 // so src and destination types are identical. BitCast is the only
236 // possibility.
237 CastInst *NC = new BitCastInst(
238 AI, AI->getType(), AI->getName()+".tmp", AfterAllocaInsertPt);
239 AI->replaceAllUsesWith(NC);
240 // Set the operand of the cast instruction back to the AllocaInst.
241 // Normally it's forbidden to replace a CastInst's operand because it
242 // could cause the opcode to reflect an illegal conversion. However,
243 // we're replacing it here with the same value it was constructed with.
244 // We do this because the above replaceAllUsesWith() clobbered the
245 // operand, but we want this one to remain.
246 NC->setOperand(0, AI);
247 }
Jim Grosbach8b818d72009-08-17 16:41:22 +0000248 }
249
250 // Finally, scan the code looking for instructions with bad live ranges.
251 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
252 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; ++II) {
253 // Ignore obvious cases we don't have to handle. In particular, most
254 // instructions either have no uses or only have a single use inside the
255 // current block. Ignore them quickly.
256 Instruction *Inst = II;
257 if (Inst->use_empty()) continue;
258 if (Inst->hasOneUse() &&
259 cast<Instruction>(Inst->use_back())->getParent() == BB &&
260 !isa<PHINode>(Inst->use_back())) continue;
261
262 // If this is an alloca in the entry block, it's not a real register
263 // value.
264 if (AllocaInst *AI = dyn_cast<AllocaInst>(Inst))
265 if (isa<ConstantInt>(AI->getArraySize()) && BB == F->begin())
266 continue;
267
268 // Avoid iterator invalidation by copying users to a temporary vector.
Jim Grosbach606f3d62009-08-17 21:40:03 +0000269 SmallVector<Instruction*,16> Users;
Jim Grosbach8b818d72009-08-17 16:41:22 +0000270 for (Value::use_iterator UI = Inst->use_begin(), E = Inst->use_end();
271 UI != E; ++UI) {
272 Instruction *User = cast<Instruction>(*UI);
273 if (User->getParent() != BB || isa<PHINode>(User))
274 Users.push_back(User);
275 }
276
Jim Grosbach8b818d72009-08-17 16:41:22 +0000277 // Find all of the blocks that this value is live in.
278 std::set<BasicBlock*> LiveBBs;
279 LiveBBs.insert(Inst->getParent());
280 while (!Users.empty()) {
281 Instruction *U = Users.back();
282 Users.pop_back();
283
284 if (!isa<PHINode>(U)) {
285 MarkBlocksLiveIn(U->getParent(), LiveBBs);
286 } else {
287 // Uses for a PHI node occur in their predecessor block.
288 PHINode *PN = cast<PHINode>(U);
289 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
290 if (PN->getIncomingValue(i) == Inst)
291 MarkBlocksLiveIn(PN->getIncomingBlock(i), LiveBBs);
292 }
293 }
294
295 // Now that we know all of the blocks that this thing is live in, see if
296 // it includes any of the unwind locations.
297 bool NeedsSpill = false;
298 for (unsigned i = 0, e = Invokes.size(); i != e; ++i) {
299 BasicBlock *UnwindBlock = Invokes[i]->getUnwindDest();
300 if (UnwindBlock != BB && LiveBBs.count(UnwindBlock)) {
301 NeedsSpill = true;
302 }
303 }
304
305 // If we decided we need a spill, do it.
Jim Grosbach956352e2010-06-16 18:45:08 +0000306 // FIXME: Spilling this way is overkill, as it forces all uses of
307 // the value to be reloaded from the stack slot, even those that aren't
308 // in the unwind blocks. We should be more selective.
Jim Grosbach8b818d72009-08-17 16:41:22 +0000309 if (NeedsSpill) {
310 ++NumSpilled;
311 DemoteRegToStack(*Inst, true);
312 }
313 }
314}
315
Bill Wendlingaef508d2011-08-22 23:38:40 +0000316/// CreateLandingPadLoad - Load the exception handling values and insert them
317/// into a structure.
318static Instruction *CreateLandingPadLoad(Function &F, Value *ExnAddr,
319 Value *SelAddr,
320 BasicBlock::iterator InsertPt) {
321 Value *Exn = new LoadInst(ExnAddr, "exn", false,
322 InsertPt);
323 Type *Ty = Type::getInt8PtrTy(F.getContext());
324 Exn = CastInst::Create(Instruction::IntToPtr, Exn, Ty, "", InsertPt);
325 Value *Sel = new LoadInst(SelAddr, "sel", false, InsertPt);
326
327 Ty = StructType::get(Exn->getType(), Sel->getType(), NULL);
328 InsertValueInst *LPadVal = InsertValueInst::Create(llvm::UndefValue::get(Ty),
329 Exn, 0,
330 "lpad.val", InsertPt);
331 return InsertValueInst::Create(LPadVal, Sel, 1, "lpad.val", InsertPt);
332}
333
334/// ReplaceLandingPadVal - Replace the landingpad instruction's value with a
335/// load from the stored values (via CreateLandingPadLoad). This looks through
336/// PHI nodes, and removes them if they are dead.
337static void ReplaceLandingPadVal(Function &F, Instruction *Inst, Value *ExnAddr,
338 Value *SelAddr) {
339 if (Inst->use_empty()) return;
340
341 while (!Inst->use_empty()) {
342 Instruction *I = cast<Instruction>(Inst->use_back());
343
344 if (PHINode *PN = dyn_cast<PHINode>(I)) {
345 ReplaceLandingPadVal(F, PN, ExnAddr, SelAddr);
346 if (PN->use_empty()) PN->eraseFromParent();
347 continue;
348 }
349
Bill Wendlingfc8713f2011-08-23 22:55:03 +0000350 I->replaceUsesOfWith(Inst, CreateLandingPadLoad(F, ExnAddr, SelAddr, I));
Bill Wendlingaef508d2011-08-22 23:38:40 +0000351 }
352}
353
Jim Grosbach8b818d72009-08-17 16:41:22 +0000354bool SjLjEHPass::insertSjLjEHSupport(Function &F) {
Jim Grosbach606f3d62009-08-17 21:40:03 +0000355 SmallVector<ReturnInst*,16> Returns;
356 SmallVector<UnwindInst*,16> Unwinds;
357 SmallVector<InvokeInst*,16> Invokes;
Jim Grosbach8b818d72009-08-17 16:41:22 +0000358
359 // Look through the terminators of the basic blocks to find invokes, returns
Jim Grosbachb58a59b2010-03-04 22:07:46 +0000360 // and unwinds.
361 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
Jim Grosbach8b818d72009-08-17 16:41:22 +0000362 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
363 // Remember all return instructions in case we insert an invoke into this
364 // function.
365 Returns.push_back(RI);
366 } else if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
367 Invokes.push_back(II);
368 } else if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator())) {
369 Unwinds.push_back(UI);
370 }
Jim Grosbachb58a59b2010-03-04 22:07:46 +0000371 }
Bill Wendling8d90b712011-01-07 02:54:45 +0000372
373 NumInvokes += Invokes.size();
374 NumUnwinds += Unwinds.size();
375
376 // If we don't have any invokes, there's nothing to do.
377 if (Invokes.empty()) return false;
Jim Grosbach8b818d72009-08-17 16:41:22 +0000378
Jim Grosbach0798edd2010-05-27 23:49:24 +0000379 // Find the eh.selector.*, eh.exception and alloca calls.
380 //
381 // Remember any allocas() that aren't in the entry block, as the
382 // jmpbuf saved SP will need to be updated for them.
383 //
384 // We'll use the first eh.selector to determine the right personality
385 // function to use. For SJLJ, we always use the same personality for the
386 // whole function, not on a per-selector basis.
Jim Grosbacha235d132009-08-23 18:13:48 +0000387 // FIXME: That's a bit ugly. Better way?
388 SmallVector<CallInst*,16> EH_Selectors;
389 SmallVector<CallInst*,16> EH_Exceptions;
Jim Grosbach0798edd2010-05-27 23:49:24 +0000390 SmallVector<Instruction*,16> JmpbufUpdatePoints;
Bill Wendling8d90b712011-01-07 02:54:45 +0000391
Bill Wendlingcfcccef2011-08-23 22:20:16 +0000392 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
393 // Note: Skip the entry block since there's nothing there that interests
394 // us. eh.selector and eh.exception shouldn't ever be there, and we
395 // want to disregard any allocas that are there.
396 //
397 // FIXME: This is awkward. The new EH scheme won't need to skip the entry
398 // block.
399 if (BB == F.begin()) {
400 if (InvokeInst *II = dyn_cast<InvokeInst>(F.begin()->getTerminator())) {
401 // FIXME: This will be always non-NULL in the new EH.
402 if (LandingPadInst *LPI = II->getUnwindDest()->getLandingPadInst())
403 if (!PersonalityFn) PersonalityFn = LPI->getPersonalityFn();
404 }
405
406 continue;
407 }
408
Jim Grosbacha235d132009-08-23 18:13:48 +0000409 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
410 if (CallInst *CI = dyn_cast<CallInst>(I)) {
Duncan Sandsb01bbdc2009-10-14 16:11:37 +0000411 if (CI->getCalledFunction() == SelectorFn) {
Gabor Greif45c097f2010-06-25 09:36:23 +0000412 if (!PersonalityFn) PersonalityFn = CI->getArgOperand(1);
Jim Grosbacha235d132009-08-23 18:13:48 +0000413 EH_Selectors.push_back(CI);
414 } else if (CI->getCalledFunction() == ExceptionFn) {
415 EH_Exceptions.push_back(CI);
Jim Grosbach0798edd2010-05-27 23:49:24 +0000416 } else if (CI->getCalledFunction() == StackRestoreFn) {
417 JmpbufUpdatePoints.push_back(CI);
Jim Grosbacha235d132009-08-23 18:13:48 +0000418 }
Jim Grosbach0798edd2010-05-27 23:49:24 +0000419 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) {
420 JmpbufUpdatePoints.push_back(AI);
Bill Wendlingaef508d2011-08-22 23:38:40 +0000421 } else if (InvokeInst *II = dyn_cast<InvokeInst>(I)) {
422 // FIXME: This will be always non-NULL in the new EH.
423 if (LandingPadInst *LPI = II->getUnwindDest()->getLandingPadInst())
424 if (!PersonalityFn) PersonalityFn = LPI->getPersonalityFn();
Jim Grosbacha235d132009-08-23 18:13:48 +0000425 }
426 }
427 }
Bill Wendling8d90b712011-01-07 02:54:45 +0000428
Jim Grosbacha235d132009-08-23 18:13:48 +0000429 // If we don't have any eh.selector calls, we can't determine the personality
430 // function. Without a personality function, we can't process exceptions.
431 if (!PersonalityFn) return false;
432
Bill Wendling8d90b712011-01-07 02:54:45 +0000433 // We have invokes, so we need to add register/unregister calls to get this
434 // function onto the global unwind stack.
435 //
436 // First thing we need to do is scan the whole function for values that are
437 // live across unwind edges. Each value that is live across an unwind edge we
438 // spill into a stack location, guaranteeing that there is nothing live across
439 // the unwind edge. This process also splits all critical edges coming out of
440 // invoke's.
441 splitLiveRangesAcrossInvokes(Invokes);
Jim Grosbach8b818d72009-08-17 16:41:22 +0000442
Bill Wendlingaef508d2011-08-22 23:38:40 +0000443
444 SmallVector<LandingPadInst*, 16> LandingPads;
445 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
446 if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator()))
447 // FIXME: This will be always non-NULL in the new EH.
448 if (LandingPadInst *LPI = II->getUnwindDest()->getLandingPadInst())
449 LandingPads.push_back(LPI);
450 }
451
452
Bill Wendling8d90b712011-01-07 02:54:45 +0000453 BasicBlock *EntryBB = F.begin();
454 // Create an alloca for the incoming jump buffer ptr and the new jump buffer
455 // that needs to be restored on all exits from the function. This is an
456 // alloca because the value needs to be added to the global context list.
457 unsigned Align = 4; // FIXME: Should be a TLI check?
458 AllocaInst *FunctionContext =
459 new AllocaInst(FunctionContextTy, 0, Align,
460 "fcn_context", F.begin()->begin());
Jim Grosbach8b818d72009-08-17 16:41:22 +0000461
Bill Wendling8d90b712011-01-07 02:54:45 +0000462 Value *Idxs[2];
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000463 Type *Int32Ty = Type::getInt32Ty(F.getContext());
Bill Wendling8d90b712011-01-07 02:54:45 +0000464 Value *Zero = ConstantInt::get(Int32Ty, 0);
465 // We need to also keep around a reference to the call_site field
466 Idxs[0] = Zero;
467 Idxs[1] = ConstantInt::get(Int32Ty, 1);
Jay Foada9203102011-07-25 09:48:08 +0000468 CallSite = GetElementPtrInst::Create(FunctionContext, Idxs, "call_site",
Bill Wendling8d90b712011-01-07 02:54:45 +0000469 EntryBB->getTerminator());
Jim Grosbach8b818d72009-08-17 16:41:22 +0000470
Bill Wendling8d90b712011-01-07 02:54:45 +0000471 // The exception selector comes back in context->data[1]
472 Idxs[1] = ConstantInt::get(Int32Ty, 2);
Jay Foada9203102011-07-25 09:48:08 +0000473 Value *FCData = GetElementPtrInst::Create(FunctionContext, Idxs, "fc_data",
Bill Wendling8d90b712011-01-07 02:54:45 +0000474 EntryBB->getTerminator());
475 Idxs[1] = ConstantInt::get(Int32Ty, 1);
Jay Foada9203102011-07-25 09:48:08 +0000476 Value *SelectorAddr = GetElementPtrInst::Create(FCData, Idxs,
Bill Wendling8d90b712011-01-07 02:54:45 +0000477 "exc_selector_gep",
478 EntryBB->getTerminator());
479 // The exception value comes back in context->data[0]
480 Idxs[1] = Zero;
Jay Foada9203102011-07-25 09:48:08 +0000481 Value *ExceptionAddr = GetElementPtrInst::Create(FCData, Idxs,
Bill Wendling8d90b712011-01-07 02:54:45 +0000482 "exception_gep",
483 EntryBB->getTerminator());
Jim Grosbach8b818d72009-08-17 16:41:22 +0000484
Bill Wendling8d90b712011-01-07 02:54:45 +0000485 // The result of the eh.selector call will be replaced with a a reference to
486 // the selector value returned in the function context. We leave the selector
487 // itself so the EH analysis later can use it.
488 for (int i = 0, e = EH_Selectors.size(); i < e; ++i) {
489 CallInst *I = EH_Selectors[i];
490 Value *SelectorVal = new LoadInst(SelectorAddr, "select_val", true, I);
491 I->replaceAllUsesWith(SelectorVal);
Jim Grosbach8b818d72009-08-17 16:41:22 +0000492 }
493
Bill Wendling8d90b712011-01-07 02:54:45 +0000494 // eh.exception calls are replaced with references to the proper location in
495 // the context. Unlike eh.selector, the eh.exception calls are removed
496 // entirely.
497 for (int i = 0, e = EH_Exceptions.size(); i < e; ++i) {
498 CallInst *I = EH_Exceptions[i];
499 // Possible for there to be duplicates, so check to make sure the
500 // instruction hasn't already been removed.
501 if (!I->getParent()) continue;
502 Value *Val = new LoadInst(ExceptionAddr, "exception", true, I);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000503 Type *Ty = Type::getInt8PtrTy(F.getContext());
Bill Wendling8d90b712011-01-07 02:54:45 +0000504 Val = CastInst::Create(Instruction::IntToPtr, Val, Ty, "", I);
505
506 I->replaceAllUsesWith(Val);
507 I->eraseFromParent();
508 }
509
Bill Wendlingaef508d2011-08-22 23:38:40 +0000510 for (unsigned i = 0, e = LandingPads.size(); i != e; ++i)
511 ReplaceLandingPadVal(F, LandingPads[i], ExceptionAddr, SelectorAddr);
512
Bill Wendling8d90b712011-01-07 02:54:45 +0000513 // The entry block changes to have the eh.sjlj.setjmp, with a conditional
514 // branch to a dispatch block for non-zero returns. If we return normally,
515 // we're not handling an exception and just register the function context and
516 // continue.
517
518 // Create the dispatch block. The dispatch block is basically a big switch
519 // statement that goes to all of the invoke landing pads.
520 BasicBlock *DispatchBlock =
521 BasicBlock::Create(F.getContext(), "eh.sjlj.setjmp.catch", &F);
522
Bill Wendling8d90b712011-01-07 02:54:45 +0000523 // Insert a load of the callsite in the dispatch block, and a switch on its
Bill Wendlingcc885952011-04-11 21:32:34 +0000524 // value. By default, we issue a trap statement.
525 BasicBlock *TrapBlock =
526 BasicBlock::Create(F.getContext(), "trapbb", &F);
527 CallInst::Create(Intrinsic::getDeclaration(F.getParent(), Intrinsic::trap),
528 "", TrapBlock);
529 new UnreachableInst(F.getContext(), TrapBlock);
Bill Wendling8d90b712011-01-07 02:54:45 +0000530
531 Value *DispatchLoad = new LoadInst(CallSite, "invoke.num", true,
532 DispatchBlock);
533 SwitchInst *DispatchSwitch =
Bill Wendlingcc885952011-04-11 21:32:34 +0000534 SwitchInst::Create(DispatchLoad, TrapBlock, Invokes.size(),
Bill Wendling8d90b712011-01-07 02:54:45 +0000535 DispatchBlock);
536 // Split the entry block to insert the conditional branch for the setjmp.
537 BasicBlock *ContBlock = EntryBB->splitBasicBlock(EntryBB->getTerminator(),
538 "eh.sjlj.setjmp.cont");
539
540 // Populate the Function Context
541 // 1. LSDA address
542 // 2. Personality function address
543 // 3. jmpbuf (save SP, FP and call eh.sjlj.setjmp)
544
545 // LSDA address
546 Idxs[0] = Zero;
547 Idxs[1] = ConstantInt::get(Int32Ty, 4);
548 Value *LSDAFieldPtr =
Jay Foada9203102011-07-25 09:48:08 +0000549 GetElementPtrInst::Create(FunctionContext, Idxs, "lsda_gep",
Bill Wendling8d90b712011-01-07 02:54:45 +0000550 EntryBB->getTerminator());
551 Value *LSDA = CallInst::Create(LSDAAddrFn, "lsda_addr",
552 EntryBB->getTerminator());
553 new StoreInst(LSDA, LSDAFieldPtr, true, EntryBB->getTerminator());
554
555 Idxs[1] = ConstantInt::get(Int32Ty, 3);
556 Value *PersonalityFieldPtr =
Jay Foada9203102011-07-25 09:48:08 +0000557 GetElementPtrInst::Create(FunctionContext, Idxs, "lsda_gep",
Bill Wendling8d90b712011-01-07 02:54:45 +0000558 EntryBB->getTerminator());
559 new StoreInst(PersonalityFn, PersonalityFieldPtr, true,
560 EntryBB->getTerminator());
561
562 // Save the frame pointer.
563 Idxs[1] = ConstantInt::get(Int32Ty, 5);
564 Value *JBufPtr
Jay Foada9203102011-07-25 09:48:08 +0000565 = GetElementPtrInst::Create(FunctionContext, Idxs, "jbuf_gep",
Bill Wendling8d90b712011-01-07 02:54:45 +0000566 EntryBB->getTerminator());
567 Idxs[1] = ConstantInt::get(Int32Ty, 0);
568 Value *FramePtr =
Jay Foada9203102011-07-25 09:48:08 +0000569 GetElementPtrInst::Create(JBufPtr, Idxs, "jbuf_fp_gep",
Bill Wendling8d90b712011-01-07 02:54:45 +0000570 EntryBB->getTerminator());
571
572 Value *Val = CallInst::Create(FrameAddrFn,
573 ConstantInt::get(Int32Ty, 0),
574 "fp",
575 EntryBB->getTerminator());
576 new StoreInst(Val, FramePtr, true, EntryBB->getTerminator());
577
578 // Save the stack pointer.
579 Idxs[1] = ConstantInt::get(Int32Ty, 2);
580 Value *StackPtr =
Jay Foada9203102011-07-25 09:48:08 +0000581 GetElementPtrInst::Create(JBufPtr, Idxs, "jbuf_sp_gep",
Bill Wendling8d90b712011-01-07 02:54:45 +0000582 EntryBB->getTerminator());
583
584 Val = CallInst::Create(StackAddrFn, "sp", EntryBB->getTerminator());
585 new StoreInst(Val, StackPtr, true, EntryBB->getTerminator());
586
587 // Call the setjmp instrinsic. It fills in the rest of the jmpbuf.
588 Value *SetjmpArg =
589 CastInst::Create(Instruction::BitCast, JBufPtr,
590 Type::getInt8PtrTy(F.getContext()), "",
591 EntryBB->getTerminator());
592 Value *DispatchVal = CallInst::Create(BuiltinSetjmpFn, SetjmpArg,
593 "dispatch",
594 EntryBB->getTerminator());
Bill Wendlingf05b1dc2011-04-05 01:37:43 +0000595
596 // Add a call to dispatch_setup after the setjmp call. This is expanded to any
597 // target-specific setup that needs to be done.
Bill Wendling61512ba2011-05-11 01:11:55 +0000598 CallInst::Create(DispatchSetupFn, DispatchVal, "", EntryBB->getTerminator());
Bill Wendlingf05b1dc2011-04-05 01:37:43 +0000599
Bill Wendling8d90b712011-01-07 02:54:45 +0000600 // check the return value of the setjmp. non-zero goes to dispatcher.
601 Value *IsNormal = new ICmpInst(EntryBB->getTerminator(),
602 ICmpInst::ICMP_EQ, DispatchVal, Zero,
603 "notunwind");
604 // Nuke the uncond branch.
605 EntryBB->getTerminator()->eraseFromParent();
606
607 // Put in a new condbranch in its place.
608 BranchInst::Create(ContBlock, DispatchBlock, IsNormal, EntryBB);
609
610 // Register the function context and make sure it's known to not throw
611 CallInst *Register =
612 CallInst::Create(RegisterFn, FunctionContext, "",
613 ContBlock->getTerminator());
614 Register->setDoesNotThrow();
615
616 // At this point, we are all set up, update the invoke instructions to mark
617 // their call_site values, and fill in the dispatch switch accordingly.
618 for (unsigned i = 0, e = Invokes.size(); i != e; ++i)
619 markInvokeCallSite(Invokes[i], i+1, CallSite, DispatchSwitch);
620
621 // Mark call instructions that aren't nounwind as no-action (call_site ==
622 // -1). Skip the entry block, as prior to then, no function context has been
623 // created for this function and any unexpected exceptions thrown will go
624 // directly to the caller's context, which is what we want anyway, so no need
625 // to do anything here.
626 for (Function::iterator BB = F.begin(), E = F.end(); ++BB != E;) {
627 for (BasicBlock::iterator I = BB->begin(), end = BB->end(); I != end; ++I)
628 if (CallInst *CI = dyn_cast<CallInst>(I)) {
629 // Ignore calls to the EH builtins (eh.selector, eh.exception)
630 Constant *Callee = CI->getCalledFunction();
631 if (Callee != SelectorFn && Callee != ExceptionFn
632 && !CI->doesNotThrow())
633 insertCallSiteStore(CI, -1, CallSite);
Bill Wendling3ae96d62011-08-24 00:00:23 +0000634 } else if (ResumeInst *RI = dyn_cast<ResumeInst>(I)) {
635 insertCallSiteStore(RI, -1, CallSite);
Bill Wendling8d90b712011-01-07 02:54:45 +0000636 }
637 }
638
639 // Replace all unwinds with a branch to the unwind handler.
640 // ??? Should this ever happen with sjlj exceptions?
641 for (unsigned i = 0, e = Unwinds.size(); i != e; ++i) {
Bill Wendlingcc885952011-04-11 21:32:34 +0000642 BranchInst::Create(TrapBlock, Unwinds[i]);
Bill Wendling8d90b712011-01-07 02:54:45 +0000643 Unwinds[i]->eraseFromParent();
644 }
645
646 // Following any allocas not in the entry block, update the saved SP in the
647 // jmpbuf to the new value.
648 for (unsigned i = 0, e = JmpbufUpdatePoints.size(); i != e; ++i) {
649 Instruction *AI = JmpbufUpdatePoints[i];
650 Instruction *StackAddr = CallInst::Create(StackAddrFn, "sp");
651 StackAddr->insertAfter(AI);
652 Instruction *StoreStackAddr = new StoreInst(StackAddr, StackPtr, true);
653 StoreStackAddr->insertAfter(StackAddr);
654 }
655
656 // Finally, for any returns from this function, if this function contains an
657 // invoke, add a call to unregister the function context.
658 for (unsigned i = 0, e = Returns.size(); i != e; ++i)
659 CallInst::Create(UnregisterFn, FunctionContext, "", Returns[i]);
660
Jim Grosbach8b818d72009-08-17 16:41:22 +0000661 return true;
662}
663
664bool SjLjEHPass::runOnFunction(Function &F) {
665 bool Res = insertSjLjEHSupport(F);
666 return Res;
667}