Redirect DataLayout from TargetMachine to Module in SjLjEHPrepare
[oota-llvm.git] / lib / CodeGen / SjLjEHPrepare.cpp
1 //===- SjLjEHPrepare.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 #include "llvm/CodeGen/Passes.h"
16 #include "llvm/ADT/DenseMap.h"
17 #include "llvm/ADT/SetVector.h"
18 #include "llvm/ADT/SmallPtrSet.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/ADT/Statistic.h"
21 #include "llvm/IR/Constants.h"
22 #include "llvm/IR/DataLayout.h"
23 #include "llvm/IR/DerivedTypes.h"
24 #include "llvm/IR/IRBuilder.h"
25 #include "llvm/IR/Instructions.h"
26 #include "llvm/IR/Intrinsics.h"
27 #include "llvm/IR/LLVMContext.h"
28 #include "llvm/IR/Module.h"
29 #include "llvm/Pass.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include "llvm/Target/TargetLowering.h"
34 #include "llvm/Target/TargetSubtargetInfo.h"
35 #include "llvm/Transforms/Scalar.h"
36 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
37 #include "llvm/Transforms/Utils/Local.h"
38 #include <set>
39 using namespace llvm;
40
41 #define DEBUG_TYPE "sjljehprepare"
42
43 STATISTIC(NumInvokes, "Number of invokes replaced");
44 STATISTIC(NumSpilled, "Number of registers live across unwind edges");
45
46 namespace {
47 class SjLjEHPrepare : public FunctionPass {
48   Type *doubleUnderDataTy;
49   Type *doubleUnderJBufTy;
50   Type *FunctionContextTy;
51   Constant *RegisterFn;
52   Constant *UnregisterFn;
53   Constant *BuiltinSetjmpFn;
54   Constant *FrameAddrFn;
55   Constant *StackAddrFn;
56   Constant *StackRestoreFn;
57   Constant *LSDAAddrFn;
58   Value *PersonalityFn;
59   Constant *CallSiteFn;
60   Constant *FuncCtxFn;
61   AllocaInst *FuncCtx;
62
63 public:
64   static char ID; // Pass identification, replacement for typeid
65   explicit SjLjEHPrepare() : FunctionPass(ID) {}
66   bool doInitialization(Module &M) override;
67   bool runOnFunction(Function &F) override;
68
69   void getAnalysisUsage(AnalysisUsage &AU) const override {}
70   const char *getPassName() const override {
71     return "SJLJ Exception Handling preparation";
72   }
73
74 private:
75   bool setupEntryBlockAndCallSites(Function &F);
76   void substituteLPadValues(LandingPadInst *LPI, Value *ExnVal, Value *SelVal);
77   Value *setupFunctionContext(Function &F, ArrayRef<LandingPadInst *> LPads);
78   void lowerIncomingArguments(Function &F);
79   void lowerAcrossUnwindEdges(Function &F, ArrayRef<InvokeInst *> Invokes);
80   void insertCallSiteStore(Instruction *I, int Number);
81 };
82 } // end anonymous namespace
83
84 char SjLjEHPrepare::ID = 0;
85
86 // Public Interface To the SjLjEHPrepare pass.
87 FunctionPass *llvm::createSjLjEHPreparePass() { return new SjLjEHPrepare(); }
88 // doInitialization - Set up decalarations and types needed to process
89 // exceptions.
90 bool SjLjEHPrepare::doInitialization(Module &M) {
91   // Build the function context structure.
92   // builtin_setjmp uses a five word jbuf
93   Type *VoidPtrTy = Type::getInt8PtrTy(M.getContext());
94   Type *Int32Ty = Type::getInt32Ty(M.getContext());
95   doubleUnderDataTy = ArrayType::get(Int32Ty, 4);
96   doubleUnderJBufTy = ArrayType::get(VoidPtrTy, 5);
97   FunctionContextTy = StructType::get(VoidPtrTy,         // __prev
98                                       Int32Ty,           // call_site
99                                       doubleUnderDataTy, // __data
100                                       VoidPtrTy,         // __personality
101                                       VoidPtrTy,         // __lsda
102                                       doubleUnderJBufTy, // __jbuf
103                                       nullptr);
104   RegisterFn = M.getOrInsertFunction(
105       "_Unwind_SjLj_Register", Type::getVoidTy(M.getContext()),
106       PointerType::getUnqual(FunctionContextTy), (Type *)nullptr);
107   UnregisterFn = M.getOrInsertFunction(
108       "_Unwind_SjLj_Unregister", Type::getVoidTy(M.getContext()),
109       PointerType::getUnqual(FunctionContextTy), (Type *)nullptr);
110   FrameAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::frameaddress);
111   StackAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::stacksave);
112   StackRestoreFn = Intrinsic::getDeclaration(&M, Intrinsic::stackrestore);
113   BuiltinSetjmpFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_setjmp);
114   LSDAAddrFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_lsda);
115   CallSiteFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_callsite);
116   FuncCtxFn = Intrinsic::getDeclaration(&M, Intrinsic::eh_sjlj_functioncontext);
117   PersonalityFn = nullptr;
118
119   return true;
120 }
121
122 /// insertCallSiteStore - Insert a store of the call-site value to the
123 /// function context
124 void SjLjEHPrepare::insertCallSiteStore(Instruction *I, int Number) {
125   IRBuilder<> Builder(I);
126
127   // Get a reference to the call_site field.
128   Type *Int32Ty = Type::getInt32Ty(I->getContext());
129   Value *Zero = ConstantInt::get(Int32Ty, 0);
130   Value *One = ConstantInt::get(Int32Ty, 1);
131   Value *Idxs[2] = { Zero, One };
132   Value *CallSite =
133       Builder.CreateGEP(FunctionContextTy, FuncCtx, Idxs, "call_site");
134
135   // Insert a store of the call-site number
136   ConstantInt *CallSiteNoC =
137       ConstantInt::get(Type::getInt32Ty(I->getContext()), Number);
138   Builder.CreateStore(CallSiteNoC, CallSite, true /*volatile*/);
139 }
140
141 /// MarkBlocksLiveIn - Insert BB and all of its predescessors into LiveBBs until
142 /// we reach blocks we've already seen.
143 static void MarkBlocksLiveIn(BasicBlock *BB,
144                              SmallPtrSetImpl<BasicBlock *> &LiveBBs) {
145   if (!LiveBBs.insert(BB).second)
146     return; // already been here.
147
148   for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
149     MarkBlocksLiveIn(*PI, LiveBBs);
150 }
151
152 /// substituteLPadValues - Substitute the values returned by the landingpad
153 /// instruction with those returned by the personality function.
154 void SjLjEHPrepare::substituteLPadValues(LandingPadInst *LPI, Value *ExnVal,
155                                          Value *SelVal) {
156   SmallVector<Value *, 8> UseWorkList(LPI->user_begin(), LPI->user_end());
157   while (!UseWorkList.empty()) {
158     Value *Val = UseWorkList.pop_back_val();
159     ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(Val);
160     if (!EVI)
161       continue;
162     if (EVI->getNumIndices() != 1)
163       continue;
164     if (*EVI->idx_begin() == 0)
165       EVI->replaceAllUsesWith(ExnVal);
166     else if (*EVI->idx_begin() == 1)
167       EVI->replaceAllUsesWith(SelVal);
168     if (EVI->getNumUses() == 0)
169       EVI->eraseFromParent();
170   }
171
172   if (LPI->getNumUses() == 0)
173     return;
174
175   // There are still some uses of LPI. Construct an aggregate with the exception
176   // values and replace the LPI with that aggregate.
177   Type *LPadType = LPI->getType();
178   Value *LPadVal = UndefValue::get(LPadType);
179   IRBuilder<> Builder(
180       std::next(BasicBlock::iterator(cast<Instruction>(SelVal))));
181   LPadVal = Builder.CreateInsertValue(LPadVal, ExnVal, 0, "lpad.val");
182   LPadVal = Builder.CreateInsertValue(LPadVal, SelVal, 1, "lpad.val");
183
184   LPI->replaceAllUsesWith(LPadVal);
185 }
186
187 /// setupFunctionContext - Allocate the function context on the stack and fill
188 /// it with all of the data that we know at this point.
189 Value *SjLjEHPrepare::setupFunctionContext(Function &F,
190                                            ArrayRef<LandingPadInst *> LPads) {
191   BasicBlock *EntryBB = F.begin();
192
193   // Create an alloca for the incoming jump buffer ptr and the new jump buffer
194   // that needs to be restored on all exits from the function. This is an alloca
195   // because the value needs to be added to the global context list.
196   auto &DL = F.getParent()->getDataLayout();
197   unsigned Align = DL.getPrefTypeAlignment(FunctionContextTy);
198   FuncCtx = new AllocaInst(FunctionContextTy, nullptr, Align, "fn_context",
199                            EntryBB->begin());
200
201   // Fill in the function context structure.
202   for (unsigned I = 0, E = LPads.size(); I != E; ++I) {
203     LandingPadInst *LPI = LPads[I];
204     IRBuilder<> Builder(LPI->getParent()->getFirstInsertionPt());
205
206     // Reference the __data field.
207     Value *FCData =
208         Builder.CreateConstGEP2_32(FunctionContextTy, FuncCtx, 0, 2, "__data");
209
210     // The exception values come back in context->__data[0].
211     Value *ExceptionAddr = Builder.CreateConstGEP2_32(doubleUnderDataTy, FCData,
212                                                       0, 0, "exception_gep");
213     Value *ExnVal = Builder.CreateLoad(ExceptionAddr, true, "exn_val");
214     ExnVal = Builder.CreateIntToPtr(ExnVal, Builder.getInt8PtrTy());
215
216     Value *SelectorAddr = Builder.CreateConstGEP2_32(doubleUnderDataTy, FCData,
217                                                      0, 1, "exn_selector_gep");
218     Value *SelVal = Builder.CreateLoad(SelectorAddr, true, "exn_selector_val");
219
220     substituteLPadValues(LPI, ExnVal, SelVal);
221   }
222
223   // Personality function
224   IRBuilder<> Builder(EntryBB->getTerminator());
225   if (!PersonalityFn)
226     PersonalityFn = F.getPersonalityFn();
227   Value *PersonalityFieldPtr = Builder.CreateConstGEP2_32(
228       FunctionContextTy, FuncCtx, 0, 3, "pers_fn_gep");
229   Builder.CreateStore(
230       Builder.CreateBitCast(PersonalityFn, Builder.getInt8PtrTy()),
231       PersonalityFieldPtr, /*isVolatile=*/true);
232
233   // LSDA address
234   Value *LSDA = Builder.CreateCall(LSDAAddrFn, {}, "lsda_addr");
235   Value *LSDAFieldPtr =
236       Builder.CreateConstGEP2_32(FunctionContextTy, FuncCtx, 0, 4, "lsda_gep");
237   Builder.CreateStore(LSDA, LSDAFieldPtr, /*isVolatile=*/true);
238
239   return FuncCtx;
240 }
241
242 /// lowerIncomingArguments - To avoid having to handle incoming arguments
243 /// specially, we lower each arg to a copy instruction in the entry block. This
244 /// ensures that the argument value itself cannot be live out of the entry
245 /// block.
246 void SjLjEHPrepare::lowerIncomingArguments(Function &F) {
247   BasicBlock::iterator AfterAllocaInsPt = F.begin()->begin();
248   while (isa<AllocaInst>(AfterAllocaInsPt) &&
249          isa<ConstantInt>(cast<AllocaInst>(AfterAllocaInsPt)->getArraySize()))
250     ++AfterAllocaInsPt;
251
252   for (Function::arg_iterator AI = F.arg_begin(), AE = F.arg_end(); AI != AE;
253        ++AI) {
254     Type *Ty = AI->getType();
255
256     // Use 'select i8 true, %arg, undef' to simulate a 'no-op' instruction.
257     Value *TrueValue = ConstantInt::getTrue(F.getContext());
258     Value *UndefValue = UndefValue::get(Ty);
259     Instruction *SI = SelectInst::Create(TrueValue, AI, UndefValue,
260                                          AI->getName() + ".tmp",
261                                          AfterAllocaInsPt);
262     AI->replaceAllUsesWith(SI);
263
264     // Reset the operand, because it  was clobbered by the RAUW above.
265     SI->setOperand(1, AI);
266   }
267 }
268
269 /// lowerAcrossUnwindEdges - Find all variables which are alive across an unwind
270 /// edge and spill them.
271 void SjLjEHPrepare::lowerAcrossUnwindEdges(Function &F,
272                                            ArrayRef<InvokeInst *> Invokes) {
273   // Finally, scan the code looking for instructions with bad live ranges.
274   for (Function::iterator BB = F.begin(), BBE = F.end(); BB != BBE; ++BB) {
275     for (BasicBlock::iterator II = BB->begin(), IIE = BB->end(); II != IIE;
276          ++II) {
277       // Ignore obvious cases we don't have to handle. In particular, most
278       // instructions either have no uses or only have a single use inside the
279       // current block. Ignore them quickly.
280       Instruction *Inst = II;
281       if (Inst->use_empty())
282         continue;
283       if (Inst->hasOneUse() &&
284           cast<Instruction>(Inst->user_back())->getParent() == BB &&
285           !isa<PHINode>(Inst->user_back()))
286         continue;
287
288       // If this is an alloca in the entry block, it's not a real register
289       // value.
290       if (AllocaInst *AI = dyn_cast<AllocaInst>(Inst))
291         if (isa<ConstantInt>(AI->getArraySize()) && BB == F.begin())
292           continue;
293
294       // Avoid iterator invalidation by copying users to a temporary vector.
295       SmallVector<Instruction *, 16> Users;
296       for (User *U : Inst->users()) {
297         Instruction *UI = cast<Instruction>(U);
298         if (UI->getParent() != BB || isa<PHINode>(UI))
299           Users.push_back(UI);
300       }
301
302       // Find all of the blocks that this value is live in.
303       SmallPtrSet<BasicBlock *, 64> LiveBBs;
304       LiveBBs.insert(Inst->getParent());
305       while (!Users.empty()) {
306         Instruction *U = Users.back();
307         Users.pop_back();
308
309         if (!isa<PHINode>(U)) {
310           MarkBlocksLiveIn(U->getParent(), LiveBBs);
311         } else {
312           // Uses for a PHI node occur in their predecessor block.
313           PHINode *PN = cast<PHINode>(U);
314           for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
315             if (PN->getIncomingValue(i) == Inst)
316               MarkBlocksLiveIn(PN->getIncomingBlock(i), LiveBBs);
317         }
318       }
319
320       // Now that we know all of the blocks that this thing is live in, see if
321       // it includes any of the unwind locations.
322       bool NeedsSpill = false;
323       for (unsigned i = 0, e = Invokes.size(); i != e; ++i) {
324         BasicBlock *UnwindBlock = Invokes[i]->getUnwindDest();
325         if (UnwindBlock != BB && LiveBBs.count(UnwindBlock)) {
326           DEBUG(dbgs() << "SJLJ Spill: " << *Inst << " around "
327                        << UnwindBlock->getName() << "\n");
328           NeedsSpill = true;
329           break;
330         }
331       }
332
333       // If we decided we need a spill, do it.
334       // FIXME: Spilling this way is overkill, as it forces all uses of
335       // the value to be reloaded from the stack slot, even those that aren't
336       // in the unwind blocks. We should be more selective.
337       if (NeedsSpill) {
338         DemoteRegToStack(*Inst, true);
339         ++NumSpilled;
340       }
341     }
342   }
343
344   // Go through the landing pads and remove any PHIs there.
345   for (unsigned i = 0, e = Invokes.size(); i != e; ++i) {
346     BasicBlock *UnwindBlock = Invokes[i]->getUnwindDest();
347     LandingPadInst *LPI = UnwindBlock->getLandingPadInst();
348
349     // Place PHIs into a set to avoid invalidating the iterator.
350     SmallPtrSet<PHINode *, 8> PHIsToDemote;
351     for (BasicBlock::iterator PN = UnwindBlock->begin(); isa<PHINode>(PN); ++PN)
352       PHIsToDemote.insert(cast<PHINode>(PN));
353     if (PHIsToDemote.empty())
354       continue;
355
356     // Demote the PHIs to the stack.
357     for (PHINode *PN : PHIsToDemote)
358       DemotePHIToStack(PN);
359
360     // Move the landingpad instruction back to the top of the landing pad block.
361     LPI->moveBefore(UnwindBlock->begin());
362   }
363 }
364
365 /// setupEntryBlockAndCallSites - Setup the entry block by creating and filling
366 /// the function context and marking the call sites with the appropriate
367 /// values. These values are used by the DWARF EH emitter.
368 bool SjLjEHPrepare::setupEntryBlockAndCallSites(Function &F) {
369   SmallVector<ReturnInst *, 16> Returns;
370   SmallVector<InvokeInst *, 16> Invokes;
371   SmallSetVector<LandingPadInst *, 16> LPads;
372
373   // Look through the terminators of the basic blocks to find invokes.
374   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
375     if (InvokeInst *II = dyn_cast<InvokeInst>(BB->getTerminator())) {
376       if (Function *Callee = II->getCalledFunction())
377         if (Callee->isIntrinsic() &&
378             Callee->getIntrinsicID() == Intrinsic::donothing) {
379           // Remove the NOP invoke.
380           BranchInst::Create(II->getNormalDest(), II);
381           II->eraseFromParent();
382           continue;
383         }
384
385       Invokes.push_back(II);
386       LPads.insert(II->getUnwindDest()->getLandingPadInst());
387     } else if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
388       Returns.push_back(RI);
389     }
390
391   if (Invokes.empty())
392     return false;
393
394   NumInvokes += Invokes.size();
395
396   lowerIncomingArguments(F);
397   lowerAcrossUnwindEdges(F, Invokes);
398
399   Value *FuncCtx =
400       setupFunctionContext(F, makeArrayRef(LPads.begin(), LPads.end()));
401   BasicBlock *EntryBB = F.begin();
402   IRBuilder<> Builder(EntryBB->getTerminator());
403
404   // Get a reference to the jump buffer.
405   Value *JBufPtr =
406       Builder.CreateConstGEP2_32(FunctionContextTy, FuncCtx, 0, 5, "jbuf_gep");
407
408   // Save the frame pointer.
409   Value *FramePtr = Builder.CreateConstGEP2_32(doubleUnderJBufTy, JBufPtr, 0, 0,
410                                                "jbuf_fp_gep");
411
412   Value *Val = Builder.CreateCall(FrameAddrFn, Builder.getInt32(0), "fp");
413   Builder.CreateStore(Val, FramePtr, /*isVolatile=*/true);
414
415   // Save the stack pointer.
416   Value *StackPtr = Builder.CreateConstGEP2_32(doubleUnderJBufTy, JBufPtr, 0, 2,
417                                                "jbuf_sp_gep");
418
419   Val = Builder.CreateCall(StackAddrFn, {}, "sp");
420   Builder.CreateStore(Val, StackPtr, /*isVolatile=*/true);
421
422   // Call the setjmp instrinsic. It fills in the rest of the jmpbuf.
423   Value *SetjmpArg = Builder.CreateBitCast(JBufPtr, Builder.getInt8PtrTy());
424   Builder.CreateCall(BuiltinSetjmpFn, SetjmpArg);
425
426   // Store a pointer to the function context so that the back-end will know
427   // where to look for it.
428   Value *FuncCtxArg = Builder.CreateBitCast(FuncCtx, Builder.getInt8PtrTy());
429   Builder.CreateCall(FuncCtxFn, FuncCtxArg);
430
431   // At this point, we are all set up, update the invoke instructions to mark
432   // their call_site values.
433   for (unsigned I = 0, E = Invokes.size(); I != E; ++I) {
434     insertCallSiteStore(Invokes[I], I + 1);
435
436     ConstantInt *CallSiteNum =
437         ConstantInt::get(Type::getInt32Ty(F.getContext()), I + 1);
438
439     // Record the call site value for the back end so it stays associated with
440     // the invoke.
441     CallInst::Create(CallSiteFn, CallSiteNum, "", Invokes[I]);
442   }
443
444   // Mark call instructions that aren't nounwind as no-action (call_site ==
445   // -1). Skip the entry block, as prior to then, no function context has been
446   // created for this function and any unexpected exceptions thrown will go
447   // directly to the caller's context, which is what we want anyway, so no need
448   // to do anything here.
449   for (Function::iterator BB = F.begin(), E = F.end(); ++BB != E;)
450     for (BasicBlock::iterator I = BB->begin(), end = BB->end(); I != end; ++I)
451       if (CallInst *CI = dyn_cast<CallInst>(I)) {
452         if (!CI->doesNotThrow())
453           insertCallSiteStore(CI, -1);
454       } else if (ResumeInst *RI = dyn_cast<ResumeInst>(I)) {
455         insertCallSiteStore(RI, -1);
456       }
457
458   // Register the function context and make sure it's known to not throw
459   CallInst *Register =
460       CallInst::Create(RegisterFn, FuncCtx, "", EntryBB->getTerminator());
461   Register->setDoesNotThrow();
462
463   // Following any allocas not in the entry block, update the saved SP in the
464   // jmpbuf to the new value.
465   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
466     if (BB == F.begin())
467       continue;
468     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
469       if (CallInst *CI = dyn_cast<CallInst>(I)) {
470         if (CI->getCalledFunction() != StackRestoreFn)
471           continue;
472       } else if (!isa<AllocaInst>(I)) {
473         continue;
474       }
475       Instruction *StackAddr = CallInst::Create(StackAddrFn, "sp");
476       StackAddr->insertAfter(I);
477       Instruction *StoreStackAddr = new StoreInst(StackAddr, StackPtr, true);
478       StoreStackAddr->insertAfter(StackAddr);
479     }
480   }
481
482   // Finally, for any returns from this function, if this function contains an
483   // invoke, add a call to unregister the function context.
484   for (unsigned I = 0, E = Returns.size(); I != E; ++I)
485     CallInst::Create(UnregisterFn, FuncCtx, "", Returns[I]);
486
487   return true;
488 }
489
490 bool SjLjEHPrepare::runOnFunction(Function &F) {
491   bool Res = setupEntryBlockAndCallSites(F);
492   return Res;
493 }