1 //===-- X86WinEHState - Insert EH state updates for win32 exceptions ------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
15 //===----------------------------------------------------------------------===//
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"
37 using namespace llvm::PatternMatch;
39 #define DEBUG_TYPE "winehstate"
41 namespace llvm { void initializeWinEHStatePassPass(PassRegistry &); }
44 class WinEHStatePass : public FunctionPass {
46 static char ID; // Pass identification, replacement for typeid.
48 WinEHStatePass() : FunctionPass(ID) {
49 initializeWinEHStatePassPass(*PassRegistry::getPassRegistry());
52 bool runOnFunction(Function &Fn) override;
54 bool doInitialization(Module &M) override;
56 bool doFinalization(Module &M) override;
58 void getAnalysisUsage(AnalysisUsage &AU) const override;
60 const char *getPassName() const override {
61 return "Windows 32-bit x86 EH state insertion";
65 void emitExceptionRegistrationRecord(Function *F);
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);
76 Value *emitEHLSDA(IRBuilder<> &Builder, Function *F);
78 Function *generateLSDAInEAXThunk(Function *ParentFunc);
80 int escapeRegNode(Function &F);
82 // Module-level type getters.
83 Type *getEHLinkRegistrationType();
84 Type *getSEHRegistrationType();
85 Type *getCXXEHRegistrationType();
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;
98 EHPersonality Personality = EHPersonality::Unknown;
99 Function *PersonalityFn = nullptr;
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;
105 /// Struct type of RegNode. Used for GEPing.
106 Type *RegNodeTy = nullptr;
108 /// The index of the state field of RegNode.
109 int StateFieldIndex = ~0U;
111 /// The linked list node subobject inside of RegNode.
112 Value *Link = nullptr;
116 FunctionPass *llvm::createX86WinEHStatePass() { return new WinEHStatePass(); }
118 char WinEHStatePass::ID = 0;
120 INITIALIZE_PASS(WinEHStatePass, "x86-winehstate",
121 "Insert stores for EH state numbers", false, false)
123 bool WinEHStatePass::doInitialization(Module &M) {
125 FrameEscape = Intrinsic::getDeclaration(TheModule, Intrinsic::localescape);
126 FrameRecover = Intrinsic::getDeclaration(TheModule, Intrinsic::localrecover);
127 FrameAddress = Intrinsic::getDeclaration(TheModule, Intrinsic::frameaddress);
129 Intrinsic::getDeclaration(TheModule, Intrinsic::x86_seh_restoreframe);
133 bool WinEHStatePass::doFinalization(Module &M) {
134 assert(TheModule == &M);
136 EHLinkRegistrationTy = nullptr;
137 CXXEHRegistrationTy = nullptr;
138 SEHRegistrationTy = nullptr;
139 FrameEscape = nullptr;
140 FrameRecover = nullptr;
141 FrameAddress = nullptr;
145 void WinEHStatePass::getAnalysisUsage(AnalysisUsage &AU) const {
146 // This pass should only insert a stack allocation, memory accesses, and
148 AU.setPreservesCFG();
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())
159 // Check the personality. Do nothing if this personality doesn't use funclets.
160 if (!F.hasPersonalityFn())
163 dyn_cast<Function>(F.getPersonalityFn()->stripPointerCasts());
166 Personality = classifyEHPersonality(PersonalityFn);
167 if (!isFuncletEHPersonality(Personality))
170 // Skip this function if there are no EH pads and we aren't using IR-level
172 if (WinEHParentName.empty()) {
173 bool HasPads = false;
174 for (BasicBlock &BB : F) {
184 // Disable frame pointer elimination in this function.
185 // FIXME: Do the nested handlers need to keep the parent ebp in ebp, or can we
186 // use an arbitrary register?
187 F.addFnAttr("no-frame-pointer-elim", "true");
189 emitExceptionRegistrationRecord(&F);
191 auto *MMI = getAnalysisIfAvailable<MachineModuleInfo>();
192 // If MMI is null, create our own WinEHFuncInfo. This only happens in opt
194 std::unique_ptr<WinEHFuncInfo> FuncInfoPtr;
196 FuncInfoPtr.reset(new WinEHFuncInfo());
197 WinEHFuncInfo &FuncInfo =
198 *(MMI ? &MMI->getWinEHFuncInfo(&F) : FuncInfoPtr.get());
200 FuncInfo.EHRegNode = RegNode;
202 switch (Personality) {
203 default: llvm_unreachable("unexpected personality function");
204 case EHPersonality::MSVC_CXX:
205 addCXXStateStores(F, FuncInfo);
207 case EHPersonality::MSVC_X86SEH:
208 addSEHStateStores(F, FuncInfo);
212 // Reset per-function state.
213 PersonalityFn = nullptr;
214 Personality = EHPersonality::Unknown;
218 /// Get the common EH registration subobject:
219 /// typedef _EXCEPTION_DISPOSITION (*PEXCEPTION_ROUTINE)(
220 /// _EXCEPTION_RECORD *, void *, _CONTEXT *, void *);
221 /// struct EHRegistrationNode {
222 /// EHRegistrationNode *Next;
223 /// PEXCEPTION_ROUTINE Handler;
225 Type *WinEHStatePass::getEHLinkRegistrationType() {
226 if (EHLinkRegistrationTy)
227 return EHLinkRegistrationTy;
228 LLVMContext &Context = TheModule->getContext();
229 EHLinkRegistrationTy = StructType::create(Context, "EHRegistrationNode");
231 EHLinkRegistrationTy->getPointerTo(0), // EHRegistrationNode *Next
232 Type::getInt8PtrTy(Context) // EXCEPTION_DISPOSITION (*Handler)(...)
234 EHLinkRegistrationTy->setBody(FieldTys, false);
235 return EHLinkRegistrationTy;
238 /// The __CxxFrameHandler3 registration node:
239 /// struct CXXExceptionRegistration {
241 /// EHRegistrationNode SubRecord;
242 /// int32_t TryLevel;
244 Type *WinEHStatePass::getCXXEHRegistrationType() {
245 if (CXXEHRegistrationTy)
246 return CXXEHRegistrationTy;
247 LLVMContext &Context = TheModule->getContext();
249 Type::getInt8PtrTy(Context), // void *SavedESP
250 getEHLinkRegistrationType(), // EHRegistrationNode SubRecord
251 Type::getInt32Ty(Context) // int32_t TryLevel
253 CXXEHRegistrationTy =
254 StructType::create(FieldTys, "CXXExceptionRegistration");
255 return CXXEHRegistrationTy;
258 /// The _except_handler3/4 registration node:
259 /// struct EH4ExceptionRegistration {
261 /// _EXCEPTION_POINTERS *ExceptionPointers;
262 /// EHRegistrationNode SubRecord;
263 /// int32_t EncodedScopeTable;
264 /// int32_t TryLevel;
266 Type *WinEHStatePass::getSEHRegistrationType() {
267 if (SEHRegistrationTy)
268 return SEHRegistrationTy;
269 LLVMContext &Context = TheModule->getContext();
271 Type::getInt8PtrTy(Context), // void *SavedESP
272 Type::getInt8PtrTy(Context), // void *ExceptionPointers
273 getEHLinkRegistrationType(), // EHRegistrationNode SubRecord
274 Type::getInt32Ty(Context), // int32_t EncodedScopeTable
275 Type::getInt32Ty(Context) // int32_t TryLevel
277 SEHRegistrationTy = StructType::create(FieldTys, "SEHExceptionRegistration");
278 return SEHRegistrationTy;
281 // Emit an exception registration record. These are stack allocations with the
282 // common subobject of two pointers: the previous registration record (the old
283 // fs:00) and the personality function for the current frame. The data before
284 // and after that is personality function specific.
285 void WinEHStatePass::emitExceptionRegistrationRecord(Function *F) {
286 assert(Personality == EHPersonality::MSVC_CXX ||
287 Personality == EHPersonality::MSVC_X86SEH);
289 StringRef PersonalityName = PersonalityFn->getName();
290 IRBuilder<> Builder(&F->getEntryBlock(), F->getEntryBlock().begin());
291 Type *Int8PtrType = Builder.getInt8PtrTy();
292 if (Personality == EHPersonality::MSVC_CXX) {
293 RegNodeTy = getCXXEHRegistrationType();
294 RegNode = Builder.CreateAlloca(RegNodeTy);
295 // SavedESP = llvm.stacksave()
296 Value *SP = Builder.CreateCall(
297 Intrinsic::getDeclaration(TheModule, Intrinsic::stacksave), {});
298 Builder.CreateStore(SP, Builder.CreateStructGEP(RegNodeTy, RegNode, 0));
301 insertStateNumberStore(RegNode, Builder.GetInsertPoint(), -1);
302 // Handler = __ehhandler$F
303 Function *Trampoline = generateLSDAInEAXThunk(F);
304 Link = Builder.CreateStructGEP(RegNodeTy, RegNode, 1);
305 linkExceptionRegistration(Builder, Trampoline);
306 } else if (Personality == EHPersonality::MSVC_X86SEH) {
307 // If _except_handler4 is in use, some additional guard checks and prologue
308 // stuff is required.
309 bool UseStackGuard = (PersonalityName == "_except_handler4");
310 RegNodeTy = getSEHRegistrationType();
311 RegNode = Builder.CreateAlloca(RegNodeTy);
312 // SavedESP = llvm.stacksave()
313 Value *SP = Builder.CreateCall(
314 Intrinsic::getDeclaration(TheModule, Intrinsic::stacksave), {});
315 Builder.CreateStore(SP, Builder.CreateStructGEP(RegNodeTy, RegNode, 0));
316 // TryLevel = -2 / -1
318 insertStateNumberStore(RegNode, Builder.GetInsertPoint(),
319 UseStackGuard ? -2 : -1);
320 // ScopeTable = llvm.x86.seh.lsda(F)
321 Value *FI8 = Builder.CreateBitCast(F, Int8PtrType);
322 Value *LSDA = Builder.CreateCall(
323 Intrinsic::getDeclaration(TheModule, Intrinsic::x86_seh_lsda), FI8);
324 Type *Int32Ty = Type::getInt32Ty(TheModule->getContext());
325 LSDA = Builder.CreatePtrToInt(LSDA, Int32Ty);
326 // If using _except_handler4, xor the address of the table with
327 // __security_cookie.
330 TheModule->getOrInsertGlobal("__security_cookie", Int32Ty);
331 Value *Val = Builder.CreateLoad(Int32Ty, Cookie);
332 LSDA = Builder.CreateXor(LSDA, Val);
334 Builder.CreateStore(LSDA, Builder.CreateStructGEP(RegNodeTy, RegNode, 3));
335 Link = Builder.CreateStructGEP(RegNodeTy, RegNode, 2);
336 linkExceptionRegistration(Builder, PersonalityFn);
338 llvm_unreachable("unexpected personality function");
341 // Insert an unlink before all returns.
342 for (BasicBlock &BB : *F) {
343 TerminatorInst *T = BB.getTerminator();
344 if (!isa<ReturnInst>(T))
346 Builder.SetInsertPoint(T);
347 unlinkExceptionRegistration(Builder);
351 Value *WinEHStatePass::emitEHLSDA(IRBuilder<> &Builder, Function *F) {
352 Value *FI8 = Builder.CreateBitCast(F, Type::getInt8PtrTy(F->getContext()));
353 return Builder.CreateCall(
354 Intrinsic::getDeclaration(TheModule, Intrinsic::x86_seh_lsda), FI8);
357 /// Generate a thunk that puts the LSDA of ParentFunc in EAX and then calls
358 /// PersonalityFn, forwarding the parameters passed to PEXCEPTION_ROUTINE:
359 /// typedef _EXCEPTION_DISPOSITION (*PEXCEPTION_ROUTINE)(
360 /// _EXCEPTION_RECORD *, void *, _CONTEXT *, void *);
361 /// We essentially want this code:
363 /// jmpl ___CxxFrameHandler3
364 Function *WinEHStatePass::generateLSDAInEAXThunk(Function *ParentFunc) {
365 LLVMContext &Context = ParentFunc->getContext();
366 Type *Int32Ty = Type::getInt32Ty(Context);
367 Type *Int8PtrType = Type::getInt8PtrTy(Context);
368 Type *ArgTys[5] = {Int8PtrType, Int8PtrType, Int8PtrType, Int8PtrType,
370 FunctionType *TrampolineTy =
371 FunctionType::get(Int32Ty, makeArrayRef(&ArgTys[0], 4),
373 FunctionType *TargetFuncTy =
374 FunctionType::get(Int32Ty, makeArrayRef(&ArgTys[0], 5),
376 Function *Trampoline =
377 Function::Create(TrampolineTy, GlobalValue::InternalLinkage,
378 Twine("__ehhandler$") + GlobalValue::getRealLinkageName(
379 ParentFunc->getName()),
381 BasicBlock *EntryBB = BasicBlock::Create(Context, "entry", Trampoline);
382 IRBuilder<> Builder(EntryBB);
383 Value *LSDA = emitEHLSDA(Builder, ParentFunc);
384 Value *CastPersonality =
385 Builder.CreateBitCast(PersonalityFn, TargetFuncTy->getPointerTo());
386 auto AI = Trampoline->arg_begin();
387 Value *Args[5] = {LSDA, AI++, AI++, AI++, AI++};
388 CallInst *Call = Builder.CreateCall(CastPersonality, Args);
389 // Can't use musttail due to prototype mismatch, but we can use tail.
390 Call->setTailCall(true);
391 // Set inreg so we pass it in EAX.
392 Call->addAttribute(1, Attribute::InReg);
393 Builder.CreateRet(Call);
397 void WinEHStatePass::linkExceptionRegistration(IRBuilder<> &Builder,
399 // Emit the .safeseh directive for this function.
400 Handler->addFnAttr("safeseh");
402 Type *LinkTy = getEHLinkRegistrationType();
404 Value *HandlerI8 = Builder.CreateBitCast(Handler, Builder.getInt8PtrTy());
405 Builder.CreateStore(HandlerI8, Builder.CreateStructGEP(LinkTy, Link, 1));
408 Constant::getNullValue(LinkTy->getPointerTo()->getPointerTo(257));
409 Value *Next = Builder.CreateLoad(FSZero);
410 Builder.CreateStore(Next, Builder.CreateStructGEP(LinkTy, Link, 0));
412 Builder.CreateStore(Link, FSZero);
415 void WinEHStatePass::unlinkExceptionRegistration(IRBuilder<> &Builder) {
416 // Clone Link into the current BB for better address mode folding.
417 if (auto *GEP = dyn_cast<GetElementPtrInst>(Link)) {
418 GEP = cast<GetElementPtrInst>(GEP->clone());
422 Type *LinkTy = getEHLinkRegistrationType();
423 // [fs:00] = Link->Next
425 Builder.CreateLoad(Builder.CreateStructGEP(LinkTy, Link, 0));
427 Constant::getNullValue(LinkTy->getPointerTo()->getPointerTo(257));
428 Builder.CreateStore(Next, FSZero);
431 void WinEHStatePass::addCXXStateStores(Function &F, WinEHFuncInfo &FuncInfo) {
432 // Set up RegNodeEscapeIndex
433 int RegNodeEscapeIndex = escapeRegNode(F);
434 FuncInfo.EHRegNodeEscapeIndex = RegNodeEscapeIndex;
436 calculateWinCXXEHStateNumbers(&F, FuncInfo);
437 addStateStoresToFunclet(RegNode, FuncInfo, F, -1);
440 /// Assign every distinct landingpad a unique state number for SEH. Unlike C++
441 /// EH, we can use this very simple algorithm while C++ EH cannot because catch
442 /// handlers aren't outlined and the runtime doesn't have to figure out which
443 /// catch handler frame to unwind to.
444 void WinEHStatePass::addSEHStateStores(Function &F, WinEHFuncInfo &FuncInfo) {
445 // Remember and return the index that we used. We save it in WinEHFuncInfo so
446 // that we can lower llvm.x86.seh.recoverfp later in filter functions without
448 int RegNodeEscapeIndex = escapeRegNode(F);
449 FuncInfo.EHRegNodeEscapeIndex = RegNodeEscapeIndex;
451 calculateSEHStateNumbers(&F, FuncInfo);
452 addStateStoresToFunclet(RegNode, FuncInfo, F, -1);
455 /// Escape RegNode so that we can access it from child handlers. Find the call
456 /// to localescape, if any, in the entry block and append RegNode to the list
458 int WinEHStatePass::escapeRegNode(Function &F) {
459 // Find the call to localescape and extract its arguments.
460 IntrinsicInst *EscapeCall = nullptr;
461 for (Instruction &I : F.getEntryBlock()) {
462 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I);
463 if (II && II->getIntrinsicID() == Intrinsic::localescape) {
468 SmallVector<Value *, 8> Args;
470 auto Ops = EscapeCall->arg_operands();
471 Args.append(Ops.begin(), Ops.end());
473 Args.push_back(RegNode);
475 // Replace the call (if it exists) with new one. Otherwise, insert at the end
476 // of the entry block.
477 Instruction *InsertPt = EscapeCall;
479 InsertPt = F.getEntryBlock().getTerminator();
480 IRBuilder<> Builder(&F.getEntryBlock(), InsertPt);
481 Builder.CreateCall(FrameEscape, Args);
483 EscapeCall->eraseFromParent();
484 return Args.size() - 1;
487 void WinEHStatePass::insertRestoreFrame(BasicBlock *BB) {
488 Instruction *Start = BB->getFirstInsertionPt();
489 if (match(Start, m_Intrinsic<Intrinsic::x86_seh_restoreframe>()))
491 IRBuilder<> Builder(Start);
492 Builder.CreateCall(RestoreFrame, {});
495 void WinEHStatePass::addStateStoresToFunclet(Value *ParentRegNode,
496 WinEHFuncInfo &FuncInfo,
497 Function &F, int BaseState) {
498 // Iterate all the instructions and emit state number stores.
499 for (BasicBlock &BB : F) {
500 for (Instruction &I : BB) {
501 if (auto *CI = dyn_cast<CallInst>(&I)) {
502 // Possibly throwing call instructions have no actions to take after
503 // an unwind. Ensure they are in the -1 state.
504 if (CI->doesNotThrow())
506 insertStateNumberStore(ParentRegNode, CI, BaseState);
507 } else if (auto *II = dyn_cast<InvokeInst>(&I)) {
508 // Look up the state number of the landingpad this unwinds to.
509 Instruction *PadInst = II->getUnwindDest()->getFirstNonPHI();
510 // FIXME: Why does this assertion fail?
511 //assert(FuncInfo.EHPadStateMap.count(PadInst) && "EH Pad has no state!");
512 int State = FuncInfo.EHPadStateMap[PadInst];
513 insertStateNumberStore(ParentRegNode, II, State);
519 void WinEHStatePass::insertStateNumberStore(Value *ParentRegNode,
520 Instruction *IP, int State) {
521 IRBuilder<> Builder(IP);
523 Builder.CreateStructGEP(RegNodeTy, ParentRegNode, StateFieldIndex);
524 Builder.CreateStore(Builder.getInt32(State), StateField);