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 addCXXStateStoresToFunclet(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;
96 EHPersonality Personality = EHPersonality::Unknown;
97 Function *PersonalityFn = nullptr;
99 /// The stack allocation containing all EH data, including the link in the
100 /// fs:00 chain and the current state.
101 AllocaInst *RegNode = nullptr;
103 /// Struct type of RegNode. Used for GEPing.
104 Type *RegNodeTy = nullptr;
106 /// The index of the state field of RegNode.
107 int StateFieldIndex = ~0U;
109 /// The linked list node subobject inside of RegNode.
110 Value *Link = nullptr;
114 FunctionPass *llvm::createX86WinEHStatePass() { return new WinEHStatePass(); }
116 char WinEHStatePass::ID = 0;
118 INITIALIZE_PASS(WinEHStatePass, "x86-winehstate",
119 "Insert stores for EH state numbers", false, false)
121 bool WinEHStatePass::doInitialization(Module &M) {
123 FrameEscape = Intrinsic::getDeclaration(TheModule, Intrinsic::localescape);
124 FrameRecover = Intrinsic::getDeclaration(TheModule, Intrinsic::localrecover);
125 FrameAddress = Intrinsic::getDeclaration(TheModule, Intrinsic::frameaddress);
129 bool WinEHStatePass::doFinalization(Module &M) {
130 assert(TheModule == &M);
132 EHLinkRegistrationTy = nullptr;
133 CXXEHRegistrationTy = nullptr;
134 SEHRegistrationTy = nullptr;
135 FrameEscape = nullptr;
136 FrameRecover = nullptr;
137 FrameAddress = nullptr;
141 void WinEHStatePass::getAnalysisUsage(AnalysisUsage &AU) const {
142 // This pass should only insert a stack allocation, memory accesses, and
144 AU.setPreservesCFG();
147 bool WinEHStatePass::runOnFunction(Function &F) {
148 // If this is an outlined handler, don't do anything. We'll do state insertion
149 // for it in the parent.
150 StringRef WinEHParentName =
151 F.getFnAttribute("wineh-parent").getValueAsString();
152 if (WinEHParentName != F.getName() && !WinEHParentName.empty())
155 // Check the personality. Do nothing if this is not an MSVC personality.
156 if (!F.hasPersonalityFn())
159 dyn_cast<Function>(F.getPersonalityFn()->stripPointerCasts());
162 Personality = classifyEHPersonality(PersonalityFn);
163 if (!isMSVCEHPersonality(Personality))
166 // Disable frame pointer elimination in this function.
167 // FIXME: Do the nested handlers need to keep the parent ebp in ebp, or can we
168 // use an arbitrary register?
169 F.addFnAttr("no-frame-pointer-elim", "true");
171 emitExceptionRegistrationRecord(&F);
173 auto *MMI = getAnalysisIfAvailable<MachineModuleInfo>();
174 // If MMI is null, create our own WinEHFuncInfo. This only happens in opt
176 std::unique_ptr<WinEHFuncInfo> FuncInfoPtr;
178 FuncInfoPtr.reset(new WinEHFuncInfo());
179 WinEHFuncInfo &FuncInfo =
180 *(MMI ? &MMI->getWinEHFuncInfo(&F) : FuncInfoPtr.get());
182 switch (Personality) {
183 default: llvm_unreachable("unexpected personality function");
184 case EHPersonality::MSVC_CXX:
185 addCXXStateStores(F, FuncInfo);
187 case EHPersonality::MSVC_X86SEH:
188 addSEHStateStores(F, FuncInfo);
192 // Reset per-function state.
193 PersonalityFn = nullptr;
194 Personality = EHPersonality::Unknown;
198 /// Get the common EH registration subobject:
199 /// typedef _EXCEPTION_DISPOSITION (*PEXCEPTION_ROUTINE)(
200 /// _EXCEPTION_RECORD *, void *, _CONTEXT *, void *);
201 /// struct EHRegistrationNode {
202 /// EHRegistrationNode *Next;
203 /// PEXCEPTION_ROUTINE Handler;
205 Type *WinEHStatePass::getEHLinkRegistrationType() {
206 if (EHLinkRegistrationTy)
207 return EHLinkRegistrationTy;
208 LLVMContext &Context = TheModule->getContext();
209 EHLinkRegistrationTy = StructType::create(Context, "EHRegistrationNode");
211 EHLinkRegistrationTy->getPointerTo(0), // EHRegistrationNode *Next
212 Type::getInt8PtrTy(Context) // EXCEPTION_DISPOSITION (*Handler)(...)
214 EHLinkRegistrationTy->setBody(FieldTys, false);
215 return EHLinkRegistrationTy;
218 /// The __CxxFrameHandler3 registration node:
219 /// struct CXXExceptionRegistration {
221 /// EHRegistrationNode SubRecord;
222 /// int32_t TryLevel;
224 Type *WinEHStatePass::getCXXEHRegistrationType() {
225 if (CXXEHRegistrationTy)
226 return CXXEHRegistrationTy;
227 LLVMContext &Context = TheModule->getContext();
229 Type::getInt8PtrTy(Context), // void *SavedESP
230 getEHLinkRegistrationType(), // EHRegistrationNode SubRecord
231 Type::getInt32Ty(Context) // int32_t TryLevel
233 CXXEHRegistrationTy =
234 StructType::create(FieldTys, "CXXExceptionRegistration");
235 return CXXEHRegistrationTy;
238 /// The _except_handler3/4 registration node:
239 /// struct EH4ExceptionRegistration {
241 /// _EXCEPTION_POINTERS *ExceptionPointers;
242 /// EHRegistrationNode SubRecord;
243 /// int32_t EncodedScopeTable;
244 /// int32_t TryLevel;
246 Type *WinEHStatePass::getSEHRegistrationType() {
247 if (SEHRegistrationTy)
248 return SEHRegistrationTy;
249 LLVMContext &Context = TheModule->getContext();
251 Type::getInt8PtrTy(Context), // void *SavedESP
252 Type::getInt8PtrTy(Context), // void *ExceptionPointers
253 getEHLinkRegistrationType(), // EHRegistrationNode SubRecord
254 Type::getInt32Ty(Context), // int32_t EncodedScopeTable
255 Type::getInt32Ty(Context) // int32_t TryLevel
257 SEHRegistrationTy = StructType::create(FieldTys, "SEHExceptionRegistration");
258 return SEHRegistrationTy;
261 // Emit an exception registration record. These are stack allocations with the
262 // common subobject of two pointers: the previous registration record (the old
263 // fs:00) and the personality function for the current frame. The data before
264 // and after that is personality function specific.
265 void WinEHStatePass::emitExceptionRegistrationRecord(Function *F) {
266 assert(Personality == EHPersonality::MSVC_CXX ||
267 Personality == EHPersonality::MSVC_X86SEH);
269 StringRef PersonalityName = PersonalityFn->getName();
270 IRBuilder<> Builder(&F->getEntryBlock(), F->getEntryBlock().begin());
271 Type *Int8PtrType = Builder.getInt8PtrTy();
272 if (Personality == EHPersonality::MSVC_CXX) {
273 RegNodeTy = getCXXEHRegistrationType();
274 RegNode = Builder.CreateAlloca(RegNodeTy);
275 // SavedESP = llvm.stacksave()
276 Value *SP = Builder.CreateCall(
277 Intrinsic::getDeclaration(TheModule, Intrinsic::stacksave), {});
278 Builder.CreateStore(SP, Builder.CreateStructGEP(RegNodeTy, RegNode, 0));
281 insertStateNumberStore(RegNode, Builder.GetInsertPoint(), -1);
282 // Handler = __ehhandler$F
283 Function *Trampoline = generateLSDAInEAXThunk(F);
284 Link = Builder.CreateStructGEP(RegNodeTy, RegNode, 1);
285 linkExceptionRegistration(Builder, Trampoline);
286 } else if (Personality == EHPersonality::MSVC_X86SEH) {
287 // If _except_handler4 is in use, some additional guard checks and prologue
288 // stuff is required.
289 bool UseStackGuard = (PersonalityName == "_except_handler4");
290 RegNodeTy = getSEHRegistrationType();
291 RegNode = Builder.CreateAlloca(RegNodeTy);
292 // SavedESP = llvm.stacksave()
293 Value *SP = Builder.CreateCall(
294 Intrinsic::getDeclaration(TheModule, Intrinsic::stacksave), {});
295 Builder.CreateStore(SP, Builder.CreateStructGEP(RegNodeTy, RegNode, 0));
296 // TryLevel = -2 / -1
298 insertStateNumberStore(RegNode, Builder.GetInsertPoint(),
299 UseStackGuard ? -2 : -1);
300 // ScopeTable = llvm.x86.seh.lsda(F)
301 Value *FI8 = Builder.CreateBitCast(F, Int8PtrType);
302 Value *LSDA = Builder.CreateCall(
303 Intrinsic::getDeclaration(TheModule, Intrinsic::x86_seh_lsda), FI8);
304 Type *Int32Ty = Type::getInt32Ty(TheModule->getContext());
305 LSDA = Builder.CreatePtrToInt(LSDA, Int32Ty);
306 // If using _except_handler4, xor the address of the table with
307 // __security_cookie.
310 TheModule->getOrInsertGlobal("__security_cookie", Int32Ty);
311 Value *Val = Builder.CreateLoad(Int32Ty, Cookie);
312 LSDA = Builder.CreateXor(LSDA, Val);
314 Builder.CreateStore(LSDA, Builder.CreateStructGEP(RegNodeTy, RegNode, 3));
315 Link = Builder.CreateStructGEP(RegNodeTy, RegNode, 2);
316 linkExceptionRegistration(Builder, PersonalityFn);
318 llvm_unreachable("unexpected personality function");
321 // Insert an unlink before all returns.
322 for (BasicBlock &BB : *F) {
323 TerminatorInst *T = BB.getTerminator();
324 if (!isa<ReturnInst>(T))
326 Builder.SetInsertPoint(T);
327 unlinkExceptionRegistration(Builder);
331 Value *WinEHStatePass::emitEHLSDA(IRBuilder<> &Builder, Function *F) {
332 Value *FI8 = Builder.CreateBitCast(F, Type::getInt8PtrTy(F->getContext()));
333 return Builder.CreateCall(
334 Intrinsic::getDeclaration(TheModule, Intrinsic::x86_seh_lsda), FI8);
337 /// Generate a thunk that puts the LSDA of ParentFunc in EAX and then calls
338 /// PersonalityFn, forwarding the parameters passed to PEXCEPTION_ROUTINE:
339 /// typedef _EXCEPTION_DISPOSITION (*PEXCEPTION_ROUTINE)(
340 /// _EXCEPTION_RECORD *, void *, _CONTEXT *, void *);
341 /// We essentially want this code:
343 /// jmpl ___CxxFrameHandler3
344 Function *WinEHStatePass::generateLSDAInEAXThunk(Function *ParentFunc) {
345 LLVMContext &Context = ParentFunc->getContext();
346 Type *Int32Ty = Type::getInt32Ty(Context);
347 Type *Int8PtrType = Type::getInt8PtrTy(Context);
348 Type *ArgTys[5] = {Int8PtrType, Int8PtrType, Int8PtrType, Int8PtrType,
350 FunctionType *TrampolineTy =
351 FunctionType::get(Int32Ty, makeArrayRef(&ArgTys[0], 4),
353 FunctionType *TargetFuncTy =
354 FunctionType::get(Int32Ty, makeArrayRef(&ArgTys[0], 5),
356 Function *Trampoline =
357 Function::Create(TrampolineTy, GlobalValue::InternalLinkage,
358 Twine("__ehhandler$") + GlobalValue::getRealLinkageName(
359 ParentFunc->getName()),
361 BasicBlock *EntryBB = BasicBlock::Create(Context, "entry", Trampoline);
362 IRBuilder<> Builder(EntryBB);
363 Value *LSDA = emitEHLSDA(Builder, ParentFunc);
364 Value *CastPersonality =
365 Builder.CreateBitCast(PersonalityFn, TargetFuncTy->getPointerTo());
366 auto AI = Trampoline->arg_begin();
367 Value *Args[5] = {LSDA, AI++, AI++, AI++, AI++};
368 CallInst *Call = Builder.CreateCall(CastPersonality, Args);
369 // Can't use musttail due to prototype mismatch, but we can use tail.
370 Call->setTailCall(true);
371 // Set inreg so we pass it in EAX.
372 Call->addAttribute(1, Attribute::InReg);
373 Builder.CreateRet(Call);
377 void WinEHStatePass::linkExceptionRegistration(IRBuilder<> &Builder,
379 // Emit the .safeseh directive for this function.
380 Handler->addFnAttr("safeseh");
382 Type *LinkTy = getEHLinkRegistrationType();
384 Value *HandlerI8 = Builder.CreateBitCast(Handler, Builder.getInt8PtrTy());
385 Builder.CreateStore(HandlerI8, Builder.CreateStructGEP(LinkTy, Link, 1));
388 Constant::getNullValue(LinkTy->getPointerTo()->getPointerTo(257));
389 Value *Next = Builder.CreateLoad(FSZero);
390 Builder.CreateStore(Next, Builder.CreateStructGEP(LinkTy, Link, 0));
392 Builder.CreateStore(Link, FSZero);
395 void WinEHStatePass::unlinkExceptionRegistration(IRBuilder<> &Builder) {
396 // Clone Link into the current BB for better address mode folding.
397 if (auto *GEP = dyn_cast<GetElementPtrInst>(Link)) {
398 GEP = cast<GetElementPtrInst>(GEP->clone());
402 Type *LinkTy = getEHLinkRegistrationType();
403 // [fs:00] = Link->Next
405 Builder.CreateLoad(Builder.CreateStructGEP(LinkTy, Link, 0));
407 Constant::getNullValue(LinkTy->getPointerTo()->getPointerTo(257));
408 Builder.CreateStore(Next, FSZero);
411 void WinEHStatePass::addCXXStateStores(Function &F, WinEHFuncInfo &FuncInfo) {
412 calculateWinCXXEHStateNumbers(&F, FuncInfo);
414 // The base state for the parent is -1.
415 addCXXStateStoresToFunclet(RegNode, FuncInfo, F, -1);
417 // Set up RegNodeEscapeIndex
418 int RegNodeEscapeIndex = escapeRegNode(F);
419 FuncInfo.EHRegNodeEscapeIndex = RegNodeEscapeIndex;
421 // Only insert stores in catch handlers.
423 ConstantExpr::getBitCast(&F, Type::getInt8PtrTy(TheModule->getContext()));
424 for (auto P : FuncInfo.HandlerBaseState) {
425 Function *Handler = const_cast<Function *>(P.first);
426 int BaseState = P.second;
427 IRBuilder<> Builder(&Handler->getEntryBlock(),
428 Handler->getEntryBlock().begin());
429 // FIXME: Find and reuse such a call if present.
430 Value *ParentFP = Builder.CreateCall(FrameAddress, {Builder.getInt32(1)});
431 Value *RecoveredRegNode = Builder.CreateCall(
432 FrameRecover, {FI8, ParentFP, Builder.getInt32(RegNodeEscapeIndex)});
434 Builder.CreateBitCast(RecoveredRegNode, RegNodeTy->getPointerTo(0));
435 addCXXStateStoresToFunclet(RecoveredRegNode, FuncInfo, *Handler, BaseState);
439 /// Escape RegNode so that we can access it from child handlers. Find the call
440 /// to localescape, if any, in the entry block and append RegNode to the list
442 int WinEHStatePass::escapeRegNode(Function &F) {
443 // Find the call to localescape and extract its arguments.
444 IntrinsicInst *EscapeCall = nullptr;
445 for (Instruction &I : F.getEntryBlock()) {
446 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I);
447 if (II && II->getIntrinsicID() == Intrinsic::localescape) {
452 SmallVector<Value *, 8> Args;
454 auto Ops = EscapeCall->arg_operands();
455 Args.append(Ops.begin(), Ops.end());
457 Args.push_back(RegNode);
459 // Replace the call (if it exists) with new one. Otherwise, insert at the end
460 // of the entry block.
461 Instruction *InsertPt = EscapeCall;
463 InsertPt = F.getEntryBlock().getTerminator();
464 IRBuilder<> Builder(&F.getEntryBlock(), InsertPt);
465 Builder.CreateCall(FrameEscape, Args);
467 EscapeCall->eraseFromParent();
468 return Args.size() - 1;
471 void WinEHStatePass::addCXXStateStoresToFunclet(Value *ParentRegNode,
472 WinEHFuncInfo &FuncInfo,
473 Function &F, int BaseState) {
474 // Iterate all the instructions and emit state number stores.
475 for (BasicBlock &BB : F) {
476 for (Instruction &I : BB) {
477 if (auto *CI = dyn_cast<CallInst>(&I)) {
478 // Possibly throwing call instructions have no actions to take after
479 // an unwind. Ensure they are in the -1 state.
480 if (CI->doesNotThrow())
482 insertStateNumberStore(ParentRegNode, CI, BaseState);
483 } else if (auto *II = dyn_cast<InvokeInst>(&I)) {
484 // Look up the state number of the landingpad this unwinds to.
485 Instruction *PadInst = II->getUnwindDest()->getFirstNonPHI();
486 // FIXME: Why does this assertion fail?
487 //assert(FuncInfo.EHPadStateMap.count(PadInst) && "EH Pad has no state!");
488 int State = FuncInfo.EHPadStateMap[PadInst];
489 insertStateNumberStore(ParentRegNode, II, State);
495 /// Assign every distinct landingpad a unique state number for SEH. Unlike C++
496 /// EH, we can use this very simple algorithm while C++ EH cannot because catch
497 /// handlers aren't outlined and the runtime doesn't have to figure out which
498 /// catch handler frame to unwind to.
499 /// FIXME: __finally blocks are outlined, so this approach may break down there.
500 void WinEHStatePass::addSEHStateStores(Function &F, WinEHFuncInfo &FuncInfo) {
501 // Remember and return the index that we used. We save it in WinEHFuncInfo so
502 // that we can lower llvm.x86.seh.recoverfp later in filter functions without
504 int RegNodeEscapeIndex = escapeRegNode(F);
505 FuncInfo.EHRegNodeEscapeIndex = RegNodeEscapeIndex;
507 // Iterate all the instructions and emit state number stores.
509 SmallPtrSet<BasicBlock *, 4> ExceptBlocks;
510 for (BasicBlock &BB : F) {
511 for (auto I = BB.begin(), E = BB.end(); I != E; ++I) {
512 if (auto *CI = dyn_cast<CallInst>(I)) {
513 auto *Intrin = dyn_cast<IntrinsicInst>(CI);
515 // Calls that "don't throw" are considered to be able to throw asynch
516 // exceptions, but intrinsics cannot.
519 insertStateNumberStore(RegNode, CI, -1);
520 } else if (auto *II = dyn_cast<InvokeInst>(I)) {
521 // Look up the state number of the landingpad this unwinds to.
522 LandingPadInst *LPI = II->getUnwindDest()->getLandingPadInst();
524 FuncInfo.EHPadStateMap.insert(std::make_pair(LPI, CurState));
525 auto Iter = InsertionPair.first;
526 int &State = Iter->second;
527 bool Inserted = InsertionPair.second;
529 // Each action consumes a state number.
530 auto *EHActions = cast<IntrinsicInst>(LPI->getNextNode());
531 SmallVector<std::unique_ptr<ActionHandler>, 4> ActionList;
532 parseEHActions(EHActions, ActionList);
533 assert(!ActionList.empty());
534 CurState += ActionList.size();
535 State += ActionList.size() - 1;
537 // Remember all the __except block targets.
538 for (auto &Handler : ActionList) {
539 if (auto *CH = dyn_cast<CatchHandler>(Handler.get())) {
540 auto *BA = cast<BlockAddress>(CH->getHandlerBlockOrFunc());
542 for (BasicBlock *Pred : predecessors(BA->getBasicBlock()))
543 assert(Pred->isLandingPad() &&
544 "WinEHPrepare failed to split block");
546 ExceptBlocks.insert(BA->getBasicBlock());
550 insertStateNumberStore(RegNode, II, State);
555 // Insert llvm.x86.seh.restoreframe() into each __except block.
556 Function *RestoreFrame =
557 Intrinsic::getDeclaration(TheModule, Intrinsic::x86_seh_restoreframe);
558 for (BasicBlock *ExceptBB : ExceptBlocks) {
559 IRBuilder<> Builder(ExceptBB->begin());
560 Builder.CreateCall(RestoreFrame, {});
564 void WinEHStatePass::insertStateNumberStore(Value *ParentRegNode,
565 Instruction *IP, int State) {
566 IRBuilder<> Builder(IP);
568 Builder.CreateStructGEP(RegNodeTy, ParentRegNode, StateFieldIndex);
569 Builder.CreateStore(Builder.getInt32(State), StateField);