27 #include "llvm/IR/IntrinsicsX86.h" 35 #define DEBUG_TYPE "winehstate" 38 const int OverdefinedState = INT_MIN;
48 bool doInitialization(
Module &M)
override;
50 bool doFinalization(
Module &M)
override;
55 return "Windows 32-bit x86 EH state insertion";
59 void emitExceptionRegistrationRecord(
Function *
F);
62 void unlinkExceptionRegistration(
IRBuilder<> &Builder);
64 void insertStateNumberStore(
Instruction *IP,
int State);
79 Type *getEHLinkRegistrationType();
80 Type *getSEHRegistrationType();
81 Type *getCXXEHRegistrationType();
84 Module *TheModule =
nullptr;
94 bool UseStackGuard =
false;
95 int ParentBaseState = 0;
107 int StateFieldIndex = ~0U;
119 "Insert stores for EH state numbers",
false,
false)
121 bool WinEHStatePass::doInitialization(
Module &M) {
126 bool WinEHStatePass::doFinalization(
Module &M) {
129 EHLinkRegistrationTy =
nullptr;
130 CXXEHRegistrationTy =
nullptr;
131 SEHRegistrationTy =
nullptr;
133 CxxLongjmpUnwind =
nullptr;
134 SehLongjmpUnwind =
nullptr;
139 void WinEHStatePass::getAnalysisUsage(
AnalysisUsage &AU)
const {
165 bool HasPads =
false;
176 SetJmp3 = TheModule->getOrInsertFunction(
182 emitExceptionRegistrationRecord(&F);
190 addStateStores(F, FuncInfo);
193 PersonalityFn =
nullptr;
195 UseStackGuard =
false;
197 EHGuardNode =
nullptr;
209 Type *WinEHStatePass::getEHLinkRegistrationType() {
210 if (EHLinkRegistrationTy)
211 return EHLinkRegistrationTy;
218 EHLinkRegistrationTy->setBody(FieldTys,
false);
219 return EHLinkRegistrationTy;
228 Type *WinEHStatePass::getCXXEHRegistrationType() {
229 if (CXXEHRegistrationTy)
230 return CXXEHRegistrationTy;
234 getEHLinkRegistrationType(),
237 CXXEHRegistrationTy =
239 return CXXEHRegistrationTy;
250 Type *WinEHStatePass::getSEHRegistrationType() {
251 if (SEHRegistrationTy)
252 return SEHRegistrationTy;
257 getEHLinkRegistrationType(),
262 return SEHRegistrationTy;
269 void WinEHStatePass::emitExceptionRegistrationRecord(
Function *F) {
282 RegNodeTy = getCXXEHRegistrationType();
283 RegNode = Builder.CreateAlloca(RegNodeTy);
285 Value *
SP = Builder.CreateCall(
287 Builder.CreateStore(SP, Builder.CreateStructGEP(RegNodeTy, RegNode, 0));
290 ParentBaseState = -1;
291 insertStateNumberStore(&*Builder.GetInsertPoint(), ParentBaseState);
293 Function *Trampoline = generateLSDAInEAXThunk(F);
294 Link = Builder.CreateStructGEP(RegNodeTy, RegNode, 1);
295 linkExceptionRegistration(Builder, Trampoline);
297 CxxLongjmpUnwind = TheModule->getOrInsertFunction(
298 "__CxxLongjmpUnwind",
300 cast<Function>(CxxLongjmpUnwind.getCallee()->stripPointerCasts())
305 StringRef PersonalityName = PersonalityFn->getName();
306 UseStackGuard = (PersonalityName ==
"_except_handler4");
309 RegNodeTy = getSEHRegistrationType();
310 RegNode = Builder.CreateAlloca(RegNodeTy);
312 EHGuardNode = Builder.CreateAlloca(Int32Ty);
315 Value *
SP = Builder.CreateCall(
317 Builder.CreateStore(SP, Builder.CreateStructGEP(RegNodeTy, RegNode, 0));
320 ParentBaseState = UseStackGuard ? -2 : -1;
321 insertStateNumberStore(&*Builder.GetInsertPoint(), ParentBaseState);
323 Value *LSDA = emitEHLSDA(Builder, F);
324 LSDA = Builder.CreatePtrToInt(LSDA, Int32Ty);
328 Cookie = TheModule->getOrInsertGlobal(
"__security_cookie", Int32Ty);
329 Value *Val = Builder.CreateLoad(Int32Ty, Cookie,
"cookie");
330 LSDA = Builder.CreateXor(LSDA, Val);
332 Builder.CreateStore(LSDA, Builder.CreateStructGEP(RegNodeTy, RegNode, 3));
336 Value *Val = Builder.CreateLoad(Int32Ty, Cookie);
337 Value *FrameAddr = Builder.CreateCall(
339 TheModule, Intrinsic::frameaddress,
340 Builder.getInt8PtrTy(
341 TheModule->getDataLayout().getAllocaAddrSpace())),
342 Builder.getInt32(0),
"frameaddr");
343 Value *FrameAddrI32 = Builder.CreatePtrToInt(FrameAddr, Int32Ty);
344 FrameAddrI32 = Builder.CreateXor(FrameAddrI32, Val);
345 Builder.CreateStore(FrameAddrI32, EHGuardNode);
349 Link = Builder.CreateStructGEP(RegNodeTy, RegNode, 2);
350 linkExceptionRegistration(Builder, PersonalityFn);
352 SehLongjmpUnwind = TheModule->getOrInsertFunction(
353 UseStackGuard ?
"_seh_longjmp_unwind4" :
"_seh_longjmp_unwind",
356 cast<Function>(SehLongjmpUnwind.getCallee()->stripPointerCasts())
365 if (!isa<ReturnInst>(T))
367 Builder.SetInsertPoint(T);
368 unlinkExceptionRegistration(Builder);
389 Type *ArgTys[5] = {Int8PtrType, Int8PtrType, Int8PtrType, Int8PtrType,
406 Value *LSDA = emitEHLSDA(Builder, ParentFunc);
407 Value *CastPersonality =
410 Value *
Args[5] = {LSDA, &*AI++, &*AI++, &*AI++, &*AI++};
420 void WinEHStatePass::linkExceptionRegistration(
IRBuilder<> &Builder,
425 Type *LinkTy = getEHLinkRegistrationType();
438 void WinEHStatePass::unlinkExceptionRegistration(
IRBuilder<> &Builder) {
440 if (
auto *
GEP = dyn_cast<GetElementPtrInst>(
Link)) {
441 GEP = cast<GetElementPtrInst>(
GEP->clone());
445 Type *LinkTy = getEHLinkRegistrationType();
471 OptionalArgs.
push_back(CxxLongjmpUnwind.getCallee());
473 OptionalArgs.
push_back(emitEHLSDA(Builder, &F));
475 OptionalArgs.
push_back(SehLongjmpUnwind.getCallee());
491 auto *CI = cast<CallInst>(Inst);
496 auto *II = cast<InvokeInst>(Inst);
498 SetJmp3, II->getNormalDest(), II->getUnwindDest(),
Args, OpBundles);
502 NewCS->setDebugLoc(CS->getDebugLoc());
511 int WinEHStatePass::getBaseStateForBB(
514 int BaseState = ParentBaseState;
515 auto &BBColors = BlockColors[BB];
517 assert(BBColors.size() == 1 &&
"multi-color BB not removed by preparation");
519 if (
auto *FuncletPad =
520 dyn_cast<FuncletPadInst>(FuncletEntryBB->getFirstNonPHI())) {
523 BaseState = BaseStateI->second;
530 int WinEHStatePass::getStateForCallSite(
540 return getBaseStateForBB(BlockColors, FuncInfo, CS.
getParent());
550 return ParentBaseState;
554 return OverdefinedState;
556 int CommonState = OverdefinedState;
560 auto PredEndState = FinalStates.
find(PredBB);
561 if (PredEndState == FinalStates.
end())
562 return OverdefinedState;
566 if (isa<CatchReturnInst>(PredBB->getTerminator()))
567 return OverdefinedState;
569 int PredState = PredEndState->second;
570 assert(PredState != OverdefinedState &&
571 "overdefined BBs shouldn't be in FinalStates");
572 if (CommonState == OverdefinedState)
573 CommonState = PredState;
577 if (CommonState != PredState)
578 return OverdefinedState;
591 return OverdefinedState;
593 int CommonState = OverdefinedState;
597 auto SuccStartState = InitialStates.
find(SuccBB);
598 if (SuccStartState == InitialStates.
end())
599 return OverdefinedState;
602 if (SuccBB->isEHPad())
603 return OverdefinedState;
605 int SuccState = SuccStartState->second;
606 assert(SuccState != OverdefinedState &&
607 "overdefined BBs shouldn't be in FinalStates");
608 if (CommonState == OverdefinedState)
609 CommonState = SuccState;
613 if (CommonState != SuccState)
614 return OverdefinedState;
620 bool WinEHStatePass::isStateStoreNeeded(
EHPersonality Personality,
644 Value *EHGuardNodeI8 =
667 std::deque<BasicBlock *> Worklist;
670 int InitialState = OverdefinedState;
673 InitialState = FinalState = ParentBaseState;
676 if (!isStateStoreNeeded(Personality, CS))
679 int State = getStateForCallSite(BlockColors, FuncInfo, CS);
680 if (InitialState == OverdefinedState)
681 InitialState = State;
686 if (InitialState == OverdefinedState) {
687 Worklist.push_back(BB);
691 <<
" InitialState=" << InitialState <<
'\n');
693 <<
" FinalState=" << FinalState <<
'\n');
694 InitialStates.
insert({BB, InitialState});
695 FinalStates.
insert({BB, FinalState});
699 while (!Worklist.empty()) {
701 Worklist.pop_front();
703 if (InitialStates.
count(BB) != 0)
706 int PredState =
getPredState(FinalStates, F, ParentBaseState, BB);
707 if (PredState == OverdefinedState)
712 InitialStates.
insert({BB, PredState});
713 FinalStates.
insert({BB, PredState});
715 Worklist.push_back(SuccBB);
720 int SuccState =
getSuccState(InitialStates, F, ParentBaseState, BB);
721 if (SuccState == OverdefinedState)
726 FinalStates.
insert({BB, SuccState});
732 auto &BBColors = BlockColors[BB];
737 int PrevState =
getPredState(FinalStates, F, ParentBaseState, BB);
739 <<
" PrevState=" << PrevState <<
'\n');
743 if (!isStateStoreNeeded(Personality, CS))
746 int State = getStateForCallSite(BlockColors, FuncInfo, CS);
747 if (State != PrevState)
748 insertStateNumberStore(&
I, State);
753 auto EndState = FinalStates.
find(BB);
754 if (EndState != FinalStates.
end())
755 if (EndState->second != PrevState)
756 insertStateNumberStore(BB->getTerminator(), EndState->second);
769 SetJmp3CallSites.push_back(CS);
773 for (
CallSite CS : SetJmp3CallSites) {
774 auto &BBColors = BlockColors[CS->
getParent()];
776 bool InCleanup = isa<CleanupPadInst>(FuncletEntryBB->
getFirstNonPHI());
782 RegNode, StateFieldIndex);
785 State = Builder.
getInt32(getStateForCallSite(BlockColors, FuncInfo, CS));
787 rewriteSetJmpCallSite(Builder, F, CS, State);
791 void WinEHStatePass::insertStateNumberStore(
Instruction *IP,
int State) {
794 RegNode, StateFieldIndex);
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
This class represents lattice values for constants.
void setAttributes(AttributeList PAL)
Set the parameter attributes of the call.
LoadInst * CreateLoad(Type *Ty, Value *Ptr, const char *Name)
Provided to resolve 'CreateLoad(Ty, Ptr, "...")' correctly, instead of converting the string to 'bool...
A Module instance is used to store all the information related to an LLVM module. ...
A handy container for a FunctionType+Callee-pointer pair, which can be passed around as a single enti...
void push_back(const T &Elt)
DenseMap< const FuncletPadInst *, int > FuncletBaseStateMap
This class represents a function call, abstracting a target machine's calling convention.
bool hasAvailableExternallyLinkage() const
void setCallingConv(CallingConv::ID CC)
Set the calling convention of the call.
void getOperandBundlesAsDefs(SmallVectorImpl< OperandBundleDef > &Defs) const
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
static int getPredState(DenseMap< BasicBlock *, int > &FinalStates, Function &F, int ParentBaseState, BasicBlock *BB)
static Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
CallingConv::ID getCallingConv() const
Get the calling convention of the call.
iterator begin()
Instruction iterator methods.
IntegerType * getInt32Ty()
Fetch the type representing a 32-bit integer.
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
void calculateSEHStateNumbers(const Function *ParentFn, WinEHFuncInfo &FuncInfo)
ArrayRef< T > makeArrayRef(const T &OneElt)
Construct an ArrayRef from a single element.
Class to represent struct types.
ValTy * getCalledValue() const
Return the pointer to function that is being called.
PointerType * getPointerTo(unsigned AddrSpace=0) const
Return a pointer to the current type.
ReturnInst * CreateRet(Value *V)
Create a 'ret <val>' instruction.
bool doesNotAccessMemory() const
Determine if the call does not access memory.
StoreInst * CreateStore(Value *Val, Value *Ptr, bool isVolatile=false)
InstrTy * getInstruction() const
Class to represent function types.
Value * CreateBitCast(Value *V, Type *DestTy, const Twine &Name="")
void setComdat(Comdat *C)
bool hasPersonalityFn() const
Check whether this function has a personality function.
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
bool doesNotThrow() const
Determine if the call cannot unwind.
void takeName(Value *V)
Transfer the name from V to this value.
Function * getDeclaration(Module *M, ID id, ArrayRef< Type *> Tys=None)
Create or insert an LLVM Function declaration for an intrinsic, and return it.
iterator find(const_arg_type_t< KeyT > Val)
const BasicBlock & getEntryBlock() const
static bool runOnFunction(Function &F, bool PostInlining)
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
const Instruction * getFirstNonPHI() const
Returns a pointer to the first instruction in this block that is not a PHINode instruction.
unsigned getNumArgOperands() const
LLVM Basic Block Representation.
The instances of the Type class are immutable: once they are created, they are never changed...
This is an important class for using LLVM in a threaded context.
This is an important base class in LLVM.
const Instruction & front() const
AttributeList getAttributes() const
Get the parameter attributes of the call.
EHPersonality classifyEHPersonality(const Value *Pers)
See if the given exception handling personality function is one that we understand.
Represent the analysis usage information of a pass.
static Type * getVoidTy(LLVMContext &C)
FunctionPass class - This class is used to implement most global optimizations.
static FunctionType * get(Type *Result, ArrayRef< Type *> Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
DenseMap< const InvokeInst *, int > InvokeStateMap
void setTailCallKind(TailCallKind TCK)
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function. ...
void setTailCall(bool isTC=true)
const Constant * stripPointerCasts() const
const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs and address space casts.
PointerType * getInt8PtrTy(unsigned AddrSpace=0)
Fetch the type representing a pointer to an 8-bit integer value.
static PointerType * getInt8PtrTy(LLVMContext &C, unsigned AS=0)
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
InvokeInst * CreateInvoke(FunctionType *Ty, Value *Callee, BasicBlock *NormalDest, BasicBlock *UnwindDest, ArrayRef< Value *> Args, ArrayRef< OperandBundleDef > OpBundles, const Twine &Name="")
Create an invoke instruction.
void calculateWinCXXEHStateNumbers(const Function *ParentFn, WinEHFuncInfo &FuncInfo)
Analyze the IR in ParentFn and it's handlers to build WinEHFuncInfo, which describes the state number...
void addParamAttr(unsigned ArgNo, Attribute::AttrKind Kind)
Adds the attribute to the indicated argument.
bool isFuncletEHPersonality(EHPersonality Pers)
Returns true if this is a personality function that invokes handler funclets (which must return to it...
static int getSuccState(DenseMap< BasicBlock *, int > &InitialStates, Function &F, int ParentBaseState, BasicBlock *BB)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Module.h This file contains the declarations for the Module class.
X86_StdCall - stdcall is the calling conventions mostly used by the Win32 API.
ConstantInt * getInt32(uint32_t C)
Get a constant 32-bit value.
pred_range predecessors(BasicBlock *BB)
void setPreservesCFG()
This function should be called by the pass, iff they do not:
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
static StringRef dropLLVMManglingEscape(StringRef Name)
If the given string begins with the GlobalValue name mangling escape character '\1', drop it.
BBTy * getParent() const
Get the basic block containing the call site.
void append(in_iter in_start, in_iter in_end)
Add the specified range to the end of the SmallVector.
const Comdat * getComdat() const
static IntegerType * getInt32Ty(LLVMContext &C)
StringRef getName() const
Return a constant reference to the value's name.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Rename collisions when linking (static functions).
CallInst * CreateCall(FunctionType *FTy, Value *Callee, ArrayRef< Value *> Args=None, const Twine &Name="", MDNode *FPMathTag=nullptr)
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
INITIALIZE_PASS(WinEHStatePass, "x86-winehstate", "Insert stores for EH state numbers", false, false) bool WinEHStatePass
InstTy * Insert(InstTy *I, const Twine &Name="") const
Insert and return the specified instruction.
bool isCall() const
Return true if a CallInst is enclosed.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
bool isAsynchronousEHPersonality(EHPersonality Pers)
Returns true if this personality function catches asynchronous exceptions.
bool isEHPad() const
Return true if this basic block is an exception handling block.
LLVM Value Representation.
Constant * getPersonalityFn() const
Get the personality function associated with this function.
succ_range successors(Instruction *I)
static StructType * create(LLVMContext &Context, StringRef Name)
This creates an identified struct.
Value * CreateStructGEP(Type *Ty, Value *Ptr, unsigned Idx, const Twine &Name="")
void addFnAttr(Attribute::AttrKind Kind)
Add function attributes to this function.
StringRef - Represent a constant reference to a string, i.e.
FunctionPass * createX86WinEHStatePass()
Return an IR pass that inserts EH registration stack objects and explicit EH state updates...
DenseMap< BasicBlock *, ColorVector > colorEHFunclets(Function &F)
If an EH funclet personality is in use (see isFuncletEHPersonality), this will recompute which blocks...
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
ValTy * getArgOperand(unsigned i) const
an instruction to allocate memory on the stack