blob: a406f8e2426794bf5dc13494bfd1b3bc3d5d2961 [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"
Bill Wendlingfbf9ff42012-03-10 07:11:55 +000024#include "llvm/Analysis/Verifier.h"
Jim Grosbach8b818d72009-08-17 16:41:22 +000025#include "llvm/CodeGen/Passes.h"
Bill Wendling2b6bd7b2011-09-28 03:14:05 +000026#include "llvm/Target/TargetData.h"
Benjamin Kramerf7888542010-11-06 11:45:59 +000027#include "llvm/Target/TargetLowering.h"
Jim Grosbach8b818d72009-08-17 16:41:22 +000028#include "llvm/Transforms/Utils/BasicBlockUtils.h"
29#include "llvm/Transforms/Utils/Local.h"
Bill Wendling2b6bd7b2011-09-28 03:14:05 +000030#include "llvm/Support/CommandLine.h"
Bill Wendlingd36b3e32011-08-22 18:44:49 +000031#include "llvm/Support/Debug.h"
Bill Wendling2b6bd7b2011-09-28 03:14:05 +000032#include "llvm/Support/IRBuilder.h"
Andrew Trick9c7b3da2012-01-07 00:54:28 +000033#include "llvm/Support/raw_ostream.h"
Bill Wendlingaef508d2011-08-22 23:38:40 +000034#include "llvm/ADT/DenseMap.h"
Bob Wilsonf1b41dd2011-11-16 07:57:21 +000035#include "llvm/ADT/SetVector.h"
Bill Wendlingd2dae0c2011-10-24 17:12:36 +000036#include "llvm/ADT/SmallPtrSet.h"
Bill Wendlingd36b3e32011-08-22 18:44:49 +000037#include "llvm/ADT/SmallVector.h"
38#include "llvm/ADT/Statistic.h"
Benjamin Kramerf7888542010-11-06 11:45:59 +000039#include <set>
Jim Grosbach8b818d72009-08-17 16:41:22 +000040using namespace llvm;
41
42STATISTIC(NumInvokes, "Number of invokes replaced");
Jim Grosbach8b818d72009-08-17 16:41:22 +000043STATISTIC(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;
Bob Wilson20c918d2011-11-16 07:12:00 +000054 Constant *StackRestoreFn;
Jim Grosbach8b818d72009-08-17 16:41:22 +000055 Constant *LSDAAddrFn;
56 Value *PersonalityFn;
Jim Grosbachca752c92010-01-28 01:45:32 +000057 Constant *CallSiteFn;
Bill Wendlingcc8cf972011-09-28 21:56:53 +000058 Constant *FuncCtxFn;
Bill Wendling4cc46662012-01-27 02:02:24 +000059 AllocaInst *FuncCtx;
Jim Grosbach8b818d72009-08-17 16:41:22 +000060 public:
61 static char ID; // Pass identification, replacement for typeid
62 explicit SjLjEHPass(const TargetLowering *tli = NULL)
Owen Anderson90c579d2010-08-06 18:33:48 +000063 : FunctionPass(ID), TLI(tli) { }
Jim Grosbach8b818d72009-08-17 16:41:22 +000064 bool doInitialization(Module &M);
65 bool runOnFunction(Function &F);
66
Bill Wendlingd36b3e32011-08-22 18:44:49 +000067 virtual void getAnalysisUsage(AnalysisUsage &AU) const {}
Jim Grosbach8b818d72009-08-17 16:41:22 +000068 const char *getPassName() const {
69 return "SJLJ Exception Handling preparation";
70 }
71
72 private:
Bill Wendling2b6bd7b2011-09-28 03:14:05 +000073 bool setupEntryBlockAndCallSites(Function &F);
Bill Wendling69fdcd72011-12-14 22:45:33 +000074 void substituteLPadValues(LandingPadInst *LPI, Value *ExnVal,
75 Value *SelVal);
Bill Wendling631d1172011-10-03 21:15:28 +000076 Value *setupFunctionContext(Function &F, ArrayRef<LandingPadInst*> LPads);
Bill Wendlingd5d17002011-10-08 00:56:47 +000077 void lowerIncomingArguments(Function &F);
78 void lowerAcrossUnwindEdges(Function &F, ArrayRef<InvokeInst*> Invokes);
Bill Wendling4cc46662012-01-27 02:02:24 +000079 void insertCallSiteStore(Instruction *I, int Number);
Jim Grosbach8b818d72009-08-17 16:41:22 +000080 };
81} // end anonymous namespace
82
83char SjLjEHPass::ID = 0;
84
85// Public Interface To the SjLjEHPass pass.
86FunctionPass *llvm::createSjLjEHPass(const TargetLowering *TLI) {
87 return new SjLjEHPass(TLI);
88}
Jim Grosbacha235d132009-08-23 18:13:48 +000089// doInitialization - Set up decalarations and types needed to process
90// exceptions.
Jim Grosbach8b818d72009-08-17 16:41:22 +000091bool SjLjEHPass::doInitialization(Module &M) {
92 // Build the function context structure.
93 // builtin_setjmp uses a five word jbuf
Jay Foad5fdd6c82011-07-12 14:06:48 +000094 Type *VoidPtrTy = Type::getInt8PtrTy(M.getContext());
95 Type *Int32Ty = Type::getInt32Ty(M.getContext());
Jim Grosbach8b818d72009-08-17 16:41:22 +000096 FunctionContextTy =
Chris Lattnerb2318662011-06-18 22:48:56 +000097 StructType::get(VoidPtrTy, // __prev
Jim Grosbach8b818d72009-08-17 16:41:22 +000098 Int32Ty, // call_site
99 ArrayType::get(Int32Ty, 4), // __data
100 VoidPtrTy, // __personality
101 VoidPtrTy, // __lsda
102 ArrayType::get(VoidPtrTy, 5), // __jbuf
103 NULL);
104 RegisterFn = M.getOrInsertFunction("_Unwind_SjLj_Register",
105 Type::getVoidTy(M.getContext()),
106 PointerType::getUnqual(FunctionContextTy),
107 (Type *)0);
108 UnregisterFn =
109 M.getOrInsertFunction("_Unwind_SjLj_Unregister",
110 Type::getVoidTy(M.getContext()),
111 PointerType::getUnqual(FunctionContextTy),
112 (Type *)0);
Jim Grosbach8b818d72009-08-17 16:41:22 +0000113 FrameAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::frameaddress);
Jim Grosbach0798edd2010-05-27 23:49:24 +0000114 StackAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::stacksave);
Bob Wilson20c918d2011-11-16 07:12:00 +0000115 StackRestoreFn = Intrinsic::getDeclaration(&M, Intrinsic::stackrestore);
Jim Grosbach8b818d72009-08-17 16:41:22 +0000116 BuiltinSetjmpFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_setjmp);
117 LSDAAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_lsda);
Jim Grosbachca752c92010-01-28 01:45:32 +0000118 CallSiteFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_callsite);
Bill Wendlingcc8cf972011-09-28 21:56:53 +0000119 FuncCtxFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_functioncontext);
Jim Grosbacha235d132009-08-23 18:13:48 +0000120 PersonalityFn = 0;
Jim Grosbach8b818d72009-08-17 16:41:22 +0000121
122 return true;
123}
124
Jim Grosbachb58a59b2010-03-04 22:07:46 +0000125/// insertCallSiteStore - Insert a store of the call-site value to the
126/// function context
Bill Wendling4cc46662012-01-27 02:02:24 +0000127void SjLjEHPass::insertCallSiteStore(Instruction *I, int Number) {
128 IRBuilder<> Builder(I);
129
130 // Get a reference to the call_site field.
131 Type *Int32Ty = Type::getInt32Ty(I->getContext());
132 Value *Zero = ConstantInt::get(Int32Ty, 0);
133 Value *One = ConstantInt::get(Int32Ty, 1);
134 Value *Idxs[2] = { Zero, One };
135 Value *CallSite = Builder.CreateGEP(FuncCtx, Idxs, "call_site");
136
137 // Insert a store of the call-site number
Jim Grosbachb58a59b2010-03-04 22:07:46 +0000138 ConstantInt *CallSiteNoC = ConstantInt::get(Type::getInt32Ty(I->getContext()),
139 Number);
Bill Wendling4cc46662012-01-27 02:02:24 +0000140 Builder.CreateStore(CallSiteNoC, CallSite, true/*volatile*/);
Jim Grosbachb58a59b2010-03-04 22:07:46 +0000141}
142
Bill Wendlingfbf9ff42012-03-10 07:11:55 +0000143/// markBlocksLiveIn - Insert BB and all of its predescessors into LiveBBs until
Jim Grosbach8b818d72009-08-17 16:41:22 +0000144/// we reach blocks we've already seen.
Bill Wendlingfbf9ff42012-03-10 07:11:55 +0000145static void markBlocksLiveIn(BasicBlock *BB, Instruction *Inst,
146 SmallPtrSet<BasicBlock*, 64> &LiveBBs,
147 SmallPtrSet<BasicBlock*, 4> &InvokesCrossed) {
Bill Wendlingd2dae0c2011-10-24 17:12:36 +0000148 if (!LiveBBs.insert(BB)) return; // already been here.
Jim Grosbach8b818d72009-08-17 16:41:22 +0000149
Bill Wendlingfbf9ff42012-03-10 07:11:55 +0000150 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
151 BasicBlock *Pred = *PI;
152 if (BB->isLandingPad() && BB != Inst->getParent())
153 InvokesCrossed.insert(Pred);
154 markBlocksLiveIn(Pred, Inst, LiveBBs, InvokesCrossed);
155 }
Jim Grosbach8b818d72009-08-17 16:41:22 +0000156}
157
Bill Wendling69fdcd72011-12-14 22:45:33 +0000158/// substituteLPadValues - Substitute the values returned by the landingpad
159/// instruction with those returned by the personality function.
160void SjLjEHPass::substituteLPadValues(LandingPadInst *LPI, Value *ExnVal,
161 Value *SelVal) {
162 SmallVector<Value*, 8> UseWorkList(LPI->use_begin(), LPI->use_end());
163 while (!UseWorkList.empty()) {
164 Value *Val = UseWorkList.pop_back_val();
165 ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(Val);
166 if (!EVI) continue;
167 if (EVI->getNumIndices() != 1) continue;
168 if (*EVI->idx_begin() == 0)
169 EVI->replaceAllUsesWith(ExnVal);
170 else if (*EVI->idx_begin() == 1)
171 EVI->replaceAllUsesWith(SelVal);
172 if (EVI->getNumUses() == 0)
173 EVI->eraseFromParent();
174 }
175
176 if (LPI->getNumUses() == 0) return;
177
178 // There are still some uses of LPI. Construct an aggregate with the exception
179 // values and replace the LPI with that aggregate.
180 Type *LPadType = LPI->getType();
181 Value *LPadVal = UndefValue::get(LPadType);
182 IRBuilder<>
183 Builder(llvm::next(BasicBlock::iterator(cast<Instruction>(SelVal))));
184 LPadVal = Builder.CreateInsertValue(LPadVal, ExnVal, 0, "lpad.val");
185 LPadVal = Builder.CreateInsertValue(LPadVal, SelVal, 1, "lpad.val");
186
187 LPI->replaceAllUsesWith(LPadVal);
188}
189
Bill Wendling2b6bd7b2011-09-28 03:14:05 +0000190/// setupFunctionContext - Allocate the function context on the stack and fill
191/// it with all of the data that we know at this point.
Bill Wendling631d1172011-10-03 21:15:28 +0000192Value *SjLjEHPass::
Bill Wendlingcc8cf972011-09-28 21:56:53 +0000193setupFunctionContext(Function &F, ArrayRef<LandingPadInst*> LPads) {
Bill Wendling2b6bd7b2011-09-28 03:14:05 +0000194 BasicBlock *EntryBB = F.begin();
195
196 // Create an alloca for the incoming jump buffer ptr and the new jump buffer
197 // that needs to be restored on all exits from the function. This is an alloca
198 // because the value needs to be added to the global context list.
199 unsigned Align =
200 TLI->getTargetData()->getPrefTypeAlignment(FunctionContextTy);
Bill Wendling4cc46662012-01-27 02:02:24 +0000201 FuncCtx =
Bill Wendling2b6bd7b2011-09-28 03:14:05 +0000202 new AllocaInst(FunctionContextTy, 0, Align, "fn_context", EntryBB->begin());
203
204 // Fill in the function context structure.
Bill Wendling2b6bd7b2011-09-28 03:14:05 +0000205 Type *Int32Ty = Type::getInt32Ty(F.getContext());
206 Value *Zero = ConstantInt::get(Int32Ty, 0);
207 Value *One = ConstantInt::get(Int32Ty, 1);
Bill Wendling4cc46662012-01-27 02:02:24 +0000208 Value *Two = ConstantInt::get(Int32Ty, 2);
209 Value *Three = ConstantInt::get(Int32Ty, 3);
210 Value *Four = ConstantInt::get(Int32Ty, 4);
Bill Wendling2b6bd7b2011-09-28 03:14:05 +0000211
Bill Wendling4cc46662012-01-27 02:02:24 +0000212 Value *Idxs[2] = { Zero, 0 };
Bill Wendling2b6bd7b2011-09-28 03:14:05 +0000213
214 for (unsigned I = 0, E = LPads.size(); I != E; ++I) {
215 LandingPadInst *LPI = LPads[I];
216 IRBuilder<> Builder(LPI->getParent()->getFirstInsertionPt());
217
Bill Wendling4cc46662012-01-27 02:02:24 +0000218 // Reference the __data field.
219 Idxs[1] = Two;
220 Value *FCData = Builder.CreateGEP(FuncCtx, Idxs, "__data");
221
222 // The exception values come back in context->__data[0].
223 Idxs[1] = Zero;
224 Value *ExceptionAddr = Builder.CreateGEP(FCData, Idxs, "exception_gep");
Bill Wendling2b6bd7b2011-09-28 03:14:05 +0000225 Value *ExnVal = Builder.CreateLoad(ExceptionAddr, true, "exn_val");
226 ExnVal = Builder.CreateIntToPtr(ExnVal, Type::getInt8PtrTy(F.getContext()));
Bill Wendling4cc46662012-01-27 02:02:24 +0000227
228 Idxs[1] = One;
229 Value *SelectorAddr = Builder.CreateGEP(FCData, Idxs, "exn_selector_gep");
Bill Wendling2b6bd7b2011-09-28 03:14:05 +0000230 Value *SelVal = Builder.CreateLoad(SelectorAddr, true, "exn_selector_val");
231
Bill Wendling69fdcd72011-12-14 22:45:33 +0000232 substituteLPadValues(LPI, ExnVal, SelVal);
Bill Wendling2b6bd7b2011-09-28 03:14:05 +0000233 }
234
235 // Personality function
Bill Wendling4cc46662012-01-27 02:02:24 +0000236 Idxs[1] = Three;
Bill Wendling2b6bd7b2011-09-28 03:14:05 +0000237 if (!PersonalityFn)
238 PersonalityFn = LPads[0]->getPersonalityFn();
239 Value *PersonalityFieldPtr =
240 GetElementPtrInst::Create(FuncCtx, Idxs, "pers_fn_gep",
241 EntryBB->getTerminator());
242 new StoreInst(PersonalityFn, PersonalityFieldPtr, true,
243 EntryBB->getTerminator());
244
245 // LSDA address
Bill Wendling2b6bd7b2011-09-28 03:14:05 +0000246 Value *LSDA = CallInst::Create(LSDAAddrFn, "lsda_addr",
247 EntryBB->getTerminator());
Bill Wendling4cc46662012-01-27 02:02:24 +0000248 Idxs[1] = Four;
249 Value *LSDAFieldPtr = GetElementPtrInst::Create(FuncCtx, Idxs, "lsda_gep",
250 EntryBB->getTerminator());
Bill Wendling2b6bd7b2011-09-28 03:14:05 +0000251 new StoreInst(LSDA, LSDAFieldPtr, true, EntryBB->getTerminator());
252
Bill Wendling631d1172011-10-03 21:15:28 +0000253 return FuncCtx;
Bill Wendlingcc8cf972011-09-28 21:56:53 +0000254}
255
Bill Wendlingd5d17002011-10-08 00:56:47 +0000256/// lowerIncomingArguments - To avoid having to handle incoming arguments
257/// specially, we lower each arg to a copy instruction in the entry block. This
258/// ensures that the argument value itself cannot be live out of the entry
259/// block.
260void SjLjEHPass::lowerIncomingArguments(Function &F) {
261 BasicBlock::iterator AfterAllocaInsPt = F.begin()->begin();
262 while (isa<AllocaInst>(AfterAllocaInsPt) &&
263 isa<ConstantInt>(cast<AllocaInst>(AfterAllocaInsPt)->getArraySize()))
264 ++AfterAllocaInsPt;
265
266 for (Function::arg_iterator
267 AI = F.arg_begin(), AE = F.arg_end(); AI != AE; ++AI) {
268 Type *Ty = AI->getType();
269
270 // Aggregate types can't be cast, but are legal argument types, so we have
271 // to handle them differently. We use an extract/insert pair as a
272 // lightweight method to achieve the same goal.
273 if (isa<StructType>(Ty) || isa<ArrayType>(Ty) || isa<VectorType>(Ty)) {
274 Instruction *EI = ExtractValueInst::Create(AI, 0, "", AfterAllocaInsPt);
275 Instruction *NI = InsertValueInst::Create(AI, EI, 0);
276 NI->insertAfter(EI);
277 AI->replaceAllUsesWith(NI);
278
279 // Set the operand of the instructions back to the AllocaInst.
280 EI->setOperand(0, AI);
281 NI->setOperand(0, AI);
282 } else {
283 // This is always a no-op cast because we're casting AI to AI->getType()
284 // so src and destination types are identical. BitCast is the only
285 // possibility.
286 CastInst *NC =
287 new BitCastInst(AI, AI->getType(), AI->getName() + ".tmp",
288 AfterAllocaInsPt);
289 AI->replaceAllUsesWith(NC);
290
291 // Set the operand of the cast instruction back to the AllocaInst.
292 // Normally it's forbidden to replace a CastInst's operand because it
293 // could cause the opcode to reflect an illegal conversion. However, we're
294 // replacing it here with the same value it was constructed with. We do
295 // this because the above replaceAllUsesWith() clobbered the operand, but
296 // we want this one to remain.
297 NC->setOperand(0, AI);
298 }
299 }
300}
301
302/// lowerAcrossUnwindEdges - Find all variables which are alive across an unwind
303/// edge and spill them.
304void SjLjEHPass::lowerAcrossUnwindEdges(Function &F,
305 ArrayRef<InvokeInst*> Invokes) {
Bill Wendlingfbf9ff42012-03-10 07:11:55 +0000306 SmallVector<std::pair<Instruction*, Instruction*>, 32> ReloadUsers;
307 DenseMap<std::pair<Instruction*, Instruction*>, AllocaInst*> AllocaMap;
308
Bill Wendlingd5d17002011-10-08 00:56:47 +0000309 // Finally, scan the code looking for instructions with bad live ranges.
310 for (Function::iterator
311 BB = F.begin(), BBE = F.end(); BB != BBE; ++BB) {
312 for (BasicBlock::iterator
313 II = BB->begin(), IIE = BB->end(); II != IIE; ++II) {
314 // Ignore obvious cases we don't have to handle. In particular, most
315 // instructions either have no uses or only have a single use inside the
316 // current block. Ignore them quickly.
317 Instruction *Inst = II;
318 if (Inst->use_empty()) continue;
319 if (Inst->hasOneUse() &&
320 cast<Instruction>(Inst->use_back())->getParent() == BB &&
321 !isa<PHINode>(Inst->use_back())) continue;
322
323 // If this is an alloca in the entry block, it's not a real register
324 // value.
325 if (AllocaInst *AI = dyn_cast<AllocaInst>(Inst))
326 if (isa<ConstantInt>(AI->getArraySize()) && BB == F.begin())
327 continue;
328
329 // Avoid iterator invalidation by copying users to a temporary vector.
330 SmallVector<Instruction*, 16> Users;
331 for (Value::use_iterator
332 UI = Inst->use_begin(), E = Inst->use_end(); UI != E; ++UI) {
333 Instruction *User = cast<Instruction>(*UI);
334 if (User->getParent() != BB || isa<PHINode>(User))
335 Users.push_back(User);
336 }
337
338 // Find all of the blocks that this value is live in.
Bill Wendlingfbf9ff42012-03-10 07:11:55 +0000339 std::map<Instruction*, SmallPtrSet<BasicBlock*, 4> > InvokesCrossed;
340 std::map<Instruction*, SmallPtrSet<BasicBlock*, 64> > LiveBBs;
Bill Wendlingd5d17002011-10-08 00:56:47 +0000341 while (!Users.empty()) {
Bill Wendlingfbf9ff42012-03-10 07:11:55 +0000342 Instruction *U = Users.pop_back_val();
343 LiveBBs[U].insert(Inst->getParent());
Bill Wendlingd5d17002011-10-08 00:56:47 +0000344
Bill Wendlingfbf9ff42012-03-10 07:11:55 +0000345 if (PHINode *PN = dyn_cast<PHINode>(U)) {
Bill Wendlingd5d17002011-10-08 00:56:47 +0000346 // Uses for a PHI node occur in their predecessor block.
Bill Wendlingd5d17002011-10-08 00:56:47 +0000347 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
348 if (PN->getIncomingValue(i) == Inst)
Bill Wendlingfbf9ff42012-03-10 07:11:55 +0000349 markBlocksLiveIn(PN->getIncomingBlock(i), Inst, LiveBBs[U],
350 InvokesCrossed[U]);
351 } else {
352 markBlocksLiveIn(U->getParent(), Inst, LiveBBs[U], InvokesCrossed[U]);
Bill Wendlingd5d17002011-10-08 00:56:47 +0000353 }
354 }
355
Bill Wendlingfbf9ff42012-03-10 07:11:55 +0000356 // Go through the invokes the value crosses and insert a spill right
357 // before the invoke.
358 for (std::map<Instruction*, SmallPtrSet<BasicBlock*, 4> >::iterator
359 MI = InvokesCrossed.begin(), ME = InvokesCrossed.end();
360 MI != ME; ++MI) {
361 Instruction *User = MI->first;
362 SmallPtrSet<BasicBlock*, 4> &Crossings = MI->second;
363 if (Crossings.empty()) continue;
364
365 ReloadUsers.push_back(std::make_pair(Inst, User));
366
367 AllocaInst *&Slot = AllocaMap[std::make_pair(Inst, User)];
368 if (!Slot)
369 Slot = new AllocaInst(Inst->getType(), 0,
370 Inst->getName() + ".reg2mem",
371 F.getEntryBlock().begin());
372
373 for (SmallPtrSet<BasicBlock*, 4>::iterator
374 CI = Crossings.begin(), CE = Crossings.end(); CI != CE; ++CI) {
375 new StoreInst(Inst, Slot, (*CI)->getTerminator());
376 ++NumSpilled;
Bill Wendlingd5d17002011-10-08 00:56:47 +0000377 }
378 }
Bill Wendlingfbf9ff42012-03-10 07:11:55 +0000379 }
380 }
Bill Wendlingd5d17002011-10-08 00:56:47 +0000381
Bill Wendlingfbf9ff42012-03-10 07:11:55 +0000382 // Now go through the instructions which were spilled and replace their uses
383 // after a crossed invoke with a reload instruction.
384 for (SmallVectorImpl<std::pair<Instruction*, Instruction*> >::iterator
385 I = ReloadUsers.begin(), E = ReloadUsers.end(); I != E; ++I) {
386 Instruction *User = I->second;
387 AllocaInst *Slot = AllocaMap[*I];
388 assert(Slot && "A spill slot hasn't been allocated yet!");
389
390 if (PHINode *PN = dyn_cast<PHINode>(User)) {
391 // If this is a PHI node, we can't insert a load of the value before the
392 // use. Instead insert the load in the predecessor block corresponding to
393 // the incoming value.
394 //
395 // Note that if there are multiple edges from a basic block to this PHI
396 // node that we cannot have multiple loads. The problem is that the
397 // resulting PHI node will have multiple values (from each load) coming in
398 // from the same block, which is illegal SSA form. For this reason, we
399 // keep track of and reuse loads we insert.
400 DenseMap<BasicBlock*, Value*> Loads;
401 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
402 if (PN->getIncomingValue(i) == I->first) {
403 Value *&V = Loads[PN->getIncomingBlock(i)];
404 if (V == 0)
405 // Insert the load into the predecessor block
406 V = new LoadInst(Slot, I->first->getName() + ".reload", true,
407 PN->getIncomingBlock(i)->getTerminator());
408
409 PN->setIncomingValue(i, V);
410 }
411 } else {
412 LoadInst *Reload = new LoadInst(Slot, Slot->getName() + ".reload", User);
413 User->replaceUsesOfWith(I->first, Reload);
Bill Wendlingd5d17002011-10-08 00:56:47 +0000414 }
415 }
Bill Wendling0ad56122011-10-21 22:08:56 +0000416
417 // Go through the landing pads and remove any PHIs there.
418 for (unsigned i = 0, e = Invokes.size(); i != e; ++i) {
419 BasicBlock *UnwindBlock = Invokes[i]->getUnwindDest();
420 LandingPadInst *LPI = UnwindBlock->getLandingPadInst();
421
422 // Place PHIs into a set to avoid invalidating the iterator.
423 SmallPtrSet<PHINode*, 8> PHIsToDemote;
424 for (BasicBlock::iterator
425 PN = UnwindBlock->begin(); isa<PHINode>(PN); ++PN)
426 PHIsToDemote.insert(cast<PHINode>(PN));
427 if (PHIsToDemote.empty()) continue;
428
429 // Demote the PHIs to the stack.
430 for (SmallPtrSet<PHINode*, 8>::iterator
431 I = PHIsToDemote.begin(), E = PHIsToDemote.end(); I != E; ++I)
432 DemotePHIToStack(*I);
433
434 // Move the landingpad instruction back to the top of the landing pad block.
435 LPI->moveBefore(UnwindBlock->begin());
436 }
Bill Wendlingd5d17002011-10-08 00:56:47 +0000437}
438
Bill Wendlingcc8cf972011-09-28 21:56:53 +0000439/// setupEntryBlockAndCallSites - Setup the entry block by creating and filling
440/// the function context and marking the call sites with the appropriate
441/// values. These values are used by the DWARF EH emitter.
442bool SjLjEHPass::setupEntryBlockAndCallSites(Function &F) {
443 SmallVector<ReturnInst*, 16> Returns;
444 SmallVector<InvokeInst*, 16> Invokes;
Bob Wilsonf1b41dd2011-11-16 07:57:21 +0000445 SmallSetVector<LandingPadInst*, 16> LPads;
Bill Wendlingcc8cf972011-09-28 21:56:53 +0000446
447 // Look through the terminators of the basic blocks to find invokes.
448 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
449 if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
450 Invokes.push_back(II);
Bob Wilsonf1b41dd2011-11-16 07:57:21 +0000451 LPads.insert(II->getUnwindDest()->getLandingPadInst());
Bill Wendlingcc8cf972011-09-28 21:56:53 +0000452 } else if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
453 Returns.push_back(RI);
454 }
455
456 if (Invokes.empty()) return false;
457
Bill Wendlingd2dae0c2011-10-24 17:12:36 +0000458 NumInvokes += Invokes.size();
459
Bill Wendlingd5d17002011-10-08 00:56:47 +0000460 lowerIncomingArguments(F);
461 lowerAcrossUnwindEdges(F, Invokes);
462
Bob Wilsonf1b41dd2011-11-16 07:57:21 +0000463 Value *FuncCtx =
464 setupFunctionContext(F, makeArrayRef(LPads.begin(), LPads.end()));
Bill Wendlingcc8cf972011-09-28 21:56:53 +0000465 BasicBlock *EntryBB = F.begin();
Bill Wendlingcc8cf972011-09-28 21:56:53 +0000466 Type *Int32Ty = Type::getInt32Ty(F.getContext());
Bill Wendling631d1172011-10-03 21:15:28 +0000467
Bill Wendlingcc8cf972011-09-28 21:56:53 +0000468 Value *Idxs[2] = {
Bill Wendling631d1172011-10-03 21:15:28 +0000469 ConstantInt::get(Int32Ty, 0), 0
Bill Wendlingcc8cf972011-09-28 21:56:53 +0000470 };
Bill Wendling631d1172011-10-03 21:15:28 +0000471
472 // Get a reference to the jump buffer.
473 Idxs[1] = ConstantInt::get(Int32Ty, 5);
Bill Wendlingda7e6a92011-10-04 00:16:40 +0000474 Value *JBufPtr = GetElementPtrInst::Create(FuncCtx, Idxs, "jbuf_gep",
475 EntryBB->getTerminator());
Bill Wendling2b6bd7b2011-09-28 03:14:05 +0000476
Bill Wendling631d1172011-10-03 21:15:28 +0000477 // Save the frame pointer.
478 Idxs[1] = ConstantInt::get(Int32Ty, 0);
Bill Wendlingda7e6a92011-10-04 00:16:40 +0000479 Value *FramePtr = GetElementPtrInst::Create(JBufPtr, Idxs, "jbuf_fp_gep",
480 EntryBB->getTerminator());
Bill Wendling631d1172011-10-03 21:15:28 +0000481
482 Value *Val = CallInst::Create(FrameAddrFn,
483 ConstantInt::get(Int32Ty, 0),
484 "fp",
485 EntryBB->getTerminator());
486 new StoreInst(Val, FramePtr, true, EntryBB->getTerminator());
487
488 // Save the stack pointer.
489 Idxs[1] = ConstantInt::get(Int32Ty, 2);
Bill Wendlingda7e6a92011-10-04 00:16:40 +0000490 Value *StackPtr = GetElementPtrInst::Create(JBufPtr, Idxs, "jbuf_sp_gep",
491 EntryBB->getTerminator());
Bill Wendling631d1172011-10-03 21:15:28 +0000492
493 Val = CallInst::Create(StackAddrFn, "sp", EntryBB->getTerminator());
Bill Wendling2b6bd7b2011-09-28 03:14:05 +0000494 new StoreInst(Val, StackPtr, true, EntryBB->getTerminator());
495
496 // Call the setjmp instrinsic. It fills in the rest of the jmpbuf.
Bill Wendlingda7e6a92011-10-04 00:16:40 +0000497 Value *SetjmpArg = CastInst::Create(Instruction::BitCast, JBufPtr,
498 Type::getInt8PtrTy(F.getContext()), "",
499 EntryBB->getTerminator());
Bill Wendlingf8520d52011-10-03 22:42:40 +0000500 CallInst::Create(BuiltinSetjmpFn, SetjmpArg, "", EntryBB->getTerminator());
Bill Wendling2b6bd7b2011-09-28 03:14:05 +0000501
Bill Wendlingcc8cf972011-09-28 21:56:53 +0000502 // Store a pointer to the function context so that the back-end will know
503 // where to look for it.
Bill Wendlingda7e6a92011-10-04 00:16:40 +0000504 Value *FuncCtxArg = CastInst::Create(Instruction::BitCast, FuncCtx,
505 Type::getInt8PtrTy(F.getContext()), "",
506 EntryBB->getTerminator());
Bill Wendlingcc8cf972011-09-28 21:56:53 +0000507 CallInst::Create(FuncCtxFn, FuncCtxArg, "", EntryBB->getTerminator());
Bill Wendling2b6bd7b2011-09-28 03:14:05 +0000508
509 // At this point, we are all set up, update the invoke instructions to mark
Bill Wendling2130ab02011-10-05 22:04:08 +0000510 // their call_site values.
Bill Wendling2b6bd7b2011-09-28 03:14:05 +0000511 for (unsigned I = 0, E = Invokes.size(); I != E; ++I) {
Bill Wendling4cc46662012-01-27 02:02:24 +0000512 insertCallSiteStore(Invokes[I], I + 1);
Bill Wendling2b6bd7b2011-09-28 03:14:05 +0000513
514 ConstantInt *CallSiteNum =
515 ConstantInt::get(Type::getInt32Ty(F.getContext()), I + 1);
516
517 // Record the call site value for the back end so it stays associated with
518 // the invoke.
519 CallInst::Create(CallSiteFn, CallSiteNum, "", Invokes[I]);
520 }
521
522 // Mark call instructions that aren't nounwind as no-action (call_site ==
523 // -1). Skip the entry block, as prior to then, no function context has been
524 // created for this function and any unexpected exceptions thrown will go
525 // directly to the caller's context, which is what we want anyway, so no need
526 // to do anything here.
Bill Wendlingda7e6a92011-10-04 00:16:40 +0000527 for (Function::iterator BB = F.begin(), E = F.end(); ++BB != E;)
Bill Wendling2b6bd7b2011-09-28 03:14:05 +0000528 for (BasicBlock::iterator I = BB->begin(), end = BB->end(); I != end; ++I)
529 if (CallInst *CI = dyn_cast<CallInst>(I)) {
530 if (!CI->doesNotThrow())
Bill Wendling4cc46662012-01-27 02:02:24 +0000531 insertCallSiteStore(CI, -1);
Bill Wendling2b6bd7b2011-09-28 03:14:05 +0000532 } else if (ResumeInst *RI = dyn_cast<ResumeInst>(I)) {
Bill Wendling4cc46662012-01-27 02:02:24 +0000533 insertCallSiteStore(RI, -1);
Bill Wendling2b6bd7b2011-09-28 03:14:05 +0000534 }
Bill Wendling2b6bd7b2011-09-28 03:14:05 +0000535
Bill Wendlingcc8cf972011-09-28 21:56:53 +0000536 // Register the function context and make sure it's known to not throw
Bill Wendling631d1172011-10-03 21:15:28 +0000537 CallInst *Register = CallInst::Create(RegisterFn, FuncCtx, "",
Bill Wendlingcc8cf972011-09-28 21:56:53 +0000538 EntryBB->getTerminator());
539 Register->setDoesNotThrow();
540
Bob Wilson20c918d2011-11-16 07:12:00 +0000541 // Following any allocas not in the entry block, update the saved SP in the
542 // jmpbuf to the new value.
543 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
544 if (BB == F.begin())
545 continue;
546 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
547 if (CallInst *CI = dyn_cast<CallInst>(I)) {
548 if (CI->getCalledFunction() != StackRestoreFn)
549 continue;
550 } else if (!isa<AllocaInst>(I)) {
551 continue;
552 }
553 Instruction *StackAddr = CallInst::Create(StackAddrFn, "sp");
554 StackAddr->insertAfter(I);
555 Instruction *StoreStackAddr = new StoreInst(StackAddr, StackPtr, true);
556 StoreStackAddr->insertAfter(StackAddr);
557 }
558 }
559
Bill Wendlingcc8cf972011-09-28 21:56:53 +0000560 // Finally, for any returns from this function, if this function contains an
561 // invoke, add a call to unregister the function context.
562 for (unsigned I = 0, E = Returns.size(); I != E; ++I)
Bill Wendling631d1172011-10-03 21:15:28 +0000563 CallInst::Create(UnregisterFn, FuncCtx, "", Returns[I]);
Bill Wendlingcc8cf972011-09-28 21:56:53 +0000564
Bill Wendling2b6bd7b2011-09-28 03:14:05 +0000565 return true;
566}
567
Jim Grosbach8b818d72009-08-17 16:41:22 +0000568bool SjLjEHPass::runOnFunction(Function &F) {
Bill Wendlingd2dae0c2011-10-24 17:12:36 +0000569 bool Res = setupEntryBlockAndCallSites(F);
Bill Wendlingfbf9ff42012-03-10 07:11:55 +0000570 DEBUG({
571 if (verifyFunction(F))
572 report_fatal_error("verifyFunction failed!");
573 });
Jim Grosbach8b818d72009-08-17 16:41:22 +0000574 return Res;
575}