[WinEH] Remove more dead code
[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/LibCallSemantics.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 addCXXStateStores(Function &F, WinEHFuncInfo &FuncInfo);
70   void addSEHStateStores(Function &F, WinEHFuncInfo &FuncInfo);
71   void addStateStoresToFunclet(Value *ParentRegNode, WinEHFuncInfo &FuncInfo,
72                                Function &F, int BaseState);
73   void insertStateNumberStore(Value *ParentRegNode, Instruction *IP, int State);
74   void insertRestoreFrame(BasicBlock *BB);
75
76   Value *emitEHLSDA(IRBuilder<> &Builder, Function *F);
77
78   Function *generateLSDAInEAXThunk(Function *ParentFunc);
79
80   int escapeRegNode(Function &F);
81
82   // Module-level type getters.
83   Type *getEHLinkRegistrationType();
84   Type *getSEHRegistrationType();
85   Type *getCXXEHRegistrationType();
86
87   // Per-module data.
88   Module *TheModule = nullptr;
89   StructType *EHLinkRegistrationTy = nullptr;
90   StructType *CXXEHRegistrationTy = nullptr;
91   StructType *SEHRegistrationTy = nullptr;
92   Function *FrameRecover = nullptr;
93   Function *FrameAddress = nullptr;
94   Function *FrameEscape = nullptr;
95   Function *RestoreFrame = nullptr;
96
97   // Per-function state
98   EHPersonality Personality = EHPersonality::Unknown;
99   Function *PersonalityFn = nullptr;
100
101   /// The stack allocation containing all EH data, including the link in the
102   /// fs:00 chain and the current state.
103   AllocaInst *RegNode = nullptr;
104
105   /// Struct type of RegNode. Used for GEPing.
106   Type *RegNodeTy = nullptr;
107
108   /// The index of the state field of RegNode.
109   int StateFieldIndex = ~0U;
110
111   /// The linked list node subobject inside of RegNode.
112   Value *Link = nullptr;
113 };
114 }
115
116 FunctionPass *llvm::createX86WinEHStatePass() { return new WinEHStatePass(); }
117
118 char WinEHStatePass::ID = 0;
119
120 INITIALIZE_PASS(WinEHStatePass, "x86-winehstate",
121                 "Insert stores for EH state numbers", false, false)
122
123 bool WinEHStatePass::doInitialization(Module &M) {
124   TheModule = &M;
125   FrameEscape = Intrinsic::getDeclaration(TheModule, Intrinsic::localescape);
126   FrameRecover = Intrinsic::getDeclaration(TheModule, Intrinsic::localrecover);
127   FrameAddress = Intrinsic::getDeclaration(TheModule, Intrinsic::frameaddress);
128   RestoreFrame =
129       Intrinsic::getDeclaration(TheModule, Intrinsic::x86_seh_restoreframe);
130   return false;
131 }
132
133 bool WinEHStatePass::doFinalization(Module &M) {
134   assert(TheModule == &M);
135   TheModule = nullptr;
136   EHLinkRegistrationTy = nullptr;
137   CXXEHRegistrationTy = nullptr;
138   SEHRegistrationTy = nullptr;
139   FrameEscape = nullptr;
140   FrameRecover = nullptr;
141   FrameAddress = nullptr;
142   return false;
143 }
144
145 void WinEHStatePass::getAnalysisUsage(AnalysisUsage &AU) const {
146   // This pass should only insert a stack allocation, memory accesses, and
147   // localrecovers.
148   AU.setPreservesCFG();
149 }
150
151 bool WinEHStatePass::runOnFunction(Function &F) {
152   // Check the personality. Do nothing if this personality doesn't use funclets.
153   if (!F.hasPersonalityFn())
154     return false;
155   PersonalityFn =
156       dyn_cast<Function>(F.getPersonalityFn()->stripPointerCasts());
157   if (!PersonalityFn)
158     return false;
159   Personality = classifyEHPersonality(PersonalityFn);
160   if (!isFuncletEHPersonality(Personality))
161     return false;
162
163   // Skip this function if there are no EH pads and we aren't using IR-level
164   // outlining.
165   bool HasPads = false;
166   for (BasicBlock &BB : F) {
167     if (BB.isEHPad()) {
168       HasPads = true;
169       break;
170     }
171   }
172   if (!HasPads)
173     return false;
174
175   // Disable frame pointer elimination in this function.
176   // FIXME: Do the nested handlers need to keep the parent ebp in ebp, or can we
177   // use an arbitrary register?
178   F.addFnAttr("no-frame-pointer-elim", "true");
179
180   emitExceptionRegistrationRecord(&F);
181
182   auto *MMI = getAnalysisIfAvailable<MachineModuleInfo>();
183   // If MMI is null, create our own WinEHFuncInfo.  This only happens in opt
184   // tests.
185   std::unique_ptr<WinEHFuncInfo> FuncInfoPtr;
186   if (!MMI)
187     FuncInfoPtr.reset(new WinEHFuncInfo());
188   WinEHFuncInfo &FuncInfo =
189       *(MMI ? &MMI->getWinEHFuncInfo(&F) : FuncInfoPtr.get());
190
191   FuncInfo.EHRegNode = RegNode;
192
193   switch (Personality) {
194   default: llvm_unreachable("unexpected personality function");
195   case EHPersonality::MSVC_CXX:
196     addCXXStateStores(F, FuncInfo);
197     break;
198   case EHPersonality::MSVC_X86SEH:
199     addSEHStateStores(F, FuncInfo);
200     break;
201   }
202
203   // Reset per-function state.
204   PersonalityFn = nullptr;
205   Personality = EHPersonality::Unknown;
206   return true;
207 }
208
209 /// Get the common EH registration subobject:
210 ///   typedef _EXCEPTION_DISPOSITION (*PEXCEPTION_ROUTINE)(
211 ///       _EXCEPTION_RECORD *, void *, _CONTEXT *, void *);
212 ///   struct EHRegistrationNode {
213 ///     EHRegistrationNode *Next;
214 ///     PEXCEPTION_ROUTINE Handler;
215 ///   };
216 Type *WinEHStatePass::getEHLinkRegistrationType() {
217   if (EHLinkRegistrationTy)
218     return EHLinkRegistrationTy;
219   LLVMContext &Context = TheModule->getContext();
220   EHLinkRegistrationTy = StructType::create(Context, "EHRegistrationNode");
221   Type *FieldTys[] = {
222       EHLinkRegistrationTy->getPointerTo(0), // EHRegistrationNode *Next
223       Type::getInt8PtrTy(Context) // EXCEPTION_DISPOSITION (*Handler)(...)
224   };
225   EHLinkRegistrationTy->setBody(FieldTys, false);
226   return EHLinkRegistrationTy;
227 }
228
229 /// The __CxxFrameHandler3 registration node:
230 ///   struct CXXExceptionRegistration {
231 ///     void *SavedESP;
232 ///     EHRegistrationNode SubRecord;
233 ///     int32_t TryLevel;
234 ///   };
235 Type *WinEHStatePass::getCXXEHRegistrationType() {
236   if (CXXEHRegistrationTy)
237     return CXXEHRegistrationTy;
238   LLVMContext &Context = TheModule->getContext();
239   Type *FieldTys[] = {
240       Type::getInt8PtrTy(Context), // void *SavedESP
241       getEHLinkRegistrationType(), // EHRegistrationNode SubRecord
242       Type::getInt32Ty(Context)    // int32_t TryLevel
243   };
244   CXXEHRegistrationTy =
245       StructType::create(FieldTys, "CXXExceptionRegistration");
246   return CXXEHRegistrationTy;
247 }
248
249 /// The _except_handler3/4 registration node:
250 ///   struct EH4ExceptionRegistration {
251 ///     void *SavedESP;
252 ///     _EXCEPTION_POINTERS *ExceptionPointers;
253 ///     EHRegistrationNode SubRecord;
254 ///     int32_t EncodedScopeTable;
255 ///     int32_t TryLevel;
256 ///   };
257 Type *WinEHStatePass::getSEHRegistrationType() {
258   if (SEHRegistrationTy)
259     return SEHRegistrationTy;
260   LLVMContext &Context = TheModule->getContext();
261   Type *FieldTys[] = {
262       Type::getInt8PtrTy(Context), // void *SavedESP
263       Type::getInt8PtrTy(Context), // void *ExceptionPointers
264       getEHLinkRegistrationType(), // EHRegistrationNode SubRecord
265       Type::getInt32Ty(Context),   // int32_t EncodedScopeTable
266       Type::getInt32Ty(Context)    // int32_t TryLevel
267   };
268   SEHRegistrationTy = StructType::create(FieldTys, "SEHExceptionRegistration");
269   return SEHRegistrationTy;
270 }
271
272 // Emit an exception registration record. These are stack allocations with the
273 // common subobject of two pointers: the previous registration record (the old
274 // fs:00) and the personality function for the current frame. The data before
275 // and after that is personality function specific.
276 void WinEHStatePass::emitExceptionRegistrationRecord(Function *F) {
277   assert(Personality == EHPersonality::MSVC_CXX ||
278          Personality == EHPersonality::MSVC_X86SEH);
279
280   StringRef PersonalityName = PersonalityFn->getName();
281   IRBuilder<> Builder(&F->getEntryBlock(), F->getEntryBlock().begin());
282   Type *Int8PtrType = Builder.getInt8PtrTy();
283   if (Personality == EHPersonality::MSVC_CXX) {
284     RegNodeTy = getCXXEHRegistrationType();
285     RegNode = Builder.CreateAlloca(RegNodeTy);
286     // SavedESP = llvm.stacksave()
287     Value *SP = Builder.CreateCall(
288         Intrinsic::getDeclaration(TheModule, Intrinsic::stacksave), {});
289     Builder.CreateStore(SP, Builder.CreateStructGEP(RegNodeTy, RegNode, 0));
290     // TryLevel = -1
291     StateFieldIndex = 2;
292     insertStateNumberStore(RegNode, Builder.GetInsertPoint(), -1);
293     // Handler = __ehhandler$F
294     Function *Trampoline = generateLSDAInEAXThunk(F);
295     Link = Builder.CreateStructGEP(RegNodeTy, RegNode, 1);
296     linkExceptionRegistration(Builder, Trampoline);
297   } else if (Personality == EHPersonality::MSVC_X86SEH) {
298     // If _except_handler4 is in use, some additional guard checks and prologue
299     // stuff is required.
300     bool UseStackGuard = (PersonalityName == "_except_handler4");
301     RegNodeTy = getSEHRegistrationType();
302     RegNode = Builder.CreateAlloca(RegNodeTy);
303     // SavedESP = llvm.stacksave()
304     Value *SP = Builder.CreateCall(
305         Intrinsic::getDeclaration(TheModule, Intrinsic::stacksave), {});
306     Builder.CreateStore(SP, Builder.CreateStructGEP(RegNodeTy, RegNode, 0));
307     // TryLevel = -2 / -1
308     StateFieldIndex = 4;
309     insertStateNumberStore(RegNode, Builder.GetInsertPoint(),
310                            UseStackGuard ? -2 : -1);
311     // ScopeTable = llvm.x86.seh.lsda(F)
312     Value *FI8 = Builder.CreateBitCast(F, Int8PtrType);
313     Value *LSDA = Builder.CreateCall(
314         Intrinsic::getDeclaration(TheModule, Intrinsic::x86_seh_lsda), FI8);
315     Type *Int32Ty = Type::getInt32Ty(TheModule->getContext());
316     LSDA = Builder.CreatePtrToInt(LSDA, Int32Ty);
317     // If using _except_handler4, xor the address of the table with
318     // __security_cookie.
319     if (UseStackGuard) {
320       Value *Cookie =
321           TheModule->getOrInsertGlobal("__security_cookie", Int32Ty);
322       Value *Val = Builder.CreateLoad(Int32Ty, Cookie);
323       LSDA = Builder.CreateXor(LSDA, Val);
324     }
325     Builder.CreateStore(LSDA, Builder.CreateStructGEP(RegNodeTy, RegNode, 3));
326     Link = Builder.CreateStructGEP(RegNodeTy, RegNode, 2);
327     linkExceptionRegistration(Builder, PersonalityFn);
328   } else {
329     llvm_unreachable("unexpected personality function");
330   }
331
332   // Insert an unlink before all returns.
333   for (BasicBlock &BB : *F) {
334     TerminatorInst *T = BB.getTerminator();
335     if (!isa<ReturnInst>(T))
336       continue;
337     Builder.SetInsertPoint(T);
338     unlinkExceptionRegistration(Builder);
339   }
340 }
341
342 Value *WinEHStatePass::emitEHLSDA(IRBuilder<> &Builder, Function *F) {
343   Value *FI8 = Builder.CreateBitCast(F, Type::getInt8PtrTy(F->getContext()));
344   return Builder.CreateCall(
345       Intrinsic::getDeclaration(TheModule, Intrinsic::x86_seh_lsda), FI8);
346 }
347
348 /// Generate a thunk that puts the LSDA of ParentFunc in EAX and then calls
349 /// PersonalityFn, forwarding the parameters passed to PEXCEPTION_ROUTINE:
350 ///   typedef _EXCEPTION_DISPOSITION (*PEXCEPTION_ROUTINE)(
351 ///       _EXCEPTION_RECORD *, void *, _CONTEXT *, void *);
352 /// We essentially want this code:
353 ///   movl $lsda, %eax
354 ///   jmpl ___CxxFrameHandler3
355 Function *WinEHStatePass::generateLSDAInEAXThunk(Function *ParentFunc) {
356   LLVMContext &Context = ParentFunc->getContext();
357   Type *Int32Ty = Type::getInt32Ty(Context);
358   Type *Int8PtrType = Type::getInt8PtrTy(Context);
359   Type *ArgTys[5] = {Int8PtrType, Int8PtrType, Int8PtrType, Int8PtrType,
360                      Int8PtrType};
361   FunctionType *TrampolineTy =
362       FunctionType::get(Int32Ty, makeArrayRef(&ArgTys[0], 4),
363                         /*isVarArg=*/false);
364   FunctionType *TargetFuncTy =
365       FunctionType::get(Int32Ty, makeArrayRef(&ArgTys[0], 5),
366                         /*isVarArg=*/false);
367   Function *Trampoline =
368       Function::Create(TrampolineTy, GlobalValue::InternalLinkage,
369                        Twine("__ehhandler$") + GlobalValue::getRealLinkageName(
370                                                    ParentFunc->getName()),
371                        TheModule);
372   BasicBlock *EntryBB = BasicBlock::Create(Context, "entry", Trampoline);
373   IRBuilder<> Builder(EntryBB);
374   Value *LSDA = emitEHLSDA(Builder, ParentFunc);
375   Value *CastPersonality =
376       Builder.CreateBitCast(PersonalityFn, TargetFuncTy->getPointerTo());
377   auto AI = Trampoline->arg_begin();
378   Value *Args[5] = {LSDA, AI++, AI++, AI++, AI++};
379   CallInst *Call = Builder.CreateCall(CastPersonality, Args);
380   // Can't use musttail due to prototype mismatch, but we can use tail.
381   Call->setTailCall(true);
382   // Set inreg so we pass it in EAX.
383   Call->addAttribute(1, Attribute::InReg);
384   Builder.CreateRet(Call);
385   return Trampoline;
386 }
387
388 void WinEHStatePass::linkExceptionRegistration(IRBuilder<> &Builder,
389                                                Function *Handler) {
390   // Emit the .safeseh directive for this function.
391   Handler->addFnAttr("safeseh");
392
393   Type *LinkTy = getEHLinkRegistrationType();
394   // Handler = Handler
395   Value *HandlerI8 = Builder.CreateBitCast(Handler, Builder.getInt8PtrTy());
396   Builder.CreateStore(HandlerI8, Builder.CreateStructGEP(LinkTy, Link, 1));
397   // Next = [fs:00]
398   Constant *FSZero =
399       Constant::getNullValue(LinkTy->getPointerTo()->getPointerTo(257));
400   Value *Next = Builder.CreateLoad(FSZero);
401   Builder.CreateStore(Next, Builder.CreateStructGEP(LinkTy, Link, 0));
402   // [fs:00] = Link
403   Builder.CreateStore(Link, FSZero);
404 }
405
406 void WinEHStatePass::unlinkExceptionRegistration(IRBuilder<> &Builder) {
407   // Clone Link into the current BB for better address mode folding.
408   if (auto *GEP = dyn_cast<GetElementPtrInst>(Link)) {
409     GEP = cast<GetElementPtrInst>(GEP->clone());
410     Builder.Insert(GEP);
411     Link = GEP;
412   }
413   Type *LinkTy = getEHLinkRegistrationType();
414   // [fs:00] = Link->Next
415   Value *Next =
416       Builder.CreateLoad(Builder.CreateStructGEP(LinkTy, Link, 0));
417   Constant *FSZero =
418       Constant::getNullValue(LinkTy->getPointerTo()->getPointerTo(257));
419   Builder.CreateStore(Next, FSZero);
420 }
421
422 void WinEHStatePass::addCXXStateStores(Function &F, WinEHFuncInfo &FuncInfo) {
423   // Set up RegNodeEscapeIndex
424   int RegNodeEscapeIndex = escapeRegNode(F);
425   FuncInfo.EHRegNodeEscapeIndex = RegNodeEscapeIndex;
426
427   calculateWinCXXEHStateNumbers(&F, FuncInfo);
428   addStateStoresToFunclet(RegNode, FuncInfo, F, -1);
429 }
430
431 /// Assign every distinct landingpad a unique state number for SEH. Unlike C++
432 /// EH, we can use this very simple algorithm while C++ EH cannot because catch
433 /// handlers aren't outlined and the runtime doesn't have to figure out which
434 /// catch handler frame to unwind to.
435 void WinEHStatePass::addSEHStateStores(Function &F, WinEHFuncInfo &FuncInfo) {
436   // Remember and return the index that we used. We save it in WinEHFuncInfo so
437   // that we can lower llvm.x86.seh.recoverfp later in filter functions without
438   // too much trouble.
439   int RegNodeEscapeIndex = escapeRegNode(F);
440   FuncInfo.EHRegNodeEscapeIndex = RegNodeEscapeIndex;
441
442   calculateSEHStateNumbers(&F, FuncInfo);
443   addStateStoresToFunclet(RegNode, FuncInfo, F, -1);
444 }
445
446 /// Escape RegNode so that we can access it from child handlers. Find the call
447 /// to localescape, if any, in the entry block and append RegNode to the list
448 /// of arguments.
449 int WinEHStatePass::escapeRegNode(Function &F) {
450   // Find the call to localescape and extract its arguments.
451   IntrinsicInst *EscapeCall = nullptr;
452   for (Instruction &I : F.getEntryBlock()) {
453     IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I);
454     if (II && II->getIntrinsicID() == Intrinsic::localescape) {
455       EscapeCall = II;
456       break;
457     }
458   }
459   SmallVector<Value *, 8> Args;
460   if (EscapeCall) {
461     auto Ops = EscapeCall->arg_operands();
462     Args.append(Ops.begin(), Ops.end());
463   }
464   Args.push_back(RegNode);
465
466   // Replace the call (if it exists) with new one. Otherwise, insert at the end
467   // of the entry block.
468   Instruction *InsertPt = EscapeCall;
469   if (!EscapeCall)
470     InsertPt = F.getEntryBlock().getTerminator();
471   IRBuilder<> Builder(&F.getEntryBlock(), InsertPt);
472   Builder.CreateCall(FrameEscape, Args);
473   if (EscapeCall)
474     EscapeCall->eraseFromParent();
475   return Args.size() - 1;
476 }
477
478 void WinEHStatePass::insertRestoreFrame(BasicBlock *BB) {
479   Instruction *Start = BB->getFirstInsertionPt();
480   if (match(Start, m_Intrinsic<Intrinsic::x86_seh_restoreframe>()))
481     return;
482   IRBuilder<> Builder(Start);
483   Builder.CreateCall(RestoreFrame, {});
484 }
485
486 void WinEHStatePass::addStateStoresToFunclet(Value *ParentRegNode,
487                                              WinEHFuncInfo &FuncInfo,
488                                              Function &F, int BaseState) {
489   // Iterate all the instructions and emit state number stores.
490   for (BasicBlock &BB : F) {
491     for (Instruction &I : BB) {
492       if (auto *CI = dyn_cast<CallInst>(&I)) {
493         // Possibly throwing call instructions have no actions to take after
494         // an unwind. Ensure they are in the -1 state.
495         if (CI->doesNotThrow())
496           continue;
497         insertStateNumberStore(ParentRegNode, CI, BaseState);
498       } else if (auto *II = dyn_cast<InvokeInst>(&I)) {
499         // Look up the state number of the landingpad this unwinds to.
500         Instruction *PadInst = II->getUnwindDest()->getFirstNonPHI();
501         // FIXME: Why does this assertion fail?
502         //assert(FuncInfo.EHPadStateMap.count(PadInst) && "EH Pad has no state!");
503         int State = FuncInfo.EHPadStateMap[PadInst];
504         insertStateNumberStore(ParentRegNode, II, State);
505       }
506     }
507   }
508 }
509
510 void WinEHStatePass::insertStateNumberStore(Value *ParentRegNode,
511                                             Instruction *IP, int State) {
512   IRBuilder<> Builder(IP);
513   Value *StateField =
514       Builder.CreateStructGEP(RegNodeTy, ParentRegNode, StateFieldIndex);
515   Builder.CreateStore(Builder.getInt32(State), StateField);
516 }