[X86] Fix emitEpilogue() to make less assumptions about pops
[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   // If this is an outlined handler, don't do anything. We'll do state insertion
153   // for it in the parent.
154   StringRef WinEHParentName =
155       F.getFnAttribute("wineh-parent").getValueAsString();
156   if (WinEHParentName != F.getName() && !WinEHParentName.empty())
157     return false;
158
159   // Check the personality. Do nothing if this is not an MSVC personality.
160   if (!F.hasPersonalityFn())
161     return false;
162   PersonalityFn =
163       dyn_cast<Function>(F.getPersonalityFn()->stripPointerCasts());
164   if (!PersonalityFn)
165     return false;
166   Personality = classifyEHPersonality(PersonalityFn);
167   if (!isMSVCEHPersonality(Personality))
168     return false;
169
170   // Disable frame pointer elimination in this function.
171   // FIXME: Do the nested handlers need to keep the parent ebp in ebp, or can we
172   // use an arbitrary register?
173   F.addFnAttr("no-frame-pointer-elim", "true");
174
175   emitExceptionRegistrationRecord(&F);
176
177   auto *MMI = getAnalysisIfAvailable<MachineModuleInfo>();
178   // If MMI is null, create our own WinEHFuncInfo.  This only happens in opt
179   // tests.
180   std::unique_ptr<WinEHFuncInfo> FuncInfoPtr;
181   if (!MMI)
182     FuncInfoPtr.reset(new WinEHFuncInfo());
183   WinEHFuncInfo &FuncInfo =
184       *(MMI ? &MMI->getWinEHFuncInfo(&F) : FuncInfoPtr.get());
185
186   FuncInfo.EHRegNode = RegNode;
187
188   switch (Personality) {
189   default: llvm_unreachable("unexpected personality function");
190   case EHPersonality::MSVC_CXX:
191     addCXXStateStores(F, FuncInfo);
192     break;
193   case EHPersonality::MSVC_X86SEH:
194     addSEHStateStores(F, FuncInfo);
195     break;
196   }
197
198   // Reset per-function state.
199   PersonalityFn = nullptr;
200   Personality = EHPersonality::Unknown;
201   return true;
202 }
203
204 /// Get the common EH registration subobject:
205 ///   typedef _EXCEPTION_DISPOSITION (*PEXCEPTION_ROUTINE)(
206 ///       _EXCEPTION_RECORD *, void *, _CONTEXT *, void *);
207 ///   struct EHRegistrationNode {
208 ///     EHRegistrationNode *Next;
209 ///     PEXCEPTION_ROUTINE Handler;
210 ///   };
211 Type *WinEHStatePass::getEHLinkRegistrationType() {
212   if (EHLinkRegistrationTy)
213     return EHLinkRegistrationTy;
214   LLVMContext &Context = TheModule->getContext();
215   EHLinkRegistrationTy = StructType::create(Context, "EHRegistrationNode");
216   Type *FieldTys[] = {
217       EHLinkRegistrationTy->getPointerTo(0), // EHRegistrationNode *Next
218       Type::getInt8PtrTy(Context) // EXCEPTION_DISPOSITION (*Handler)(...)
219   };
220   EHLinkRegistrationTy->setBody(FieldTys, false);
221   return EHLinkRegistrationTy;
222 }
223
224 /// The __CxxFrameHandler3 registration node:
225 ///   struct CXXExceptionRegistration {
226 ///     void *SavedESP;
227 ///     EHRegistrationNode SubRecord;
228 ///     int32_t TryLevel;
229 ///   };
230 Type *WinEHStatePass::getCXXEHRegistrationType() {
231   if (CXXEHRegistrationTy)
232     return CXXEHRegistrationTy;
233   LLVMContext &Context = TheModule->getContext();
234   Type *FieldTys[] = {
235       Type::getInt8PtrTy(Context), // void *SavedESP
236       getEHLinkRegistrationType(), // EHRegistrationNode SubRecord
237       Type::getInt32Ty(Context)    // int32_t TryLevel
238   };
239   CXXEHRegistrationTy =
240       StructType::create(FieldTys, "CXXExceptionRegistration");
241   return CXXEHRegistrationTy;
242 }
243
244 /// The _except_handler3/4 registration node:
245 ///   struct EH4ExceptionRegistration {
246 ///     void *SavedESP;
247 ///     _EXCEPTION_POINTERS *ExceptionPointers;
248 ///     EHRegistrationNode SubRecord;
249 ///     int32_t EncodedScopeTable;
250 ///     int32_t TryLevel;
251 ///   };
252 Type *WinEHStatePass::getSEHRegistrationType() {
253   if (SEHRegistrationTy)
254     return SEHRegistrationTy;
255   LLVMContext &Context = TheModule->getContext();
256   Type *FieldTys[] = {
257       Type::getInt8PtrTy(Context), // void *SavedESP
258       Type::getInt8PtrTy(Context), // void *ExceptionPointers
259       getEHLinkRegistrationType(), // EHRegistrationNode SubRecord
260       Type::getInt32Ty(Context),   // int32_t EncodedScopeTable
261       Type::getInt32Ty(Context)    // int32_t TryLevel
262   };
263   SEHRegistrationTy = StructType::create(FieldTys, "SEHExceptionRegistration");
264   return SEHRegistrationTy;
265 }
266
267 // Emit an exception registration record. These are stack allocations with the
268 // common subobject of two pointers: the previous registration record (the old
269 // fs:00) and the personality function for the current frame. The data before
270 // and after that is personality function specific.
271 void WinEHStatePass::emitExceptionRegistrationRecord(Function *F) {
272   assert(Personality == EHPersonality::MSVC_CXX ||
273          Personality == EHPersonality::MSVC_X86SEH);
274
275   StringRef PersonalityName = PersonalityFn->getName();
276   IRBuilder<> Builder(&F->getEntryBlock(), F->getEntryBlock().begin());
277   Type *Int8PtrType = Builder.getInt8PtrTy();
278   if (Personality == EHPersonality::MSVC_CXX) {
279     RegNodeTy = getCXXEHRegistrationType();
280     RegNode = Builder.CreateAlloca(RegNodeTy);
281     // SavedESP = llvm.stacksave()
282     Value *SP = Builder.CreateCall(
283         Intrinsic::getDeclaration(TheModule, Intrinsic::stacksave), {});
284     Builder.CreateStore(SP, Builder.CreateStructGEP(RegNodeTy, RegNode, 0));
285     // TryLevel = -1
286     StateFieldIndex = 2;
287     insertStateNumberStore(RegNode, Builder.GetInsertPoint(), -1);
288     // Handler = __ehhandler$F
289     Function *Trampoline = generateLSDAInEAXThunk(F);
290     Link = Builder.CreateStructGEP(RegNodeTy, RegNode, 1);
291     linkExceptionRegistration(Builder, Trampoline);
292   } else if (Personality == EHPersonality::MSVC_X86SEH) {
293     // If _except_handler4 is in use, some additional guard checks and prologue
294     // stuff is required.
295     bool UseStackGuard = (PersonalityName == "_except_handler4");
296     RegNodeTy = getSEHRegistrationType();
297     RegNode = Builder.CreateAlloca(RegNodeTy);
298     // SavedESP = llvm.stacksave()
299     Value *SP = Builder.CreateCall(
300         Intrinsic::getDeclaration(TheModule, Intrinsic::stacksave), {});
301     Builder.CreateStore(SP, Builder.CreateStructGEP(RegNodeTy, RegNode, 0));
302     // TryLevel = -2 / -1
303     StateFieldIndex = 4;
304     insertStateNumberStore(RegNode, Builder.GetInsertPoint(),
305                            UseStackGuard ? -2 : -1);
306     // ScopeTable = llvm.x86.seh.lsda(F)
307     Value *FI8 = Builder.CreateBitCast(F, Int8PtrType);
308     Value *LSDA = Builder.CreateCall(
309         Intrinsic::getDeclaration(TheModule, Intrinsic::x86_seh_lsda), FI8);
310     Type *Int32Ty = Type::getInt32Ty(TheModule->getContext());
311     LSDA = Builder.CreatePtrToInt(LSDA, Int32Ty);
312     // If using _except_handler4, xor the address of the table with
313     // __security_cookie.
314     if (UseStackGuard) {
315       Value *Cookie =
316           TheModule->getOrInsertGlobal("__security_cookie", Int32Ty);
317       Value *Val = Builder.CreateLoad(Int32Ty, Cookie);
318       LSDA = Builder.CreateXor(LSDA, Val);
319     }
320     Builder.CreateStore(LSDA, Builder.CreateStructGEP(RegNodeTy, RegNode, 3));
321     Link = Builder.CreateStructGEP(RegNodeTy, RegNode, 2);
322     linkExceptionRegistration(Builder, PersonalityFn);
323   } else {
324     llvm_unreachable("unexpected personality function");
325   }
326
327   // Insert an unlink before all returns.
328   for (BasicBlock &BB : *F) {
329     TerminatorInst *T = BB.getTerminator();
330     if (!isa<ReturnInst>(T))
331       continue;
332     Builder.SetInsertPoint(T);
333     unlinkExceptionRegistration(Builder);
334   }
335 }
336
337 Value *WinEHStatePass::emitEHLSDA(IRBuilder<> &Builder, Function *F) {
338   Value *FI8 = Builder.CreateBitCast(F, Type::getInt8PtrTy(F->getContext()));
339   return Builder.CreateCall(
340       Intrinsic::getDeclaration(TheModule, Intrinsic::x86_seh_lsda), FI8);
341 }
342
343 /// Generate a thunk that puts the LSDA of ParentFunc in EAX and then calls
344 /// PersonalityFn, forwarding the parameters passed to PEXCEPTION_ROUTINE:
345 ///   typedef _EXCEPTION_DISPOSITION (*PEXCEPTION_ROUTINE)(
346 ///       _EXCEPTION_RECORD *, void *, _CONTEXT *, void *);
347 /// We essentially want this code:
348 ///   movl $lsda, %eax
349 ///   jmpl ___CxxFrameHandler3
350 Function *WinEHStatePass::generateLSDAInEAXThunk(Function *ParentFunc) {
351   LLVMContext &Context = ParentFunc->getContext();
352   Type *Int32Ty = Type::getInt32Ty(Context);
353   Type *Int8PtrType = Type::getInt8PtrTy(Context);
354   Type *ArgTys[5] = {Int8PtrType, Int8PtrType, Int8PtrType, Int8PtrType,
355                      Int8PtrType};
356   FunctionType *TrampolineTy =
357       FunctionType::get(Int32Ty, makeArrayRef(&ArgTys[0], 4),
358                         /*isVarArg=*/false);
359   FunctionType *TargetFuncTy =
360       FunctionType::get(Int32Ty, makeArrayRef(&ArgTys[0], 5),
361                         /*isVarArg=*/false);
362   Function *Trampoline =
363       Function::Create(TrampolineTy, GlobalValue::InternalLinkage,
364                        Twine("__ehhandler$") + GlobalValue::getRealLinkageName(
365                                                    ParentFunc->getName()),
366                        TheModule);
367   BasicBlock *EntryBB = BasicBlock::Create(Context, "entry", Trampoline);
368   IRBuilder<> Builder(EntryBB);
369   Value *LSDA = emitEHLSDA(Builder, ParentFunc);
370   Value *CastPersonality =
371       Builder.CreateBitCast(PersonalityFn, TargetFuncTy->getPointerTo());
372   auto AI = Trampoline->arg_begin();
373   Value *Args[5] = {LSDA, AI++, AI++, AI++, AI++};
374   CallInst *Call = Builder.CreateCall(CastPersonality, Args);
375   // Can't use musttail due to prototype mismatch, but we can use tail.
376   Call->setTailCall(true);
377   // Set inreg so we pass it in EAX.
378   Call->addAttribute(1, Attribute::InReg);
379   Builder.CreateRet(Call);
380   return Trampoline;
381 }
382
383 void WinEHStatePass::linkExceptionRegistration(IRBuilder<> &Builder,
384                                                Function *Handler) {
385   // Emit the .safeseh directive for this function.
386   Handler->addFnAttr("safeseh");
387
388   Type *LinkTy = getEHLinkRegistrationType();
389   // Handler = Handler
390   Value *HandlerI8 = Builder.CreateBitCast(Handler, Builder.getInt8PtrTy());
391   Builder.CreateStore(HandlerI8, Builder.CreateStructGEP(LinkTy, Link, 1));
392   // Next = [fs:00]
393   Constant *FSZero =
394       Constant::getNullValue(LinkTy->getPointerTo()->getPointerTo(257));
395   Value *Next = Builder.CreateLoad(FSZero);
396   Builder.CreateStore(Next, Builder.CreateStructGEP(LinkTy, Link, 0));
397   // [fs:00] = Link
398   Builder.CreateStore(Link, FSZero);
399 }
400
401 void WinEHStatePass::unlinkExceptionRegistration(IRBuilder<> &Builder) {
402   // Clone Link into the current BB for better address mode folding.
403   if (auto *GEP = dyn_cast<GetElementPtrInst>(Link)) {
404     GEP = cast<GetElementPtrInst>(GEP->clone());
405     Builder.Insert(GEP);
406     Link = GEP;
407   }
408   Type *LinkTy = getEHLinkRegistrationType();
409   // [fs:00] = Link->Next
410   Value *Next =
411       Builder.CreateLoad(Builder.CreateStructGEP(LinkTy, Link, 0));
412   Constant *FSZero =
413       Constant::getNullValue(LinkTy->getPointerTo()->getPointerTo(257));
414   Builder.CreateStore(Next, FSZero);
415 }
416
417 void WinEHStatePass::addCXXStateStores(Function &F, WinEHFuncInfo &FuncInfo) {
418   calculateWinCXXEHStateNumbers(&F, FuncInfo);
419
420   // The base state for the parent is -1.
421   addStateStoresToFunclet(RegNode, FuncInfo, F, -1);
422
423   // Set up RegNodeEscapeIndex
424   int RegNodeEscapeIndex = escapeRegNode(F);
425   FuncInfo.EHRegNodeEscapeIndex = RegNodeEscapeIndex;
426
427   // Only insert stores in catch handlers.
428   Constant *FI8 =
429       ConstantExpr::getBitCast(&F, Type::getInt8PtrTy(TheModule->getContext()));
430   for (auto P : FuncInfo.HandlerBaseState) {
431     Function *Handler = const_cast<Function *>(P.first);
432     int BaseState = P.second;
433     IRBuilder<> Builder(&Handler->getEntryBlock(),
434                         Handler->getEntryBlock().begin());
435     // FIXME: Find and reuse such a call if present.
436     Value *ParentFP = Builder.CreateCall(FrameAddress, {Builder.getInt32(1)});
437     Value *RecoveredRegNode = Builder.CreateCall(
438         FrameRecover, {FI8, ParentFP, Builder.getInt32(RegNodeEscapeIndex)});
439     RecoveredRegNode =
440         Builder.CreateBitCast(RecoveredRegNode, RegNodeTy->getPointerTo(0));
441     addStateStoresToFunclet(RecoveredRegNode, FuncInfo, *Handler, BaseState);
442   }
443 }
444
445 /// Escape RegNode so that we can access it from child handlers. Find the call
446 /// to localescape, if any, in the entry block and append RegNode to the list
447 /// of arguments.
448 int WinEHStatePass::escapeRegNode(Function &F) {
449   // Find the call to localescape and extract its arguments.
450   IntrinsicInst *EscapeCall = nullptr;
451   for (Instruction &I : F.getEntryBlock()) {
452     IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I);
453     if (II && II->getIntrinsicID() == Intrinsic::localescape) {
454       EscapeCall = II;
455       break;
456     }
457   }
458   SmallVector<Value *, 8> Args;
459   if (EscapeCall) {
460     auto Ops = EscapeCall->arg_operands();
461     Args.append(Ops.begin(), Ops.end());
462   }
463   Args.push_back(RegNode);
464
465   // Replace the call (if it exists) with new one. Otherwise, insert at the end
466   // of the entry block.
467   Instruction *InsertPt = EscapeCall;
468   if (!EscapeCall)
469     InsertPt = F.getEntryBlock().getTerminator();
470   IRBuilder<> Builder(&F.getEntryBlock(), InsertPt);
471   Builder.CreateCall(FrameEscape, Args);
472   if (EscapeCall)
473     EscapeCall->eraseFromParent();
474   return Args.size() - 1;
475 }
476
477 void WinEHStatePass::insertRestoreFrame(BasicBlock *BB) {
478   Instruction *Start = BB->getFirstInsertionPt();
479   if (match(Start, m_Intrinsic<Intrinsic::x86_seh_restoreframe>()))
480     return;
481   IRBuilder<> Builder(Start);
482   Builder.CreateCall(RestoreFrame, {});
483 }
484
485 void WinEHStatePass::addStateStoresToFunclet(Value *ParentRegNode,
486                                              WinEHFuncInfo &FuncInfo,
487                                              Function &F, int BaseState) {
488   // Iterate all the instructions and emit state number stores.
489   for (BasicBlock &BB : F) {
490     for (Instruction &I : BB) {
491       if (auto *CI = dyn_cast<CallInst>(&I)) {
492         // Possibly throwing call instructions have no actions to take after
493         // an unwind. Ensure they are in the -1 state.
494         if (CI->doesNotThrow())
495           continue;
496         insertStateNumberStore(ParentRegNode, CI, BaseState);
497       } else if (auto *II = dyn_cast<InvokeInst>(&I)) {
498         // Look up the state number of the landingpad this unwinds to.
499         Instruction *PadInst = II->getUnwindDest()->getFirstNonPHI();
500         // FIXME: Why does this assertion fail?
501         //assert(FuncInfo.EHPadStateMap.count(PadInst) && "EH Pad has no state!");
502         int State = FuncInfo.EHPadStateMap[PadInst];
503         insertStateNumberStore(ParentRegNode, II, State);
504       }
505     }
506
507     // Insert calls to llvm.x86.seh.restoreframe at catchret destinations.  In
508     // SEH, insert them before the catchret.
509     // FIXME: We should probably do this as part of catchret lowering in the
510     // DAG.
511     if (auto *CR = dyn_cast<CatchReturnInst>(BB.getTerminator()))
512       insertRestoreFrame(Personality == EHPersonality::MSVC_X86SEH
513                              ? CR->getParent()
514                              : CR->getSuccessor());
515   }
516 }
517
518 /// Assign every distinct landingpad a unique state number for SEH. Unlike C++
519 /// EH, we can use this very simple algorithm while C++ EH cannot because catch
520 /// handlers aren't outlined and the runtime doesn't have to figure out which
521 /// catch handler frame to unwind to.
522 /// FIXME: __finally blocks are outlined, so this approach may break down there.
523 void WinEHStatePass::addSEHStateStores(Function &F, WinEHFuncInfo &FuncInfo) {
524   // Remember and return the index that we used. We save it in WinEHFuncInfo so
525   // that we can lower llvm.x86.seh.recoverfp later in filter functions without
526   // too much trouble.
527   int RegNodeEscapeIndex = escapeRegNode(F);
528   FuncInfo.EHRegNodeEscapeIndex = RegNodeEscapeIndex;
529
530   // If this funciton uses the new EH IR, use the explicit state numbering
531   // algorithm and return early.
532   bool UsesLPads = false;
533   for (BasicBlock &BB : F) {
534     if (BB.isLandingPad()) {
535       UsesLPads = true;
536       break;
537     }
538   }
539   if (!UsesLPads) {
540     calculateSEHStateNumbers(&F, FuncInfo);
541     addStateStoresToFunclet(RegNode, FuncInfo, F, -1);
542     return;
543   }
544   // FIXME: Delete the rest of this code and clean things up when new EH is
545   // done.
546
547   // Iterate all the instructions and emit state number stores.
548   int CurState = 0;
549   SmallPtrSet<BasicBlock *, 4> ExceptBlocks;
550   for (BasicBlock &BB : F) {
551     for (auto I = BB.begin(), E = BB.end(); I != E; ++I) {
552       if (auto *CI = dyn_cast<CallInst>(I)) {
553         auto *Intrin = dyn_cast<IntrinsicInst>(CI);
554         if (Intrin) {
555           // Calls that "don't throw" are considered to be able to throw asynch
556           // exceptions, but intrinsics cannot.
557           continue;
558         }
559         insertStateNumberStore(RegNode, CI, -1);
560       } else if (auto *II = dyn_cast<InvokeInst>(I)) {
561         // Look up the state number of the landingpad this unwinds to.
562         LandingPadInst *LPI = II->getUnwindDest()->getLandingPadInst();
563         auto InsertionPair =
564             FuncInfo.EHPadStateMap.insert(std::make_pair(LPI, CurState));
565         auto Iter = InsertionPair.first;
566         int &State = Iter->second;
567         bool Inserted = InsertionPair.second;
568         if (Inserted) {
569           // Each action consumes a state number.
570           auto *EHActions = cast<IntrinsicInst>(LPI->getNextNode());
571           SmallVector<std::unique_ptr<ActionHandler>, 4> ActionList;
572           parseEHActions(EHActions, ActionList);
573           assert(!ActionList.empty());
574           CurState += ActionList.size();
575           State += ActionList.size() - 1;
576
577           // Remember all the __except block targets.
578           for (auto &Handler : ActionList) {
579             if (auto *CH = dyn_cast<CatchHandler>(Handler.get())) {
580               auto *BA = cast<BlockAddress>(CH->getHandlerBlockOrFunc());
581 #ifndef NDEBUG
582               for (BasicBlock *Pred : predecessors(BA->getBasicBlock()))
583                 assert(Pred->isLandingPad() &&
584                        "WinEHPrepare failed to split block");
585 #endif
586               ExceptBlocks.insert(BA->getBasicBlock());
587             }
588           }
589         }
590         insertStateNumberStore(RegNode, II, State);
591       }
592     }
593   }
594
595   // Insert llvm.x86.seh.restoreframe() into each __except block.
596   Function *RestoreFrame =
597       Intrinsic::getDeclaration(TheModule, Intrinsic::x86_seh_restoreframe);
598   for (BasicBlock *ExceptBB : ExceptBlocks) {
599     IRBuilder<> Builder(ExceptBB->begin());
600     Builder.CreateCall(RestoreFrame, {});
601   }
602 }
603
604 void WinEHStatePass::insertStateNumberStore(Value *ParentRegNode,
605                                             Instruction *IP, int State) {
606   IRBuilder<> Builder(IP);
607   Value *StateField =
608       Builder.CreateStructGEP(RegNodeTy, ParentRegNode, StateFieldIndex);
609   Builder.CreateStore(Builder.getInt32(State), StateField);
610 }