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"
42 class WinEHStatePass : public FunctionPass {
44 static char ID; // Pass identification, replacement for typeid.
46 WinEHStatePass() : FunctionPass(ID) {}
48 bool runOnFunction(Function &Fn) override;
50 bool doInitialization(Module &M) override;
52 bool doFinalization(Module &M) override;
54 void getAnalysisUsage(AnalysisUsage &AU) const override;
56 const char *getPassName() const override {
57 return "Windows 32-bit x86 EH state insertion";
61 void emitExceptionRegistrationRecord(Function *F);
63 void linkExceptionRegistration(IRBuilder<> &Builder, Value *Handler);
64 void unlinkExceptionRegistration(IRBuilder<> &Builder);
65 void addCXXStateStores(Function &F, MachineModuleInfo &MMI);
66 void addCXXStateStoresToFunclet(Value *ParentRegNode, WinEHFuncInfo &FuncInfo,
67 Function &F, int BaseState);
68 void insertStateNumberStore(Value *ParentRegNode, Instruction *IP, int State);
70 Value *emitEHLSDA(IRBuilder<> &Builder, Function *F);
72 Function *generateLSDAInEAXThunk(Function *ParentFunc);
74 int escapeRegNode(Function &F);
76 // Module-level type getters.
77 Type *getEHLinkRegistrationType();
78 Type *getSEHRegistrationType();
79 Type *getCXXEHRegistrationType();
82 Module *TheModule = nullptr;
83 StructType *EHLinkRegistrationTy = nullptr;
84 StructType *CXXEHRegistrationTy = nullptr;
85 StructType *SEHRegistrationTy = nullptr;
88 EHPersonality Personality = EHPersonality::Unknown;
89 Function *PersonalityFn = nullptr;
91 /// The stack allocation containing all EH data, including the link in the
92 /// fs:00 chain and the current state.
93 AllocaInst *RegNode = nullptr;
95 /// Struct type of RegNode. Used for GEPing.
96 Type *RegNodeTy = nullptr;
98 /// The index of the state field of RegNode.
99 int StateFieldIndex = ~0U;
101 /// The linked list node subobject inside of RegNode.
102 Value *Link = nullptr;
106 FunctionPass *llvm::createX86WinEHStatePass() { return new WinEHStatePass(); }
108 char WinEHStatePass::ID = 0;
110 bool WinEHStatePass::doInitialization(Module &M) {
115 bool WinEHStatePass::doFinalization(Module &M) {
116 assert(TheModule == &M);
118 EHLinkRegistrationTy = nullptr;
119 CXXEHRegistrationTy = nullptr;
120 SEHRegistrationTy = nullptr;
124 void WinEHStatePass::getAnalysisUsage(AnalysisUsage &AU) const {
125 // This pass should only insert a stack allocation, memory accesses, and
127 AU.setPreservesCFG();
130 bool WinEHStatePass::runOnFunction(Function &F) {
131 // If this is an outlined handler, don't do anything. We'll do state insertion
132 // for it in the parent.
133 StringRef WinEHParentName =
134 F.getFnAttribute("wineh-parent").getValueAsString();
135 if (WinEHParentName != F.getName() && !WinEHParentName.empty())
138 // Check the personality. Do nothing if this is not an MSVC personality.
139 LandingPadInst *LP = nullptr;
140 for (BasicBlock &BB : F) {
141 LP = BB.getLandingPadInst();
148 dyn_cast<Function>(LP->getPersonalityFn()->stripPointerCasts());
151 Personality = classifyEHPersonality(PersonalityFn);
152 if (!isMSVCEHPersonality(Personality))
155 // Disable frame pointer elimination in this function.
156 // FIXME: Do the nested handlers need to keep the parent ebp in ebp, or can we
157 // use an arbitrary register?
158 F.addFnAttr("no-frame-pointer-elim", "true");
160 emitExceptionRegistrationRecord(&F);
162 auto *MMIPtr = getAnalysisIfAvailable<MachineModuleInfo>();
163 assert(MMIPtr && "MachineModuleInfo should always be available");
164 MachineModuleInfo &MMI = *MMIPtr;
165 if (Personality == EHPersonality::MSVC_CXX) {
166 addCXXStateStores(F, MMI);
169 // Reset per-function state.
170 PersonalityFn = nullptr;
171 Personality = EHPersonality::Unknown;
175 /// Get the common EH registration subobject:
176 /// typedef _EXCEPTION_DISPOSITION (*PEXCEPTION_ROUTINE)(
177 /// _EXCEPTION_RECORD *, void *, _CONTEXT *, void *);
178 /// struct EHRegistrationNode {
179 /// EHRegistrationNode *Next;
180 /// PEXCEPTION_ROUTINE Handler;
182 Type *WinEHStatePass::getEHLinkRegistrationType() {
183 if (EHLinkRegistrationTy)
184 return EHLinkRegistrationTy;
185 LLVMContext &Context = TheModule->getContext();
186 EHLinkRegistrationTy = StructType::create(Context, "EHRegistrationNode");
188 EHLinkRegistrationTy->getPointerTo(0), // EHRegistrationNode *Next
189 Type::getInt8PtrTy(Context) // EXCEPTION_DISPOSITION (*Handler)(...)
191 EHLinkRegistrationTy->setBody(FieldTys, false);
192 return EHLinkRegistrationTy;
195 /// The __CxxFrameHandler3 registration node:
196 /// struct CXXExceptionRegistration {
198 /// EHRegistrationNode SubRecord;
199 /// int32_t TryLevel;
201 Type *WinEHStatePass::getCXXEHRegistrationType() {
202 if (CXXEHRegistrationTy)
203 return CXXEHRegistrationTy;
204 LLVMContext &Context = TheModule->getContext();
206 Type::getInt8PtrTy(Context), // void *SavedESP
207 getEHLinkRegistrationType(), // EHRegistrationNode SubRecord
208 Type::getInt32Ty(Context) // int32_t TryLevel
210 CXXEHRegistrationTy =
211 StructType::create(FieldTys, "CXXExceptionRegistration");
212 return CXXEHRegistrationTy;
215 /// The _except_handler3/4 registration node:
216 /// struct EH4ExceptionRegistration {
218 /// _EXCEPTION_POINTERS *ExceptionPointers;
219 /// EHRegistrationNode SubRecord;
220 /// int32_t EncodedScopeTable;
221 /// int32_t TryLevel;
223 Type *WinEHStatePass::getSEHRegistrationType() {
224 if (SEHRegistrationTy)
225 return SEHRegistrationTy;
226 LLVMContext &Context = TheModule->getContext();
228 Type::getInt8PtrTy(Context), // void *SavedESP
229 Type::getInt8PtrTy(Context), // void *ExceptionPointers
230 getEHLinkRegistrationType(), // EHRegistrationNode SubRecord
231 Type::getInt32Ty(Context), // int32_t EncodedScopeTable
232 Type::getInt32Ty(Context) // int32_t TryLevel
234 SEHRegistrationTy = StructType::create(FieldTys, "SEHExceptionRegistration");
235 return SEHRegistrationTy;
238 // Emit an exception registration record. These are stack allocations with the
239 // common subobject of two pointers: the previous registration record (the old
240 // fs:00) and the personality function for the current frame. The data before
241 // and after that is personality function specific.
242 void WinEHStatePass::emitExceptionRegistrationRecord(Function *F) {
243 assert(Personality == EHPersonality::MSVC_CXX ||
244 Personality == EHPersonality::MSVC_X86SEH);
246 StringRef PersonalityName = PersonalityFn->getName();
247 IRBuilder<> Builder(&F->getEntryBlock(), F->getEntryBlock().begin());
248 Type *Int8PtrType = Builder.getInt8PtrTy();
249 if (Personality == EHPersonality::MSVC_CXX) {
250 RegNodeTy = getCXXEHRegistrationType();
251 RegNode = Builder.CreateAlloca(RegNodeTy);
252 // FIXME: We can skip this in -GS- mode, when we figure that out.
253 // SavedESP = llvm.stacksave()
254 Value *SP = Builder.CreateCall(
255 Intrinsic::getDeclaration(TheModule, Intrinsic::stacksave), {});
256 Builder.CreateStore(SP, Builder.CreateStructGEP(RegNodeTy, RegNode, 0));
259 insertStateNumberStore(RegNode, Builder.GetInsertPoint(), -1);
260 // Handler = __ehhandler$F
261 Function *Trampoline = generateLSDAInEAXThunk(F);
262 Link = Builder.CreateStructGEP(RegNodeTy, RegNode, 1);
263 linkExceptionRegistration(Builder, Trampoline);
264 } else if (Personality == EHPersonality::MSVC_X86SEH) {
265 // If _except_handler4 is in use, some additional guard checks and prologue
266 // stuff is required.
267 bool UseStackGuard = (PersonalityName == "_except_handler4");
268 RegNodeTy = getSEHRegistrationType();
269 RegNode = Builder.CreateAlloca(RegNodeTy);
270 // SavedESP = llvm.stacksave()
271 Value *SP = Builder.CreateCall(
272 Intrinsic::getDeclaration(TheModule, Intrinsic::stacksave), {});
273 Builder.CreateStore(SP, Builder.CreateStructGEP(RegNodeTy, RegNode, 0));
274 // TryLevel = -2 / -1
276 insertStateNumberStore(RegNode, Builder.GetInsertPoint(),
277 UseStackGuard ? -2 : -1);
278 // ScopeTable = llvm.x86.seh.lsda(F)
279 Value *FI8 = Builder.CreateBitCast(F, Int8PtrType);
280 Value *LSDA = Builder.CreateCall(
281 Intrinsic::getDeclaration(TheModule, Intrinsic::x86_seh_lsda), FI8);
282 Type *Int32Ty = Type::getInt32Ty(TheModule->getContext());
283 LSDA = Builder.CreatePtrToInt(LSDA, Int32Ty);
284 // If using _except_handler4, xor the address of the table with
285 // __security_cookie.
288 TheModule->getOrInsertGlobal("__security_cookie", Int32Ty);
289 Value *Val = Builder.CreateLoad(Int32Ty, Cookie);
290 LSDA = Builder.CreateXor(LSDA, Val);
292 Builder.CreateStore(LSDA, Builder.CreateStructGEP(RegNodeTy, RegNode, 3));
293 Link = Builder.CreateStructGEP(RegNodeTy, RegNode, 2);
294 linkExceptionRegistration(Builder, PersonalityFn);
296 llvm_unreachable("unexpected personality function");
299 // Insert an unlink before all returns.
300 for (BasicBlock &BB : *F) {
301 TerminatorInst *T = BB.getTerminator();
302 if (!isa<ReturnInst>(T))
304 Builder.SetInsertPoint(T);
305 unlinkExceptionRegistration(Builder);
309 Value *WinEHStatePass::emitEHLSDA(IRBuilder<> &Builder, Function *F) {
310 Value *FI8 = Builder.CreateBitCast(F, Type::getInt8PtrTy(F->getContext()));
311 return Builder.CreateCall(
312 Intrinsic::getDeclaration(TheModule, Intrinsic::x86_seh_lsda), FI8);
315 /// Generate a thunk that puts the LSDA of ParentFunc in EAX and then calls
316 /// PersonalityFn, forwarding the parameters passed to PEXCEPTION_ROUTINE:
317 /// typedef _EXCEPTION_DISPOSITION (*PEXCEPTION_ROUTINE)(
318 /// _EXCEPTION_RECORD *, void *, _CONTEXT *, void *);
319 /// We essentially want this code:
321 /// jmpl ___CxxFrameHandler3
322 Function *WinEHStatePass::generateLSDAInEAXThunk(Function *ParentFunc) {
323 LLVMContext &Context = ParentFunc->getContext();
324 Type *Int32Ty = Type::getInt32Ty(Context);
325 Type *Int8PtrType = Type::getInt8PtrTy(Context);
326 Type *ArgTys[5] = {Int8PtrType, Int8PtrType, Int8PtrType, Int8PtrType,
328 FunctionType *TrampolineTy =
329 FunctionType::get(Int32Ty, makeArrayRef(&ArgTys[0], 4),
331 FunctionType *TargetFuncTy =
332 FunctionType::get(Int32Ty, makeArrayRef(&ArgTys[0], 5),
334 Function *Trampoline = Function::Create(
335 TrampolineTy, GlobalValue::InternalLinkage,
336 Twine("__ehhandler$") + ParentFunc->getName(), TheModule);
337 BasicBlock *EntryBB = BasicBlock::Create(Context, "entry", Trampoline);
338 IRBuilder<> Builder(EntryBB);
339 Value *LSDA = emitEHLSDA(Builder, ParentFunc);
340 Value *CastPersonality =
341 Builder.CreateBitCast(PersonalityFn, TargetFuncTy->getPointerTo());
342 auto AI = Trampoline->arg_begin();
343 Value *Args[5] = {LSDA, AI++, AI++, AI++, AI++};
344 CallInst *Call = Builder.CreateCall(CastPersonality, Args);
345 // Can't use musttail due to prototype mismatch, but we can use tail.
346 Call->setTailCall(true);
347 // Set inreg so we pass it in EAX.
348 Call->addAttribute(1, Attribute::InReg);
349 Builder.CreateRet(Call);
353 void WinEHStatePass::linkExceptionRegistration(IRBuilder<> &Builder,
355 Type *LinkTy = getEHLinkRegistrationType();
357 Handler = Builder.CreateBitCast(Handler, Builder.getInt8PtrTy());
358 Builder.CreateStore(Handler, Builder.CreateStructGEP(LinkTy, Link, 1));
361 Constant::getNullValue(LinkTy->getPointerTo()->getPointerTo(257));
362 Value *Next = Builder.CreateLoad(FSZero);
363 Builder.CreateStore(Next, Builder.CreateStructGEP(LinkTy, Link, 0));
365 Builder.CreateStore(Link, FSZero);
368 void WinEHStatePass::unlinkExceptionRegistration(IRBuilder<> &Builder) {
369 // Clone Link into the current BB for better address mode folding.
370 if (auto *GEP = dyn_cast<GetElementPtrInst>(Link)) {
371 GEP = cast<GetElementPtrInst>(GEP->clone());
375 Type *LinkTy = getEHLinkRegistrationType();
376 // [fs:00] = Link->Next
378 Builder.CreateLoad(Builder.CreateStructGEP(LinkTy, Link, 0));
380 Constant::getNullValue(LinkTy->getPointerTo()->getPointerTo(257));
381 Builder.CreateStore(Next, FSZero);
384 void WinEHStatePass::addCXXStateStores(Function &F, MachineModuleInfo &MMI) {
385 WinEHFuncInfo &FuncInfo = MMI.getWinEHFuncInfo(&F);
386 calculateWinCXXEHStateNumbers(&F, FuncInfo);
388 // The base state for the parent is -1.
389 addCXXStateStoresToFunclet(RegNode, FuncInfo, F, -1);
391 // Set up RegNodeEscapeIndex
392 int RegNodeEscapeIndex = escapeRegNode(F);
394 // Only insert stores in catch handlers.
395 Function *FrameRecover =
396 Intrinsic::getDeclaration(TheModule, Intrinsic::framerecover);
397 Function *FrameAddress =
398 Intrinsic::getDeclaration(TheModule, Intrinsic::frameaddress);
400 ConstantExpr::getBitCast(&F, Type::getInt8PtrTy(TheModule->getContext()));
401 for (auto P : FuncInfo.HandlerBaseState) {
402 Function *Handler = const_cast<Function *>(P.first);
403 int BaseState = P.second;
404 IRBuilder<> Builder(&Handler->getEntryBlock(),
405 Handler->getEntryBlock().begin());
406 // FIXME: Find and reuse such a call if present.
407 Value *ParentFP = Builder.CreateCall(FrameAddress, {Builder.getInt32(1)});
408 Value *RecoveredRegNode = Builder.CreateCall(
409 FrameRecover, {FI8, ParentFP, Builder.getInt32(RegNodeEscapeIndex)});
411 Builder.CreateBitCast(RecoveredRegNode, RegNodeTy->getPointerTo(0));
412 addCXXStateStoresToFunclet(RecoveredRegNode, FuncInfo, *Handler, BaseState);
416 /// Escape RegNode so that we can access it from child handlers. Find the call
417 /// to frameescape, if any, in the entry block and append RegNode to the list
419 int WinEHStatePass::escapeRegNode(Function &F) {
420 // Find the call to frameescape and extract its arguments.
421 IntrinsicInst *EscapeCall = nullptr;
422 for (Instruction &I : F.getEntryBlock()) {
423 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I);
424 if (II && II->getIntrinsicID() == Intrinsic::frameescape) {
429 SmallVector<Value *, 8> Args;
431 auto Ops = EscapeCall->arg_operands();
432 Args.append(Ops.begin(), Ops.end());
434 Args.push_back(RegNode);
436 // Replace the call (if it exists) with new one. Otherwise, insert at the end
437 // of the entry block.
438 IRBuilder<> Builder(&F.getEntryBlock(),
439 EscapeCall ? EscapeCall : F.getEntryBlock().end());
441 Intrinsic::getDeclaration(TheModule, Intrinsic::frameescape), Args);
443 EscapeCall->eraseFromParent();
444 return Args.size() - 1;
447 void WinEHStatePass::addCXXStateStoresToFunclet(Value *ParentRegNode,
448 WinEHFuncInfo &FuncInfo,
449 Function &F, int BaseState) {
450 // Iterate all the instructions and emit state number stores.
451 for (BasicBlock &BB : F) {
452 for (Instruction &I : BB) {
453 if (auto *CI = dyn_cast<CallInst>(&I)) {
454 // Possibly throwing call instructions have no actions to take after
455 // an unwind. Ensure they are in the -1 state.
456 if (CI->doesNotThrow())
458 insertStateNumberStore(ParentRegNode, CI, BaseState);
459 } else if (auto *II = dyn_cast<InvokeInst>(&I)) {
460 // Look up the state number of the landingpad this unwinds to.
461 LandingPadInst *LPI = II->getUnwindDest()->getLandingPadInst();
462 // FIXME: Why does this assertion fail?
463 //assert(FuncInfo.LandingPadStateMap.count(LPI) && "LP has no state!");
464 int State = FuncInfo.LandingPadStateMap[LPI];
465 insertStateNumberStore(ParentRegNode, II, State);
471 void WinEHStatePass::insertStateNumberStore(Value *ParentRegNode,
472 Instruction *IP, int State) {
473 IRBuilder<> Builder(IP);
475 Builder.CreateStructGEP(RegNodeTy, ParentRegNode, StateFieldIndex);
476 Builder.CreateStore(Builder.getInt32(State), StateField);