[WinEH] Emit .safeseh directives for all 32-bit exception handlers
[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 {
42 class WinEHStatePass : public FunctionPass {
43 public:
44   static char ID; // Pass identification, replacement for typeid.
45
46   WinEHStatePass() : FunctionPass(ID) {}
47
48   bool runOnFunction(Function &Fn) override;
49
50   bool doInitialization(Module &M) override;
51
52   bool doFinalization(Module &M) override;
53
54   void getAnalysisUsage(AnalysisUsage &AU) const override;
55
56   const char *getPassName() const override {
57     return "Windows 32-bit x86 EH state insertion";
58   }
59
60 private:
61   void emitExceptionRegistrationRecord(Function *F);
62
63   void linkExceptionRegistration(IRBuilder<> &Builder, Function *Handler);
64   void unlinkExceptionRegistration(IRBuilder<> &Builder);
65   void addCXXStateStores(Function &F, MachineModuleInfo &MMI);
66   void addSEHStateStores(Function &F, MachineModuleInfo &MMI);
67   void addCXXStateStoresToFunclet(Value *ParentRegNode, WinEHFuncInfo &FuncInfo,
68                                   Function &F, int BaseState);
69   void insertStateNumberStore(Value *ParentRegNode, Instruction *IP, int State);
70   iplist<Instruction>::iterator
71   rewriteExceptionInfoIntrinsics(IntrinsicInst *Intrin);
72
73   Value *emitEHLSDA(IRBuilder<> &Builder, Function *F);
74
75   Function *generateLSDAInEAXThunk(Function *ParentFunc);
76
77   int escapeRegNode(Function &F);
78
79   // Module-level type getters.
80   Type *getEHLinkRegistrationType();
81   Type *getSEHRegistrationType();
82   Type *getCXXEHRegistrationType();
83
84   // Per-module data.
85   Module *TheModule = nullptr;
86   StructType *EHLinkRegistrationTy = nullptr;
87   StructType *CXXEHRegistrationTy = nullptr;
88   StructType *SEHRegistrationTy = nullptr;
89   Function *FrameRecover = nullptr;
90   Function *FrameAddress = nullptr;
91   Function *FrameEscape = nullptr;
92
93   // Per-function state
94   EHPersonality Personality = EHPersonality::Unknown;
95   Function *PersonalityFn = nullptr;
96
97   /// The stack allocation containing all EH data, including the link in the
98   /// fs:00 chain and the current state.
99   AllocaInst *RegNode = nullptr;
100
101   /// Struct type of RegNode. Used for GEPing.
102   Type *RegNodeTy = nullptr;
103
104   /// The index of the state field of RegNode.
105   int StateFieldIndex = ~0U;
106
107   /// The linked list node subobject inside of RegNode.
108   Value *Link = nullptr;
109 };
110 }
111
112 FunctionPass *llvm::createX86WinEHStatePass() { return new WinEHStatePass(); }
113
114 char WinEHStatePass::ID = 0;
115
116 bool WinEHStatePass::doInitialization(Module &M) {
117   TheModule = &M;
118   FrameEscape = Intrinsic::getDeclaration(TheModule, Intrinsic::frameescape);
119   FrameRecover = Intrinsic::getDeclaration(TheModule, Intrinsic::framerecover);
120   FrameAddress = Intrinsic::getDeclaration(TheModule, Intrinsic::frameaddress);
121   return false;
122 }
123
124 bool WinEHStatePass::doFinalization(Module &M) {
125   assert(TheModule == &M);
126   TheModule = nullptr;
127   EHLinkRegistrationTy = nullptr;
128   CXXEHRegistrationTy = nullptr;
129   SEHRegistrationTy = nullptr;
130   FrameEscape = nullptr;
131   FrameRecover = nullptr;
132   FrameAddress = nullptr;
133   return false;
134 }
135
136 void WinEHStatePass::getAnalysisUsage(AnalysisUsage &AU) const {
137   // This pass should only insert a stack allocation, memory accesses, and
138   // framerecovers.
139   AU.setPreservesCFG();
140 }
141
142 bool WinEHStatePass::runOnFunction(Function &F) {
143   // If this is an outlined handler, don't do anything. We'll do state insertion
144   // for it in the parent.
145   StringRef WinEHParentName =
146       F.getFnAttribute("wineh-parent").getValueAsString();
147   if (WinEHParentName != F.getName() && !WinEHParentName.empty())
148     return false;
149
150   // Check the personality. Do nothing if this is not an MSVC personality.
151   LandingPadInst *LP = nullptr;
152   for (BasicBlock &BB : F) {
153     LP = BB.getLandingPadInst();
154     if (LP)
155       break;
156   }
157   if (!LP)
158     return false;
159   PersonalityFn =
160       dyn_cast<Function>(LP->getPersonalityFn()->stripPointerCasts());
161   if (!PersonalityFn)
162     return false;
163   Personality = classifyEHPersonality(PersonalityFn);
164   if (!isMSVCEHPersonality(Personality))
165     return false;
166
167   // Disable frame pointer elimination in this function.
168   // FIXME: Do the nested handlers need to keep the parent ebp in ebp, or can we
169   // use an arbitrary register?
170   F.addFnAttr("no-frame-pointer-elim", "true");
171
172   emitExceptionRegistrationRecord(&F);
173
174   auto *MMIPtr = getAnalysisIfAvailable<MachineModuleInfo>();
175   assert(MMIPtr && "MachineModuleInfo should always be available");
176   MachineModuleInfo &MMI = *MMIPtr;
177   switch (Personality) {
178   default: llvm_unreachable("unexpected personality function");
179   case EHPersonality::MSVC_CXX:    addCXXStateStores(F, MMI); break;
180   case EHPersonality::MSVC_X86SEH: addSEHStateStores(F, MMI); break;
181   }
182
183   // Reset per-function state.
184   PersonalityFn = nullptr;
185   Personality = EHPersonality::Unknown;
186   return true;
187 }
188
189 /// Get the common EH registration subobject:
190 ///   typedef _EXCEPTION_DISPOSITION (*PEXCEPTION_ROUTINE)(
191 ///       _EXCEPTION_RECORD *, void *, _CONTEXT *, void *);
192 ///   struct EHRegistrationNode {
193 ///     EHRegistrationNode *Next;
194 ///     PEXCEPTION_ROUTINE Handler;
195 ///   };
196 Type *WinEHStatePass::getEHLinkRegistrationType() {
197   if (EHLinkRegistrationTy)
198     return EHLinkRegistrationTy;
199   LLVMContext &Context = TheModule->getContext();
200   EHLinkRegistrationTy = StructType::create(Context, "EHRegistrationNode");
201   Type *FieldTys[] = {
202       EHLinkRegistrationTy->getPointerTo(0), // EHRegistrationNode *Next
203       Type::getInt8PtrTy(Context) // EXCEPTION_DISPOSITION (*Handler)(...)
204   };
205   EHLinkRegistrationTy->setBody(FieldTys, false);
206   return EHLinkRegistrationTy;
207 }
208
209 /// The __CxxFrameHandler3 registration node:
210 ///   struct CXXExceptionRegistration {
211 ///     void *SavedESP;
212 ///     EHRegistrationNode SubRecord;
213 ///     int32_t TryLevel;
214 ///   };
215 Type *WinEHStatePass::getCXXEHRegistrationType() {
216   if (CXXEHRegistrationTy)
217     return CXXEHRegistrationTy;
218   LLVMContext &Context = TheModule->getContext();
219   Type *FieldTys[] = {
220       Type::getInt8PtrTy(Context), // void *SavedESP
221       getEHLinkRegistrationType(), // EHRegistrationNode SubRecord
222       Type::getInt32Ty(Context)    // int32_t TryLevel
223   };
224   CXXEHRegistrationTy =
225       StructType::create(FieldTys, "CXXExceptionRegistration");
226   return CXXEHRegistrationTy;
227 }
228
229 /// The _except_handler3/4 registration node:
230 ///   struct EH4ExceptionRegistration {
231 ///     void *SavedESP;
232 ///     _EXCEPTION_POINTERS *ExceptionPointers;
233 ///     EHRegistrationNode SubRecord;
234 ///     int32_t EncodedScopeTable;
235 ///     int32_t TryLevel;
236 ///   };
237 Type *WinEHStatePass::getSEHRegistrationType() {
238   if (SEHRegistrationTy)
239     return SEHRegistrationTy;
240   LLVMContext &Context = TheModule->getContext();
241   Type *FieldTys[] = {
242       Type::getInt8PtrTy(Context), // void *SavedESP
243       Type::getInt8PtrTy(Context), // void *ExceptionPointers
244       getEHLinkRegistrationType(), // EHRegistrationNode SubRecord
245       Type::getInt32Ty(Context),   // int32_t EncodedScopeTable
246       Type::getInt32Ty(Context)    // int32_t TryLevel
247   };
248   SEHRegistrationTy = StructType::create(FieldTys, "SEHExceptionRegistration");
249   return SEHRegistrationTy;
250 }
251
252 // Emit an exception registration record. These are stack allocations with the
253 // common subobject of two pointers: the previous registration record (the old
254 // fs:00) and the personality function for the current frame. The data before
255 // and after that is personality function specific.
256 void WinEHStatePass::emitExceptionRegistrationRecord(Function *F) {
257   assert(Personality == EHPersonality::MSVC_CXX ||
258          Personality == EHPersonality::MSVC_X86SEH);
259
260   StringRef PersonalityName = PersonalityFn->getName();
261   IRBuilder<> Builder(&F->getEntryBlock(), F->getEntryBlock().begin());
262   Type *Int8PtrType = Builder.getInt8PtrTy();
263   if (Personality == EHPersonality::MSVC_CXX) {
264     RegNodeTy = getCXXEHRegistrationType();
265     RegNode = Builder.CreateAlloca(RegNodeTy);
266     // FIXME: We can skip this in -GS- mode, when we figure that out.
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 = Function::Create(
349       TrampolineTy, GlobalValue::InternalLinkage,
350       Twine("__ehhandler$") + ParentFunc->getName(), TheModule);
351   BasicBlock *EntryBB = BasicBlock::Create(Context, "entry", Trampoline);
352   IRBuilder<> Builder(EntryBB);
353   Value *LSDA = emitEHLSDA(Builder, ParentFunc);
354   Value *CastPersonality =
355       Builder.CreateBitCast(PersonalityFn, TargetFuncTy->getPointerTo());
356   auto AI = Trampoline->arg_begin();
357   Value *Args[5] = {LSDA, AI++, AI++, AI++, AI++};
358   CallInst *Call = Builder.CreateCall(CastPersonality, Args);
359   // Can't use musttail due to prototype mismatch, but we can use tail.
360   Call->setTailCall(true);
361   // Set inreg so we pass it in EAX.
362   Call->addAttribute(1, Attribute::InReg);
363   Builder.CreateRet(Call);
364   return Trampoline;
365 }
366
367 void WinEHStatePass::linkExceptionRegistration(IRBuilder<> &Builder,
368                                                Function *Handler) {
369   // Emit the .safeseh directive for this function.
370   Handler->addFnAttr("safeseh");
371
372   Type *LinkTy = getEHLinkRegistrationType();
373   // Handler = Handler
374   Value *HandlerI8 = Builder.CreateBitCast(Handler, Builder.getInt8PtrTy());
375   Builder.CreateStore(HandlerI8, Builder.CreateStructGEP(LinkTy, Link, 1));
376   // Next = [fs:00]
377   Constant *FSZero =
378       Constant::getNullValue(LinkTy->getPointerTo()->getPointerTo(257));
379   Value *Next = Builder.CreateLoad(FSZero);
380   Builder.CreateStore(Next, Builder.CreateStructGEP(LinkTy, Link, 0));
381   // [fs:00] = Link
382   Builder.CreateStore(Link, FSZero);
383 }
384
385 void WinEHStatePass::unlinkExceptionRegistration(IRBuilder<> &Builder) {
386   // Clone Link into the current BB for better address mode folding.
387   if (auto *GEP = dyn_cast<GetElementPtrInst>(Link)) {
388     GEP = cast<GetElementPtrInst>(GEP->clone());
389     Builder.Insert(GEP);
390     Link = GEP;
391   }
392   Type *LinkTy = getEHLinkRegistrationType();
393   // [fs:00] = Link->Next
394   Value *Next =
395       Builder.CreateLoad(Builder.CreateStructGEP(LinkTy, Link, 0));
396   Constant *FSZero =
397       Constant::getNullValue(LinkTy->getPointerTo()->getPointerTo(257));
398   Builder.CreateStore(Next, FSZero);
399 }
400
401 void WinEHStatePass::addCXXStateStores(Function &F, MachineModuleInfo &MMI) {
402   WinEHFuncInfo &FuncInfo = MMI.getWinEHFuncInfo(&F);
403   calculateWinCXXEHStateNumbers(&F, FuncInfo);
404
405   // The base state for the parent is -1.
406   addCXXStateStoresToFunclet(RegNode, FuncInfo, F, -1);
407
408   // Set up RegNodeEscapeIndex
409   int RegNodeEscapeIndex = escapeRegNode(F);
410
411   // Only insert stores in catch handlers.
412   Constant *FI8 =
413       ConstantExpr::getBitCast(&F, Type::getInt8PtrTy(TheModule->getContext()));
414   for (auto P : FuncInfo.HandlerBaseState) {
415     Function *Handler = const_cast<Function *>(P.first);
416     int BaseState = P.second;
417     IRBuilder<> Builder(&Handler->getEntryBlock(),
418                         Handler->getEntryBlock().begin());
419     // FIXME: Find and reuse such a call if present.
420     Value *ParentFP = Builder.CreateCall(FrameAddress, {Builder.getInt32(1)});
421     Value *RecoveredRegNode = Builder.CreateCall(
422         FrameRecover, {FI8, ParentFP, Builder.getInt32(RegNodeEscapeIndex)});
423     RecoveredRegNode =
424         Builder.CreateBitCast(RecoveredRegNode, RegNodeTy->getPointerTo(0));
425     addCXXStateStoresToFunclet(RecoveredRegNode, FuncInfo, *Handler, BaseState);
426   }
427 }
428
429 /// Escape RegNode so that we can access it from child handlers. Find the call
430 /// to frameescape, if any, in the entry block and append RegNode to the list
431 /// of arguments.
432 int WinEHStatePass::escapeRegNode(Function &F) {
433   // Find the call to frameescape and extract its arguments.
434   IntrinsicInst *EscapeCall = nullptr;
435   for (Instruction &I : F.getEntryBlock()) {
436     IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I);
437     if (II && II->getIntrinsicID() == Intrinsic::frameescape) {
438       EscapeCall = II;
439       break;
440     }
441   }
442   SmallVector<Value *, 8> Args;
443   if (EscapeCall) {
444     auto Ops = EscapeCall->arg_operands();
445     Args.append(Ops.begin(), Ops.end());
446   }
447   Args.push_back(RegNode);
448
449   // Replace the call (if it exists) with new one. Otherwise, insert at the end
450   // of the entry block.
451   IRBuilder<> Builder(&F.getEntryBlock(),
452                       EscapeCall ? EscapeCall : F.getEntryBlock().end());
453   Builder.CreateCall(FrameEscape, Args);
454   if (EscapeCall)
455     EscapeCall->eraseFromParent();
456   return Args.size() - 1;
457 }
458
459 void WinEHStatePass::addCXXStateStoresToFunclet(Value *ParentRegNode,
460                                                 WinEHFuncInfo &FuncInfo,
461                                                 Function &F, int BaseState) {
462   // Iterate all the instructions and emit state number stores.
463   for (BasicBlock &BB : F) {
464     for (Instruction &I : BB) {
465       if (auto *CI = dyn_cast<CallInst>(&I)) {
466         // Possibly throwing call instructions have no actions to take after
467         // an unwind. Ensure they are in the -1 state.
468         if (CI->doesNotThrow())
469           continue;
470         insertStateNumberStore(ParentRegNode, CI, BaseState);
471       } else if (auto *II = dyn_cast<InvokeInst>(&I)) {
472         // Look up the state number of the landingpad this unwinds to.
473         LandingPadInst *LPI = II->getUnwindDest()->getLandingPadInst();
474         // FIXME: Why does this assertion fail?
475         //assert(FuncInfo.LandingPadStateMap.count(LPI) && "LP has no state!");
476         int State = FuncInfo.LandingPadStateMap[LPI];
477         insertStateNumberStore(ParentRegNode, II, State);
478       }
479     }
480   }
481 }
482
483 /// Assign every distinct landingpad a unique state number for SEH. Unlike C++
484 /// EH, we can use this very simple algorithm while C++ EH cannot because catch
485 /// handlers aren't outlined and the runtime doesn't have to figure out which
486 /// catch handler frame to unwind to.
487 /// FIXME: __finally blocks are outlined, so this approach may break down there.
488 void WinEHStatePass::addSEHStateStores(Function &F, MachineModuleInfo &MMI) {
489   WinEHFuncInfo &FuncInfo = MMI.getWinEHFuncInfo(&F);
490
491   // Iterate all the instructions and emit state number stores.
492   int CurState = 0;
493   for (BasicBlock &BB : F) {
494     for (auto I = BB.begin(), E = BB.end(); I != E; ++I) {
495       if (auto *CI = dyn_cast<CallInst>(I)) {
496         auto *Intrin = dyn_cast<IntrinsicInst>(CI);
497         if (Intrin) {
498           I = rewriteExceptionInfoIntrinsics(Intrin);
499           // Calls that "don't throw" are considered to be able to throw asynch
500           // exceptions, but intrinsics cannot.
501           continue;
502         }
503         insertStateNumberStore(RegNode, CI, -1);
504       } else if (auto *II = dyn_cast<InvokeInst>(I)) {
505         // Look up the state number of the landingpad this unwinds to.
506         LandingPadInst *LPI = II->getUnwindDest()->getLandingPadInst();
507         auto InsertionPair =
508             FuncInfo.LandingPadStateMap.insert(std::make_pair(LPI, 0));
509         auto Iter = InsertionPair.first;
510         int &State = Iter->second;
511         bool Inserted = InsertionPair.second;
512         if (Inserted) {
513           // Each action consumes a state number.
514           auto *EHActions = cast<IntrinsicInst>(LPI->getNextNode());
515           SmallVector<std::unique_ptr<ActionHandler>, 4> ActionList;
516           parseEHActions(EHActions, ActionList);
517           assert(!ActionList.empty());
518           CurState += ActionList.size();
519           State += ActionList.size() - 1;
520         }
521         insertStateNumberStore(RegNode, II, State);
522       }
523     }
524   }
525 }
526
527 /// Rewrite llvm.eh.exceptioncode and llvm.eh.exceptioninfo to memory loads in
528 /// IR.
529 iplist<Instruction>::iterator
530 WinEHStatePass::rewriteExceptionInfoIntrinsics(IntrinsicInst *Intrin) {
531   Intrinsic::ID ID = Intrin->getIntrinsicID();
532   if (ID != Intrinsic::eh_exceptioncode && ID != Intrinsic::eh_exceptioninfo)
533     return Intrin;
534
535   // RegNode->ExceptionPointers
536   IRBuilder<> Builder(Intrin);
537   Value *Ptrs =
538       Builder.CreateLoad(Builder.CreateStructGEP(RegNodeTy, RegNode, 1));
539   Value *Res;
540   if (ID == Intrinsic::eh_exceptioncode) {
541     // Ptrs->ExceptionRecord->Code
542     Ptrs = Builder.CreateBitCast(
543         Ptrs, Builder.getInt32Ty()->getPointerTo()->getPointerTo());
544     Value *Rec = Builder.CreateLoad(Ptrs);
545     Res = Builder.CreateLoad(Rec);
546   } else {
547     Res = Ptrs;
548   }
549   Intrin->replaceAllUsesWith(Res);
550   return Intrin->eraseFromParent();
551 }
552
553 void WinEHStatePass::insertStateNumberStore(Value *ParentRegNode,
554                                             Instruction *IP, int State) {
555   IRBuilder<> Builder(IP);
556   Value *StateField =
557       Builder.CreateStructGEP(RegNodeTy, ParentRegNode, StateFieldIndex);
558   Builder.CreateStore(Builder.getInt32(State), StateField);
559 }