blob: ded2459d4278efca2be7f95c2a9da74375018a95 [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"
Bill Wendling2b6bd7b2011-09-28 03:14:05 +000025#include "llvm/Target/TargetData.h"
Benjamin Kramerf7888542010-11-06 11:45:59 +000026#include "llvm/Target/TargetLowering.h"
Jim Grosbach8b818d72009-08-17 16:41:22 +000027#include "llvm/Transforms/Utils/BasicBlockUtils.h"
28#include "llvm/Transforms/Utils/Local.h"
Bill Wendling2b6bd7b2011-09-28 03:14:05 +000029#include "llvm/Support/CommandLine.h"
Bill Wendlingd36b3e32011-08-22 18:44:49 +000030#include "llvm/Support/Debug.h"
Bill Wendling2b6bd7b2011-09-28 03:14:05 +000031#include "llvm/Support/IRBuilder.h"
Bill Wendlingaef508d2011-08-22 23:38:40 +000032#include "llvm/ADT/DenseMap.h"
Bill Wendlingd36b3e32011-08-22 18:44:49 +000033#include "llvm/ADT/SmallVector.h"
34#include "llvm/ADT/Statistic.h"
Benjamin Kramerf7888542010-11-06 11:45:59 +000035#include <set>
Jim Grosbach8b818d72009-08-17 16:41:22 +000036using namespace llvm;
37
Bill Wendling2b6bd7b2011-09-28 03:14:05 +000038static cl::opt<bool> DisableOldSjLjEH("disable-old-sjlj-eh", cl::Hidden,
39 cl::desc("Disable the old SjLj EH preparation pass"));
40
Jim Grosbach8b818d72009-08-17 16:41:22 +000041STATISTIC(NumInvokes, "Number of invokes replaced");
42STATISTIC(NumUnwinds, "Number of unwinds replaced");
43STATISTIC(NumSpilled, "Number of registers live across unwind edges");
44
45namespace {
Nick Lewycky6726b6d2009-10-25 06:33:48 +000046 class SjLjEHPass : public FunctionPass {
Jim Grosbach8b818d72009-08-17 16:41:22 +000047 const TargetLowering *TLI;
Chris Lattnerdb125cf2011-07-18 04:54:35 +000048 Type *FunctionContextTy;
Jim Grosbach8b818d72009-08-17 16:41:22 +000049 Constant *RegisterFn;
50 Constant *UnregisterFn;
Jim Grosbach8b818d72009-08-17 16:41:22 +000051 Constant *BuiltinSetjmpFn;
52 Constant *FrameAddrFn;
Jim Grosbach0798edd2010-05-27 23:49:24 +000053 Constant *StackAddrFn;
54 Constant *StackRestoreFn;
Jim Grosbach8b818d72009-08-17 16:41:22 +000055 Constant *LSDAAddrFn;
56 Value *PersonalityFn;
Duncan Sandsb01bbdc2009-10-14 16:11:37 +000057 Constant *SelectorFn;
Jim Grosbach8b818d72009-08-17 16:41:22 +000058 Constant *ExceptionFn;
Jim Grosbachca752c92010-01-28 01:45:32 +000059 Constant *CallSiteFn;
Jim Grosbache4ad3872010-10-19 23:27:08 +000060 Constant *DispatchSetupFn;
Bill Wendlingcc8cf972011-09-28 21:56:53 +000061 Constant *FuncCtxFn;
Jim Grosbach8b818d72009-08-17 16:41:22 +000062 Value *CallSite;
Bill Wendlingaef508d2011-08-22 23:38:40 +000063 DenseMap<InvokeInst*, BasicBlock*> LPadSuccMap;
Jim Grosbach8b818d72009-08-17 16:41:22 +000064 public:
65 static char ID; // Pass identification, replacement for typeid
66 explicit SjLjEHPass(const TargetLowering *tli = NULL)
Owen Anderson90c579d2010-08-06 18:33:48 +000067 : FunctionPass(ID), TLI(tli) { }
Jim Grosbach8b818d72009-08-17 16:41:22 +000068 bool doInitialization(Module &M);
69 bool runOnFunction(Function &F);
70
Bill Wendlingd36b3e32011-08-22 18:44:49 +000071 virtual void getAnalysisUsage(AnalysisUsage &AU) const {}
Jim Grosbach8b818d72009-08-17 16:41:22 +000072 const char *getPassName() const {
73 return "SJLJ Exception Handling preparation";
74 }
75
76 private:
Bill Wendling2b6bd7b2011-09-28 03:14:05 +000077 bool setupEntryBlockAndCallSites(Function &F);
Bill Wendling631d1172011-10-03 21:15:28 +000078 Value *setupFunctionContext(Function &F, ArrayRef<LandingPadInst*> LPads);
Bill Wendlingd5d17002011-10-08 00:56:47 +000079 void lowerIncomingArguments(Function &F);
80 void lowerAcrossUnwindEdges(Function &F, ArrayRef<InvokeInst*> Invokes);
Bill Wendling2b6bd7b2011-09-28 03:14:05 +000081
Jim Grosbachb58a59b2010-03-04 22:07:46 +000082 void insertCallSiteStore(Instruction *I, int Number, Value *CallSite);
83 void markInvokeCallSite(InvokeInst *II, int InvokeNo, Value *CallSite,
Jim Grosbach0bb61c52009-08-31 01:35:03 +000084 SwitchInst *CatchSwitch);
Jim Grosbach288694f2010-06-15 18:53:34 +000085 void splitLiveRangesAcrossInvokes(SmallVector<InvokeInst*,16> &Invokes);
Bill Wendling36699152011-09-12 21:56:59 +000086 void splitLandingPad(InvokeInst *II);
Jim Grosbach8b818d72009-08-17 16:41:22 +000087 bool insertSjLjEHSupport(Function &F);
88 };
89} // end anonymous namespace
90
91char SjLjEHPass::ID = 0;
92
93// Public Interface To the SjLjEHPass pass.
94FunctionPass *llvm::createSjLjEHPass(const TargetLowering *TLI) {
95 return new SjLjEHPass(TLI);
96}
Jim Grosbacha235d132009-08-23 18:13:48 +000097// doInitialization - Set up decalarations and types needed to process
98// exceptions.
Jim Grosbach8b818d72009-08-17 16:41:22 +000099bool SjLjEHPass::doInitialization(Module &M) {
100 // Build the function context structure.
101 // builtin_setjmp uses a five word jbuf
Jay Foad5fdd6c82011-07-12 14:06:48 +0000102 Type *VoidPtrTy = Type::getInt8PtrTy(M.getContext());
103 Type *Int32Ty = Type::getInt32Ty(M.getContext());
Jim Grosbach8b818d72009-08-17 16:41:22 +0000104 FunctionContextTy =
Chris Lattnerb2318662011-06-18 22:48:56 +0000105 StructType::get(VoidPtrTy, // __prev
Jim Grosbach8b818d72009-08-17 16:41:22 +0000106 Int32Ty, // call_site
107 ArrayType::get(Int32Ty, 4), // __data
108 VoidPtrTy, // __personality
109 VoidPtrTy, // __lsda
110 ArrayType::get(VoidPtrTy, 5), // __jbuf
111 NULL);
112 RegisterFn = M.getOrInsertFunction("_Unwind_SjLj_Register",
113 Type::getVoidTy(M.getContext()),
114 PointerType::getUnqual(FunctionContextTy),
115 (Type *)0);
116 UnregisterFn =
117 M.getOrInsertFunction("_Unwind_SjLj_Unregister",
118 Type::getVoidTy(M.getContext()),
119 PointerType::getUnqual(FunctionContextTy),
120 (Type *)0);
Jim Grosbach8b818d72009-08-17 16:41:22 +0000121 FrameAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::frameaddress);
Jim Grosbach0798edd2010-05-27 23:49:24 +0000122 StackAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::stacksave);
123 StackRestoreFn = Intrinsic::getDeclaration(&M, Intrinsic::stackrestore);
Jim Grosbach8b818d72009-08-17 16:41:22 +0000124 BuiltinSetjmpFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_setjmp);
125 LSDAAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_lsda);
Duncan Sandsb01bbdc2009-10-14 16:11:37 +0000126 SelectorFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_selector);
Jim Grosbach8b818d72009-08-17 16:41:22 +0000127 ExceptionFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_exception);
Jim Grosbachca752c92010-01-28 01:45:32 +0000128 CallSiteFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_callsite);
Jim Grosbache4ad3872010-10-19 23:27:08 +0000129 DispatchSetupFn
130 = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_dispatch_setup);
Bill Wendlingcc8cf972011-09-28 21:56:53 +0000131 FuncCtxFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_functioncontext);
Jim Grosbacha235d132009-08-23 18:13:48 +0000132 PersonalityFn = 0;
Jim Grosbach8b818d72009-08-17 16:41:22 +0000133
134 return true;
135}
136
Jim Grosbachb58a59b2010-03-04 22:07:46 +0000137/// insertCallSiteStore - Insert a store of the call-site value to the
138/// function context
139void SjLjEHPass::insertCallSiteStore(Instruction *I, int Number,
140 Value *CallSite) {
141 ConstantInt *CallSiteNoC = ConstantInt::get(Type::getInt32Ty(I->getContext()),
142 Number);
143 // Insert a store of the call-site number
144 new StoreInst(CallSiteNoC, CallSite, true, I); // volatile
145}
146
Bill Wendling36699152011-09-12 21:56:59 +0000147/// splitLandingPad - Split a landing pad. This takes considerable care because
148/// of PHIs and other nasties. The problem is that the jump table needs to jump
149/// to the landing pad block. However, the landing pad block can be jumped to
150/// only by an invoke instruction. So we clone the landingpad instruction into
151/// its own basic block, have the invoke jump to there. The landingpad
152/// instruction's basic block's successor is now the target for the jump table.
153///
154/// But because of PHI nodes, we need to create another basic block for the jump
155/// table to jump to. This is definitely a hack, because the values for the PHI
156/// nodes may not be defined on the edge from the jump table. But that's okay,
157/// because the jump table is simply a construct to mimic what is happening in
158/// the CFG. So the values are mysteriously there, even though there is no value
159/// for the PHI from the jump table's edge (hence calling this a hack).
160void SjLjEHPass::splitLandingPad(InvokeInst *II) {
161 SmallVector<BasicBlock*, 2> NewBBs;
162 SplitLandingPadPredecessors(II->getUnwindDest(), II->getParent(),
163 ".1", ".2", this, NewBBs);
164
165 // Create an empty block so that the jump table has something to jump to
166 // which doesn't have any PHI nodes.
167 BasicBlock *LPad = NewBBs[0];
168 BasicBlock *Succ = *succ_begin(LPad);
169 BasicBlock *JumpTo = BasicBlock::Create(II->getContext(), "jt.land",
170 LPad->getParent(), Succ);
171 LPad->getTerminator()->eraseFromParent();
172 BranchInst::Create(JumpTo, LPad);
173 BranchInst::Create(Succ, JumpTo);
174 LPadSuccMap[II] = JumpTo;
175
176 for (BasicBlock::iterator I = Succ->begin(); isa<PHINode>(I); ++I) {
177 PHINode *PN = cast<PHINode>(I);
178 Value *Val = PN->removeIncomingValue(LPad, false);
179 PN->addIncoming(Val, JumpTo);
180 }
181}
182
Jim Grosbach8b818d72009-08-17 16:41:22 +0000183/// markInvokeCallSite - Insert code to mark the call_site for this invoke
Jim Grosbachb58a59b2010-03-04 22:07:46 +0000184void SjLjEHPass::markInvokeCallSite(InvokeInst *II, int InvokeNo,
Jim Grosbach0bb61c52009-08-31 01:35:03 +0000185 Value *CallSite,
186 SwitchInst *CatchSwitch) {
Jim Grosbach8b818d72009-08-17 16:41:22 +0000187 ConstantInt *CallSiteNoC= ConstantInt::get(Type::getInt32Ty(II->getContext()),
Jim Grosbachb58a59b2010-03-04 22:07:46 +0000188 InvokeNo);
Jim Grosbach0bb61c52009-08-31 01:35:03 +0000189 // The runtime comes back to the dispatcher with the call_site - 1 in
190 // the context. Odd, but there it is.
191 ConstantInt *SwitchValC = ConstantInt::get(Type::getInt32Ty(II->getContext()),
Bill Wendling36699152011-09-12 21:56:59 +0000192 InvokeNo - 1);
Jim Grosbach8b818d72009-08-17 16:41:22 +0000193
194 // If the unwind edge has phi nodes, split the edge.
195 if (isa<PHINode>(II->getUnwindDest()->begin())) {
Bill Wendling51fb91c2011-08-26 21:18:55 +0000196 // FIXME: New EH - This if-condition will be always true in the new scheme.
Bill Wendling36699152011-09-12 21:56:59 +0000197 if (II->getUnwindDest()->isLandingPad())
198 splitLandingPad(II);
199 else
Bill Wendling51fb91c2011-08-26 21:18:55 +0000200 SplitCriticalEdge(II, 1, this);
Jim Grosbach8b818d72009-08-17 16:41:22 +0000201
202 // If there are any phi nodes left, they must have a single predecessor.
203 while (PHINode *PN = dyn_cast<PHINode>(II->getUnwindDest()->begin())) {
204 PN->replaceAllUsesWith(PN->getIncomingValue(0));
205 PN->eraseFromParent();
206 }
207 }
208
Jim Grosbachb58a59b2010-03-04 22:07:46 +0000209 // Insert the store of the call site value
210 insertCallSiteStore(II, InvokeNo, CallSite);
211
212 // Record the call site value for the back end so it stays associated with
213 // the invoke.
Jim Grosbachca752c92010-01-28 01:45:32 +0000214 CallInst::Create(CallSiteFn, CallSiteNoC, "", II);
Jim Grosbach8b818d72009-08-17 16:41:22 +0000215
Jim Grosbach0bb61c52009-08-31 01:35:03 +0000216 // Add a switch case to our unwind block.
Bill Wendlingaef508d2011-08-22 23:38:40 +0000217 if (BasicBlock *SuccBB = LPadSuccMap[II]) {
218 CatchSwitch->addCase(SwitchValC, SuccBB);
219 } else {
220 CatchSwitch->addCase(SwitchValC, II->getUnwindDest());
221 }
222
Jim Grosbachca752c92010-01-28 01:45:32 +0000223 // We still want this to look like an invoke so we emit the LSDA properly,
224 // so we don't transform the invoke into a call here.
Jim Grosbach8b818d72009-08-17 16:41:22 +0000225}
226
227/// MarkBlocksLiveIn - Insert BB and all of its predescessors into LiveBBs until
228/// we reach blocks we've already seen.
229static void MarkBlocksLiveIn(BasicBlock *BB, std::set<BasicBlock*> &LiveBBs) {
230 if (!LiveBBs.insert(BB).second) return; // already been here.
231
232 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
233 MarkBlocksLiveIn(*PI, LiveBBs);
234}
235
Jim Grosbach606f3d62009-08-17 21:40:03 +0000236/// splitLiveRangesAcrossInvokes - Each value that is live across an unwind edge
237/// we spill into a stack location, guaranteeing that there is nothing live
238/// across the unwind edge. This process also splits all critical edges
239/// coming out of invoke's.
Jim Grosbach2f3257e2010-06-01 18:06:35 +0000240/// FIXME: Move this function to a common utility file (Local.cpp?) so
241/// both SjLj and LowerInvoke can use it.
Jim Grosbach8b818d72009-08-17 16:41:22 +0000242void SjLjEHPass::
Jim Grosbach288694f2010-06-15 18:53:34 +0000243splitLiveRangesAcrossInvokes(SmallVector<InvokeInst*,16> &Invokes) {
Jim Grosbach8b818d72009-08-17 16:41:22 +0000244 // First step, split all critical edges from invoke instructions.
245 for (unsigned i = 0, e = Invokes.size(); i != e; ++i) {
246 InvokeInst *II = Invokes[i];
247 SplitCriticalEdge(II, 0, this);
Bill Wendlingaef508d2011-08-22 23:38:40 +0000248
249 // FIXME: New EH - This if-condition will be always true in the new scheme.
Bill Wendling36699152011-09-12 21:56:59 +0000250 if (II->getUnwindDest()->isLandingPad())
251 splitLandingPad(II);
252 else
Bill Wendlingaef508d2011-08-22 23:38:40 +0000253 SplitCriticalEdge(II, 1, this);
Bill Wendlingaef508d2011-08-22 23:38:40 +0000254
Jim Grosbach8b818d72009-08-17 16:41:22 +0000255 assert(!isa<PHINode>(II->getNormalDest()) &&
256 !isa<PHINode>(II->getUnwindDest()) &&
Bill Wendlingd36b3e32011-08-22 18:44:49 +0000257 "Critical edge splitting left single entry phi nodes?");
Jim Grosbach8b818d72009-08-17 16:41:22 +0000258 }
259
260 Function *F = Invokes.back()->getParent()->getParent();
261
262 // To avoid having to handle incoming arguments specially, we lower each arg
263 // to a copy instruction in the entry block. This ensures that the argument
264 // value itself cannot be live across the entry block.
265 BasicBlock::iterator AfterAllocaInsertPt = F->begin()->begin();
266 while (isa<AllocaInst>(AfterAllocaInsertPt) &&
267 isa<ConstantInt>(cast<AllocaInst>(AfterAllocaInsertPt)->getArraySize()))
268 ++AfterAllocaInsertPt;
269 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
270 AI != E; ++AI) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000271 Type *Ty = AI->getType();
Jim Grosbache70fc8e2010-06-30 22:20:38 +0000272 // Aggregate types can't be cast, but are legal argument types, so we have
Jim Grosbachdc58b252010-06-01 18:04:09 +0000273 // to handle them differently. We use an extract/insert pair as a
274 // lightweight method to achieve the same goal.
Jim Grosbache70fc8e2010-06-30 22:20:38 +0000275 if (isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<VectorType>(Ty)) {
276 Instruction *EI = ExtractValueInst::Create(AI, 0, "",AfterAllocaInsertPt);
Jim Grosbachdc58b252010-06-01 18:04:09 +0000277 Instruction *NI = InsertValueInst::Create(AI, EI, 0);
278 NI->insertAfter(EI);
279 AI->replaceAllUsesWith(NI);
Jim Grosbache70fc8e2010-06-30 22:20:38 +0000280 // Set the operand of the instructions back to the AllocaInst.
Jim Grosbachdc58b252010-06-01 18:04:09 +0000281 EI->setOperand(0, AI);
282 NI->setOperand(0, AI);
283 } else {
284 // This is always a no-op cast because we're casting AI to AI->getType()
285 // so src and destination types are identical. BitCast is the only
286 // possibility.
287 CastInst *NC = new BitCastInst(
288 AI, AI->getType(), AI->getName()+".tmp", AfterAllocaInsertPt);
289 AI->replaceAllUsesWith(NC);
290 // Set the operand of the cast instruction back to the AllocaInst.
291 // Normally it's forbidden to replace a CastInst's operand because it
292 // could cause the opcode to reflect an illegal conversion. However,
293 // we're replacing it here with the same value it was constructed with.
294 // We do this because the above replaceAllUsesWith() clobbered the
295 // operand, but we want this one to remain.
296 NC->setOperand(0, AI);
297 }
Jim Grosbach8b818d72009-08-17 16:41:22 +0000298 }
299
300 // Finally, scan the code looking for instructions with bad live ranges.
301 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
302 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; ++II) {
303 // Ignore obvious cases we don't have to handle. In particular, most
304 // instructions either have no uses or only have a single use inside the
305 // current block. Ignore them quickly.
306 Instruction *Inst = II;
307 if (Inst->use_empty()) continue;
308 if (Inst->hasOneUse() &&
309 cast<Instruction>(Inst->use_back())->getParent() == BB &&
310 !isa<PHINode>(Inst->use_back())) continue;
311
312 // If this is an alloca in the entry block, it's not a real register
313 // value.
314 if (AllocaInst *AI = dyn_cast<AllocaInst>(Inst))
315 if (isa<ConstantInt>(AI->getArraySize()) && BB == F->begin())
316 continue;
317
318 // Avoid iterator invalidation by copying users to a temporary vector.
Jim Grosbach606f3d62009-08-17 21:40:03 +0000319 SmallVector<Instruction*,16> Users;
Jim Grosbach8b818d72009-08-17 16:41:22 +0000320 for (Value::use_iterator UI = Inst->use_begin(), E = Inst->use_end();
321 UI != E; ++UI) {
322 Instruction *User = cast<Instruction>(*UI);
323 if (User->getParent() != BB || isa<PHINode>(User))
324 Users.push_back(User);
325 }
326
Jim Grosbach8b818d72009-08-17 16:41:22 +0000327 // Find all of the blocks that this value is live in.
328 std::set<BasicBlock*> LiveBBs;
329 LiveBBs.insert(Inst->getParent());
330 while (!Users.empty()) {
331 Instruction *U = Users.back();
332 Users.pop_back();
333
334 if (!isa<PHINode>(U)) {
335 MarkBlocksLiveIn(U->getParent(), LiveBBs);
336 } else {
337 // Uses for a PHI node occur in their predecessor block.
338 PHINode *PN = cast<PHINode>(U);
339 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
340 if (PN->getIncomingValue(i) == Inst)
341 MarkBlocksLiveIn(PN->getIncomingBlock(i), LiveBBs);
342 }
343 }
344
345 // Now that we know all of the blocks that this thing is live in, see if
346 // it includes any of the unwind locations.
347 bool NeedsSpill = false;
348 for (unsigned i = 0, e = Invokes.size(); i != e; ++i) {
349 BasicBlock *UnwindBlock = Invokes[i]->getUnwindDest();
Bill Wendlingd5d17002011-10-08 00:56:47 +0000350 if (UnwindBlock != BB && LiveBBs.count(UnwindBlock))
Jim Grosbach8b818d72009-08-17 16:41:22 +0000351 NeedsSpill = true;
Jim Grosbach8b818d72009-08-17 16:41:22 +0000352 }
353
354 // If we decided we need a spill, do it.
Jim Grosbach956352e2010-06-16 18:45:08 +0000355 // FIXME: Spilling this way is overkill, as it forces all uses of
356 // the value to be reloaded from the stack slot, even those that aren't
357 // in the unwind blocks. We should be more selective.
Jim Grosbach8b818d72009-08-17 16:41:22 +0000358 if (NeedsSpill) {
359 ++NumSpilled;
360 DemoteRegToStack(*Inst, true);
361 }
362 }
363}
364
Bill Wendlingaef508d2011-08-22 23:38:40 +0000365/// CreateLandingPadLoad - Load the exception handling values and insert them
366/// into a structure.
367static Instruction *CreateLandingPadLoad(Function &F, Value *ExnAddr,
368 Value *SelAddr,
369 BasicBlock::iterator InsertPt) {
370 Value *Exn = new LoadInst(ExnAddr, "exn", false,
371 InsertPt);
372 Type *Ty = Type::getInt8PtrTy(F.getContext());
373 Exn = CastInst::Create(Instruction::IntToPtr, Exn, Ty, "", InsertPt);
374 Value *Sel = new LoadInst(SelAddr, "sel", false, InsertPt);
375
376 Ty = StructType::get(Exn->getType(), Sel->getType(), NULL);
377 InsertValueInst *LPadVal = InsertValueInst::Create(llvm::UndefValue::get(Ty),
378 Exn, 0,
379 "lpad.val", InsertPt);
380 return InsertValueInst::Create(LPadVal, Sel, 1, "lpad.val", InsertPt);
381}
382
383/// ReplaceLandingPadVal - Replace the landingpad instruction's value with a
384/// load from the stored values (via CreateLandingPadLoad). This looks through
385/// PHI nodes, and removes them if they are dead.
386static void ReplaceLandingPadVal(Function &F, Instruction *Inst, Value *ExnAddr,
387 Value *SelAddr) {
388 if (Inst->use_empty()) return;
389
390 while (!Inst->use_empty()) {
391 Instruction *I = cast<Instruction>(Inst->use_back());
392
393 if (PHINode *PN = dyn_cast<PHINode>(I)) {
394 ReplaceLandingPadVal(F, PN, ExnAddr, SelAddr);
395 if (PN->use_empty()) PN->eraseFromParent();
396 continue;
397 }
398
Bill Wendlingfc8713f2011-08-23 22:55:03 +0000399 I->replaceUsesOfWith(Inst, CreateLandingPadLoad(F, ExnAddr, SelAddr, I));
Bill Wendlingaef508d2011-08-22 23:38:40 +0000400 }
401}
402
Jim Grosbach8b818d72009-08-17 16:41:22 +0000403bool SjLjEHPass::insertSjLjEHSupport(Function &F) {
Jim Grosbach606f3d62009-08-17 21:40:03 +0000404 SmallVector<ReturnInst*,16> Returns;
405 SmallVector<UnwindInst*,16> Unwinds;
406 SmallVector<InvokeInst*,16> Invokes;
Jim Grosbach8b818d72009-08-17 16:41:22 +0000407
408 // Look through the terminators of the basic blocks to find invokes, returns
Jim Grosbachb58a59b2010-03-04 22:07:46 +0000409 // and unwinds.
410 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
Jim Grosbach8b818d72009-08-17 16:41:22 +0000411 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
412 // Remember all return instructions in case we insert an invoke into this
413 // function.
414 Returns.push_back(RI);
415 } else if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
416 Invokes.push_back(II);
417 } else if (UnwindInst *UI = dyn_cast<UnwindInst>(BB->getTerminator())) {
418 Unwinds.push_back(UI);
419 }
Jim Grosbachb58a59b2010-03-04 22:07:46 +0000420 }
Bill Wendling8d90b712011-01-07 02:54:45 +0000421
422 NumInvokes += Invokes.size();
423 NumUnwinds += Unwinds.size();
424
425 // If we don't have any invokes, there's nothing to do.
426 if (Invokes.empty()) return false;
Jim Grosbach8b818d72009-08-17 16:41:22 +0000427
Jim Grosbach0798edd2010-05-27 23:49:24 +0000428 // Find the eh.selector.*, eh.exception and alloca calls.
429 //
430 // Remember any allocas() that aren't in the entry block, as the
431 // jmpbuf saved SP will need to be updated for them.
432 //
433 // We'll use the first eh.selector to determine the right personality
434 // function to use. For SJLJ, we always use the same personality for the
435 // whole function, not on a per-selector basis.
Jim Grosbacha235d132009-08-23 18:13:48 +0000436 // FIXME: That's a bit ugly. Better way?
437 SmallVector<CallInst*,16> EH_Selectors;
438 SmallVector<CallInst*,16> EH_Exceptions;
Jim Grosbach0798edd2010-05-27 23:49:24 +0000439 SmallVector<Instruction*,16> JmpbufUpdatePoints;
Bill Wendling8d90b712011-01-07 02:54:45 +0000440
Bill Wendlingcfcccef2011-08-23 22:20:16 +0000441 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
442 // Note: Skip the entry block since there's nothing there that interests
443 // us. eh.selector and eh.exception shouldn't ever be there, and we
444 // want to disregard any allocas that are there.
445 //
446 // FIXME: This is awkward. The new EH scheme won't need to skip the entry
447 // block.
448 if (BB == F.begin()) {
449 if (InvokeInst *II = dyn_cast<InvokeInst>(F.begin()->getTerminator())) {
450 // FIXME: This will be always non-NULL in the new EH.
451 if (LandingPadInst *LPI = II->getUnwindDest()->getLandingPadInst())
452 if (!PersonalityFn) PersonalityFn = LPI->getPersonalityFn();
453 }
454
455 continue;
456 }
457
Jim Grosbacha235d132009-08-23 18:13:48 +0000458 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
459 if (CallInst *CI = dyn_cast<CallInst>(I)) {
Duncan Sandsb01bbdc2009-10-14 16:11:37 +0000460 if (CI->getCalledFunction() == SelectorFn) {
Gabor Greif45c097f2010-06-25 09:36:23 +0000461 if (!PersonalityFn) PersonalityFn = CI->getArgOperand(1);
Jim Grosbacha235d132009-08-23 18:13:48 +0000462 EH_Selectors.push_back(CI);
463 } else if (CI->getCalledFunction() == ExceptionFn) {
464 EH_Exceptions.push_back(CI);
Jim Grosbach0798edd2010-05-27 23:49:24 +0000465 } else if (CI->getCalledFunction() == StackRestoreFn) {
466 JmpbufUpdatePoints.push_back(CI);
Jim Grosbacha235d132009-08-23 18:13:48 +0000467 }
Jim Grosbach0798edd2010-05-27 23:49:24 +0000468 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) {
469 JmpbufUpdatePoints.push_back(AI);
Bill Wendlingaef508d2011-08-22 23:38:40 +0000470 } else if (InvokeInst *II = dyn_cast<InvokeInst>(I)) {
471 // FIXME: This will be always non-NULL in the new EH.
472 if (LandingPadInst *LPI = II->getUnwindDest()->getLandingPadInst())
473 if (!PersonalityFn) PersonalityFn = LPI->getPersonalityFn();
Jim Grosbacha235d132009-08-23 18:13:48 +0000474 }
475 }
476 }
Bill Wendling8d90b712011-01-07 02:54:45 +0000477
Jim Grosbacha235d132009-08-23 18:13:48 +0000478 // If we don't have any eh.selector calls, we can't determine the personality
479 // function. Without a personality function, we can't process exceptions.
480 if (!PersonalityFn) return false;
481
Bill Wendling8d90b712011-01-07 02:54:45 +0000482 // We have invokes, so we need to add register/unregister calls to get this
483 // function onto the global unwind stack.
484 //
485 // First thing we need to do is scan the whole function for values that are
486 // live across unwind edges. Each value that is live across an unwind edge we
487 // spill into a stack location, guaranteeing that there is nothing live across
488 // the unwind edge. This process also splits all critical edges coming out of
489 // invoke's.
490 splitLiveRangesAcrossInvokes(Invokes);
Jim Grosbach8b818d72009-08-17 16:41:22 +0000491
Bill Wendlingaef508d2011-08-22 23:38:40 +0000492
493 SmallVector<LandingPadInst*, 16> LandingPads;
494 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
495 if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator()))
496 // FIXME: This will be always non-NULL in the new EH.
497 if (LandingPadInst *LPI = II->getUnwindDest()->getLandingPadInst())
498 LandingPads.push_back(LPI);
499 }
500
501
Bill Wendling8d90b712011-01-07 02:54:45 +0000502 BasicBlock *EntryBB = F.begin();
503 // Create an alloca for the incoming jump buffer ptr and the new jump buffer
504 // that needs to be restored on all exits from the function. This is an
505 // alloca because the value needs to be added to the global context list.
506 unsigned Align = 4; // FIXME: Should be a TLI check?
507 AllocaInst *FunctionContext =
508 new AllocaInst(FunctionContextTy, 0, Align,
509 "fcn_context", F.begin()->begin());
Jim Grosbach8b818d72009-08-17 16:41:22 +0000510
Bill Wendling8d90b712011-01-07 02:54:45 +0000511 Value *Idxs[2];
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000512 Type *Int32Ty = Type::getInt32Ty(F.getContext());
Bill Wendling8d90b712011-01-07 02:54:45 +0000513 Value *Zero = ConstantInt::get(Int32Ty, 0);
514 // We need to also keep around a reference to the call_site field
515 Idxs[0] = Zero;
516 Idxs[1] = ConstantInt::get(Int32Ty, 1);
Jay Foada9203102011-07-25 09:48:08 +0000517 CallSite = GetElementPtrInst::Create(FunctionContext, Idxs, "call_site",
Bill Wendling8d90b712011-01-07 02:54:45 +0000518 EntryBB->getTerminator());
Jim Grosbach8b818d72009-08-17 16:41:22 +0000519
Bill Wendling8d90b712011-01-07 02:54:45 +0000520 // The exception selector comes back in context->data[1]
521 Idxs[1] = ConstantInt::get(Int32Ty, 2);
Jay Foada9203102011-07-25 09:48:08 +0000522 Value *FCData = GetElementPtrInst::Create(FunctionContext, Idxs, "fc_data",
Bill Wendling8d90b712011-01-07 02:54:45 +0000523 EntryBB->getTerminator());
524 Idxs[1] = ConstantInt::get(Int32Ty, 1);
Jay Foada9203102011-07-25 09:48:08 +0000525 Value *SelectorAddr = GetElementPtrInst::Create(FCData, Idxs,
Bill Wendling8d90b712011-01-07 02:54:45 +0000526 "exc_selector_gep",
527 EntryBB->getTerminator());
528 // The exception value comes back in context->data[0]
529 Idxs[1] = Zero;
Jay Foada9203102011-07-25 09:48:08 +0000530 Value *ExceptionAddr = GetElementPtrInst::Create(FCData, Idxs,
Bill Wendling8d90b712011-01-07 02:54:45 +0000531 "exception_gep",
532 EntryBB->getTerminator());
Jim Grosbach8b818d72009-08-17 16:41:22 +0000533
Bill Wendling8d90b712011-01-07 02:54:45 +0000534 // The result of the eh.selector call will be replaced with a a reference to
535 // the selector value returned in the function context. We leave the selector
536 // itself so the EH analysis later can use it.
537 for (int i = 0, e = EH_Selectors.size(); i < e; ++i) {
538 CallInst *I = EH_Selectors[i];
539 Value *SelectorVal = new LoadInst(SelectorAddr, "select_val", true, I);
540 I->replaceAllUsesWith(SelectorVal);
Jim Grosbach8b818d72009-08-17 16:41:22 +0000541 }
542
Bill Wendling8d90b712011-01-07 02:54:45 +0000543 // eh.exception calls are replaced with references to the proper location in
544 // the context. Unlike eh.selector, the eh.exception calls are removed
545 // entirely.
546 for (int i = 0, e = EH_Exceptions.size(); i < e; ++i) {
547 CallInst *I = EH_Exceptions[i];
548 // Possible for there to be duplicates, so check to make sure the
549 // instruction hasn't already been removed.
550 if (!I->getParent()) continue;
551 Value *Val = new LoadInst(ExceptionAddr, "exception", true, I);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000552 Type *Ty = Type::getInt8PtrTy(F.getContext());
Bill Wendling8d90b712011-01-07 02:54:45 +0000553 Val = CastInst::Create(Instruction::IntToPtr, Val, Ty, "", I);
554
555 I->replaceAllUsesWith(Val);
556 I->eraseFromParent();
557 }
558
Bill Wendlingaef508d2011-08-22 23:38:40 +0000559 for (unsigned i = 0, e = LandingPads.size(); i != e; ++i)
560 ReplaceLandingPadVal(F, LandingPads[i], ExceptionAddr, SelectorAddr);
561
Bill Wendling8d90b712011-01-07 02:54:45 +0000562 // The entry block changes to have the eh.sjlj.setjmp, with a conditional
563 // branch to a dispatch block for non-zero returns. If we return normally,
564 // we're not handling an exception and just register the function context and
565 // continue.
566
567 // Create the dispatch block. The dispatch block is basically a big switch
568 // statement that goes to all of the invoke landing pads.
569 BasicBlock *DispatchBlock =
570 BasicBlock::Create(F.getContext(), "eh.sjlj.setjmp.catch", &F);
571
Bill Wendling8d90b712011-01-07 02:54:45 +0000572 // Insert a load of the callsite in the dispatch block, and a switch on its
Bill Wendlingcc885952011-04-11 21:32:34 +0000573 // value. By default, we issue a trap statement.
574 BasicBlock *TrapBlock =
575 BasicBlock::Create(F.getContext(), "trapbb", &F);
576 CallInst::Create(Intrinsic::getDeclaration(F.getParent(), Intrinsic::trap),
577 "", TrapBlock);
578 new UnreachableInst(F.getContext(), TrapBlock);
Bill Wendling8d90b712011-01-07 02:54:45 +0000579
580 Value *DispatchLoad = new LoadInst(CallSite, "invoke.num", true,
581 DispatchBlock);
582 SwitchInst *DispatchSwitch =
Bill Wendlingcc885952011-04-11 21:32:34 +0000583 SwitchInst::Create(DispatchLoad, TrapBlock, Invokes.size(),
Bill Wendling8d90b712011-01-07 02:54:45 +0000584 DispatchBlock);
585 // Split the entry block to insert the conditional branch for the setjmp.
586 BasicBlock *ContBlock = EntryBB->splitBasicBlock(EntryBB->getTerminator(),
587 "eh.sjlj.setjmp.cont");
588
589 // Populate the Function Context
590 // 1. LSDA address
591 // 2. Personality function address
592 // 3. jmpbuf (save SP, FP and call eh.sjlj.setjmp)
593
594 // LSDA address
595 Idxs[0] = Zero;
596 Idxs[1] = ConstantInt::get(Int32Ty, 4);
597 Value *LSDAFieldPtr =
Jay Foada9203102011-07-25 09:48:08 +0000598 GetElementPtrInst::Create(FunctionContext, Idxs, "lsda_gep",
Bill Wendling8d90b712011-01-07 02:54:45 +0000599 EntryBB->getTerminator());
600 Value *LSDA = CallInst::Create(LSDAAddrFn, "lsda_addr",
601 EntryBB->getTerminator());
602 new StoreInst(LSDA, LSDAFieldPtr, true, EntryBB->getTerminator());
603
604 Idxs[1] = ConstantInt::get(Int32Ty, 3);
605 Value *PersonalityFieldPtr =
Jay Foada9203102011-07-25 09:48:08 +0000606 GetElementPtrInst::Create(FunctionContext, Idxs, "lsda_gep",
Bill Wendling8d90b712011-01-07 02:54:45 +0000607 EntryBB->getTerminator());
608 new StoreInst(PersonalityFn, PersonalityFieldPtr, true,
609 EntryBB->getTerminator());
610
611 // Save the frame pointer.
612 Idxs[1] = ConstantInt::get(Int32Ty, 5);
613 Value *JBufPtr
Jay Foada9203102011-07-25 09:48:08 +0000614 = GetElementPtrInst::Create(FunctionContext, Idxs, "jbuf_gep",
Bill Wendling8d90b712011-01-07 02:54:45 +0000615 EntryBB->getTerminator());
616 Idxs[1] = ConstantInt::get(Int32Ty, 0);
617 Value *FramePtr =
Jay Foada9203102011-07-25 09:48:08 +0000618 GetElementPtrInst::Create(JBufPtr, Idxs, "jbuf_fp_gep",
Bill Wendling8d90b712011-01-07 02:54:45 +0000619 EntryBB->getTerminator());
620
621 Value *Val = CallInst::Create(FrameAddrFn,
622 ConstantInt::get(Int32Ty, 0),
623 "fp",
624 EntryBB->getTerminator());
625 new StoreInst(Val, FramePtr, true, EntryBB->getTerminator());
626
627 // Save the stack pointer.
628 Idxs[1] = ConstantInt::get(Int32Ty, 2);
629 Value *StackPtr =
Jay Foada9203102011-07-25 09:48:08 +0000630 GetElementPtrInst::Create(JBufPtr, Idxs, "jbuf_sp_gep",
Bill Wendling8d90b712011-01-07 02:54:45 +0000631 EntryBB->getTerminator());
632
633 Val = CallInst::Create(StackAddrFn, "sp", EntryBB->getTerminator());
634 new StoreInst(Val, StackPtr, true, EntryBB->getTerminator());
635
636 // Call the setjmp instrinsic. It fills in the rest of the jmpbuf.
637 Value *SetjmpArg =
638 CastInst::Create(Instruction::BitCast, JBufPtr,
639 Type::getInt8PtrTy(F.getContext()), "",
640 EntryBB->getTerminator());
641 Value *DispatchVal = CallInst::Create(BuiltinSetjmpFn, SetjmpArg,
Bill Wendlingda7e6a92011-10-04 00:16:40 +0000642 "",
Bill Wendling8d90b712011-01-07 02:54:45 +0000643 EntryBB->getTerminator());
Bill Wendlingf05b1dc2011-04-05 01:37:43 +0000644
645 // Add a call to dispatch_setup after the setjmp call. This is expanded to any
646 // target-specific setup that needs to be done.
Bill Wendling61512ba2011-05-11 01:11:55 +0000647 CallInst::Create(DispatchSetupFn, DispatchVal, "", EntryBB->getTerminator());
Bill Wendlingf05b1dc2011-04-05 01:37:43 +0000648
Bill Wendling8d90b712011-01-07 02:54:45 +0000649 // check the return value of the setjmp. non-zero goes to dispatcher.
650 Value *IsNormal = new ICmpInst(EntryBB->getTerminator(),
651 ICmpInst::ICMP_EQ, DispatchVal, Zero,
652 "notunwind");
653 // Nuke the uncond branch.
654 EntryBB->getTerminator()->eraseFromParent();
655
656 // Put in a new condbranch in its place.
657 BranchInst::Create(ContBlock, DispatchBlock, IsNormal, EntryBB);
658
659 // Register the function context and make sure it's known to not throw
660 CallInst *Register =
661 CallInst::Create(RegisterFn, FunctionContext, "",
662 ContBlock->getTerminator());
663 Register->setDoesNotThrow();
664
665 // At this point, we are all set up, update the invoke instructions to mark
666 // their call_site values, and fill in the dispatch switch accordingly.
667 for (unsigned i = 0, e = Invokes.size(); i != e; ++i)
668 markInvokeCallSite(Invokes[i], i+1, CallSite, DispatchSwitch);
669
670 // Mark call instructions that aren't nounwind as no-action (call_site ==
671 // -1). Skip the entry block, as prior to then, no function context has been
672 // created for this function and any unexpected exceptions thrown will go
673 // directly to the caller's context, which is what we want anyway, so no need
674 // to do anything here.
675 for (Function::iterator BB = F.begin(), E = F.end(); ++BB != E;) {
676 for (BasicBlock::iterator I = BB->begin(), end = BB->end(); I != end; ++I)
677 if (CallInst *CI = dyn_cast<CallInst>(I)) {
678 // Ignore calls to the EH builtins (eh.selector, eh.exception)
679 Constant *Callee = CI->getCalledFunction();
680 if (Callee != SelectorFn && Callee != ExceptionFn
681 && !CI->doesNotThrow())
682 insertCallSiteStore(CI, -1, CallSite);
Bill Wendling3ae96d62011-08-24 00:00:23 +0000683 } else if (ResumeInst *RI = dyn_cast<ResumeInst>(I)) {
684 insertCallSiteStore(RI, -1, CallSite);
Bill Wendling8d90b712011-01-07 02:54:45 +0000685 }
686 }
687
688 // Replace all unwinds with a branch to the unwind handler.
689 // ??? Should this ever happen with sjlj exceptions?
690 for (unsigned i = 0, e = Unwinds.size(); i != e; ++i) {
Bill Wendlingcc885952011-04-11 21:32:34 +0000691 BranchInst::Create(TrapBlock, Unwinds[i]);
Bill Wendling8d90b712011-01-07 02:54:45 +0000692 Unwinds[i]->eraseFromParent();
693 }
694
695 // Following any allocas not in the entry block, update the saved SP in the
696 // jmpbuf to the new value.
697 for (unsigned i = 0, e = JmpbufUpdatePoints.size(); i != e; ++i) {
698 Instruction *AI = JmpbufUpdatePoints[i];
699 Instruction *StackAddr = CallInst::Create(StackAddrFn, "sp");
700 StackAddr->insertAfter(AI);
701 Instruction *StoreStackAddr = new StoreInst(StackAddr, StackPtr, true);
702 StoreStackAddr->insertAfter(StackAddr);
703 }
704
705 // Finally, for any returns from this function, if this function contains an
706 // invoke, add a call to unregister the function context.
707 for (unsigned i = 0, e = Returns.size(); i != e; ++i)
708 CallInst::Create(UnregisterFn, FunctionContext, "", Returns[i]);
709
Jim Grosbach8b818d72009-08-17 16:41:22 +0000710 return true;
711}
712
Bill Wendling2b6bd7b2011-09-28 03:14:05 +0000713/// setupFunctionContext - Allocate the function context on the stack and fill
714/// it with all of the data that we know at this point.
Bill Wendling631d1172011-10-03 21:15:28 +0000715Value *SjLjEHPass::
Bill Wendlingcc8cf972011-09-28 21:56:53 +0000716setupFunctionContext(Function &F, ArrayRef<LandingPadInst*> LPads) {
Bill Wendling2b6bd7b2011-09-28 03:14:05 +0000717 BasicBlock *EntryBB = F.begin();
718
719 // Create an alloca for the incoming jump buffer ptr and the new jump buffer
720 // that needs to be restored on all exits from the function. This is an alloca
721 // because the value needs to be added to the global context list.
722 unsigned Align =
723 TLI->getTargetData()->getPrefTypeAlignment(FunctionContextTy);
724 AllocaInst *FuncCtx =
725 new AllocaInst(FunctionContextTy, 0, Align, "fn_context", EntryBB->begin());
726
727 // Fill in the function context structure.
728 Value *Idxs[2];
729 Type *Int32Ty = Type::getInt32Ty(F.getContext());
730 Value *Zero = ConstantInt::get(Int32Ty, 0);
731 Value *One = ConstantInt::get(Int32Ty, 1);
732
733 // Keep around a reference to the call_site field.
734 Idxs[0] = Zero;
735 Idxs[1] = One;
736 CallSite = GetElementPtrInst::Create(FuncCtx, Idxs, "call_site",
737 EntryBB->getTerminator());
738
739 // Reference the __data field.
740 Idxs[1] = ConstantInt::get(Int32Ty, 2);
741 Value *FCData = GetElementPtrInst::Create(FuncCtx, Idxs, "__data",
742 EntryBB->getTerminator());
743
744 // The exception value comes back in context->__data[0].
745 Idxs[1] = Zero;
746 Value *ExceptionAddr = GetElementPtrInst::Create(FCData, Idxs,
747 "exception_gep",
748 EntryBB->getTerminator());
749
750 // The exception selector comes back in context->__data[1].
751 Idxs[1] = One;
752 Value *SelectorAddr = GetElementPtrInst::Create(FCData, Idxs,
753 "exn_selector_gep",
754 EntryBB->getTerminator());
755
756 for (unsigned I = 0, E = LPads.size(); I != E; ++I) {
757 LandingPadInst *LPI = LPads[I];
758 IRBuilder<> Builder(LPI->getParent()->getFirstInsertionPt());
759
760 Value *ExnVal = Builder.CreateLoad(ExceptionAddr, true, "exn_val");
761 ExnVal = Builder.CreateIntToPtr(ExnVal, Type::getInt8PtrTy(F.getContext()));
762 Value *SelVal = Builder.CreateLoad(SelectorAddr, true, "exn_selector_val");
763
764 Type *LPadType = LPI->getType();
765 Value *LPadVal = UndefValue::get(LPadType);
766 LPadVal = Builder.CreateInsertValue(LPadVal, ExnVal, 0, "lpad.val");
767 LPadVal = Builder.CreateInsertValue(LPadVal, SelVal, 1, "lpad.val");
768
769 LPI->replaceAllUsesWith(LPadVal);
770 }
771
772 // Personality function
773 Idxs[1] = ConstantInt::get(Int32Ty, 3);
774 if (!PersonalityFn)
775 PersonalityFn = LPads[0]->getPersonalityFn();
776 Value *PersonalityFieldPtr =
777 GetElementPtrInst::Create(FuncCtx, Idxs, "pers_fn_gep",
778 EntryBB->getTerminator());
779 new StoreInst(PersonalityFn, PersonalityFieldPtr, true,
780 EntryBB->getTerminator());
781
782 // LSDA address
783 Idxs[1] = ConstantInt::get(Int32Ty, 4);
Bill Wendlingda7e6a92011-10-04 00:16:40 +0000784 Value *LSDAFieldPtr = GetElementPtrInst::Create(FuncCtx, Idxs, "lsda_gep",
785 EntryBB->getTerminator());
Bill Wendling2b6bd7b2011-09-28 03:14:05 +0000786 Value *LSDA = CallInst::Create(LSDAAddrFn, "lsda_addr",
787 EntryBB->getTerminator());
788 new StoreInst(LSDA, LSDAFieldPtr, true, EntryBB->getTerminator());
789
Bill Wendling631d1172011-10-03 21:15:28 +0000790 return FuncCtx;
Bill Wendlingcc8cf972011-09-28 21:56:53 +0000791}
792
Bill Wendlingd5d17002011-10-08 00:56:47 +0000793/// lowerIncomingArguments - To avoid having to handle incoming arguments
794/// specially, we lower each arg to a copy instruction in the entry block. This
795/// ensures that the argument value itself cannot be live out of the entry
796/// block.
797void SjLjEHPass::lowerIncomingArguments(Function &F) {
798 BasicBlock::iterator AfterAllocaInsPt = F.begin()->begin();
799 while (isa<AllocaInst>(AfterAllocaInsPt) &&
800 isa<ConstantInt>(cast<AllocaInst>(AfterAllocaInsPt)->getArraySize()))
801 ++AfterAllocaInsPt;
802
803 for (Function::arg_iterator
804 AI = F.arg_begin(), AE = F.arg_end(); AI != AE; ++AI) {
805 Type *Ty = AI->getType();
806
807 // Aggregate types can't be cast, but are legal argument types, so we have
808 // to handle them differently. We use an extract/insert pair as a
809 // lightweight method to achieve the same goal.
810 if (isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<VectorType>(Ty)) {
811 Instruction *EI = ExtractValueInst::Create(AI, 0, "", AfterAllocaInsPt);
812 Instruction *NI = InsertValueInst::Create(AI, EI, 0);
813 NI->insertAfter(EI);
814 AI->replaceAllUsesWith(NI);
815
816 // Set the operand of the instructions back to the AllocaInst.
817 EI->setOperand(0, AI);
818 NI->setOperand(0, AI);
819 } else {
820 // This is always a no-op cast because we're casting AI to AI->getType()
821 // so src and destination types are identical. BitCast is the only
822 // possibility.
823 CastInst *NC =
824 new BitCastInst(AI, AI->getType(), AI->getName() + ".tmp",
825 AfterAllocaInsPt);
826 AI->replaceAllUsesWith(NC);
827
828 // Set the operand of the cast instruction back to the AllocaInst.
829 // Normally it's forbidden to replace a CastInst's operand because it
830 // could cause the opcode to reflect an illegal conversion. However, we're
831 // replacing it here with the same value it was constructed with. We do
832 // this because the above replaceAllUsesWith() clobbered the operand, but
833 // we want this one to remain.
834 NC->setOperand(0, AI);
835 }
836 }
837}
838
839/// lowerAcrossUnwindEdges - Find all variables which are alive across an unwind
840/// edge and spill them.
841void SjLjEHPass::lowerAcrossUnwindEdges(Function &F,
842 ArrayRef<InvokeInst*> Invokes) {
843 // Finally, scan the code looking for instructions with bad live ranges.
844 for (Function::iterator
845 BB = F.begin(), BBE = F.end(); BB != BBE; ++BB) {
846 for (BasicBlock::iterator
847 II = BB->begin(), IIE = BB->end(); II != IIE; ++II) {
848 // Ignore obvious cases we don't have to handle. In particular, most
849 // instructions either have no uses or only have a single use inside the
850 // current block. Ignore them quickly.
851 Instruction *Inst = II;
852 if (Inst->use_empty()) continue;
853 if (Inst->hasOneUse() &&
854 cast<Instruction>(Inst->use_back())->getParent() == BB &&
855 !isa<PHINode>(Inst->use_back())) continue;
856
857 // If this is an alloca in the entry block, it's not a real register
858 // value.
859 if (AllocaInst *AI = dyn_cast<AllocaInst>(Inst))
860 if (isa<ConstantInt>(AI->getArraySize()) && BB == F.begin())
861 continue;
862
863 // Avoid iterator invalidation by copying users to a temporary vector.
864 SmallVector<Instruction*, 16> Users;
865 for (Value::use_iterator
866 UI = Inst->use_begin(), E = Inst->use_end(); UI != E; ++UI) {
867 Instruction *User = cast<Instruction>(*UI);
868 if (User->getParent() != BB || isa<PHINode>(User))
869 Users.push_back(User);
870 }
871
872 // Find all of the blocks that this value is live in.
873 std::set<BasicBlock*> LiveBBs;
874 LiveBBs.insert(Inst->getParent());
875 while (!Users.empty()) {
876 Instruction *U = Users.back();
877 Users.pop_back();
878
879 if (!isa<PHINode>(U)) {
880 MarkBlocksLiveIn(U->getParent(), LiveBBs);
881 } else {
882 // Uses for a PHI node occur in their predecessor block.
883 PHINode *PN = cast<PHINode>(U);
884 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
885 if (PN->getIncomingValue(i) == Inst)
886 MarkBlocksLiveIn(PN->getIncomingBlock(i), LiveBBs);
887 }
888 }
889
890 // Now that we know all of the blocks that this thing is live in, see if
891 // it includes any of the unwind locations.
892 bool NeedsSpill = false;
893 for (unsigned i = 0, e = Invokes.size(); i != e; ++i) {
894 BasicBlock *UnwindBlock = Invokes[i]->getUnwindDest();
895 if (UnwindBlock != BB && LiveBBs.count(UnwindBlock)) {
896 NeedsSpill = true;
897 }
898 }
899
900 // If we decided we need a spill, do it.
901 // FIXME: Spilling this way is overkill, as it forces all uses of
902 // the value to be reloaded from the stack slot, even those that aren't
903 // in the unwind blocks. We should be more selective.
904 if (NeedsSpill) {
905 ++NumSpilled;
906 DemoteRegToStack(*Inst, true);
907 }
908 }
909 }
910}
911
Bill Wendlingcc8cf972011-09-28 21:56:53 +0000912/// setupEntryBlockAndCallSites - Setup the entry block by creating and filling
913/// the function context and marking the call sites with the appropriate
914/// values. These values are used by the DWARF EH emitter.
915bool SjLjEHPass::setupEntryBlockAndCallSites(Function &F) {
916 SmallVector<ReturnInst*, 16> Returns;
917 SmallVector<InvokeInst*, 16> Invokes;
918 SmallVector<LandingPadInst*, 16> LPads;
919
920 // Look through the terminators of the basic blocks to find invokes.
921 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
922 if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
923 Invokes.push_back(II);
924 LPads.push_back(II->getUnwindDest()->getLandingPadInst());
925 } else if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
926 Returns.push_back(RI);
927 }
928
929 if (Invokes.empty()) return false;
930
Bill Wendlingd5d17002011-10-08 00:56:47 +0000931 lowerIncomingArguments(F);
932 lowerAcrossUnwindEdges(F, Invokes);
933
Bill Wendling631d1172011-10-03 21:15:28 +0000934 Value *FuncCtx = setupFunctionContext(F, LPads);
Bill Wendlingcc8cf972011-09-28 21:56:53 +0000935 BasicBlock *EntryBB = F.begin();
Bill Wendlingcc8cf972011-09-28 21:56:53 +0000936 Type *Int32Ty = Type::getInt32Ty(F.getContext());
Bill Wendling631d1172011-10-03 21:15:28 +0000937
Bill Wendlingcc8cf972011-09-28 21:56:53 +0000938 Value *Idxs[2] = {
Bill Wendling631d1172011-10-03 21:15:28 +0000939 ConstantInt::get(Int32Ty, 0), 0
Bill Wendlingcc8cf972011-09-28 21:56:53 +0000940 };
Bill Wendling631d1172011-10-03 21:15:28 +0000941
942 // Get a reference to the jump buffer.
943 Idxs[1] = ConstantInt::get(Int32Ty, 5);
Bill Wendlingda7e6a92011-10-04 00:16:40 +0000944 Value *JBufPtr = GetElementPtrInst::Create(FuncCtx, Idxs, "jbuf_gep",
945 EntryBB->getTerminator());
Bill Wendling2b6bd7b2011-09-28 03:14:05 +0000946
Bill Wendling631d1172011-10-03 21:15:28 +0000947 // Save the frame pointer.
948 Idxs[1] = ConstantInt::get(Int32Ty, 0);
Bill Wendlingda7e6a92011-10-04 00:16:40 +0000949 Value *FramePtr = GetElementPtrInst::Create(JBufPtr, Idxs, "jbuf_fp_gep",
950 EntryBB->getTerminator());
Bill Wendling631d1172011-10-03 21:15:28 +0000951
952 Value *Val = CallInst::Create(FrameAddrFn,
953 ConstantInt::get(Int32Ty, 0),
954 "fp",
955 EntryBB->getTerminator());
956 new StoreInst(Val, FramePtr, true, EntryBB->getTerminator());
957
958 // Save the stack pointer.
959 Idxs[1] = ConstantInt::get(Int32Ty, 2);
Bill Wendlingda7e6a92011-10-04 00:16:40 +0000960 Value *StackPtr = GetElementPtrInst::Create(JBufPtr, Idxs, "jbuf_sp_gep",
961 EntryBB->getTerminator());
Bill Wendling631d1172011-10-03 21:15:28 +0000962
963 Val = CallInst::Create(StackAddrFn, "sp", EntryBB->getTerminator());
Bill Wendling2b6bd7b2011-09-28 03:14:05 +0000964 new StoreInst(Val, StackPtr, true, EntryBB->getTerminator());
965
966 // Call the setjmp instrinsic. It fills in the rest of the jmpbuf.
Bill Wendlingda7e6a92011-10-04 00:16:40 +0000967 Value *SetjmpArg = CastInst::Create(Instruction::BitCast, JBufPtr,
968 Type::getInt8PtrTy(F.getContext()), "",
969 EntryBB->getTerminator());
Bill Wendlingf8520d52011-10-03 22:42:40 +0000970 CallInst::Create(BuiltinSetjmpFn, SetjmpArg, "", EntryBB->getTerminator());
Bill Wendling2b6bd7b2011-09-28 03:14:05 +0000971
Bill Wendlingcc8cf972011-09-28 21:56:53 +0000972 // Store a pointer to the function context so that the back-end will know
973 // where to look for it.
Bill Wendlingda7e6a92011-10-04 00:16:40 +0000974 Value *FuncCtxArg = CastInst::Create(Instruction::BitCast, FuncCtx,
975 Type::getInt8PtrTy(F.getContext()), "",
976 EntryBB->getTerminator());
Bill Wendlingcc8cf972011-09-28 21:56:53 +0000977 CallInst::Create(FuncCtxFn, FuncCtxArg, "", EntryBB->getTerminator());
Bill Wendling2b6bd7b2011-09-28 03:14:05 +0000978
979 // At this point, we are all set up, update the invoke instructions to mark
Bill Wendling2130ab02011-10-05 22:04:08 +0000980 // their call_site values.
Bill Wendling2b6bd7b2011-09-28 03:14:05 +0000981 for (unsigned I = 0, E = Invokes.size(); I != E; ++I) {
982 insertCallSiteStore(Invokes[I], I + 1, CallSite);
983
984 ConstantInt *CallSiteNum =
985 ConstantInt::get(Type::getInt32Ty(F.getContext()), I + 1);
986
987 // Record the call site value for the back end so it stays associated with
988 // the invoke.
989 CallInst::Create(CallSiteFn, CallSiteNum, "", Invokes[I]);
990 }
991
992 // Mark call instructions that aren't nounwind as no-action (call_site ==
993 // -1). Skip the entry block, as prior to then, no function context has been
994 // created for this function and any unexpected exceptions thrown will go
995 // directly to the caller's context, which is what we want anyway, so no need
996 // to do anything here.
Bill Wendlingda7e6a92011-10-04 00:16:40 +0000997 for (Function::iterator BB = F.begin(), E = F.end(); ++BB != E;)
Bill Wendling2b6bd7b2011-09-28 03:14:05 +0000998 for (BasicBlock::iterator I = BB->begin(), end = BB->end(); I != end; ++I)
999 if (CallInst *CI = dyn_cast<CallInst>(I)) {
1000 if (!CI->doesNotThrow())
1001 insertCallSiteStore(CI, -1, CallSite);
1002 } else if (ResumeInst *RI = dyn_cast<ResumeInst>(I)) {
1003 insertCallSiteStore(RI, -1, CallSite);
1004 }
Bill Wendling2b6bd7b2011-09-28 03:14:05 +00001005
Bill Wendlingcc8cf972011-09-28 21:56:53 +00001006 // Register the function context and make sure it's known to not throw
Bill Wendling631d1172011-10-03 21:15:28 +00001007 CallInst *Register = CallInst::Create(RegisterFn, FuncCtx, "",
Bill Wendlingcc8cf972011-09-28 21:56:53 +00001008 EntryBB->getTerminator());
1009 Register->setDoesNotThrow();
1010
1011 // Finally, for any returns from this function, if this function contains an
1012 // invoke, add a call to unregister the function context.
1013 for (unsigned I = 0, E = Returns.size(); I != E; ++I)
Bill Wendling631d1172011-10-03 21:15:28 +00001014 CallInst::Create(UnregisterFn, FuncCtx, "", Returns[I]);
Bill Wendlingcc8cf972011-09-28 21:56:53 +00001015
Bill Wendling2b6bd7b2011-09-28 03:14:05 +00001016 return true;
1017}
1018
Jim Grosbach8b818d72009-08-17 16:41:22 +00001019bool SjLjEHPass::runOnFunction(Function &F) {
Bill Wendling2b6bd7b2011-09-28 03:14:05 +00001020 bool Res = false;
1021 if (!DisableOldSjLjEH)
1022 Res = insertSjLjEHSupport(F);
1023 else
1024 Res = setupEntryBlockAndCallSites(F);
Jim Grosbach8b818d72009-08-17 16:41:22 +00001025 return Res;
1026}