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