LLVM  3.7.0
X86WinEHState.cpp
Go to the documentation of this file.
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"
20 #include "llvm/CodeGen/Passes.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"
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 
71  Value *emitEHLSDA(IRBuilder<> &Builder, Function *F);
72 
73  Function *generateLSDAInEAXThunk(Function *ParentFunc);
74 
75  int escapeRegNode(Function &F);
76 
77  // Module-level type getters.
78  Type *getEHLinkRegistrationType();
79  Type *getSEHRegistrationType();
80  Type *getCXXEHRegistrationType();
81 
82  // Per-module data.
83  Module *TheModule = nullptr;
84  StructType *EHLinkRegistrationTy = nullptr;
85  StructType *CXXEHRegistrationTy = nullptr;
86  StructType *SEHRegistrationTy = nullptr;
87  Function *FrameRecover = nullptr;
88  Function *FrameAddress = nullptr;
89  Function *FrameEscape = nullptr;
90 
91  // Per-function state
93  Function *PersonalityFn = nullptr;
94 
95  /// The stack allocation containing all EH data, including the link in the
96  /// fs:00 chain and the current state.
97  AllocaInst *RegNode = nullptr;
98 
99  /// Struct type of RegNode. Used for GEPing.
100  Type *RegNodeTy = nullptr;
101 
102  /// The index of the state field of RegNode.
103  int StateFieldIndex = ~0U;
104 
105  /// The linked list node subobject inside of RegNode.
106  Value *Link = nullptr;
107 };
108 }
109 
110 FunctionPass *llvm::createX86WinEHStatePass() { return new WinEHStatePass(); }
111 
112 char WinEHStatePass::ID = 0;
113 
114 bool WinEHStatePass::doInitialization(Module &M) {
115  TheModule = &M;
116  FrameEscape = Intrinsic::getDeclaration(TheModule, Intrinsic::localescape);
117  FrameRecover = Intrinsic::getDeclaration(TheModule, Intrinsic::localrecover);
118  FrameAddress = Intrinsic::getDeclaration(TheModule, Intrinsic::frameaddress);
119  return false;
120 }
121 
122 bool WinEHStatePass::doFinalization(Module &M) {
123  assert(TheModule == &M);
124  TheModule = nullptr;
125  EHLinkRegistrationTy = nullptr;
126  CXXEHRegistrationTy = nullptr;
127  SEHRegistrationTy = nullptr;
128  FrameEscape = nullptr;
129  FrameRecover = nullptr;
130  FrameAddress = nullptr;
131  return false;
132 }
133 
134 void WinEHStatePass::getAnalysisUsage(AnalysisUsage &AU) const {
135  // This pass should only insert a stack allocation, memory accesses, and
136  // localrecovers.
137  AU.setPreservesCFG();
138 }
139 
140 bool WinEHStatePass::runOnFunction(Function &F) {
141  // If this is an outlined handler, don't do anything. We'll do state insertion
142  // for it in the parent.
143  StringRef WinEHParentName =
144  F.getFnAttribute("wineh-parent").getValueAsString();
145  if (WinEHParentName != F.getName() && !WinEHParentName.empty())
146  return false;
147 
148  // Check the personality. Do nothing if this is not an MSVC personality.
149  if (!F.hasPersonalityFn())
150  return false;
151  PersonalityFn =
153  if (!PersonalityFn)
154  return false;
155  Personality = classifyEHPersonality(PersonalityFn);
156  if (!isMSVCEHPersonality(Personality))
157  return false;
158 
159  // Disable frame pointer elimination in this function.
160  // FIXME: Do the nested handlers need to keep the parent ebp in ebp, or can we
161  // use an arbitrary register?
162  F.addFnAttr("no-frame-pointer-elim", "true");
163 
164  emitExceptionRegistrationRecord(&F);
165 
166  auto *MMIPtr = getAnalysisIfAvailable<MachineModuleInfo>();
167  assert(MMIPtr && "MachineModuleInfo should always be available");
168  MachineModuleInfo &MMI = *MMIPtr;
169  switch (Personality) {
170  default: llvm_unreachable("unexpected personality function");
171  case EHPersonality::MSVC_CXX: addCXXStateStores(F, MMI); break;
172  case EHPersonality::MSVC_X86SEH: addSEHStateStores(F, MMI); break;
173  }
174 
175  // Reset per-function state.
176  PersonalityFn = nullptr;
177  Personality = EHPersonality::Unknown;
178  return true;
179 }
180 
181 /// Get the common EH registration subobject:
182 /// typedef _EXCEPTION_DISPOSITION (*PEXCEPTION_ROUTINE)(
183 /// _EXCEPTION_RECORD *, void *, _CONTEXT *, void *);
184 /// struct EHRegistrationNode {
185 /// EHRegistrationNode *Next;
186 /// PEXCEPTION_ROUTINE Handler;
187 /// };
188 Type *WinEHStatePass::getEHLinkRegistrationType() {
189  if (EHLinkRegistrationTy)
190  return EHLinkRegistrationTy;
191  LLVMContext &Context = TheModule->getContext();
192  EHLinkRegistrationTy = StructType::create(Context, "EHRegistrationNode");
193  Type *FieldTys[] = {
194  EHLinkRegistrationTy->getPointerTo(0), // EHRegistrationNode *Next
195  Type::getInt8PtrTy(Context) // EXCEPTION_DISPOSITION (*Handler)(...)
196  };
197  EHLinkRegistrationTy->setBody(FieldTys, false);
198  return EHLinkRegistrationTy;
199 }
200 
201 /// The __CxxFrameHandler3 registration node:
202 /// struct CXXExceptionRegistration {
203 /// void *SavedESP;
204 /// EHRegistrationNode SubRecord;
205 /// int32_t TryLevel;
206 /// };
207 Type *WinEHStatePass::getCXXEHRegistrationType() {
208  if (CXXEHRegistrationTy)
209  return CXXEHRegistrationTy;
210  LLVMContext &Context = TheModule->getContext();
211  Type *FieldTys[] = {
212  Type::getInt8PtrTy(Context), // void *SavedESP
213  getEHLinkRegistrationType(), // EHRegistrationNode SubRecord
214  Type::getInt32Ty(Context) // int32_t TryLevel
215  };
216  CXXEHRegistrationTy =
217  StructType::create(FieldTys, "CXXExceptionRegistration");
218  return CXXEHRegistrationTy;
219 }
220 
221 /// The _except_handler3/4 registration node:
222 /// struct EH4ExceptionRegistration {
223 /// void *SavedESP;
224 /// _EXCEPTION_POINTERS *ExceptionPointers;
225 /// EHRegistrationNode SubRecord;
226 /// int32_t EncodedScopeTable;
227 /// int32_t TryLevel;
228 /// };
229 Type *WinEHStatePass::getSEHRegistrationType() {
230  if (SEHRegistrationTy)
231  return SEHRegistrationTy;
232  LLVMContext &Context = TheModule->getContext();
233  Type *FieldTys[] = {
234  Type::getInt8PtrTy(Context), // void *SavedESP
235  Type::getInt8PtrTy(Context), // void *ExceptionPointers
236  getEHLinkRegistrationType(), // EHRegistrationNode SubRecord
237  Type::getInt32Ty(Context), // int32_t EncodedScopeTable
238  Type::getInt32Ty(Context) // int32_t TryLevel
239  };
240  SEHRegistrationTy = StructType::create(FieldTys, "SEHExceptionRegistration");
241  return SEHRegistrationTy;
242 }
243 
244 // Emit an exception registration record. These are stack allocations with the
245 // common subobject of two pointers: the previous registration record (the old
246 // fs:00) and the personality function for the current frame. The data before
247 // and after that is personality function specific.
248 void WinEHStatePass::emitExceptionRegistrationRecord(Function *F) {
249  assert(Personality == EHPersonality::MSVC_CXX ||
250  Personality == EHPersonality::MSVC_X86SEH);
251 
252  StringRef PersonalityName = PersonalityFn->getName();
253  IRBuilder<> Builder(&F->getEntryBlock(), F->getEntryBlock().begin());
254  Type *Int8PtrType = Builder.getInt8PtrTy();
255  if (Personality == EHPersonality::MSVC_CXX) {
256  RegNodeTy = getCXXEHRegistrationType();
257  RegNode = Builder.CreateAlloca(RegNodeTy);
258  // SavedESP = llvm.stacksave()
259  Value *SP = Builder.CreateCall(
260  Intrinsic::getDeclaration(TheModule, Intrinsic::stacksave), {});
261  Builder.CreateStore(SP, Builder.CreateStructGEP(RegNodeTy, RegNode, 0));
262  // TryLevel = -1
263  StateFieldIndex = 2;
264  insertStateNumberStore(RegNode, Builder.GetInsertPoint(), -1);
265  // Handler = __ehhandler$F
266  Function *Trampoline = generateLSDAInEAXThunk(F);
267  Link = Builder.CreateStructGEP(RegNodeTy, RegNode, 1);
268  linkExceptionRegistration(Builder, Trampoline);
269  } else if (Personality == EHPersonality::MSVC_X86SEH) {
270  // If _except_handler4 is in use, some additional guard checks and prologue
271  // stuff is required.
272  bool UseStackGuard = (PersonalityName == "_except_handler4");
273  RegNodeTy = getSEHRegistrationType();
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 = -2 / -1
280  StateFieldIndex = 4;
281  insertStateNumberStore(RegNode, Builder.GetInsertPoint(),
282  UseStackGuard ? -2 : -1);
283  // ScopeTable = llvm.x86.seh.lsda(F)
284  Value *FI8 = Builder.CreateBitCast(F, Int8PtrType);
285  Value *LSDA = Builder.CreateCall(
286  Intrinsic::getDeclaration(TheModule, Intrinsic::x86_seh_lsda), FI8);
287  Type *Int32Ty = Type::getInt32Ty(TheModule->getContext());
288  LSDA = Builder.CreatePtrToInt(LSDA, Int32Ty);
289  // If using _except_handler4, xor the address of the table with
290  // __security_cookie.
291  if (UseStackGuard) {
292  Value *Cookie =
293  TheModule->getOrInsertGlobal("__security_cookie", Int32Ty);
294  Value *Val = Builder.CreateLoad(Int32Ty, Cookie);
295  LSDA = Builder.CreateXor(LSDA, Val);
296  }
297  Builder.CreateStore(LSDA, Builder.CreateStructGEP(RegNodeTy, RegNode, 3));
298  Link = Builder.CreateStructGEP(RegNodeTy, RegNode, 2);
299  linkExceptionRegistration(Builder, PersonalityFn);
300  } else {
301  llvm_unreachable("unexpected personality function");
302  }
303 
304  // Insert an unlink before all returns.
305  for (BasicBlock &BB : *F) {
306  TerminatorInst *T = BB.getTerminator();
307  if (!isa<ReturnInst>(T))
308  continue;
309  Builder.SetInsertPoint(T);
310  unlinkExceptionRegistration(Builder);
311  }
312 }
313 
314 Value *WinEHStatePass::emitEHLSDA(IRBuilder<> &Builder, Function *F) {
315  Value *FI8 = Builder.CreateBitCast(F, Type::getInt8PtrTy(F->getContext()));
316  return Builder.CreateCall(
317  Intrinsic::getDeclaration(TheModule, Intrinsic::x86_seh_lsda), FI8);
318 }
319 
320 /// Generate a thunk that puts the LSDA of ParentFunc in EAX and then calls
321 /// PersonalityFn, forwarding the parameters passed to PEXCEPTION_ROUTINE:
322 /// typedef _EXCEPTION_DISPOSITION (*PEXCEPTION_ROUTINE)(
323 /// _EXCEPTION_RECORD *, void *, _CONTEXT *, void *);
324 /// We essentially want this code:
325 /// movl $lsda, %eax
326 /// jmpl ___CxxFrameHandler3
327 Function *WinEHStatePass::generateLSDAInEAXThunk(Function *ParentFunc) {
328  LLVMContext &Context = ParentFunc->getContext();
329  Type *Int32Ty = Type::getInt32Ty(Context);
330  Type *Int8PtrType = Type::getInt8PtrTy(Context);
331  Type *ArgTys[5] = {Int8PtrType, Int8PtrType, Int8PtrType, Int8PtrType,
332  Int8PtrType};
333  FunctionType *TrampolineTy =
334  FunctionType::get(Int32Ty, makeArrayRef(&ArgTys[0], 4),
335  /*isVarArg=*/false);
336  FunctionType *TargetFuncTy =
337  FunctionType::get(Int32Ty, makeArrayRef(&ArgTys[0], 5),
338  /*isVarArg=*/false);
339  Function *Trampoline =
341  Twine("__ehhandler$") + GlobalValue::getRealLinkageName(
342  ParentFunc->getName()),
343  TheModule);
344  BasicBlock *EntryBB = BasicBlock::Create(Context, "entry", Trampoline);
345  IRBuilder<> Builder(EntryBB);
346  Value *LSDA = emitEHLSDA(Builder, ParentFunc);
347  Value *CastPersonality =
348  Builder.CreateBitCast(PersonalityFn, TargetFuncTy->getPointerTo());
349  auto AI = Trampoline->arg_begin();
350  Value *Args[5] = {LSDA, AI++, AI++, AI++, AI++};
351  CallInst *Call = Builder.CreateCall(CastPersonality, Args);
352  // Can't use musttail due to prototype mismatch, but we can use tail.
353  Call->setTailCall(true);
354  // Set inreg so we pass it in EAX.
355  Call->addAttribute(1, Attribute::InReg);
356  Builder.CreateRet(Call);
357  return Trampoline;
358 }
359 
360 void WinEHStatePass::linkExceptionRegistration(IRBuilder<> &Builder,
361  Function *Handler) {
362  // Emit the .safeseh directive for this function.
363  Handler->addFnAttr("safeseh");
364 
365  Type *LinkTy = getEHLinkRegistrationType();
366  // Handler = Handler
367  Value *HandlerI8 = Builder.CreateBitCast(Handler, Builder.getInt8PtrTy());
368  Builder.CreateStore(HandlerI8, Builder.CreateStructGEP(LinkTy, Link, 1));
369  // Next = [fs:00]
370  Constant *FSZero =
372  Value *Next = Builder.CreateLoad(FSZero);
373  Builder.CreateStore(Next, Builder.CreateStructGEP(LinkTy, Link, 0));
374  // [fs:00] = Link
375  Builder.CreateStore(Link, FSZero);
376 }
377 
378 void WinEHStatePass::unlinkExceptionRegistration(IRBuilder<> &Builder) {
379  // Clone Link into the current BB for better address mode folding.
380  if (auto *GEP = dyn_cast<GetElementPtrInst>(Link)) {
381  GEP = cast<GetElementPtrInst>(GEP->clone());
382  Builder.Insert(GEP);
383  Link = GEP;
384  }
385  Type *LinkTy = getEHLinkRegistrationType();
386  // [fs:00] = Link->Next
387  Value *Next =
388  Builder.CreateLoad(Builder.CreateStructGEP(LinkTy, Link, 0));
389  Constant *FSZero =
391  Builder.CreateStore(Next, FSZero);
392 }
393 
394 void WinEHStatePass::addCXXStateStores(Function &F, MachineModuleInfo &MMI) {
395  WinEHFuncInfo &FuncInfo = MMI.getWinEHFuncInfo(&F);
396  calculateWinCXXEHStateNumbers(&F, FuncInfo);
397 
398  // The base state for the parent is -1.
399  addCXXStateStoresToFunclet(RegNode, FuncInfo, F, -1);
400 
401  // Set up RegNodeEscapeIndex
402  int RegNodeEscapeIndex = escapeRegNode(F);
403  FuncInfo.EHRegNodeEscapeIndex = RegNodeEscapeIndex;
404 
405  // Only insert stores in catch handlers.
406  Constant *FI8 =
407  ConstantExpr::getBitCast(&F, Type::getInt8PtrTy(TheModule->getContext()));
408  for (auto P : FuncInfo.HandlerBaseState) {
409  Function *Handler = const_cast<Function *>(P.first);
410  int BaseState = P.second;
411  IRBuilder<> Builder(&Handler->getEntryBlock(),
412  Handler->getEntryBlock().begin());
413  // FIXME: Find and reuse such a call if present.
414  Value *ParentFP = Builder.CreateCall(FrameAddress, {Builder.getInt32(1)});
415  Value *RecoveredRegNode = Builder.CreateCall(
416  FrameRecover, {FI8, ParentFP, Builder.getInt32(RegNodeEscapeIndex)});
417  RecoveredRegNode =
418  Builder.CreateBitCast(RecoveredRegNode, RegNodeTy->getPointerTo(0));
419  addCXXStateStoresToFunclet(RecoveredRegNode, FuncInfo, *Handler, BaseState);
420  }
421 }
422 
423 /// Escape RegNode so that we can access it from child handlers. Find the call
424 /// to localescape, if any, in the entry block and append RegNode to the list
425 /// of arguments.
426 int WinEHStatePass::escapeRegNode(Function &F) {
427  // Find the call to localescape and extract its arguments.
428  IntrinsicInst *EscapeCall = nullptr;
429  for (Instruction &I : F.getEntryBlock()) {
431  if (II && II->getIntrinsicID() == Intrinsic::localescape) {
432  EscapeCall = II;
433  break;
434  }
435  }
437  if (EscapeCall) {
438  auto Ops = EscapeCall->arg_operands();
439  Args.append(Ops.begin(), Ops.end());
440  }
441  Args.push_back(RegNode);
442 
443  // Replace the call (if it exists) with new one. Otherwise, insert at the end
444  // of the entry block.
445  Instruction *InsertPt = EscapeCall;
446  if (!EscapeCall)
447  InsertPt = F.getEntryBlock().getTerminator();
448  IRBuilder<> Builder(&F.getEntryBlock(), InsertPt);
449  Builder.CreateCall(FrameEscape, Args);
450  if (EscapeCall)
451  EscapeCall->eraseFromParent();
452  return Args.size() - 1;
453 }
454 
455 void WinEHStatePass::addCXXStateStoresToFunclet(Value *ParentRegNode,
456  WinEHFuncInfo &FuncInfo,
457  Function &F, int BaseState) {
458  // Iterate all the instructions and emit state number stores.
459  for (BasicBlock &BB : F) {
460  for (Instruction &I : BB) {
461  if (auto *CI = dyn_cast<CallInst>(&I)) {
462  // Possibly throwing call instructions have no actions to take after
463  // an unwind. Ensure they are in the -1 state.
464  if (CI->doesNotThrow())
465  continue;
466  insertStateNumberStore(ParentRegNode, CI, BaseState);
467  } else if (auto *II = dyn_cast<InvokeInst>(&I)) {
468  // Look up the state number of the landingpad this unwinds to.
469  LandingPadInst *LPI = II->getUnwindDest()->getLandingPadInst();
470  // FIXME: Why does this assertion fail?
471  //assert(FuncInfo.LandingPadStateMap.count(LPI) && "LP has no state!");
472  int State = FuncInfo.LandingPadStateMap[LPI];
473  insertStateNumberStore(ParentRegNode, II, State);
474  }
475  }
476  }
477 }
478 
479 /// Assign every distinct landingpad a unique state number for SEH. Unlike C++
480 /// EH, we can use this very simple algorithm while C++ EH cannot because catch
481 /// handlers aren't outlined and the runtime doesn't have to figure out which
482 /// catch handler frame to unwind to.
483 /// FIXME: __finally blocks are outlined, so this approach may break down there.
484 void WinEHStatePass::addSEHStateStores(Function &F, MachineModuleInfo &MMI) {
485  WinEHFuncInfo &FuncInfo = MMI.getWinEHFuncInfo(&F);
486 
487  // Remember and return the index that we used. We save it in WinEHFuncInfo so
488  // that we can lower llvm.x86.seh.recoverfp later in filter functions without
489  // too much trouble.
490  int RegNodeEscapeIndex = escapeRegNode(F);
491  FuncInfo.EHRegNodeEscapeIndex = RegNodeEscapeIndex;
492 
493  // Iterate all the instructions and emit state number stores.
494  int CurState = 0;
495  SmallPtrSet<BasicBlock *, 4> ExceptBlocks;
496  for (BasicBlock &BB : F) {
497  for (auto I = BB.begin(), E = BB.end(); I != E; ++I) {
498  if (auto *CI = dyn_cast<CallInst>(I)) {
499  auto *Intrin = dyn_cast<IntrinsicInst>(CI);
500  if (Intrin) {
501  // Calls that "don't throw" are considered to be able to throw asynch
502  // exceptions, but intrinsics cannot.
503  continue;
504  }
505  insertStateNumberStore(RegNode, CI, -1);
506  } else if (auto *II = dyn_cast<InvokeInst>(I)) {
507  // Look up the state number of the landingpad this unwinds to.
508  LandingPadInst *LPI = II->getUnwindDest()->getLandingPadInst();
509  auto InsertionPair =
510  FuncInfo.LandingPadStateMap.insert(std::make_pair(LPI, CurState));
511  auto Iter = InsertionPair.first;
512  int &State = Iter->second;
513  bool Inserted = InsertionPair.second;
514  if (Inserted) {
515  // Each action consumes a state number.
516  auto *EHActions = cast<IntrinsicInst>(LPI->getNextNode());
518  parseEHActions(EHActions, ActionList);
519  assert(!ActionList.empty());
520  CurState += ActionList.size();
521  State += ActionList.size() - 1;
522 
523  // Remember all the __except block targets.
524  for (auto &Handler : ActionList) {
525  if (auto *CH = dyn_cast<CatchHandler>(Handler.get())) {
526  auto *BA = cast<BlockAddress>(CH->getHandlerBlockOrFunc());
527 #ifndef NDEBUG
528  for (BasicBlock *Pred : predecessors(BA->getBasicBlock()))
529  assert(Pred->isLandingPad() &&
530  "WinEHPrepare failed to split block");
531 #endif
532  ExceptBlocks.insert(BA->getBasicBlock());
533  }
534  }
535  }
536  insertStateNumberStore(RegNode, II, State);
537  }
538  }
539  }
540 
541  // Insert llvm.x86.seh.restoreframe() into each __except block.
542  Function *RestoreFrame =
543  Intrinsic::getDeclaration(TheModule, Intrinsic::x86_seh_restoreframe);
544  for (BasicBlock *ExceptBB : ExceptBlocks) {
545  IRBuilder<> Builder(ExceptBB->begin());
546  Builder.CreateCall(RestoreFrame, {});
547  }
548 }
549 
550 void WinEHStatePass::insertStateNumberStore(Value *ParentRegNode,
551  Instruction *IP, int State) {
552  IRBuilder<> Builder(IP);
553  Value *StateField =
554  Builder.CreateStructGEP(RegNodeTy, ParentRegNode, StateFieldIndex);
555  Builder.CreateStore(Builder.getInt32(State), StateField);
556 }
iplist< Instruction >::iterator eraseFromParent()
eraseFromParent - This method unlinks 'this' from the containing basic block and deletes it...
Definition: Instruction.cpp:70
LoadInst * CreateLoad(Value *Ptr, const char *Name)
Definition: IRBuilder.h:973
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function. ...
Definition: Function.cpp:223
Force argument to be passed in register.
Definition: Attributes.h:78
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:114
WinEHFuncInfo & getWinEHFuncInfo(const Function *F)
Intrinsic::ID getIntrinsicID() const
getIntrinsicID - Return the intrinsic ID of this intrinsic.
Definition: IntrinsicInst.h:44
CallInst - This class represents a function call, abstracting a target machine's calling convention...
Attribute getFnAttribute(Attribute::AttrKind Kind) const
Return the attribute for the given attribute kind.
Definition: Function.h:225
F(f)
Hexagon Common GEP
InstTy * Insert(InstTy *I, const Twine &Name="") const
Insert and return the specified instruction.
Definition: IRBuilder.h:565
static Constant * getNullValue(Type *Ty)
Definition: Constants.cpp:178
StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:188
iterator begin()
Instruction iterator methods.
Definition: BasicBlock.h:231
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:79
NodeTy * getNextNode()
Get the next node, or 0 for the list tail.
Definition: ilist_node.h:80
ArrayRef< T > makeArrayRef(const T &OneElt)
Construct an ArrayRef from a single element.
Definition: ArrayRef.h:308
StructType - Class to represent struct types.
Definition: DerivedTypes.h:191
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Definition: ErrorHandling.h:98
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition: IRBuilder.h:517
void addFnAttr(Attribute::AttrKind N)
Add function attributes to this function.
Definition: Function.h:187
int EHRegNodeEscapeIndex
localescape index of the 32-bit EH registration node.
FunctionType - Class to represent function types.
Definition: DerivedTypes.h:96
static FunctionType * get(Type *Result, ArrayRef< Type * > Params, bool isVarArg)
FunctionType::get - This static method is the primary way of constructing a FunctionType.
Definition: Type.cpp:361
Function * getDeclaration(Module *M, ID id, ArrayRef< Type * > Tys=None)
Create or insert an LLVM Function declaration for an intrinsic, and return it.
Definition: Function.cpp:866
StoreInst * CreateStore(Value *Val, Value *Ptr, bool isVolatile=false)
Definition: IRBuilder.h:985
void addAttribute(unsigned i, Attribute::AttrKind attr)
addAttribute - adds the attribute to the list of attributes.
static Constant * getBitCast(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Definition: Constants.cpp:1835
DenseMap< const LandingPadInst *, int > LandingPadStateMap
#define P(N)
LandingPadInst - The landingpad instruction holds all of the information necessary to generate correc...
Subclasses of this class are all able to terminate a basic block.
Definition: InstrTypes.h:35
Constant * stripPointerCasts()
Definition: Constant.h:170
LLVM Basic Block Representation.
Definition: BasicBlock.h:65
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:45
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:41
This is an important base class in LLVM.
Definition: Constant.h:41
ReturnInst * CreateRet(Value *V)
Create a 'ret <val>' instruction.
Definition: IRBuilder.h:597
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Definition: SmallPtrSet.h:264
bool hasPersonalityFn() const
Get the personality function associated with this function.
Definition: Function.h:132
EHPersonality classifyEHPersonality(const Value *Pers)
See if the given exception handling personality function is one that we understand.
Represent the analysis usage information of a pass.
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:294
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition: BasicBlock.h:103
arg_iterator arg_begin()
Definition: Function.h:472
void append(in_iter in_start, in_iter in_end)
Add the specified range to the end of the SmallVector.
Definition: SmallVector.h:416
void setTailCall(bool isTC=true)
CallInst * CreateCall(Value *Callee, ArrayRef< Value * > Args=None, const Twine &Name="")
Definition: IRBuilder.h:1467
PointerType * getPointerTo(unsigned AddrSpace=0)
getPointerTo - Return a pointer to the current type.
Definition: Type.cpp:764
PointerType * getInt8PtrTy(unsigned AddrSpace=0)
Fetch the type representing a pointer to an 8-bit integer value.
Definition: IRBuilder.h:346
static PointerType * getInt8PtrTy(LLVMContext &C, unsigned AS=0)
Definition: Type.cpp:283
void calculateWinCXXEHStateNumbers(const Function *ParentFn, WinEHFuncInfo &FuncInfo)
Analyze the IR in ParentFn and it's handlers to build WinEHFuncInfo, which describes the state number...
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
Definition: SmallPtrSet.h:299
Value * CreateBitCast(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:1253
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:861
Module.h This file contains the declarations for the Module class.
ConstantInt * getInt32(uint32_t C)
Get a constant 32-bit value.
Definition: IRBuilder.h:266
pred_range predecessors(BasicBlock *BB)
Definition: IR/CFG.h:102
void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition: Pass.cpp:263
const BasicBlock & getEntryBlock() const
Definition: Function.h:442
Value * CreateStructGEP(Type *Ty, Value *Ptr, unsigned Idx, const Twine &Name="")
Definition: IRBuilder.h:1170
LLVM_ATTRIBUTE_UNUSED_RESULT std::enable_if< !is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:285
static StringRef getRealLinkageName(StringRef Name)
If special LLVM prefix that is used to inform the asm printer to not emit usual symbol prefix before ...
Definition: GlobalValue.h:306
static IntegerType * getInt32Ty(LLVMContext &C)
Definition: Type.cpp:239
Constant * getPersonalityFn() const
Definition: Function.h:133
#define I(x, y, z)
Definition: MD5.cpp:54
TerminatorInst * getTerminator()
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Definition: BasicBlock.cpp:124
Rename collisions when linking (static functions).
Definition: GlobalValue.h:47
iterator_range< op_iterator > arg_operands()
arg_operands - iteration adapter for range-for loops.
StringRef getValueAsString() const
Return the attribute's value as a string.
Definition: Attributes.cpp:140
LLVM Value Representation.
Definition: Value.h:69
static StructType * create(LLVMContext &Context, StringRef Name)
StructType::create - This creates an identified struct.
Definition: Type.cpp:490
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:40
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, const Twine &N="", Module *M=nullptr)
Definition: Function.h:121
FunctionPass * createX86WinEHStatePass()
createX86WinEHStatePass - Return an IR pass that inserts EH registration stack objects and explicit E...
DenseMap< const Function *, int > HandlerBaseState
bool isMSVCEHPersonality(EHPersonality Pers)
Returns true if this is an MSVC personality function.
IntrinsicInst - A useful wrapper class for inspecting calls to intrinsic functions.
Definition: IntrinsicInst.h:37
void parseEHActions(const IntrinsicInst *II, SmallVectorImpl< std::unique_ptr< ActionHandler >> &Actions)
MachineModuleInfo - This class contains meta information specific to a module.
AllocaInst - an instruction to allocate memory on the stack.
Definition: Instructions.h:76
bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:110