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 // Check the personality. Do nothing if this personality doesn't use funclets.
153 if (!F.hasPersonalityFn())
156 dyn_cast<Function>(F.getPersonalityFn()->stripPointerCasts());
159 Personality = classifyEHPersonality(PersonalityFn);
160 if (!isFuncletEHPersonality(Personality))
163 // Skip this function if there are no EH pads and we aren't using IR-level
165 bool HasPads = false;
166 for (BasicBlock &BB : F) {
175 // Disable frame pointer elimination in this function.
176 // FIXME: Do the nested handlers need to keep the parent ebp in ebp, or can we
177 // use an arbitrary register?
178 F.addFnAttr("no-frame-pointer-elim", "true");
180 emitExceptionRegistrationRecord(&F);
182 auto *MMI = getAnalysisIfAvailable<MachineModuleInfo>();
183 // If MMI is null, create our own WinEHFuncInfo. This only happens in opt
185 std::unique_ptr<WinEHFuncInfo> FuncInfoPtr;
187 FuncInfoPtr.reset(new WinEHFuncInfo());
188 WinEHFuncInfo &FuncInfo =
189 *(MMI ? &MMI->getWinEHFuncInfo(&F) : FuncInfoPtr.get());
191 FuncInfo.EHRegNode = RegNode;
193 switch (Personality) {
194 default: llvm_unreachable("unexpected personality function");
195 case EHPersonality::MSVC_CXX:
196 addCXXStateStores(F, FuncInfo);
198 case EHPersonality::MSVC_X86SEH:
199 addSEHStateStores(F, FuncInfo);
203 // Reset per-function state.
204 PersonalityFn = nullptr;
205 Personality = EHPersonality::Unknown;
209 /// Get the common EH registration subobject:
210 /// typedef _EXCEPTION_DISPOSITION (*PEXCEPTION_ROUTINE)(
211 /// _EXCEPTION_RECORD *, void *, _CONTEXT *, void *);
212 /// struct EHRegistrationNode {
213 /// EHRegistrationNode *Next;
214 /// PEXCEPTION_ROUTINE Handler;
216 Type *WinEHStatePass::getEHLinkRegistrationType() {
217 if (EHLinkRegistrationTy)
218 return EHLinkRegistrationTy;
219 LLVMContext &Context = TheModule->getContext();
220 EHLinkRegistrationTy = StructType::create(Context, "EHRegistrationNode");
222 EHLinkRegistrationTy->getPointerTo(0), // EHRegistrationNode *Next
223 Type::getInt8PtrTy(Context) // EXCEPTION_DISPOSITION (*Handler)(...)
225 EHLinkRegistrationTy->setBody(FieldTys, false);
226 return EHLinkRegistrationTy;
229 /// The __CxxFrameHandler3 registration node:
230 /// struct CXXExceptionRegistration {
232 /// EHRegistrationNode SubRecord;
233 /// int32_t TryLevel;
235 Type *WinEHStatePass::getCXXEHRegistrationType() {
236 if (CXXEHRegistrationTy)
237 return CXXEHRegistrationTy;
238 LLVMContext &Context = TheModule->getContext();
240 Type::getInt8PtrTy(Context), // void *SavedESP
241 getEHLinkRegistrationType(), // EHRegistrationNode SubRecord
242 Type::getInt32Ty(Context) // int32_t TryLevel
244 CXXEHRegistrationTy =
245 StructType::create(FieldTys, "CXXExceptionRegistration");
246 return CXXEHRegistrationTy;
249 /// The _except_handler3/4 registration node:
250 /// struct EH4ExceptionRegistration {
252 /// _EXCEPTION_POINTERS *ExceptionPointers;
253 /// EHRegistrationNode SubRecord;
254 /// int32_t EncodedScopeTable;
255 /// int32_t TryLevel;
257 Type *WinEHStatePass::getSEHRegistrationType() {
258 if (SEHRegistrationTy)
259 return SEHRegistrationTy;
260 LLVMContext &Context = TheModule->getContext();
262 Type::getInt8PtrTy(Context), // void *SavedESP
263 Type::getInt8PtrTy(Context), // void *ExceptionPointers
264 getEHLinkRegistrationType(), // EHRegistrationNode SubRecord
265 Type::getInt32Ty(Context), // int32_t EncodedScopeTable
266 Type::getInt32Ty(Context) // int32_t TryLevel
268 SEHRegistrationTy = StructType::create(FieldTys, "SEHExceptionRegistration");
269 return SEHRegistrationTy;
272 // Emit an exception registration record. These are stack allocations with the
273 // common subobject of two pointers: the previous registration record (the old
274 // fs:00) and the personality function for the current frame. The data before
275 // and after that is personality function specific.
276 void WinEHStatePass::emitExceptionRegistrationRecord(Function *F) {
277 assert(Personality == EHPersonality::MSVC_CXX ||
278 Personality == EHPersonality::MSVC_X86SEH);
280 StringRef PersonalityName = PersonalityFn->getName();
281 IRBuilder<> Builder(&F->getEntryBlock(), F->getEntryBlock().begin());
282 Type *Int8PtrType = Builder.getInt8PtrTy();
283 if (Personality == EHPersonality::MSVC_CXX) {
284 RegNodeTy = getCXXEHRegistrationType();
285 RegNode = Builder.CreateAlloca(RegNodeTy);
286 // SavedESP = llvm.stacksave()
287 Value *SP = Builder.CreateCall(
288 Intrinsic::getDeclaration(TheModule, Intrinsic::stacksave), {});
289 Builder.CreateStore(SP, Builder.CreateStructGEP(RegNodeTy, RegNode, 0));
292 insertStateNumberStore(RegNode, Builder.GetInsertPoint(), -1);
293 // Handler = __ehhandler$F
294 Function *Trampoline = generateLSDAInEAXThunk(F);
295 Link = Builder.CreateStructGEP(RegNodeTy, RegNode, 1);
296 linkExceptionRegistration(Builder, Trampoline);
297 } else if (Personality == EHPersonality::MSVC_X86SEH) {
298 // If _except_handler4 is in use, some additional guard checks and prologue
299 // stuff is required.
300 bool UseStackGuard = (PersonalityName == "_except_handler4");
301 RegNodeTy = getSEHRegistrationType();
302 RegNode = Builder.CreateAlloca(RegNodeTy);
303 // SavedESP = llvm.stacksave()
304 Value *SP = Builder.CreateCall(
305 Intrinsic::getDeclaration(TheModule, Intrinsic::stacksave), {});
306 Builder.CreateStore(SP, Builder.CreateStructGEP(RegNodeTy, RegNode, 0));
307 // TryLevel = -2 / -1
309 insertStateNumberStore(RegNode, Builder.GetInsertPoint(),
310 UseStackGuard ? -2 : -1);
311 // ScopeTable = llvm.x86.seh.lsda(F)
312 Value *FI8 = Builder.CreateBitCast(F, Int8PtrType);
313 Value *LSDA = Builder.CreateCall(
314 Intrinsic::getDeclaration(TheModule, Intrinsic::x86_seh_lsda), FI8);
315 Type *Int32Ty = Type::getInt32Ty(TheModule->getContext());
316 LSDA = Builder.CreatePtrToInt(LSDA, Int32Ty);
317 // If using _except_handler4, xor the address of the table with
318 // __security_cookie.
321 TheModule->getOrInsertGlobal("__security_cookie", Int32Ty);
322 Value *Val = Builder.CreateLoad(Int32Ty, Cookie);
323 LSDA = Builder.CreateXor(LSDA, Val);
325 Builder.CreateStore(LSDA, Builder.CreateStructGEP(RegNodeTy, RegNode, 3));
326 Link = Builder.CreateStructGEP(RegNodeTy, RegNode, 2);
327 linkExceptionRegistration(Builder, PersonalityFn);
329 llvm_unreachable("unexpected personality function");
332 // Insert an unlink before all returns.
333 for (BasicBlock &BB : *F) {
334 TerminatorInst *T = BB.getTerminator();
335 if (!isa<ReturnInst>(T))
337 Builder.SetInsertPoint(T);
338 unlinkExceptionRegistration(Builder);
342 Value *WinEHStatePass::emitEHLSDA(IRBuilder<> &Builder, Function *F) {
343 Value *FI8 = Builder.CreateBitCast(F, Type::getInt8PtrTy(F->getContext()));
344 return Builder.CreateCall(
345 Intrinsic::getDeclaration(TheModule, Intrinsic::x86_seh_lsda), FI8);
348 /// Generate a thunk that puts the LSDA of ParentFunc in EAX and then calls
349 /// PersonalityFn, forwarding the parameters passed to PEXCEPTION_ROUTINE:
350 /// typedef _EXCEPTION_DISPOSITION (*PEXCEPTION_ROUTINE)(
351 /// _EXCEPTION_RECORD *, void *, _CONTEXT *, void *);
352 /// We essentially want this code:
354 /// jmpl ___CxxFrameHandler3
355 Function *WinEHStatePass::generateLSDAInEAXThunk(Function *ParentFunc) {
356 LLVMContext &Context = ParentFunc->getContext();
357 Type *Int32Ty = Type::getInt32Ty(Context);
358 Type *Int8PtrType = Type::getInt8PtrTy(Context);
359 Type *ArgTys[5] = {Int8PtrType, Int8PtrType, Int8PtrType, Int8PtrType,
361 FunctionType *TrampolineTy =
362 FunctionType::get(Int32Ty, makeArrayRef(&ArgTys[0], 4),
364 FunctionType *TargetFuncTy =
365 FunctionType::get(Int32Ty, makeArrayRef(&ArgTys[0], 5),
367 Function *Trampoline =
368 Function::Create(TrampolineTy, GlobalValue::InternalLinkage,
369 Twine("__ehhandler$") + GlobalValue::getRealLinkageName(
370 ParentFunc->getName()),
372 BasicBlock *EntryBB = BasicBlock::Create(Context, "entry", Trampoline);
373 IRBuilder<> Builder(EntryBB);
374 Value *LSDA = emitEHLSDA(Builder, ParentFunc);
375 Value *CastPersonality =
376 Builder.CreateBitCast(PersonalityFn, TargetFuncTy->getPointerTo());
377 auto AI = Trampoline->arg_begin();
378 Value *Args[5] = {LSDA, AI++, AI++, AI++, AI++};
379 CallInst *Call = Builder.CreateCall(CastPersonality, Args);
380 // Can't use musttail due to prototype mismatch, but we can use tail.
381 Call->setTailCall(true);
382 // Set inreg so we pass it in EAX.
383 Call->addAttribute(1, Attribute::InReg);
384 Builder.CreateRet(Call);
388 void WinEHStatePass::linkExceptionRegistration(IRBuilder<> &Builder,
390 // Emit the .safeseh directive for this function.
391 Handler->addFnAttr("safeseh");
393 Type *LinkTy = getEHLinkRegistrationType();
395 Value *HandlerI8 = Builder.CreateBitCast(Handler, Builder.getInt8PtrTy());
396 Builder.CreateStore(HandlerI8, Builder.CreateStructGEP(LinkTy, Link, 1));
399 Constant::getNullValue(LinkTy->getPointerTo()->getPointerTo(257));
400 Value *Next = Builder.CreateLoad(FSZero);
401 Builder.CreateStore(Next, Builder.CreateStructGEP(LinkTy, Link, 0));
403 Builder.CreateStore(Link, FSZero);
406 void WinEHStatePass::unlinkExceptionRegistration(IRBuilder<> &Builder) {
407 // Clone Link into the current BB for better address mode folding.
408 if (auto *GEP = dyn_cast<GetElementPtrInst>(Link)) {
409 GEP = cast<GetElementPtrInst>(GEP->clone());
413 Type *LinkTy = getEHLinkRegistrationType();
414 // [fs:00] = Link->Next
416 Builder.CreateLoad(Builder.CreateStructGEP(LinkTy, Link, 0));
418 Constant::getNullValue(LinkTy->getPointerTo()->getPointerTo(257));
419 Builder.CreateStore(Next, FSZero);
422 void WinEHStatePass::addCXXStateStores(Function &F, WinEHFuncInfo &FuncInfo) {
423 // Set up RegNodeEscapeIndex
424 int RegNodeEscapeIndex = escapeRegNode(F);
425 FuncInfo.EHRegNodeEscapeIndex = RegNodeEscapeIndex;
427 calculateWinCXXEHStateNumbers(&F, FuncInfo);
428 addStateStoresToFunclet(RegNode, FuncInfo, F, -1);
431 /// Assign every distinct landingpad a unique state number for SEH. Unlike C++
432 /// EH, we can use this very simple algorithm while C++ EH cannot because catch
433 /// handlers aren't outlined and the runtime doesn't have to figure out which
434 /// catch handler frame to unwind to.
435 void WinEHStatePass::addSEHStateStores(Function &F, WinEHFuncInfo &FuncInfo) {
436 // Remember and return the index that we used. We save it in WinEHFuncInfo so
437 // that we can lower llvm.x86.seh.recoverfp later in filter functions without
439 int RegNodeEscapeIndex = escapeRegNode(F);
440 FuncInfo.EHRegNodeEscapeIndex = RegNodeEscapeIndex;
442 calculateSEHStateNumbers(&F, FuncInfo);
443 addStateStoresToFunclet(RegNode, FuncInfo, F, -1);
446 /// Escape RegNode so that we can access it from child handlers. Find the call
447 /// to localescape, if any, in the entry block and append RegNode to the list
449 int WinEHStatePass::escapeRegNode(Function &F) {
450 // Find the call to localescape and extract its arguments.
451 IntrinsicInst *EscapeCall = nullptr;
452 for (Instruction &I : F.getEntryBlock()) {
453 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I);
454 if (II && II->getIntrinsicID() == Intrinsic::localescape) {
459 SmallVector<Value *, 8> Args;
461 auto Ops = EscapeCall->arg_operands();
462 Args.append(Ops.begin(), Ops.end());
464 Args.push_back(RegNode);
466 // Replace the call (if it exists) with new one. Otherwise, insert at the end
467 // of the entry block.
468 Instruction *InsertPt = EscapeCall;
470 InsertPt = F.getEntryBlock().getTerminator();
471 IRBuilder<> Builder(&F.getEntryBlock(), InsertPt);
472 Builder.CreateCall(FrameEscape, Args);
474 EscapeCall->eraseFromParent();
475 return Args.size() - 1;
478 void WinEHStatePass::insertRestoreFrame(BasicBlock *BB) {
479 Instruction *Start = BB->getFirstInsertionPt();
480 if (match(Start, m_Intrinsic<Intrinsic::x86_seh_restoreframe>()))
482 IRBuilder<> Builder(Start);
483 Builder.CreateCall(RestoreFrame, {});
486 void WinEHStatePass::addStateStoresToFunclet(Value *ParentRegNode,
487 WinEHFuncInfo &FuncInfo,
488 Function &F, int BaseState) {
489 // Iterate all the instructions and emit state number stores.
490 for (BasicBlock &BB : F) {
491 for (Instruction &I : BB) {
492 if (auto *CI = dyn_cast<CallInst>(&I)) {
493 // Possibly throwing call instructions have no actions to take after
494 // an unwind. Ensure they are in the -1 state.
495 if (CI->doesNotThrow())
497 insertStateNumberStore(ParentRegNode, CI, BaseState);
498 } else if (auto *II = dyn_cast<InvokeInst>(&I)) {
499 // Look up the state number of the landingpad this unwinds to.
500 Instruction *PadInst = II->getUnwindDest()->getFirstNonPHI();
501 // FIXME: Why does this assertion fail?
502 //assert(FuncInfo.EHPadStateMap.count(PadInst) && "EH Pad has no state!");
503 int State = FuncInfo.EHPadStateMap[PadInst];
504 insertStateNumberStore(ParentRegNode, II, State);
510 void WinEHStatePass::insertStateNumberStore(Value *ParentRegNode,
511 Instruction *IP, int State) {
512 IRBuilder<> Builder(IP);
514 Builder.CreateStructGEP(RegNodeTy, ParentRegNode, StateFieldIndex);
515 Builder.CreateStore(Builder.getInt32(State), StateField);