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/Passes.h"
20 #include "llvm/CodeGen/WinEHFuncInfo.h"
21 #include "llvm/IR/Dominators.h"
22 #include "llvm/IR/Function.h"
23 #include "llvm/IR/IRBuilder.h"
24 #include "llvm/IR/Instructions.h"
25 #include "llvm/IR/IntrinsicInst.h"
26 #include "llvm/IR/Module.h"
27 #include "llvm/IR/PatternMatch.h"
28 #include "llvm/Pass.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Support/raw_ostream.h"
31 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
32 #include "llvm/Transforms/Utils/Cloning.h"
33 #include "llvm/Transforms/Utils/Local.h"
36 using namespace llvm::PatternMatch;
38 #define DEBUG_TYPE "winehstate"
41 class WinEHStatePass : public FunctionPass {
43 static char ID; // Pass identification, replacement for typeid.
45 WinEHStatePass() : FunctionPass(ID) {}
47 bool runOnFunction(Function &Fn) override;
49 bool doInitialization(Module &M) override;
51 bool doFinalization(Module &M) override;
53 void getAnalysisUsage(AnalysisUsage &AU) const override;
55 const char *getPassName() const override {
56 return "Windows 32-bit x86 EH state insertion";
60 void emitExceptionRegistrationRecord(Function *F);
62 void linkExceptionRegistration(IRBuilder<> &Builder, Value *RegNode,
64 void unlinkExceptionRegistration(IRBuilder<> &Builder, Value *RegNode);
66 // Module-level type getters.
67 Type *getEHRegistrationType();
68 Type *getSEH3RegistrationType();
69 Type *getSEH4RegistrationType();
70 Type *getCXXEH3RegistrationType();
73 Module *TheModule = nullptr;
74 StructType *EHRegistrationTy = nullptr;
75 StructType *CXXEH3RegistrationTy = nullptr;
76 StructType *SEH3RegistrationTy = nullptr;
77 StructType *SEH4RegistrationTy = nullptr;
80 EHPersonality Personality = EHPersonality::Unknown;
81 Function *PersonalityFn = nullptr;
85 FunctionPass *llvm::createX86WinEHStatePass() { return new WinEHStatePass(); }
87 char WinEHStatePass::ID = 0;
89 bool WinEHStatePass::doInitialization(Module &M) {
94 bool WinEHStatePass::doFinalization(Module &M) {
95 assert(TheModule == &M);
97 EHRegistrationTy = nullptr;
98 CXXEH3RegistrationTy = nullptr;
99 SEH3RegistrationTy = nullptr;
100 SEH4RegistrationTy = nullptr;
104 void WinEHStatePass::getAnalysisUsage(AnalysisUsage &AU) const {
105 // This pass should only insert a stack allocation, memory accesses, and
107 AU.setPreservesCFG();
110 bool WinEHStatePass::runOnFunction(Function &F) {
111 // Check the personality. Do nothing if this is not an MSVC personality.
112 LandingPadInst *LP = nullptr;
113 for (BasicBlock &BB : F) {
114 LP = BB.getLandingPadInst();
121 dyn_cast<Function>(LP->getPersonalityFn()->stripPointerCasts());
124 Personality = classifyEHPersonality(PersonalityFn);
125 if (!isMSVCEHPersonality(Personality))
128 emitExceptionRegistrationRecord(&F);
129 // FIXME: State insertion.
131 // Reset per-function state.
132 PersonalityFn = nullptr;
133 Personality = EHPersonality::Unknown;
137 /// Get the common EH registration subobject:
138 /// struct EHRegistrationNode {
139 /// EHRegistrationNode *Next;
140 /// EXCEPTION_DISPOSITION (*Handler)(...);
142 Type *WinEHStatePass::getEHRegistrationType() {
143 if (EHRegistrationTy)
144 return EHRegistrationTy;
145 LLVMContext &Context = TheModule->getContext();
146 EHRegistrationTy = StructType::create(Context, "EHRegistrationNode");
148 EHRegistrationTy->getPointerTo(0), // EHRegistrationNode *Next
149 Type::getInt8PtrTy(Context) // EXCEPTION_DISPOSITION (*Handler)(...)
151 EHRegistrationTy->setBody(FieldTys, false);
152 return EHRegistrationTy;
155 /// The __CxxFrameHandler3 registration node:
156 /// struct CXXExceptionRegistration {
158 /// EHRegistrationNode SubRecord;
159 /// int32_t TryLevel;
161 Type *WinEHStatePass::getCXXEH3RegistrationType() {
162 if (CXXEH3RegistrationTy)
163 return CXXEH3RegistrationTy;
164 LLVMContext &Context = TheModule->getContext();
166 Type::getInt8PtrTy(Context), // void *SavedESP
167 getEHRegistrationType(), // EHRegistrationNode SubRecord
168 Type::getInt32Ty(Context) // int32_t TryLevel
170 CXXEH3RegistrationTy =
171 StructType::create(FieldTys, "CXXExceptionRegistration");
172 return CXXEH3RegistrationTy;
175 /// The _except_handler3 registration node:
176 /// struct EH3ExceptionRegistration {
177 /// EHRegistrationNode SubRecord;
178 /// void *ScopeTable;
179 /// int32_t TryLevel;
181 Type *WinEHStatePass::getSEH3RegistrationType() {
182 if (SEH3RegistrationTy)
183 return SEH3RegistrationTy;
184 LLVMContext &Context = TheModule->getContext();
186 getEHRegistrationType(), // EHRegistrationNode SubRecord
187 Type::getInt8PtrTy(Context), // void *ScopeTable
188 Type::getInt32Ty(Context) // int32_t TryLevel
190 SEH3RegistrationTy = StructType::create(FieldTys, "EH3ExceptionRegistration");
191 return SEH3RegistrationTy;
194 /// The _except_handler4 registration node:
195 /// struct EH4ExceptionRegistration {
197 /// _EXCEPTION_POINTERS *ExceptionPointers;
198 /// EHRegistrationNode SubRecord;
199 /// int32_t EncodedScopeTable;
200 /// int32_t TryLevel;
202 Type *WinEHStatePass::getSEH4RegistrationType() {
203 if (SEH4RegistrationTy)
204 return SEH4RegistrationTy;
205 LLVMContext &Context = TheModule->getContext();
207 Type::getInt8PtrTy(Context), // void *SavedESP
208 Type::getInt8PtrTy(Context), // void *ExceptionPointers
209 getEHRegistrationType(), // EHRegistrationNode SubRecord
210 Type::getInt32Ty(Context), // int32_t EncodedScopeTable
211 Type::getInt32Ty(Context) // int32_t TryLevel
213 SEH4RegistrationTy = StructType::create(FieldTys, "EH4ExceptionRegistration");
214 return SEH4RegistrationTy;
217 // Emit an exception registration record. These are stack allocations with the
218 // common subobject of two pointers: the previous registration record (the old
219 // fs:00) and the personality function for the current frame. The data before
220 // and after that is personality function specific.
221 void WinEHStatePass::emitExceptionRegistrationRecord(Function *F) {
222 assert(Personality == EHPersonality::MSVC_CXX ||
223 Personality == EHPersonality::MSVC_X86SEH);
225 StringRef PersonalityName = PersonalityFn->getName();
226 IRBuilder<> Builder(&F->getEntryBlock(), F->getEntryBlock().begin());
227 Type *Int8PtrType = Builder.getInt8PtrTy();
228 Value *SubRecord = nullptr;
229 if (PersonalityName == "__CxxFrameHandler3") {
230 Type *RegNodeTy = getCXXEH3RegistrationType();
231 Value *RegNode = Builder.CreateAlloca(RegNodeTy);
232 // FIXME: We can skip this in -GS- mode, when we figure that out.
233 // SavedESP = llvm.stacksave()
234 Value *SP = Builder.CreateCall(
235 Intrinsic::getDeclaration(TheModule, Intrinsic::stacksave));
236 Builder.CreateStore(SP, Builder.CreateStructGEP(RegNodeTy, RegNode, 0));
238 Builder.CreateStore(Builder.getInt32(-1),
239 Builder.CreateStructGEP(RegNodeTy, RegNode, 2));
240 // FIXME: 'Personality' is incorrect here. We need to generate a trampoline
241 // that effectively gets the LSDA.
242 SubRecord = Builder.CreateStructGEP(RegNodeTy, RegNode, 1);
243 linkExceptionRegistration(Builder, SubRecord, PersonalityFn);
244 } else if (PersonalityName == "_except_handler3") {
245 Type *RegNodeTy = getSEH3RegistrationType();
246 Value *RegNode = Builder.CreateAlloca(RegNodeTy);
248 Builder.CreateStore(Builder.getInt32(-1),
249 Builder.CreateStructGEP(RegNodeTy, RegNode, 2));
250 // FIXME: Generalize llvm.eh.sjljl.lsda for this.
251 // ScopeTable = nullptr
252 Builder.CreateStore(Constant::getNullValue(Int8PtrType),
253 Builder.CreateStructGEP(RegNodeTy, RegNode, 1));
254 SubRecord = Builder.CreateStructGEP(RegNodeTy, RegNode, 0);
255 linkExceptionRegistration(Builder, SubRecord, PersonalityFn);
256 } else if (PersonalityName == "_except_handler4") {
257 Type *RegNodeTy = getSEH4RegistrationType();
258 Value *RegNode = Builder.CreateAlloca(RegNodeTy);
259 // SavedESP = llvm.stacksave()
260 Value *SP = Builder.CreateCall(
261 Intrinsic::getDeclaration(TheModule, Intrinsic::stacksave));
262 Builder.CreateStore(SP, Builder.CreateStructGEP(RegNodeTy, RegNode, 0));
264 Builder.CreateStore(Builder.getInt32(-2),
265 Builder.CreateStructGEP(RegNodeTy, RegNode, 4));
266 // FIXME: Generalize llvm.eh.sjljl.lsda for this, and then do the stack
268 // ScopeTable = nullptr
269 Builder.CreateStore(Builder.getInt32(0),
270 Builder.CreateStructGEP(RegNodeTy, RegNode, 3));
271 SubRecord = Builder.CreateStructGEP(RegNodeTy, RegNode, 2);
272 linkExceptionRegistration(Builder, SubRecord, PersonalityFn);
274 llvm_unreachable("unexpected personality function");
277 // FIXME: Insert an unlink before all returns.
278 for (BasicBlock &BB : *F) {
279 TerminatorInst *T = BB.getTerminator();
280 if (!isa<ReturnInst>(T))
282 Builder.SetInsertPoint(T);
283 unlinkExceptionRegistration(Builder, SubRecord);
287 void WinEHStatePass::linkExceptionRegistration(IRBuilder<> &Builder,
288 Value *RegNode, Value *Handler) {
289 Type *RegNodeTy = getEHRegistrationType();
291 Handler = Builder.CreateBitCast(Handler, Builder.getInt8PtrTy());
292 Builder.CreateStore(Handler, Builder.CreateStructGEP(RegNodeTy, RegNode, 1));
295 Constant::getNullValue(RegNodeTy->getPointerTo()->getPointerTo(257));
296 Value *Next = Builder.CreateLoad(FSZero);
297 Builder.CreateStore(Next, Builder.CreateStructGEP(RegNodeTy, RegNode, 0));
299 Builder.CreateStore(RegNode, FSZero);
302 void WinEHStatePass::unlinkExceptionRegistration(IRBuilder<> &Builder,
304 // Clone RegNode into the current BB for better address mode folding.
305 if (auto *GEP = dyn_cast<GetElementPtrInst>(RegNode)) {
306 GEP = cast<GetElementPtrInst>(GEP->clone());
310 Type *RegNodeTy = getEHRegistrationType();
311 // [fs:00] = RegNode->Next
313 Builder.CreateLoad(Builder.CreateStructGEP(RegNodeTy, RegNode, 0));
315 Constant::getNullValue(RegNodeTy->getPointerTo()->getPointerTo(257));
316 Builder.CreateStore(Next, FSZero);