Move EH-specific helper functions to a more appropriate place
[oota-llvm.git] / lib / Target / X86 / X86WinEHState.cpp
1 //===-- X86WinEHState - Insert EH state updates for win32 exceptions ------===//
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 // All functions using an MSVC EH personality use an explicitly updated state
11 // number stored in an exception registration stack object. The registration
12 // object is linked into a thread-local chain of registrations stored at fs:00.
13 // This pass adds the registration object and EH state updates.
14 //
15 //===----------------------------------------------------------------------===//
16
17 #include "X86.h"
18 #include "llvm/Analysis/EHPersonalities.h"
19 #include "llvm/CodeGen/MachineModuleInfo.h"
20 #include "llvm/CodeGen/Passes.h"
21 #include "llvm/CodeGen/WinEHFuncInfo.h"
22 #include "llvm/IR/Dominators.h"
23 #include "llvm/IR/Function.h"
24 #include "llvm/IR/IRBuilder.h"
25 #include "llvm/IR/Instructions.h"
26 #include "llvm/IR/IntrinsicInst.h"
27 #include "llvm/IR/Module.h"
28 #include "llvm/IR/PatternMatch.h"
29 #include "llvm/Pass.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/raw_ostream.h"
32 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
33 #include "llvm/Transforms/Utils/Cloning.h"
34 #include "llvm/Transforms/Utils/Local.h"
35
36 using namespace llvm;
37 using namespace llvm::PatternMatch;
38
39 #define DEBUG_TYPE "winehstate"
40
41 namespace llvm { void initializeWinEHStatePassPass(PassRegistry &); }
42
43 namespace {
44 class WinEHStatePass : public FunctionPass {
45 public:
46   static char ID; // Pass identification, replacement for typeid.
47
48   WinEHStatePass() : FunctionPass(ID) {
49     initializeWinEHStatePassPass(*PassRegistry::getPassRegistry());
50   }
51
52   bool runOnFunction(Function &Fn) override;
53
54   bool doInitialization(Module &M) override;
55
56   bool doFinalization(Module &M) override;
57
58   void getAnalysisUsage(AnalysisUsage &AU) const override;
59
60   const char *getPassName() const override {
61     return "Windows 32-bit x86 EH state insertion";
62   }
63
64 private:
65   void emitExceptionRegistrationRecord(Function *F);
66
67   void linkExceptionRegistration(IRBuilder<> &Builder, Function *Handler);
68   void unlinkExceptionRegistration(IRBuilder<> &Builder);
69   void addStateStores(Function &F, WinEHFuncInfo &FuncInfo);
70   void insertStateNumberStore(Value *ParentRegNode, Instruction *IP, int State);
71
72   Value *emitEHLSDA(IRBuilder<> &Builder, Function *F);
73
74   Function *generateLSDAInEAXThunk(Function *ParentFunc);
75
76   // Module-level type getters.
77   Type *getEHLinkRegistrationType();
78   Type *getSEHRegistrationType();
79   Type *getCXXEHRegistrationType();
80
81   // Per-module data.
82   Module *TheModule = nullptr;
83   StructType *EHLinkRegistrationTy = nullptr;
84   StructType *CXXEHRegistrationTy = nullptr;
85   StructType *SEHRegistrationTy = nullptr;
86   Function *FrameRecover = nullptr;
87   Function *FrameAddress = nullptr;
88   Function *FrameEscape = nullptr;
89   Function *RestoreFrame = nullptr;
90
91   // Per-function state
92   EHPersonality Personality = EHPersonality::Unknown;
93   Function *PersonalityFn = nullptr;
94
95   /// The stack allocation containing all EH data, including the link in the
96   /// fs:00 chain and the current state.
97   AllocaInst *RegNode = nullptr;
98
99   /// Struct type of RegNode. Used for GEPing.
100   Type *RegNodeTy = nullptr;
101
102   /// The index of the state field of RegNode.
103   int StateFieldIndex = ~0U;
104
105   /// The linked list node subobject inside of RegNode.
106   Value *Link = nullptr;
107 };
108 }
109
110 FunctionPass *llvm::createX86WinEHStatePass() { return new WinEHStatePass(); }
111
112 char WinEHStatePass::ID = 0;
113
114 INITIALIZE_PASS(WinEHStatePass, "x86-winehstate",
115                 "Insert stores for EH state numbers", false, false)
116
117 bool WinEHStatePass::doInitialization(Module &M) {
118   TheModule = &M;
119   FrameEscape = Intrinsic::getDeclaration(TheModule, Intrinsic::localescape);
120   FrameRecover = Intrinsic::getDeclaration(TheModule, Intrinsic::localrecover);
121   FrameAddress = Intrinsic::getDeclaration(TheModule, Intrinsic::frameaddress);
122   RestoreFrame =
123       Intrinsic::getDeclaration(TheModule, Intrinsic::x86_seh_restoreframe);
124   return false;
125 }
126
127 bool WinEHStatePass::doFinalization(Module &M) {
128   assert(TheModule == &M);
129   TheModule = nullptr;
130   EHLinkRegistrationTy = nullptr;
131   CXXEHRegistrationTy = nullptr;
132   SEHRegistrationTy = nullptr;
133   FrameEscape = nullptr;
134   FrameRecover = nullptr;
135   FrameAddress = nullptr;
136   return false;
137 }
138
139 void WinEHStatePass::getAnalysisUsage(AnalysisUsage &AU) const {
140   // This pass should only insert a stack allocation, memory accesses, and
141   // localrecovers.
142   AU.setPreservesCFG();
143 }
144
145 bool WinEHStatePass::runOnFunction(Function &F) {
146   // Check the personality. Do nothing if this personality doesn't use funclets.
147   if (!F.hasPersonalityFn())
148     return false;
149   PersonalityFn =
150       dyn_cast<Function>(F.getPersonalityFn()->stripPointerCasts());
151   if (!PersonalityFn)
152     return false;
153   Personality = classifyEHPersonality(PersonalityFn);
154   if (!isFuncletEHPersonality(Personality))
155     return false;
156
157   // Skip this function if there are no EH pads and we aren't using IR-level
158   // outlining.
159   bool HasPads = false;
160   for (BasicBlock &BB : F) {
161     if (BB.isEHPad()) {
162       HasPads = true;
163       break;
164     }
165   }
166   if (!HasPads)
167     return false;
168
169   // Disable frame pointer elimination in this function.
170   // FIXME: Do the nested handlers need to keep the parent ebp in ebp, or can we
171   // use an arbitrary register?
172   F.addFnAttr("no-frame-pointer-elim", "true");
173
174   emitExceptionRegistrationRecord(&F);
175
176   // The state numbers calculated here in IR must agree with what we calculate
177   // later on for the MachineFunction. In particular, if an IR pass deletes an
178   // unreachable EH pad after this point before machine CFG construction, we
179   // will be in trouble. If this assumption is ever broken, we should turn the
180   // numbers into an immutable analysis pass.
181   WinEHFuncInfo FuncInfo;
182   addStateStores(F, FuncInfo);
183
184   // Reset per-function state.
185   PersonalityFn = nullptr;
186   Personality = EHPersonality::Unknown;
187   return true;
188 }
189
190 /// Get the common EH registration subobject:
191 ///   typedef _EXCEPTION_DISPOSITION (*PEXCEPTION_ROUTINE)(
192 ///       _EXCEPTION_RECORD *, void *, _CONTEXT *, void *);
193 ///   struct EHRegistrationNode {
194 ///     EHRegistrationNode *Next;
195 ///     PEXCEPTION_ROUTINE Handler;
196 ///   };
197 Type *WinEHStatePass::getEHLinkRegistrationType() {
198   if (EHLinkRegistrationTy)
199     return EHLinkRegistrationTy;
200   LLVMContext &Context = TheModule->getContext();
201   EHLinkRegistrationTy = StructType::create(Context, "EHRegistrationNode");
202   Type *FieldTys[] = {
203       EHLinkRegistrationTy->getPointerTo(0), // EHRegistrationNode *Next
204       Type::getInt8PtrTy(Context) // EXCEPTION_DISPOSITION (*Handler)(...)
205   };
206   EHLinkRegistrationTy->setBody(FieldTys, false);
207   return EHLinkRegistrationTy;
208 }
209
210 /// The __CxxFrameHandler3 registration node:
211 ///   struct CXXExceptionRegistration {
212 ///     void *SavedESP;
213 ///     EHRegistrationNode SubRecord;
214 ///     int32_t TryLevel;
215 ///   };
216 Type *WinEHStatePass::getCXXEHRegistrationType() {
217   if (CXXEHRegistrationTy)
218     return CXXEHRegistrationTy;
219   LLVMContext &Context = TheModule->getContext();
220   Type *FieldTys[] = {
221       Type::getInt8PtrTy(Context), // void *SavedESP
222       getEHLinkRegistrationType(), // EHRegistrationNode SubRecord
223       Type::getInt32Ty(Context)    // int32_t TryLevel
224   };
225   CXXEHRegistrationTy =
226       StructType::create(FieldTys, "CXXExceptionRegistration");
227   return CXXEHRegistrationTy;
228 }
229
230 /// The _except_handler3/4 registration node:
231 ///   struct EH4ExceptionRegistration {
232 ///     void *SavedESP;
233 ///     _EXCEPTION_POINTERS *ExceptionPointers;
234 ///     EHRegistrationNode SubRecord;
235 ///     int32_t EncodedScopeTable;
236 ///     int32_t TryLevel;
237 ///   };
238 Type *WinEHStatePass::getSEHRegistrationType() {
239   if (SEHRegistrationTy)
240     return SEHRegistrationTy;
241   LLVMContext &Context = TheModule->getContext();
242   Type *FieldTys[] = {
243       Type::getInt8PtrTy(Context), // void *SavedESP
244       Type::getInt8PtrTy(Context), // void *ExceptionPointers
245       getEHLinkRegistrationType(), // EHRegistrationNode SubRecord
246       Type::getInt32Ty(Context),   // int32_t EncodedScopeTable
247       Type::getInt32Ty(Context)    // int32_t TryLevel
248   };
249   SEHRegistrationTy = StructType::create(FieldTys, "SEHExceptionRegistration");
250   return SEHRegistrationTy;
251 }
252
253 // Emit an exception registration record. These are stack allocations with the
254 // common subobject of two pointers: the previous registration record (the old
255 // fs:00) and the personality function for the current frame. The data before
256 // and after that is personality function specific.
257 void WinEHStatePass::emitExceptionRegistrationRecord(Function *F) {
258   assert(Personality == EHPersonality::MSVC_CXX ||
259          Personality == EHPersonality::MSVC_X86SEH);
260
261   StringRef PersonalityName = PersonalityFn->getName();
262   IRBuilder<> Builder(&F->getEntryBlock(), F->getEntryBlock().begin());
263   Type *Int8PtrType = Builder.getInt8PtrTy();
264   if (Personality == EHPersonality::MSVC_CXX) {
265     RegNodeTy = getCXXEHRegistrationType();
266     RegNode = Builder.CreateAlloca(RegNodeTy);
267     // SavedESP = llvm.stacksave()
268     Value *SP = Builder.CreateCall(
269         Intrinsic::getDeclaration(TheModule, Intrinsic::stacksave), {});
270     Builder.CreateStore(SP, Builder.CreateStructGEP(RegNodeTy, RegNode, 0));
271     // TryLevel = -1
272     StateFieldIndex = 2;
273     insertStateNumberStore(RegNode, &*Builder.GetInsertPoint(), -1);
274     // Handler = __ehhandler$F
275     Function *Trampoline = generateLSDAInEAXThunk(F);
276     Link = Builder.CreateStructGEP(RegNodeTy, RegNode, 1);
277     linkExceptionRegistration(Builder, Trampoline);
278   } else if (Personality == EHPersonality::MSVC_X86SEH) {
279     // If _except_handler4 is in use, some additional guard checks and prologue
280     // stuff is required.
281     bool UseStackGuard = (PersonalityName == "_except_handler4");
282     RegNodeTy = getSEHRegistrationType();
283     RegNode = Builder.CreateAlloca(RegNodeTy);
284     // SavedESP = llvm.stacksave()
285     Value *SP = Builder.CreateCall(
286         Intrinsic::getDeclaration(TheModule, Intrinsic::stacksave), {});
287     Builder.CreateStore(SP, Builder.CreateStructGEP(RegNodeTy, RegNode, 0));
288     // TryLevel = -2 / -1
289     StateFieldIndex = 4;
290     insertStateNumberStore(RegNode, &*Builder.GetInsertPoint(),
291                            UseStackGuard ? -2 : -1);
292     // ScopeTable = llvm.x86.seh.lsda(F)
293     Value *FI8 = Builder.CreateBitCast(F, Int8PtrType);
294     Value *LSDA = Builder.CreateCall(
295         Intrinsic::getDeclaration(TheModule, Intrinsic::x86_seh_lsda), FI8);
296     Type *Int32Ty = Type::getInt32Ty(TheModule->getContext());
297     LSDA = Builder.CreatePtrToInt(LSDA, Int32Ty);
298     // If using _except_handler4, xor the address of the table with
299     // __security_cookie.
300     if (UseStackGuard) {
301       Value *Cookie =
302           TheModule->getOrInsertGlobal("__security_cookie", Int32Ty);
303       Value *Val = Builder.CreateLoad(Int32Ty, Cookie);
304       LSDA = Builder.CreateXor(LSDA, Val);
305     }
306     Builder.CreateStore(LSDA, Builder.CreateStructGEP(RegNodeTy, RegNode, 3));
307     Link = Builder.CreateStructGEP(RegNodeTy, RegNode, 2);
308     linkExceptionRegistration(Builder, PersonalityFn);
309   } else {
310     llvm_unreachable("unexpected personality function");
311   }
312
313   // Insert an unlink before all returns.
314   for (BasicBlock &BB : *F) {
315     TerminatorInst *T = BB.getTerminator();
316     if (!isa<ReturnInst>(T))
317       continue;
318     Builder.SetInsertPoint(T);
319     unlinkExceptionRegistration(Builder);
320   }
321 }
322
323 Value *WinEHStatePass::emitEHLSDA(IRBuilder<> &Builder, Function *F) {
324   Value *FI8 = Builder.CreateBitCast(F, Type::getInt8PtrTy(F->getContext()));
325   return Builder.CreateCall(
326       Intrinsic::getDeclaration(TheModule, Intrinsic::x86_seh_lsda), FI8);
327 }
328
329 /// Generate a thunk that puts the LSDA of ParentFunc in EAX and then calls
330 /// PersonalityFn, forwarding the parameters passed to PEXCEPTION_ROUTINE:
331 ///   typedef _EXCEPTION_DISPOSITION (*PEXCEPTION_ROUTINE)(
332 ///       _EXCEPTION_RECORD *, void *, _CONTEXT *, void *);
333 /// We essentially want this code:
334 ///   movl $lsda, %eax
335 ///   jmpl ___CxxFrameHandler3
336 Function *WinEHStatePass::generateLSDAInEAXThunk(Function *ParentFunc) {
337   LLVMContext &Context = ParentFunc->getContext();
338   Type *Int32Ty = Type::getInt32Ty(Context);
339   Type *Int8PtrType = Type::getInt8PtrTy(Context);
340   Type *ArgTys[5] = {Int8PtrType, Int8PtrType, Int8PtrType, Int8PtrType,
341                      Int8PtrType};
342   FunctionType *TrampolineTy =
343       FunctionType::get(Int32Ty, makeArrayRef(&ArgTys[0], 4),
344                         /*isVarArg=*/false);
345   FunctionType *TargetFuncTy =
346       FunctionType::get(Int32Ty, makeArrayRef(&ArgTys[0], 5),
347                         /*isVarArg=*/false);
348   Function *Trampoline =
349       Function::Create(TrampolineTy, GlobalValue::InternalLinkage,
350                        Twine("__ehhandler$") + GlobalValue::getRealLinkageName(
351                                                    ParentFunc->getName()),
352                        TheModule);
353   BasicBlock *EntryBB = BasicBlock::Create(Context, "entry", Trampoline);
354   IRBuilder<> Builder(EntryBB);
355   Value *LSDA = emitEHLSDA(Builder, ParentFunc);
356   Value *CastPersonality =
357       Builder.CreateBitCast(PersonalityFn, TargetFuncTy->getPointerTo());
358   auto AI = Trampoline->arg_begin();
359   Value *Args[5] = {LSDA, &*AI++, &*AI++, &*AI++, &*AI++};
360   CallInst *Call = Builder.CreateCall(CastPersonality, Args);
361   // Can't use musttail due to prototype mismatch, but we can use tail.
362   Call->setTailCall(true);
363   // Set inreg so we pass it in EAX.
364   Call->addAttribute(1, Attribute::InReg);
365   Builder.CreateRet(Call);
366   return Trampoline;
367 }
368
369 void WinEHStatePass::linkExceptionRegistration(IRBuilder<> &Builder,
370                                                Function *Handler) {
371   // Emit the .safeseh directive for this function.
372   Handler->addFnAttr("safeseh");
373
374   Type *LinkTy = getEHLinkRegistrationType();
375   // Handler = Handler
376   Value *HandlerI8 = Builder.CreateBitCast(Handler, Builder.getInt8PtrTy());
377   Builder.CreateStore(HandlerI8, Builder.CreateStructGEP(LinkTy, Link, 1));
378   // Next = [fs:00]
379   Constant *FSZero =
380       Constant::getNullValue(LinkTy->getPointerTo()->getPointerTo(257));
381   Value *Next = Builder.CreateLoad(FSZero);
382   Builder.CreateStore(Next, Builder.CreateStructGEP(LinkTy, Link, 0));
383   // [fs:00] = Link
384   Builder.CreateStore(Link, FSZero);
385 }
386
387 void WinEHStatePass::unlinkExceptionRegistration(IRBuilder<> &Builder) {
388   // Clone Link into the current BB for better address mode folding.
389   if (auto *GEP = dyn_cast<GetElementPtrInst>(Link)) {
390     GEP = cast<GetElementPtrInst>(GEP->clone());
391     Builder.Insert(GEP);
392     Link = GEP;
393   }
394   Type *LinkTy = getEHLinkRegistrationType();
395   // [fs:00] = Link->Next
396   Value *Next =
397       Builder.CreateLoad(Builder.CreateStructGEP(LinkTy, Link, 0));
398   Constant *FSZero =
399       Constant::getNullValue(LinkTy->getPointerTo()->getPointerTo(257));
400   Builder.CreateStore(Next, FSZero);
401 }
402
403 void WinEHStatePass::addStateStores(Function &F, WinEHFuncInfo &FuncInfo) {
404   // Mark the registration node. The backend needs to know which alloca it is so
405   // that it can recover the original frame pointer.
406   IRBuilder<> Builder(RegNode->getParent(), std::next(RegNode->getIterator()));
407   Value *RegNodeI8 = Builder.CreateBitCast(RegNode, Builder.getInt8PtrTy());
408   Builder.CreateCall(
409       Intrinsic::getDeclaration(TheModule, Intrinsic::x86_seh_ehregnode),
410       {RegNodeI8});
411
412   // Calculate state numbers.
413   if (isAsynchronousEHPersonality(Personality))
414     calculateSEHStateNumbers(&F, FuncInfo);
415   else
416     calculateWinCXXEHStateNumbers(&F, FuncInfo);
417
418   // Iterate all the instructions and emit state number stores.
419   for (BasicBlock &BB : F) {
420     for (Instruction &I : BB) {
421       if (auto *CI = dyn_cast<CallInst>(&I)) {
422         // Possibly throwing call instructions have no actions to take after
423         // an unwind. Ensure they are in the -1 state.
424         if (CI->doesNotThrow())
425           continue;
426         insertStateNumberStore(RegNode, CI, -1);
427       } else if (auto *II = dyn_cast<InvokeInst>(&I)) {
428         // Look up the state number of the landingpad this unwinds to.
429         Instruction *PadInst = II->getUnwindDest()->getFirstNonPHI();
430         // FIXME: Why does this assertion fail?
431         //assert(FuncInfo.EHPadStateMap.count(PadInst) && "EH Pad has no state!");
432         int State = FuncInfo.EHPadStateMap[PadInst];
433         insertStateNumberStore(RegNode, II, State);
434       }
435     }
436   }
437 }
438
439 void WinEHStatePass::insertStateNumberStore(Value *ParentRegNode,
440                                             Instruction *IP, int State) {
441   IRBuilder<> Builder(IP);
442   Value *StateField =
443       Builder.CreateStructGEP(RegNodeTy, ParentRegNode, StateFieldIndex);
444   Builder.CreateStore(Builder.getInt32(State), StateField);
445 }