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/EHPersonalities.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 addStateStores(Function &F, WinEHFuncInfo &FuncInfo);
70 void insertStateNumberStore(Value *ParentRegNode, Instruction *IP, int State);
72 Value *emitEHLSDA(IRBuilder<> &Builder, Function *F);
74 Function *generateLSDAInEAXThunk(Function *ParentFunc);
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;
86 Function *FrameRecover = nullptr;
87 Function *FrameAddress = nullptr;
88 Function *FrameEscape = nullptr;
89 Function *RestoreFrame = nullptr;
92 EHPersonality Personality = EHPersonality::Unknown;
93 Function *PersonalityFn = nullptr;
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;
99 /// Struct type of RegNode. Used for GEPing.
100 Type *RegNodeTy = nullptr;
102 /// The index of the state field of RegNode.
103 int StateFieldIndex = ~0U;
105 /// The linked list node subobject inside of RegNode.
106 Value *Link = nullptr;
110 FunctionPass *llvm::createX86WinEHStatePass() { return new WinEHStatePass(); }
112 char WinEHStatePass::ID = 0;
114 INITIALIZE_PASS(WinEHStatePass, "x86-winehstate",
115 "Insert stores for EH state numbers", false, false)
117 bool WinEHStatePass::doInitialization(Module &M) {
119 FrameEscape = Intrinsic::getDeclaration(TheModule, Intrinsic::localescape);
120 FrameRecover = Intrinsic::getDeclaration(TheModule, Intrinsic::localrecover);
121 FrameAddress = Intrinsic::getDeclaration(TheModule, Intrinsic::frameaddress);
123 Intrinsic::getDeclaration(TheModule, Intrinsic::x86_seh_restoreframe);
127 bool WinEHStatePass::doFinalization(Module &M) {
128 assert(TheModule == &M);
130 EHLinkRegistrationTy = nullptr;
131 CXXEHRegistrationTy = nullptr;
132 SEHRegistrationTy = nullptr;
133 FrameEscape = nullptr;
134 FrameRecover = nullptr;
135 FrameAddress = nullptr;
139 void WinEHStatePass::getAnalysisUsage(AnalysisUsage &AU) const {
140 // This pass should only insert a stack allocation, memory accesses, and
142 AU.setPreservesCFG();
145 bool WinEHStatePass::runOnFunction(Function &F) {
146 // Check the personality. Do nothing if this personality doesn't use funclets.
147 if (!F.hasPersonalityFn())
150 dyn_cast<Function>(F.getPersonalityFn()->stripPointerCasts());
153 Personality = classifyEHPersonality(PersonalityFn);
154 if (!isFuncletEHPersonality(Personality))
157 // Skip this function if there are no EH pads and we aren't using IR-level
159 bool HasPads = false;
160 for (BasicBlock &BB : F) {
169 // Disable frame pointer elimination in this function.
170 // FIXME: Do the nested handlers need to keep the parent ebp in ebp, or can we
171 // use an arbitrary register?
172 F.addFnAttr("no-frame-pointer-elim", "true");
174 emitExceptionRegistrationRecord(&F);
176 // The state numbers calculated here in IR must agree with what we calculate
177 // later on for the MachineFunction. In particular, if an IR pass deletes an
178 // unreachable EH pad after this point before machine CFG construction, we
179 // will be in trouble. If this assumption is ever broken, we should turn the
180 // numbers into an immutable analysis pass.
181 WinEHFuncInfo FuncInfo;
182 addStateStores(F, FuncInfo);
184 // Reset per-function state.
185 PersonalityFn = nullptr;
186 Personality = EHPersonality::Unknown;
190 /// Get the common EH registration subobject:
191 /// typedef _EXCEPTION_DISPOSITION (*PEXCEPTION_ROUTINE)(
192 /// _EXCEPTION_RECORD *, void *, _CONTEXT *, void *);
193 /// struct EHRegistrationNode {
194 /// EHRegistrationNode *Next;
195 /// PEXCEPTION_ROUTINE Handler;
197 Type *WinEHStatePass::getEHLinkRegistrationType() {
198 if (EHLinkRegistrationTy)
199 return EHLinkRegistrationTy;
200 LLVMContext &Context = TheModule->getContext();
201 EHLinkRegistrationTy = StructType::create(Context, "EHRegistrationNode");
203 EHLinkRegistrationTy->getPointerTo(0), // EHRegistrationNode *Next
204 Type::getInt8PtrTy(Context) // EXCEPTION_DISPOSITION (*Handler)(...)
206 EHLinkRegistrationTy->setBody(FieldTys, false);
207 return EHLinkRegistrationTy;
210 /// The __CxxFrameHandler3 registration node:
211 /// struct CXXExceptionRegistration {
213 /// EHRegistrationNode SubRecord;
214 /// int32_t TryLevel;
216 Type *WinEHStatePass::getCXXEHRegistrationType() {
217 if (CXXEHRegistrationTy)
218 return CXXEHRegistrationTy;
219 LLVMContext &Context = TheModule->getContext();
221 Type::getInt8PtrTy(Context), // void *SavedESP
222 getEHLinkRegistrationType(), // EHRegistrationNode SubRecord
223 Type::getInt32Ty(Context) // int32_t TryLevel
225 CXXEHRegistrationTy =
226 StructType::create(FieldTys, "CXXExceptionRegistration");
227 return CXXEHRegistrationTy;
230 /// The _except_handler3/4 registration node:
231 /// struct EH4ExceptionRegistration {
233 /// _EXCEPTION_POINTERS *ExceptionPointers;
234 /// EHRegistrationNode SubRecord;
235 /// int32_t EncodedScopeTable;
236 /// int32_t TryLevel;
238 Type *WinEHStatePass::getSEHRegistrationType() {
239 if (SEHRegistrationTy)
240 return SEHRegistrationTy;
241 LLVMContext &Context = TheModule->getContext();
243 Type::getInt8PtrTy(Context), // void *SavedESP
244 Type::getInt8PtrTy(Context), // void *ExceptionPointers
245 getEHLinkRegistrationType(), // EHRegistrationNode SubRecord
246 Type::getInt32Ty(Context), // int32_t EncodedScopeTable
247 Type::getInt32Ty(Context) // int32_t TryLevel
249 SEHRegistrationTy = StructType::create(FieldTys, "SEHExceptionRegistration");
250 return SEHRegistrationTy;
253 // Emit an exception registration record. These are stack allocations with the
254 // common subobject of two pointers: the previous registration record (the old
255 // fs:00) and the personality function for the current frame. The data before
256 // and after that is personality function specific.
257 void WinEHStatePass::emitExceptionRegistrationRecord(Function *F) {
258 assert(Personality == EHPersonality::MSVC_CXX ||
259 Personality == EHPersonality::MSVC_X86SEH);
261 StringRef PersonalityName = PersonalityFn->getName();
262 IRBuilder<> Builder(&F->getEntryBlock(), F->getEntryBlock().begin());
263 Type *Int8PtrType = Builder.getInt8PtrTy();
264 if (Personality == EHPersonality::MSVC_CXX) {
265 RegNodeTy = getCXXEHRegistrationType();
266 RegNode = Builder.CreateAlloca(RegNodeTy);
267 // SavedESP = llvm.stacksave()
268 Value *SP = Builder.CreateCall(
269 Intrinsic::getDeclaration(TheModule, Intrinsic::stacksave), {});
270 Builder.CreateStore(SP, Builder.CreateStructGEP(RegNodeTy, RegNode, 0));
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
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.
302 TheModule->getOrInsertGlobal("__security_cookie", Int32Ty);
303 Value *Val = Builder.CreateLoad(Int32Ty, Cookie);
304 LSDA = Builder.CreateXor(LSDA, Val);
306 Builder.CreateStore(LSDA, Builder.CreateStructGEP(RegNodeTy, RegNode, 3));
307 Link = Builder.CreateStructGEP(RegNodeTy, RegNode, 2);
308 linkExceptionRegistration(Builder, PersonalityFn);
310 llvm_unreachable("unexpected personality function");
313 // Insert an unlink before all returns.
314 for (BasicBlock &BB : *F) {
315 TerminatorInst *T = BB.getTerminator();
316 if (!isa<ReturnInst>(T))
318 Builder.SetInsertPoint(T);
319 unlinkExceptionRegistration(Builder);
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);
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:
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,
342 FunctionType *TrampolineTy =
343 FunctionType::get(Int32Ty, makeArrayRef(&ArgTys[0], 4),
345 FunctionType *TargetFuncTy =
346 FunctionType::get(Int32Ty, makeArrayRef(&ArgTys[0], 5),
348 Function *Trampoline =
349 Function::Create(TrampolineTy, GlobalValue::InternalLinkage,
350 Twine("__ehhandler$") + GlobalValue::getRealLinkageName(
351 ParentFunc->getName()),
353 BasicBlock *EntryBB = BasicBlock::Create(Context, "entry", Trampoline);
354 IRBuilder<> Builder(EntryBB);
355 Value *LSDA = emitEHLSDA(Builder, ParentFunc);
356 Value *CastPersonality =
357 Builder.CreateBitCast(PersonalityFn, TargetFuncTy->getPointerTo());
358 auto AI = Trampoline->arg_begin();
359 Value *Args[5] = {LSDA, &*AI++, &*AI++, &*AI++, &*AI++};
360 CallInst *Call = Builder.CreateCall(CastPersonality, Args);
361 // Can't use musttail due to prototype mismatch, but we can use tail.
362 Call->setTailCall(true);
363 // Set inreg so we pass it in EAX.
364 Call->addAttribute(1, Attribute::InReg);
365 Builder.CreateRet(Call);
369 void WinEHStatePass::linkExceptionRegistration(IRBuilder<> &Builder,
371 // Emit the .safeseh directive for this function.
372 Handler->addFnAttr("safeseh");
374 Type *LinkTy = getEHLinkRegistrationType();
376 Value *HandlerI8 = Builder.CreateBitCast(Handler, Builder.getInt8PtrTy());
377 Builder.CreateStore(HandlerI8, Builder.CreateStructGEP(LinkTy, Link, 1));
380 Constant::getNullValue(LinkTy->getPointerTo()->getPointerTo(257));
381 Value *Next = Builder.CreateLoad(FSZero);
382 Builder.CreateStore(Next, Builder.CreateStructGEP(LinkTy, Link, 0));
384 Builder.CreateStore(Link, FSZero);
387 void WinEHStatePass::unlinkExceptionRegistration(IRBuilder<> &Builder) {
388 // Clone Link into the current BB for better address mode folding.
389 if (auto *GEP = dyn_cast<GetElementPtrInst>(Link)) {
390 GEP = cast<GetElementPtrInst>(GEP->clone());
394 Type *LinkTy = getEHLinkRegistrationType();
395 // [fs:00] = Link->Next
397 Builder.CreateLoad(Builder.CreateStructGEP(LinkTy, Link, 0));
399 Constant::getNullValue(LinkTy->getPointerTo()->getPointerTo(257));
400 Builder.CreateStore(Next, FSZero);
403 void WinEHStatePass::addStateStores(Function &F, WinEHFuncInfo &FuncInfo) {
404 // Mark the registration node. The backend needs to know which alloca it is so
405 // that it can recover the original frame pointer.
406 IRBuilder<> Builder(RegNode->getParent(), std::next(RegNode->getIterator()));
407 Value *RegNodeI8 = Builder.CreateBitCast(RegNode, Builder.getInt8PtrTy());
409 Intrinsic::getDeclaration(TheModule, Intrinsic::x86_seh_ehregnode),
412 // Calculate state numbers.
413 if (isAsynchronousEHPersonality(Personality))
414 calculateSEHStateNumbers(&F, FuncInfo);
416 calculateWinCXXEHStateNumbers(&F, FuncInfo);
418 // Iterate all the instructions and emit state number stores.
419 for (BasicBlock &BB : F) {
420 for (Instruction &I : BB) {
421 if (auto *CI = dyn_cast<CallInst>(&I)) {
422 // Possibly throwing call instructions have no actions to take after
423 // an unwind. Ensure they are in the -1 state.
424 if (CI->doesNotThrow())
426 insertStateNumberStore(RegNode, CI, -1);
427 } else if (auto *II = dyn_cast<InvokeInst>(&I)) {
428 // Look up the state number of the landingpad this unwinds to.
429 Instruction *PadInst = II->getUnwindDest()->getFirstNonPHI();
430 // FIXME: Why does this assertion fail?
431 //assert(FuncInfo.EHPadStateMap.count(PadInst) && "EH Pad has no state!");
432 int State = FuncInfo.EHPadStateMap[PadInst];
433 insertStateNumberStore(RegNode, II, State);
439 void WinEHStatePass::insertStateNumberStore(Value *ParentRegNode,
440 Instruction *IP, int State) {
441 IRBuilder<> Builder(IP);
443 Builder.CreateStructGEP(RegNodeTy, ParentRegNode, StateFieldIndex);
444 Builder.CreateStore(Builder.getInt32(State), StateField);