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);
75 Value *emitEHLSDA(IRBuilder<> &Builder, Function *F);
77 Function *generateLSDAInEAXThunk(Function *ParentFunc);
79 int escapeRegNode(Function &F);
81 // Module-level type getters.
82 Type *getEHLinkRegistrationType();
83 Type *getSEHRegistrationType();
84 Type *getCXXEHRegistrationType();
87 Module *TheModule = nullptr;
88 StructType *EHLinkRegistrationTy = nullptr;
89 StructType *CXXEHRegistrationTy = nullptr;
90 StructType *SEHRegistrationTy = nullptr;
91 Function *FrameRecover = nullptr;
92 Function *FrameAddress = nullptr;
93 Function *FrameEscape = nullptr;
94 Function *RestoreFrame = nullptr;
97 EHPersonality Personality = EHPersonality::Unknown;
98 Function *PersonalityFn = nullptr;
100 /// The stack allocation containing all EH data, including the link in the
101 /// fs:00 chain and the current state.
102 AllocaInst *RegNode = nullptr;
104 /// Struct type of RegNode. Used for GEPing.
105 Type *RegNodeTy = nullptr;
107 /// The index of the state field of RegNode.
108 int StateFieldIndex = ~0U;
110 /// The linked list node subobject inside of RegNode.
111 Value *Link = nullptr;
115 FunctionPass *llvm::createX86WinEHStatePass() { return new WinEHStatePass(); }
117 char WinEHStatePass::ID = 0;
119 INITIALIZE_PASS(WinEHStatePass, "x86-winehstate",
120 "Insert stores for EH state numbers", false, false)
122 bool WinEHStatePass::doInitialization(Module &M) {
124 FrameEscape = Intrinsic::getDeclaration(TheModule, Intrinsic::localescape);
125 FrameRecover = Intrinsic::getDeclaration(TheModule, Intrinsic::localrecover);
126 FrameAddress = Intrinsic::getDeclaration(TheModule, Intrinsic::frameaddress);
128 Intrinsic::getDeclaration(TheModule, Intrinsic::x86_seh_restoreframe);
132 bool WinEHStatePass::doFinalization(Module &M) {
133 assert(TheModule == &M);
135 EHLinkRegistrationTy = nullptr;
136 CXXEHRegistrationTy = nullptr;
137 SEHRegistrationTy = nullptr;
138 FrameEscape = nullptr;
139 FrameRecover = nullptr;
140 FrameAddress = nullptr;
144 void WinEHStatePass::getAnalysisUsage(AnalysisUsage &AU) const {
145 // This pass should only insert a stack allocation, memory accesses, and
147 AU.setPreservesCFG();
150 bool WinEHStatePass::runOnFunction(Function &F) {
151 // Check the personality. Do nothing if this personality doesn't use funclets.
152 if (!F.hasPersonalityFn())
155 dyn_cast<Function>(F.getPersonalityFn()->stripPointerCasts());
158 Personality = classifyEHPersonality(PersonalityFn);
159 if (!isFuncletEHPersonality(Personality))
162 // Skip this function if there are no EH pads and we aren't using IR-level
164 bool HasPads = false;
165 for (BasicBlock &BB : F) {
174 // Disable frame pointer elimination in this function.
175 // FIXME: Do the nested handlers need to keep the parent ebp in ebp, or can we
176 // use an arbitrary register?
177 F.addFnAttr("no-frame-pointer-elim", "true");
179 emitExceptionRegistrationRecord(&F);
181 auto *MMI = getAnalysisIfAvailable<MachineModuleInfo>();
182 // If MMI is null, create our own WinEHFuncInfo. This only happens in opt
184 std::unique_ptr<WinEHFuncInfo> FuncInfoPtr;
186 FuncInfoPtr.reset(new WinEHFuncInfo());
187 WinEHFuncInfo &FuncInfo =
188 *(MMI ? &MMI->getWinEHFuncInfo(&F) : FuncInfoPtr.get());
190 FuncInfo.EHRegNode = RegNode;
192 switch (Personality) {
193 default: llvm_unreachable("unexpected personality function");
194 case EHPersonality::MSVC_CXX:
195 addCXXStateStores(F, FuncInfo);
197 case EHPersonality::MSVC_X86SEH:
198 addSEHStateStores(F, FuncInfo);
202 // Reset per-function state.
203 PersonalityFn = nullptr;
204 Personality = EHPersonality::Unknown;
208 /// Get the common EH registration subobject:
209 /// typedef _EXCEPTION_DISPOSITION (*PEXCEPTION_ROUTINE)(
210 /// _EXCEPTION_RECORD *, void *, _CONTEXT *, void *);
211 /// struct EHRegistrationNode {
212 /// EHRegistrationNode *Next;
213 /// PEXCEPTION_ROUTINE Handler;
215 Type *WinEHStatePass::getEHLinkRegistrationType() {
216 if (EHLinkRegistrationTy)
217 return EHLinkRegistrationTy;
218 LLVMContext &Context = TheModule->getContext();
219 EHLinkRegistrationTy = StructType::create(Context, "EHRegistrationNode");
221 EHLinkRegistrationTy->getPointerTo(0), // EHRegistrationNode *Next
222 Type::getInt8PtrTy(Context) // EXCEPTION_DISPOSITION (*Handler)(...)
224 EHLinkRegistrationTy->setBody(FieldTys, false);
225 return EHLinkRegistrationTy;
228 /// The __CxxFrameHandler3 registration node:
229 /// struct CXXExceptionRegistration {
231 /// EHRegistrationNode SubRecord;
232 /// int32_t TryLevel;
234 Type *WinEHStatePass::getCXXEHRegistrationType() {
235 if (CXXEHRegistrationTy)
236 return CXXEHRegistrationTy;
237 LLVMContext &Context = TheModule->getContext();
239 Type::getInt8PtrTy(Context), // void *SavedESP
240 getEHLinkRegistrationType(), // EHRegistrationNode SubRecord
241 Type::getInt32Ty(Context) // int32_t TryLevel
243 CXXEHRegistrationTy =
244 StructType::create(FieldTys, "CXXExceptionRegistration");
245 return CXXEHRegistrationTy;
248 /// The _except_handler3/4 registration node:
249 /// struct EH4ExceptionRegistration {
251 /// _EXCEPTION_POINTERS *ExceptionPointers;
252 /// EHRegistrationNode SubRecord;
253 /// int32_t EncodedScopeTable;
254 /// int32_t TryLevel;
256 Type *WinEHStatePass::getSEHRegistrationType() {
257 if (SEHRegistrationTy)
258 return SEHRegistrationTy;
259 LLVMContext &Context = TheModule->getContext();
261 Type::getInt8PtrTy(Context), // void *SavedESP
262 Type::getInt8PtrTy(Context), // void *ExceptionPointers
263 getEHLinkRegistrationType(), // EHRegistrationNode SubRecord
264 Type::getInt32Ty(Context), // int32_t EncodedScopeTable
265 Type::getInt32Ty(Context) // int32_t TryLevel
267 SEHRegistrationTy = StructType::create(FieldTys, "SEHExceptionRegistration");
268 return SEHRegistrationTy;
271 // Emit an exception registration record. These are stack allocations with the
272 // common subobject of two pointers: the previous registration record (the old
273 // fs:00) and the personality function for the current frame. The data before
274 // and after that is personality function specific.
275 void WinEHStatePass::emitExceptionRegistrationRecord(Function *F) {
276 assert(Personality == EHPersonality::MSVC_CXX ||
277 Personality == EHPersonality::MSVC_X86SEH);
279 StringRef PersonalityName = PersonalityFn->getName();
280 IRBuilder<> Builder(&F->getEntryBlock(), F->getEntryBlock().begin());
281 Type *Int8PtrType = Builder.getInt8PtrTy();
282 if (Personality == EHPersonality::MSVC_CXX) {
283 RegNodeTy = getCXXEHRegistrationType();
284 RegNode = Builder.CreateAlloca(RegNodeTy);
285 // SavedESP = llvm.stacksave()
286 Value *SP = Builder.CreateCall(
287 Intrinsic::getDeclaration(TheModule, Intrinsic::stacksave), {});
288 Builder.CreateStore(SP, Builder.CreateStructGEP(RegNodeTy, RegNode, 0));
291 insertStateNumberStore(RegNode, Builder.GetInsertPoint(), -1);
292 // Handler = __ehhandler$F
293 Function *Trampoline = generateLSDAInEAXThunk(F);
294 Link = Builder.CreateStructGEP(RegNodeTy, RegNode, 1);
295 linkExceptionRegistration(Builder, Trampoline);
296 } else if (Personality == EHPersonality::MSVC_X86SEH) {
297 // If _except_handler4 is in use, some additional guard checks and prologue
298 // stuff is required.
299 bool UseStackGuard = (PersonalityName == "_except_handler4");
300 RegNodeTy = getSEHRegistrationType();
301 RegNode = Builder.CreateAlloca(RegNodeTy);
302 // SavedESP = llvm.stacksave()
303 Value *SP = Builder.CreateCall(
304 Intrinsic::getDeclaration(TheModule, Intrinsic::stacksave), {});
305 Builder.CreateStore(SP, Builder.CreateStructGEP(RegNodeTy, RegNode, 0));
306 // TryLevel = -2 / -1
308 insertStateNumberStore(RegNode, Builder.GetInsertPoint(),
309 UseStackGuard ? -2 : -1);
310 // ScopeTable = llvm.x86.seh.lsda(F)
311 Value *FI8 = Builder.CreateBitCast(F, Int8PtrType);
312 Value *LSDA = Builder.CreateCall(
313 Intrinsic::getDeclaration(TheModule, Intrinsic::x86_seh_lsda), FI8);
314 Type *Int32Ty = Type::getInt32Ty(TheModule->getContext());
315 LSDA = Builder.CreatePtrToInt(LSDA, Int32Ty);
316 // If using _except_handler4, xor the address of the table with
317 // __security_cookie.
320 TheModule->getOrInsertGlobal("__security_cookie", Int32Ty);
321 Value *Val = Builder.CreateLoad(Int32Ty, Cookie);
322 LSDA = Builder.CreateXor(LSDA, Val);
324 Builder.CreateStore(LSDA, Builder.CreateStructGEP(RegNodeTy, RegNode, 3));
325 Link = Builder.CreateStructGEP(RegNodeTy, RegNode, 2);
326 linkExceptionRegistration(Builder, PersonalityFn);
328 llvm_unreachable("unexpected personality function");
331 // Insert an unlink before all returns.
332 for (BasicBlock &BB : *F) {
333 TerminatorInst *T = BB.getTerminator();
334 if (!isa<ReturnInst>(T))
336 Builder.SetInsertPoint(T);
337 unlinkExceptionRegistration(Builder);
341 Value *WinEHStatePass::emitEHLSDA(IRBuilder<> &Builder, Function *F) {
342 Value *FI8 = Builder.CreateBitCast(F, Type::getInt8PtrTy(F->getContext()));
343 return Builder.CreateCall(
344 Intrinsic::getDeclaration(TheModule, Intrinsic::x86_seh_lsda), FI8);
347 /// Generate a thunk that puts the LSDA of ParentFunc in EAX and then calls
348 /// PersonalityFn, forwarding the parameters passed to PEXCEPTION_ROUTINE:
349 /// typedef _EXCEPTION_DISPOSITION (*PEXCEPTION_ROUTINE)(
350 /// _EXCEPTION_RECORD *, void *, _CONTEXT *, void *);
351 /// We essentially want this code:
353 /// jmpl ___CxxFrameHandler3
354 Function *WinEHStatePass::generateLSDAInEAXThunk(Function *ParentFunc) {
355 LLVMContext &Context = ParentFunc->getContext();
356 Type *Int32Ty = Type::getInt32Ty(Context);
357 Type *Int8PtrType = Type::getInt8PtrTy(Context);
358 Type *ArgTys[5] = {Int8PtrType, Int8PtrType, Int8PtrType, Int8PtrType,
360 FunctionType *TrampolineTy =
361 FunctionType::get(Int32Ty, makeArrayRef(&ArgTys[0], 4),
363 FunctionType *TargetFuncTy =
364 FunctionType::get(Int32Ty, makeArrayRef(&ArgTys[0], 5),
366 Function *Trampoline =
367 Function::Create(TrampolineTy, GlobalValue::InternalLinkage,
368 Twine("__ehhandler$") + GlobalValue::getRealLinkageName(
369 ParentFunc->getName()),
371 BasicBlock *EntryBB = BasicBlock::Create(Context, "entry", Trampoline);
372 IRBuilder<> Builder(EntryBB);
373 Value *LSDA = emitEHLSDA(Builder, ParentFunc);
374 Value *CastPersonality =
375 Builder.CreateBitCast(PersonalityFn, TargetFuncTy->getPointerTo());
376 auto AI = Trampoline->arg_begin();
377 Value *Args[5] = {LSDA, AI++, AI++, AI++, AI++};
378 CallInst *Call = Builder.CreateCall(CastPersonality, Args);
379 // Can't use musttail due to prototype mismatch, but we can use tail.
380 Call->setTailCall(true);
381 // Set inreg so we pass it in EAX.
382 Call->addAttribute(1, Attribute::InReg);
383 Builder.CreateRet(Call);
387 void WinEHStatePass::linkExceptionRegistration(IRBuilder<> &Builder,
389 // Emit the .safeseh directive for this function.
390 Handler->addFnAttr("safeseh");
392 Type *LinkTy = getEHLinkRegistrationType();
394 Value *HandlerI8 = Builder.CreateBitCast(Handler, Builder.getInt8PtrTy());
395 Builder.CreateStore(HandlerI8, Builder.CreateStructGEP(LinkTy, Link, 1));
398 Constant::getNullValue(LinkTy->getPointerTo()->getPointerTo(257));
399 Value *Next = Builder.CreateLoad(FSZero);
400 Builder.CreateStore(Next, Builder.CreateStructGEP(LinkTy, Link, 0));
402 Builder.CreateStore(Link, FSZero);
405 void WinEHStatePass::unlinkExceptionRegistration(IRBuilder<> &Builder) {
406 // Clone Link into the current BB for better address mode folding.
407 if (auto *GEP = dyn_cast<GetElementPtrInst>(Link)) {
408 GEP = cast<GetElementPtrInst>(GEP->clone());
412 Type *LinkTy = getEHLinkRegistrationType();
413 // [fs:00] = Link->Next
415 Builder.CreateLoad(Builder.CreateStructGEP(LinkTy, Link, 0));
417 Constant::getNullValue(LinkTy->getPointerTo()->getPointerTo(257));
418 Builder.CreateStore(Next, FSZero);
421 void WinEHStatePass::addCXXStateStores(Function &F, WinEHFuncInfo &FuncInfo) {
422 // Set up RegNodeEscapeIndex
423 int RegNodeEscapeIndex = escapeRegNode(F);
424 FuncInfo.EHRegNodeEscapeIndex = RegNodeEscapeIndex;
426 calculateWinCXXEHStateNumbers(&F, FuncInfo);
427 addStateStoresToFunclet(RegNode, FuncInfo, F, -1);
430 /// Assign every distinct landingpad a unique state number for SEH. Unlike C++
431 /// EH, we can use this very simple algorithm while C++ EH cannot because catch
432 /// handlers aren't outlined and the runtime doesn't have to figure out which
433 /// catch handler frame to unwind to.
434 void WinEHStatePass::addSEHStateStores(Function &F, WinEHFuncInfo &FuncInfo) {
435 // Remember and return the index that we used. We save it in WinEHFuncInfo so
436 // that we can lower llvm.x86.seh.recoverfp later in filter functions without
438 int RegNodeEscapeIndex = escapeRegNode(F);
439 FuncInfo.EHRegNodeEscapeIndex = RegNodeEscapeIndex;
441 calculateSEHStateNumbers(&F, FuncInfo);
442 addStateStoresToFunclet(RegNode, FuncInfo, F, -1);
445 /// Escape RegNode so that we can access it from child handlers. Find the call
446 /// to localescape, if any, in the entry block and append RegNode to the list
448 int WinEHStatePass::escapeRegNode(Function &F) {
449 // Find the call to localescape and extract its arguments.
450 IntrinsicInst *EscapeCall = nullptr;
451 for (Instruction &I : F.getEntryBlock()) {
452 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I);
453 if (II && II->getIntrinsicID() == Intrinsic::localescape) {
458 SmallVector<Value *, 8> Args;
460 auto Ops = EscapeCall->arg_operands();
461 Args.append(Ops.begin(), Ops.end());
463 Args.push_back(RegNode);
465 // Replace the call (if it exists) with new one. Otherwise, insert at the end
466 // of the entry block.
467 Instruction *InsertPt = EscapeCall;
469 InsertPt = F.getEntryBlock().getTerminator();
470 IRBuilder<> Builder(&F.getEntryBlock(), InsertPt);
471 Builder.CreateCall(FrameEscape, Args);
473 EscapeCall->eraseFromParent();
474 return Args.size() - 1;
477 void WinEHStatePass::addStateStoresToFunclet(Value *ParentRegNode,
478 WinEHFuncInfo &FuncInfo,
479 Function &F, int BaseState) {
480 // Iterate all the instructions and emit state number stores.
481 for (BasicBlock &BB : F) {
482 for (Instruction &I : BB) {
483 if (auto *CI = dyn_cast<CallInst>(&I)) {
484 // Possibly throwing call instructions have no actions to take after
485 // an unwind. Ensure they are in the -1 state.
486 if (CI->doesNotThrow())
488 insertStateNumberStore(ParentRegNode, CI, BaseState);
489 } else if (auto *II = dyn_cast<InvokeInst>(&I)) {
490 // Look up the state number of the landingpad this unwinds to.
491 Instruction *PadInst = II->getUnwindDest()->getFirstNonPHI();
492 // FIXME: Why does this assertion fail?
493 //assert(FuncInfo.EHPadStateMap.count(PadInst) && "EH Pad has no state!");
494 int State = FuncInfo.EHPadStateMap[PadInst];
495 insertStateNumberStore(ParentRegNode, II, State);
501 void WinEHStatePass::insertStateNumberStore(Value *ParentRegNode,
502 Instruction *IP, int State) {
503 IRBuilder<> Builder(IP);
505 Builder.CreateStructGEP(RegNodeTy, ParentRegNode, StateFieldIndex);
506 Builder.CreateStore(Builder.getInt32(State), StateField);