#include "CGCXXABI.h"
#include "CGCleanup.h"
#include "CGVTables.h"
#include "CodeGenModule.h"
#include "CodeGenTypes.h"
#include "TargetInfo.h"
#include "clang/AST/Attr.h"
#include "clang/AST/CXXInheritance.h"
#include "clang/AST/Decl.h"
#include "clang/AST/DeclCXX.h"
#include "clang/AST/StmtCXX.h"
#include "clang/AST/VTableBuilder.h"
#include "clang/CodeGen/ConstantInitBuilder.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/StringSet.h"
#include "llvm/IR/Intrinsics.h"
using namespace clang;
using namespace CodeGen;
namespace {
struct VBTableGlobals {
const VPtrInfoVector *VBTables;
SmallVector<llvm::GlobalVariable *, 2> Globals;
};
class MicrosoftCXXABI : public CGCXXABI {
public:
MicrosoftCXXABI(CodeGenModule &CGM)
: CGCXXABI(CGM), BaseClassDescriptorType(nullptr),
ClassHierarchyDescriptorType(nullptr),
CompleteObjectLocatorType(nullptr), CatchableTypeType(nullptr),
ThrowInfoType(nullptr) {
assert(!(CGM.getLangOpts().isExplicitDefaultVisibilityExportMapping() ||
CGM.getLangOpts().isAllDefaultVisibilityExportMapping()) &&
"visibility export mapping option unimplemented in this ABI");
}
bool HasThisReturn(GlobalDecl GD) const override;
bool hasMostDerivedReturn(GlobalDecl GD) const override;
bool classifyReturnType(CGFunctionInfo &FI) const override;
RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const override;
bool isSRetParameterAfterThis() const override { return true; }
bool isThisCompleteObject(GlobalDecl GD) const override {
if (isa<CXXDestructorDecl>(GD.getDecl())) {
switch (GD.getDtorType()) {
case Dtor_Complete:
case Dtor_Deleting:
return true;
case Dtor_Base:
return false;
case Dtor_Comdat: llvm_unreachable("emitting dtor comdat as function?");
}
llvm_unreachable("bad dtor kind");
}
return false;
}
size_t getSrcArgforCopyCtor(const CXXConstructorDecl *CD,
FunctionArgList &Args) const override {
assert(Args.size() >= 2 &&
"expected the arglist to have at least two args!");
if (CD->getParent()->getNumVBases() > 0 &&
CD->getType()->castAs<FunctionProtoType>()->isVariadic())
return 2;
return 1;
}
std::vector<CharUnits> getVBPtrOffsets(const CXXRecordDecl *RD) override {
std::vector<CharUnits> VBPtrOffsets;
const ASTContext &Context = getContext();
const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
const VBTableGlobals &VBGlobals = enumerateVBTables(RD);
for (const std::unique_ptr<VPtrInfo> &VBT : *VBGlobals.VBTables) {
const ASTRecordLayout &SubobjectLayout =
Context.getASTRecordLayout(VBT->IntroducingObject);
CharUnits Offs = VBT->NonVirtualOffset;
Offs += SubobjectLayout.getVBPtrOffset();
if (VBT->getVBaseWithVPtr())
Offs += Layout.getVBaseClassOffset(VBT->getVBaseWithVPtr());
VBPtrOffsets.push_back(Offs);
}
llvm::array_pod_sort(VBPtrOffsets.begin(), VBPtrOffsets.end());
return VBPtrOffsets;
}
StringRef GetPureVirtualCallName() override { return "_purecall"; }
StringRef GetDeletedVirtualCallName() override { return "_purecall"; }
void emitVirtualObjectDelete(CodeGenFunction &CGF, const CXXDeleteExpr *DE,
Address Ptr, QualType ElementType,
const CXXDestructorDecl *Dtor) override;
void emitRethrow(CodeGenFunction &CGF, bool isNoReturn) override;
void emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) override;
void emitBeginCatch(CodeGenFunction &CGF, const CXXCatchStmt *C) override;
llvm::GlobalVariable *getMSCompleteObjectLocator(const CXXRecordDecl *RD,
const VPtrInfo &Info);
llvm::Constant *getAddrOfRTTIDescriptor(QualType Ty) override;
CatchTypeInfo
getAddrOfCXXCatchHandlerType(QualType Ty, QualType CatchHandlerType) override;
CatchTypeInfo getCatchAllTypeInfo() override {
if (getContext().getLangOpts().EHAsynch)
return CatchTypeInfo{nullptr, 0};
else
return CatchTypeInfo{nullptr, 0x40};
}
bool shouldTypeidBeNullChecked(bool IsDeref, QualType SrcRecordTy) override;
void EmitBadTypeidCall(CodeGenFunction &CGF) override;
llvm::Value *EmitTypeid(CodeGenFunction &CGF, QualType SrcRecordTy,
Address ThisPtr,
llvm::Type *StdTypeInfoPtrTy) override;
bool shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
QualType SrcRecordTy) override;
llvm::Value *EmitDynamicCastCall(CodeGenFunction &CGF, Address Value,
QualType SrcRecordTy, QualType DestTy,
QualType DestRecordTy,
llvm::BasicBlock *CastEnd) override;
llvm::Value *EmitDynamicCastToVoid(CodeGenFunction &CGF, Address Value,
QualType SrcRecordTy,
QualType DestTy) override;
bool EmitBadCastCall(CodeGenFunction &CGF) override;
bool canSpeculativelyEmitVTable(const CXXRecordDecl *RD) const override {
return false;
}
llvm::Value *
GetVirtualBaseClassOffset(CodeGenFunction &CGF, Address This,
const CXXRecordDecl *ClassDecl,
const CXXRecordDecl *BaseClassDecl) override;
llvm::BasicBlock *
EmitCtorCompleteObjectHandler(CodeGenFunction &CGF,
const CXXRecordDecl *RD) override;
llvm::BasicBlock *
EmitDtorCompleteObjectHandler(CodeGenFunction &CGF);
void initializeHiddenVirtualInheritanceMembers(CodeGenFunction &CGF,
const CXXRecordDecl *RD) override;
void EmitCXXConstructors(const CXXConstructorDecl *D) override;
AddedStructorArgCounts
buildStructorSignature(GlobalDecl GD,
SmallVectorImpl<CanQualType> &ArgTys) override;
bool useThunkForDtorVariant(const CXXDestructorDecl *Dtor,
CXXDtorType DT) const override {
return DT != Dtor_Base;
}
void setCXXDestructorDLLStorage(llvm::GlobalValue *GV,
const CXXDestructorDecl *Dtor,
CXXDtorType DT) const override;
llvm::GlobalValue::LinkageTypes
getCXXDestructorLinkage(GVALinkage Linkage, const CXXDestructorDecl *Dtor,
CXXDtorType DT) const override;
void EmitCXXDestructors(const CXXDestructorDecl *D) override;
const CXXRecordDecl *
getThisArgumentTypeForMethod(const CXXMethodDecl *MD) override {
if (MD->isVirtual() && !isa<CXXDestructorDecl>(MD)) {
MethodVFTableLocation ML =
CGM.getMicrosoftVTableContext().getMethodVFTableLocation(MD);
if (ML.VBase || !ML.VFPtrOffset.isZero())
return nullptr;
}
return MD->getParent();
}
Address
adjustThisArgumentForVirtualFunctionCall(CodeGenFunction &CGF, GlobalDecl GD,
Address This,
bool VirtualCall) override;
void addImplicitStructorParams(CodeGenFunction &CGF, QualType &ResTy,
FunctionArgList &Params) override;
void EmitInstanceFunctionProlog(CodeGenFunction &CGF) override;
AddedStructorArgs getImplicitConstructorArgs(CodeGenFunction &CGF,
const CXXConstructorDecl *D,
CXXCtorType Type,
bool ForVirtualBase,
bool Delegating) override;
llvm::Value *getCXXDestructorImplicitParam(CodeGenFunction &CGF,
const CXXDestructorDecl *DD,
CXXDtorType Type,
bool ForVirtualBase,
bool Delegating) override;
void EmitDestructorCall(CodeGenFunction &CGF, const CXXDestructorDecl *DD,
CXXDtorType Type, bool ForVirtualBase,
bool Delegating, Address This,
QualType ThisTy) override;
void emitVTableTypeMetadata(const VPtrInfo &Info, const CXXRecordDecl *RD,
llvm::GlobalVariable *VTable);
void emitVTableDefinitions(CodeGenVTables &CGVT,
const CXXRecordDecl *RD) override;
bool isVirtualOffsetNeededForVTableField(CodeGenFunction &CGF,
CodeGenFunction::VPtr Vptr) override;
bool doStructorsInitializeVPtrs(const CXXRecordDecl *VTableClass) override {
return !VTableClass->hasAttr<MSNoVTableAttr>();
}
llvm::Constant *
getVTableAddressPoint(BaseSubobject Base,
const CXXRecordDecl *VTableClass) override;
llvm::Value *getVTableAddressPointInStructor(
CodeGenFunction &CGF, const CXXRecordDecl *VTableClass,
BaseSubobject Base, const CXXRecordDecl *NearestVBase) override;
llvm::Constant *
getVTableAddressPointForConstExpr(BaseSubobject Base,
const CXXRecordDecl *VTableClass) override;
llvm::GlobalVariable *getAddrOfVTable(const CXXRecordDecl *RD,
CharUnits VPtrOffset) override;
CGCallee getVirtualFunctionPointer(CodeGenFunction &CGF, GlobalDecl GD,
Address This, llvm::Type *Ty,
SourceLocation Loc) override;
llvm::Value *EmitVirtualDestructorCall(CodeGenFunction &CGF,
const CXXDestructorDecl *Dtor,
CXXDtorType DtorType, Address This,
DeleteOrMemberCallExpr E) override;
void adjustCallArgsForDestructorThunk(CodeGenFunction &CGF, GlobalDecl GD,
CallArgList &CallArgs) override {
assert(GD.getDtorType() == Dtor_Deleting &&
"Only deleting destructor thunks are available in this ABI");
CallArgs.add(RValue::get(getStructorImplicitParamValue(CGF)),
getContext().IntTy);
}
void emitVirtualInheritanceTables(const CXXRecordDecl *RD) override;
llvm::GlobalVariable *
getAddrOfVBTable(const VPtrInfo &VBT, const CXXRecordDecl *RD,
llvm::GlobalVariable::LinkageTypes Linkage);
llvm::GlobalVariable *
getAddrOfVirtualDisplacementMap(const CXXRecordDecl *SrcRD,
const CXXRecordDecl *DstRD) {
SmallString<256> OutName;
llvm::raw_svector_ostream Out(OutName);
getMangleContext().mangleCXXVirtualDisplacementMap(SrcRD, DstRD, Out);
StringRef MangledName = OutName.str();
if (auto *VDispMap = CGM.getModule().getNamedGlobal(MangledName))
return VDispMap;
MicrosoftVTableContext &VTContext = CGM.getMicrosoftVTableContext();
unsigned NumEntries = 1 + SrcRD->getNumVBases();
SmallVector<llvm::Constant *, 4> Map(NumEntries,
llvm::UndefValue::get(CGM.IntTy));
Map[0] = llvm::ConstantInt::get(CGM.IntTy, 0);
bool AnyDifferent = false;
for (const auto &I : SrcRD->vbases()) {
const CXXRecordDecl *VBase = I.getType()->getAsCXXRecordDecl();
if (!DstRD->isVirtuallyDerivedFrom(VBase))
continue;
unsigned SrcVBIndex = VTContext.getVBTableIndex(SrcRD, VBase);
unsigned DstVBIndex = VTContext.getVBTableIndex(DstRD, VBase);
Map[SrcVBIndex] = llvm::ConstantInt::get(CGM.IntTy, DstVBIndex * 4);
AnyDifferent |= SrcVBIndex != DstVBIndex;
}
if (!AnyDifferent)
return nullptr;
llvm::ArrayType *VDispMapTy = llvm::ArrayType::get(CGM.IntTy, Map.size());
llvm::Constant *Init = llvm::ConstantArray::get(VDispMapTy, Map);
llvm::GlobalValue::LinkageTypes Linkage =
SrcRD->isExternallyVisible() && DstRD->isExternallyVisible()
? llvm::GlobalValue::LinkOnceODRLinkage
: llvm::GlobalValue::InternalLinkage;
auto *VDispMap = new llvm::GlobalVariable(
CGM.getModule(), VDispMapTy, true, Linkage,
Init, MangledName);
return VDispMap;
}
void emitVBTableDefinition(const VPtrInfo &VBT, const CXXRecordDecl *RD,
llvm::GlobalVariable *GV) const;
void setThunkLinkage(llvm::Function *Thunk, bool ForVTable,
GlobalDecl GD, bool ReturnAdjustment) override {
GVALinkage Linkage =
getContext().GetGVALinkageForFunction(cast<FunctionDecl>(GD.getDecl()));
if (Linkage == GVA_Internal)
Thunk->setLinkage(llvm::GlobalValue::InternalLinkage);
else if (ReturnAdjustment)
Thunk->setLinkage(llvm::GlobalValue::WeakODRLinkage);
else
Thunk->setLinkage(llvm::GlobalValue::LinkOnceODRLinkage);
}
bool exportThunk() override { return false; }
llvm::Value *performThisAdjustment(CodeGenFunction &CGF, Address This,
const ThisAdjustment &TA) override;
llvm::Value *performReturnAdjustment(CodeGenFunction &CGF, Address Ret,
const ReturnAdjustment &RA) override;
void EmitThreadLocalInitFuncs(
CodeGenModule &CGM, ArrayRef<const VarDecl *> CXXThreadLocals,
ArrayRef<llvm::Function *> CXXThreadLocalInits,
ArrayRef<const VarDecl *> CXXThreadLocalInitVars) override;
bool usesThreadWrapperFunction(const VarDecl *VD) const override {
return getContext().getLangOpts().isCompatibleWithMSVC(
LangOptions::MSVC2019_5) &&
(!isEmittedWithConstantInitializer(VD) || mayNeedDestruction(VD));
}
LValue EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF, const VarDecl *VD,
QualType LValType) override;
void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
llvm::GlobalVariable *DeclPtr,
bool PerformInit) override;
void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
llvm::FunctionCallee Dtor,
llvm::Constant *Addr) override;
bool requiresArrayCookie(const CXXDeleteExpr *expr,
QualType elementType) override;
bool requiresArrayCookie(const CXXNewExpr *expr) override;
CharUnits getArrayCookieSizeImpl(QualType type) override;
Address InitializeArrayCookie(CodeGenFunction &CGF,
Address NewPtr,
llvm::Value *NumElements,
const CXXNewExpr *expr,
QualType ElementType) override;
llvm::Value *readArrayCookieImpl(CodeGenFunction &CGF,
Address allocPtr,
CharUnits cookieSize) override;
friend struct MSRTTIBuilder;
bool isImageRelative() const {
return CGM.getTarget().getPointerWidth(0) == 64;
}
llvm::StructType *getTypeDescriptorType(StringRef TypeInfoString) {
llvm::SmallString<32> TDTypeName("rtti.TypeDescriptor");
TDTypeName += llvm::utostr(TypeInfoString.size());
llvm::StructType *&TypeDescriptorType =
TypeDescriptorTypeMap[TypeInfoString.size()];
if (TypeDescriptorType)
return TypeDescriptorType;
llvm::Type *FieldTypes[] = {
CGM.Int8PtrPtrTy,
CGM.Int8PtrTy,
llvm::ArrayType::get(CGM.Int8Ty, TypeInfoString.size() + 1)};
TypeDescriptorType =
llvm::StructType::create(CGM.getLLVMContext(), FieldTypes, TDTypeName);
return TypeDescriptorType;
}
llvm::Type *getImageRelativeType(llvm::Type *PtrType) {
if (!isImageRelative())
return PtrType;
return CGM.IntTy;
}
llvm::StructType *getBaseClassDescriptorType() {
if (BaseClassDescriptorType)
return BaseClassDescriptorType;
llvm::Type *FieldTypes[] = {
getImageRelativeType(CGM.Int8PtrTy),
CGM.IntTy,
CGM.IntTy,
CGM.IntTy,
CGM.IntTy,
CGM.IntTy,
getImageRelativeType(getClassHierarchyDescriptorType()->getPointerTo()),
};
BaseClassDescriptorType = llvm::StructType::create(
CGM.getLLVMContext(), FieldTypes, "rtti.BaseClassDescriptor");
return BaseClassDescriptorType;
}
llvm::StructType *getClassHierarchyDescriptorType() {
if (ClassHierarchyDescriptorType)
return ClassHierarchyDescriptorType;
ClassHierarchyDescriptorType = llvm::StructType::create(
CGM.getLLVMContext(), "rtti.ClassHierarchyDescriptor");
llvm::Type *FieldTypes[] = {
CGM.IntTy,
CGM.IntTy,
CGM.IntTy,
getImageRelativeType(
getBaseClassDescriptorType()->getPointerTo()->getPointerTo()),
};
ClassHierarchyDescriptorType->setBody(FieldTypes);
return ClassHierarchyDescriptorType;
}
llvm::StructType *getCompleteObjectLocatorType() {
if (CompleteObjectLocatorType)
return CompleteObjectLocatorType;
CompleteObjectLocatorType = llvm::StructType::create(
CGM.getLLVMContext(), "rtti.CompleteObjectLocator");
llvm::Type *FieldTypes[] = {
CGM.IntTy,
CGM.IntTy,
CGM.IntTy,
getImageRelativeType(CGM.Int8PtrTy),
getImageRelativeType(getClassHierarchyDescriptorType()->getPointerTo()),
getImageRelativeType(CompleteObjectLocatorType),
};
llvm::ArrayRef<llvm::Type *> FieldTypesRef(FieldTypes);
if (!isImageRelative())
FieldTypesRef = FieldTypesRef.drop_back();
CompleteObjectLocatorType->setBody(FieldTypesRef);
return CompleteObjectLocatorType;
}
llvm::GlobalVariable *getImageBase() {
StringRef Name = "__ImageBase";
if (llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(Name))
return GV;
auto *GV = new llvm::GlobalVariable(CGM.getModule(), CGM.Int8Ty,
true,
llvm::GlobalValue::ExternalLinkage,
nullptr, Name);
CGM.setDSOLocal(GV);
return GV;
}
llvm::Constant *getImageRelativeConstant(llvm::Constant *PtrVal) {
if (!isImageRelative())
return PtrVal;
if (PtrVal->isNullValue())
return llvm::Constant::getNullValue(CGM.IntTy);
llvm::Constant *ImageBaseAsInt =
llvm::ConstantExpr::getPtrToInt(getImageBase(), CGM.IntPtrTy);
llvm::Constant *PtrValAsInt =
llvm::ConstantExpr::getPtrToInt(PtrVal, CGM.IntPtrTy);
llvm::Constant *Diff =
llvm::ConstantExpr::getSub(PtrValAsInt, ImageBaseAsInt,
true, true);
return llvm::ConstantExpr::getTrunc(Diff, CGM.IntTy);
}
private:
MicrosoftMangleContext &getMangleContext() {
return cast<MicrosoftMangleContext>(CodeGen::CGCXXABI::getMangleContext());
}
llvm::Constant *getZeroInt() {
return llvm::ConstantInt::get(CGM.IntTy, 0);
}
llvm::Constant *getAllOnesInt() {
return llvm::Constant::getAllOnesValue(CGM.IntTy);
}
CharUnits getVirtualFunctionPrologueThisAdjustment(GlobalDecl GD) override;
void
GetNullMemberPointerFields(const MemberPointerType *MPT,
llvm::SmallVectorImpl<llvm::Constant *> &fields);
llvm::Value *GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,
Address Base,
llvm::Value *VBPtrOffset,
llvm::Value *VBTableOffset,
llvm::Value **VBPtr = nullptr);
llvm::Value *GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,
Address Base,
int32_t VBPtrOffset,
int32_t VBTableOffset,
llvm::Value **VBPtr = nullptr) {
assert(VBTableOffset % 4 == 0 && "should be byte offset into table of i32s");
llvm::Value *VBPOffset = llvm::ConstantInt::get(CGM.IntTy, VBPtrOffset),
*VBTOffset = llvm::ConstantInt::get(CGM.IntTy, VBTableOffset);
return GetVBaseOffsetFromVBPtr(CGF, Base, VBPOffset, VBTOffset, VBPtr);
}
std::tuple<Address, llvm::Value *, const CXXRecordDecl *>
performBaseAdjustment(CodeGenFunction &CGF, Address Value,
QualType SrcRecordTy);
llvm::Value *AdjustVirtualBase(CodeGenFunction &CGF, const Expr *E,
const CXXRecordDecl *RD, Address Base,
llvm::Value *VirtualBaseAdjustmentOffset,
llvm::Value *VBPtrOffset );
llvm::Constant *EmitFullMemberPointer(llvm::Constant *FirstField,
bool IsMemberFunction,
const CXXRecordDecl *RD,
CharUnits NonVirtualBaseAdjustment,
unsigned VBTableIndex);
bool MemberPointerConstantIsNull(const MemberPointerType *MPT,
llvm::Constant *MP);
void EmitVBPtrStores(CodeGenFunction &CGF, const CXXRecordDecl *RD);
const VBTableGlobals &enumerateVBTables(const CXXRecordDecl *RD);
llvm::Function *EmitVirtualMemPtrThunk(const CXXMethodDecl *MD,
const MethodVFTableLocation &ML);
llvm::Constant *EmitMemberDataPointer(const CXXRecordDecl *RD,
CharUnits offset);
public:
llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT) override;
bool isZeroInitializable(const MemberPointerType *MPT) override;
bool isMemberPointerConvertible(const MemberPointerType *MPT) const override {
const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
return RD->hasAttr<MSInheritanceAttr>();
}
llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT) override;
llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT,
CharUnits offset) override;
llvm::Constant *EmitMemberFunctionPointer(const CXXMethodDecl *MD) override;
llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT) override;
llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF,
llvm::Value *L,
llvm::Value *R,
const MemberPointerType *MPT,
bool Inequality) override;
llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
llvm::Value *MemPtr,
const MemberPointerType *MPT) override;
llvm::Value *
EmitMemberDataPointerAddress(CodeGenFunction &CGF, const Expr *E,
Address Base, llvm::Value *MemPtr,
const MemberPointerType *MPT) override;
llvm::Value *EmitNonNullMemberPointerConversion(
const MemberPointerType *SrcTy, const MemberPointerType *DstTy,
CastKind CK, CastExpr::path_const_iterator PathBegin,
CastExpr::path_const_iterator PathEnd, llvm::Value *Src,
CGBuilderTy &Builder);
llvm::Value *EmitMemberPointerConversion(CodeGenFunction &CGF,
const CastExpr *E,
llvm::Value *Src) override;
llvm::Constant *EmitMemberPointerConversion(const CastExpr *E,
llvm::Constant *Src) override;
llvm::Constant *EmitMemberPointerConversion(
const MemberPointerType *SrcTy, const MemberPointerType *DstTy,
CastKind CK, CastExpr::path_const_iterator PathBegin,
CastExpr::path_const_iterator PathEnd, llvm::Constant *Src);
CGCallee
EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF, const Expr *E,
Address This, llvm::Value *&ThisPtrForCall,
llvm::Value *MemPtr,
const MemberPointerType *MPT) override;
void emitCXXStructor(GlobalDecl GD) override;
llvm::StructType *getCatchableTypeType() {
if (CatchableTypeType)
return CatchableTypeType;
llvm::Type *FieldTypes[] = {
CGM.IntTy, getImageRelativeType(CGM.Int8PtrTy), CGM.IntTy, CGM.IntTy, CGM.IntTy, CGM.IntTy, getImageRelativeType(CGM.Int8PtrTy) };
CatchableTypeType = llvm::StructType::create(
CGM.getLLVMContext(), FieldTypes, "eh.CatchableType");
return CatchableTypeType;
}
llvm::StructType *getCatchableTypeArrayType(uint32_t NumEntries) {
llvm::StructType *&CatchableTypeArrayType =
CatchableTypeArrayTypeMap[NumEntries];
if (CatchableTypeArrayType)
return CatchableTypeArrayType;
llvm::SmallString<23> CTATypeName("eh.CatchableTypeArray.");
CTATypeName += llvm::utostr(NumEntries);
llvm::Type *CTType =
getImageRelativeType(getCatchableTypeType()->getPointerTo());
llvm::Type *FieldTypes[] = {
CGM.IntTy, llvm::ArrayType::get(CTType, NumEntries) };
CatchableTypeArrayType =
llvm::StructType::create(CGM.getLLVMContext(), FieldTypes, CTATypeName);
return CatchableTypeArrayType;
}
llvm::StructType *getThrowInfoType() {
if (ThrowInfoType)
return ThrowInfoType;
llvm::Type *FieldTypes[] = {
CGM.IntTy, getImageRelativeType(CGM.Int8PtrTy), getImageRelativeType(CGM.Int8PtrTy), getImageRelativeType(CGM.Int8PtrTy) };
ThrowInfoType = llvm::StructType::create(CGM.getLLVMContext(), FieldTypes,
"eh.ThrowInfo");
return ThrowInfoType;
}
llvm::FunctionCallee getThrowFn() {
llvm::Type *Args[] = {CGM.Int8PtrTy, getThrowInfoType()->getPointerTo()};
llvm::FunctionType *FTy =
llvm::FunctionType::get(CGM.VoidTy, Args, false);
llvm::FunctionCallee Throw =
CGM.CreateRuntimeFunction(FTy, "_CxxThrowException");
if (CGM.getTarget().getTriple().getArch() == llvm::Triple::x86) {
if (auto *Fn = dyn_cast<llvm::Function>(Throw.getCallee()))
Fn->setCallingConv(llvm::CallingConv::X86_StdCall);
}
return Throw;
}
llvm::Function *getAddrOfCXXCtorClosure(const CXXConstructorDecl *CD,
CXXCtorType CT);
llvm::Constant *getCatchableType(QualType T,
uint32_t NVOffset = 0,
int32_t VBPtrOffset = -1,
uint32_t VBIndex = 0);
llvm::GlobalVariable *getCatchableTypeArray(QualType T);
llvm::GlobalVariable *getThrowInfo(QualType T) override;
std::pair<llvm::Value *, const CXXRecordDecl *>
LoadVTablePtr(CodeGenFunction &CGF, Address This,
const CXXRecordDecl *RD) override;
bool
isPermittedToBeHomogeneousAggregate(const CXXRecordDecl *RD) const override;
private:
typedef std::pair<const CXXRecordDecl *, CharUnits> VFTableIdTy;
typedef llvm::DenseMap<VFTableIdTy, llvm::GlobalVariable *> VTablesMapTy;
typedef llvm::DenseMap<VFTableIdTy, llvm::GlobalValue *> VFTablesMapTy;
VFTablesMapTy VFTablesMap;
VTablesMapTy VTablesMap;
llvm::SmallPtrSet<const CXXRecordDecl *, 4> DeferredVFTables;
llvm::DenseMap<const CXXRecordDecl *, VBTableGlobals> VBTablesMap;
struct GuardInfo {
GuardInfo() : Guard(nullptr), BitIndex(0) {}
llvm::GlobalVariable *Guard;
unsigned BitIndex;
};
llvm::DenseMap<const DeclContext *, GuardInfo> GuardVariableMap;
llvm::DenseMap<const DeclContext *, GuardInfo> ThreadLocalGuardVariableMap;
llvm::DenseMap<const DeclContext *, unsigned> ThreadSafeGuardNumMap;
llvm::DenseMap<size_t, llvm::StructType *> TypeDescriptorTypeMap;
llvm::StructType *BaseClassDescriptorType;
llvm::StructType *ClassHierarchyDescriptorType;
llvm::StructType *CompleteObjectLocatorType;
llvm::DenseMap<QualType, llvm::GlobalVariable *> CatchableTypeArrays;
llvm::StructType *CatchableTypeType;
llvm::DenseMap<uint32_t, llvm::StructType *> CatchableTypeArrayTypeMap;
llvm::StructType *ThrowInfoType;
};
}
CGCXXABI::RecordArgABI
MicrosoftCXXABI::getRecordArgABI(const CXXRecordDecl *RD) const {
if (RD->canPassInRegisters())
return RAA_Default;
switch (CGM.getTarget().getTriple().getArch()) {
default:
return RAA_Indirect;
case llvm::Triple::thumb:
return RAA_Indirect;
case llvm::Triple::x86: {
TypeInfo Info = getContext().getTypeInfo(RD->getTypeForDecl());
if (Info.isAlignRequired() && Info.Align > 4)
return RAA_Indirect;
return RAA_DirectInMemory;
}
case llvm::Triple::x86_64:
case llvm::Triple::aarch64:
return RAA_Indirect;
}
llvm_unreachable("invalid enum");
}
void MicrosoftCXXABI::emitVirtualObjectDelete(CodeGenFunction &CGF,
const CXXDeleteExpr *DE,
Address Ptr,
QualType ElementType,
const CXXDestructorDecl *Dtor) {
bool UseGlobalDelete = DE->isGlobalDelete();
CXXDtorType DtorType = UseGlobalDelete ? Dtor_Complete : Dtor_Deleting;
llvm::Value *MDThis = EmitVirtualDestructorCall(CGF, Dtor, DtorType, Ptr, DE);
if (UseGlobalDelete)
CGF.EmitDeleteCall(DE->getOperatorDelete(), MDThis, ElementType);
}
void MicrosoftCXXABI::emitRethrow(CodeGenFunction &CGF, bool isNoReturn) {
llvm::Value *Args[] = {
llvm::ConstantPointerNull::get(CGM.Int8PtrTy),
llvm::ConstantPointerNull::get(getThrowInfoType()->getPointerTo())};
llvm::FunctionCallee Fn = getThrowFn();
if (isNoReturn)
CGF.EmitNoreturnRuntimeCallOrInvoke(Fn, Args);
else
CGF.EmitRuntimeCallOrInvoke(Fn, Args);
}
void MicrosoftCXXABI::emitBeginCatch(CodeGenFunction &CGF,
const CXXCatchStmt *S) {
VarDecl *CatchParam = S->getExceptionDecl();
llvm::BasicBlock *CatchPadBB = CGF.Builder.GetInsertBlock();
llvm::CatchPadInst *CPI =
cast<llvm::CatchPadInst>(CatchPadBB->getFirstNonPHI());
CGF.CurrentFuncletPad = CPI;
if (!CatchParam || !CatchParam->getDeclName()) {
CGF.EHStack.pushCleanup<CatchRetScope>(NormalCleanup, CPI);
return;
}
CodeGenFunction::AutoVarEmission var = CGF.EmitAutoVarAlloca(*CatchParam);
CPI->setArgOperand(2, var.getObjectAddress(CGF).getPointer());
CGF.EHStack.pushCleanup<CatchRetScope>(NormalCleanup, CPI);
CGF.EmitAutoVarCleanups(var);
}
std::tuple<Address, llvm::Value *, const CXXRecordDecl *>
MicrosoftCXXABI::performBaseAdjustment(CodeGenFunction &CGF, Address Value,
QualType SrcRecordTy) {
Value = CGF.Builder.CreateElementBitCast(Value, CGF.Int8Ty);
const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
const ASTContext &Context = getContext();
if (Context.getASTRecordLayout(SrcDecl).hasExtendableVFPtr())
return std::make_tuple(Value, llvm::ConstantInt::get(CGF.Int32Ty, 0),
SrcDecl);
const CXXRecordDecl *PolymorphicBase = nullptr;
for (auto &Base : SrcDecl->vbases()) {
const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
if (Context.getASTRecordLayout(BaseDecl).hasExtendableVFPtr()) {
PolymorphicBase = BaseDecl;
break;
}
}
assert(PolymorphicBase && "polymorphic class has no apparent vfptr?");
llvm::Value *Offset =
GetVirtualBaseClassOffset(CGF, Value, SrcDecl, PolymorphicBase);
llvm::Value *Ptr = CGF.Builder.CreateInBoundsGEP(
Value.getElementType(), Value.getPointer(), Offset);
CharUnits VBaseAlign =
CGF.CGM.getVBaseAlignment(Value.getAlignment(), SrcDecl, PolymorphicBase);
return std::make_tuple(Address(Ptr, CGF.Int8Ty, VBaseAlign), Offset,
PolymorphicBase);
}
bool MicrosoftCXXABI::shouldTypeidBeNullChecked(bool IsDeref,
QualType SrcRecordTy) {
const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
return IsDeref &&
!getContext().getASTRecordLayout(SrcDecl).hasExtendableVFPtr();
}
static llvm::CallBase *emitRTtypeidCall(CodeGenFunction &CGF,
llvm::Value *Argument) {
llvm::Type *ArgTypes[] = {CGF.Int8PtrTy};
llvm::FunctionType *FTy =
llvm::FunctionType::get(CGF.Int8PtrTy, ArgTypes, false);
llvm::Value *Args[] = {Argument};
llvm::FunctionCallee Fn = CGF.CGM.CreateRuntimeFunction(FTy, "__RTtypeid");
return CGF.EmitRuntimeCallOrInvoke(Fn, Args);
}
void MicrosoftCXXABI::EmitBadTypeidCall(CodeGenFunction &CGF) {
llvm::CallBase *Call =
emitRTtypeidCall(CGF, llvm::Constant::getNullValue(CGM.VoidPtrTy));
Call->setDoesNotReturn();
CGF.Builder.CreateUnreachable();
}
llvm::Value *MicrosoftCXXABI::EmitTypeid(CodeGenFunction &CGF,
QualType SrcRecordTy,
Address ThisPtr,
llvm::Type *StdTypeInfoPtrTy) {
std::tie(ThisPtr, std::ignore, std::ignore) =
performBaseAdjustment(CGF, ThisPtr, SrcRecordTy);
llvm::CallBase *Typeid = emitRTtypeidCall(CGF, ThisPtr.getPointer());
return CGF.Builder.CreateBitCast(Typeid, StdTypeInfoPtrTy);
}
bool MicrosoftCXXABI::shouldDynamicCastCallBeNullChecked(bool SrcIsPtr,
QualType SrcRecordTy) {
const CXXRecordDecl *SrcDecl = SrcRecordTy->getAsCXXRecordDecl();
return SrcIsPtr &&
!getContext().getASTRecordLayout(SrcDecl).hasExtendableVFPtr();
}
llvm::Value *MicrosoftCXXABI::EmitDynamicCastCall(
CodeGenFunction &CGF, Address This, QualType SrcRecordTy,
QualType DestTy, QualType DestRecordTy, llvm::BasicBlock *CastEnd) {
llvm::Type *DestLTy = CGF.ConvertType(DestTy);
llvm::Value *SrcRTTI =
CGF.CGM.GetAddrOfRTTIDescriptor(SrcRecordTy.getUnqualifiedType());
llvm::Value *DestRTTI =
CGF.CGM.GetAddrOfRTTIDescriptor(DestRecordTy.getUnqualifiedType());
llvm::Value *Offset;
std::tie(This, Offset, std::ignore) =
performBaseAdjustment(CGF, This, SrcRecordTy);
llvm::Value *ThisPtr = This.getPointer();
Offset = CGF.Builder.CreateTrunc(Offset, CGF.Int32Ty);
llvm::Type *ArgTypes[] = {CGF.Int8PtrTy, CGF.Int32Ty, CGF.Int8PtrTy,
CGF.Int8PtrTy, CGF.Int32Ty};
llvm::FunctionCallee Function = CGF.CGM.CreateRuntimeFunction(
llvm::FunctionType::get(CGF.Int8PtrTy, ArgTypes, false),
"__RTDynamicCast");
llvm::Value *Args[] = {
ThisPtr, Offset, SrcRTTI, DestRTTI,
llvm::ConstantInt::get(CGF.Int32Ty, DestTy->isReferenceType())};
ThisPtr = CGF.EmitRuntimeCallOrInvoke(Function, Args);
return CGF.Builder.CreateBitCast(ThisPtr, DestLTy);
}
llvm::Value *
MicrosoftCXXABI::EmitDynamicCastToVoid(CodeGenFunction &CGF, Address Value,
QualType SrcRecordTy,
QualType DestTy) {
std::tie(Value, std::ignore, std::ignore) =
performBaseAdjustment(CGF, Value, SrcRecordTy);
llvm::Type *ArgTypes[] = {CGF.Int8PtrTy};
llvm::FunctionCallee Function = CGF.CGM.CreateRuntimeFunction(
llvm::FunctionType::get(CGF.Int8PtrTy, ArgTypes, false),
"__RTCastToVoid");
llvm::Value *Args[] = {Value.getPointer()};
return CGF.EmitRuntimeCall(Function, Args);
}
bool MicrosoftCXXABI::EmitBadCastCall(CodeGenFunction &CGF) {
return false;
}
llvm::Value *MicrosoftCXXABI::GetVirtualBaseClassOffset(
CodeGenFunction &CGF, Address This, const CXXRecordDecl *ClassDecl,
const CXXRecordDecl *BaseClassDecl) {
const ASTContext &Context = getContext();
int64_t VBPtrChars =
Context.getASTRecordLayout(ClassDecl).getVBPtrOffset().getQuantity();
llvm::Value *VBPtrOffset = llvm::ConstantInt::get(CGM.PtrDiffTy, VBPtrChars);
CharUnits IntSize = Context.getTypeSizeInChars(Context.IntTy);
CharUnits VBTableChars =
IntSize *
CGM.getMicrosoftVTableContext().getVBTableIndex(ClassDecl, BaseClassDecl);
llvm::Value *VBTableOffset =
llvm::ConstantInt::get(CGM.IntTy, VBTableChars.getQuantity());
llvm::Value *VBPtrToNewBase =
GetVBaseOffsetFromVBPtr(CGF, This, VBPtrOffset, VBTableOffset);
VBPtrToNewBase =
CGF.Builder.CreateSExtOrBitCast(VBPtrToNewBase, CGM.PtrDiffTy);
return CGF.Builder.CreateNSWAdd(VBPtrOffset, VBPtrToNewBase);
}
bool MicrosoftCXXABI::HasThisReturn(GlobalDecl GD) const {
return isa<CXXConstructorDecl>(GD.getDecl());
}
static bool isDeletingDtor(GlobalDecl GD) {
return isa<CXXDestructorDecl>(GD.getDecl()) &&
GD.getDtorType() == Dtor_Deleting;
}
bool MicrosoftCXXABI::hasMostDerivedReturn(GlobalDecl GD) const {
return isDeletingDtor(GD);
}
static bool isTrivialForAArch64MSVC(const CXXRecordDecl *RD) {
if (RD->hasProtectedFields() || RD->hasPrivateFields())
return false;
if (RD->getNumBases() > 0)
return false;
if (RD->isPolymorphic())
return false;
if (RD->hasNonTrivialCopyAssignment())
return false;
for (const CXXConstructorDecl *Ctor : RD->ctors())
if (Ctor->isUserProvided())
return false;
if (RD->hasNonTrivialDestructor())
return false;
return true;
}
bool MicrosoftCXXABI::classifyReturnType(CGFunctionInfo &FI) const {
const CXXRecordDecl *RD = FI.getReturnType()->getAsCXXRecordDecl();
if (!RD)
return false;
bool isTrivialForABI = RD->isPOD();
bool isAArch64 = CGM.getTarget().getTriple().isAArch64();
if (isAArch64)
isTrivialForABI = RD->canPassInRegisters() && isTrivialForAArch64MSVC(RD);
bool isIndirectReturn = !isTrivialForABI || FI.isInstanceMethod();
if (isIndirectReturn) {
CharUnits Align = CGM.getContext().getTypeAlignInChars(FI.getReturnType());
FI.getReturnInfo() = ABIArgInfo::getIndirect(Align, false);
FI.getReturnInfo().setSRetAfterThis(FI.isInstanceMethod());
FI.getReturnInfo().setInReg(isAArch64);
return true;
}
return false;
}
llvm::BasicBlock *
MicrosoftCXXABI::EmitCtorCompleteObjectHandler(CodeGenFunction &CGF,
const CXXRecordDecl *RD) {
llvm::Value *IsMostDerivedClass = getStructorImplicitParamValue(CGF);
assert(IsMostDerivedClass &&
"ctor for a class with virtual bases must have an implicit parameter");
llvm::Value *IsCompleteObject =
CGF.Builder.CreateIsNotNull(IsMostDerivedClass, "is_complete_object");
llvm::BasicBlock *CallVbaseCtorsBB = CGF.createBasicBlock("ctor.init_vbases");
llvm::BasicBlock *SkipVbaseCtorsBB = CGF.createBasicBlock("ctor.skip_vbases");
CGF.Builder.CreateCondBr(IsCompleteObject,
CallVbaseCtorsBB, SkipVbaseCtorsBB);
CGF.EmitBlock(CallVbaseCtorsBB);
EmitVBPtrStores(CGF, RD);
return SkipVbaseCtorsBB;
}
llvm::BasicBlock *
MicrosoftCXXABI::EmitDtorCompleteObjectHandler(CodeGenFunction &CGF) {
llvm::Value *IsMostDerivedClass = getStructorImplicitParamValue(CGF);
assert(IsMostDerivedClass &&
"ctor for a class with virtual bases must have an implicit parameter");
llvm::Value *IsCompleteObject =
CGF.Builder.CreateIsNotNull(IsMostDerivedClass, "is_complete_object");
llvm::BasicBlock *CallVbaseDtorsBB = CGF.createBasicBlock("Dtor.dtor_vbases");
llvm::BasicBlock *SkipVbaseDtorsBB = CGF.createBasicBlock("Dtor.skip_vbases");
CGF.Builder.CreateCondBr(IsCompleteObject,
CallVbaseDtorsBB, SkipVbaseDtorsBB);
CGF.EmitBlock(CallVbaseDtorsBB);
return SkipVbaseDtorsBB;
}
void MicrosoftCXXABI::initializeHiddenVirtualInheritanceMembers(
CodeGenFunction &CGF, const CXXRecordDecl *RD) {
const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
typedef ASTRecordLayout::VBaseOffsetsMapTy VBOffsets;
const VBOffsets &VBaseMap = Layout.getVBaseOffsetsMap();
CGBuilderTy &Builder = CGF.Builder;
unsigned AS = getThisAddress(CGF).getAddressSpace();
llvm::Value *Int8This = nullptr;
for (const CXXBaseSpecifier &S : RD->vbases()) {
const CXXRecordDecl *VBase = S.getType()->getAsCXXRecordDecl();
auto I = VBaseMap.find(VBase);
assert(I != VBaseMap.end());
if (!I->second.hasVtorDisp())
continue;
llvm::Value *VBaseOffset =
GetVirtualBaseClassOffset(CGF, getThisAddress(CGF), RD, VBase);
uint64_t ConstantVBaseOffset = I->second.VBaseOffset.getQuantity();
llvm::Value *VtorDispValue = Builder.CreateSub(
VBaseOffset, llvm::ConstantInt::get(CGM.PtrDiffTy, ConstantVBaseOffset),
"vtordisp.value");
VtorDispValue = Builder.CreateTruncOrBitCast(VtorDispValue, CGF.Int32Ty);
if (!Int8This)
Int8This = Builder.CreateBitCast(getThisValue(CGF),
CGF.Int8Ty->getPointerTo(AS));
llvm::Value *VtorDispPtr =
Builder.CreateInBoundsGEP(CGF.Int8Ty, Int8This, VBaseOffset);
VtorDispPtr = Builder.CreateConstGEP1_32(CGF.Int8Ty, VtorDispPtr, -4);
VtorDispPtr = Builder.CreateBitCast(
VtorDispPtr, CGF.Int32Ty->getPointerTo(AS), "vtordisp.ptr");
Builder.CreateAlignedStore(VtorDispValue, VtorDispPtr,
CharUnits::fromQuantity(4));
}
}
static bool hasDefaultCXXMethodCC(ASTContext &Context,
const CXXMethodDecl *MD) {
CallingConv ExpectedCallingConv = Context.getDefaultCallingConvention(
false, true);
CallingConv ActualCallingConv =
MD->getType()->castAs<FunctionProtoType>()->getCallConv();
return ExpectedCallingConv == ActualCallingConv;
}
void MicrosoftCXXABI::EmitCXXConstructors(const CXXConstructorDecl *D) {
CGM.EmitGlobal(GlobalDecl(D, Ctor_Complete));
if (D->hasAttr<DLLExportAttr>() && D->isDefaultConstructor() &&
D->isDefined()) {
if (!hasDefaultCXXMethodCC(getContext(), D) || D->getNumParams() != 0) {
llvm::Function *Fn = getAddrOfCXXCtorClosure(D, Ctor_DefaultClosure);
Fn->setLinkage(llvm::GlobalValue::WeakODRLinkage);
CGM.setGVProperties(Fn, D);
}
}
}
void MicrosoftCXXABI::EmitVBPtrStores(CodeGenFunction &CGF,
const CXXRecordDecl *RD) {
Address This = getThisAddress(CGF);
This = CGF.Builder.CreateElementBitCast(This, CGM.Int8Ty, "this.int8");
const ASTContext &Context = getContext();
const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
const VBTableGlobals &VBGlobals = enumerateVBTables(RD);
for (unsigned I = 0, E = VBGlobals.VBTables->size(); I != E; ++I) {
const std::unique_ptr<VPtrInfo> &VBT = (*VBGlobals.VBTables)[I];
llvm::GlobalVariable *GV = VBGlobals.Globals[I];
const ASTRecordLayout &SubobjectLayout =
Context.getASTRecordLayout(VBT->IntroducingObject);
CharUnits Offs = VBT->NonVirtualOffset;
Offs += SubobjectLayout.getVBPtrOffset();
if (VBT->getVBaseWithVPtr())
Offs += Layout.getVBaseClassOffset(VBT->getVBaseWithVPtr());
Address VBPtr = CGF.Builder.CreateConstInBoundsByteGEP(This, Offs);
llvm::Value *GVPtr =
CGF.Builder.CreateConstInBoundsGEP2_32(GV->getValueType(), GV, 0, 0);
VBPtr = CGF.Builder.CreateElementBitCast(VBPtr, GVPtr->getType(),
"vbptr." + VBT->ObjectWithVPtr->getName());
CGF.Builder.CreateStore(GVPtr, VBPtr);
}
}
CGCXXABI::AddedStructorArgCounts
MicrosoftCXXABI::buildStructorSignature(GlobalDecl GD,
SmallVectorImpl<CanQualType> &ArgTys) {
AddedStructorArgCounts Added;
if (isa<CXXDestructorDecl>(GD.getDecl()) &&
GD.getDtorType() == Dtor_Deleting) {
ArgTys.push_back(getContext().IntTy);
++Added.Suffix;
}
auto *CD = dyn_cast<CXXConstructorDecl>(GD.getDecl());
if (!CD)
return Added;
const CXXRecordDecl *Class = CD->getParent();
const FunctionProtoType *FPT = CD->getType()->castAs<FunctionProtoType>();
if (Class->getNumVBases()) {
if (FPT->isVariadic()) {
ArgTys.insert(ArgTys.begin() + 1, getContext().IntTy);
++Added.Prefix;
} else {
ArgTys.push_back(getContext().IntTy);
++Added.Suffix;
}
}
return Added;
}
void MicrosoftCXXABI::setCXXDestructorDLLStorage(llvm::GlobalValue *GV,
const CXXDestructorDecl *Dtor,
CXXDtorType DT) const {
if (DT == Dtor_Deleting) {
GV->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
} else {
const NamedDecl *ND = Dtor;
CGM.setDLLImportDLLExport(GV, ND);
}
}
llvm::GlobalValue::LinkageTypes MicrosoftCXXABI::getCXXDestructorLinkage(
GVALinkage Linkage, const CXXDestructorDecl *Dtor, CXXDtorType DT) const {
if (Linkage == GVA_Internal)
return llvm::GlobalValue::InternalLinkage;
switch (DT) {
case Dtor_Base:
return CGM.getLLVMLinkageForDeclarator(Dtor, Linkage,
false);
case Dtor_Complete:
if (Dtor->hasAttr<DLLExportAttr>())
return llvm::GlobalValue::WeakODRLinkage;
if (Dtor->hasAttr<DLLImportAttr>())
return llvm::GlobalValue::AvailableExternallyLinkage;
return llvm::GlobalValue::LinkOnceODRLinkage;
case Dtor_Deleting:
return llvm::GlobalValue::LinkOnceODRLinkage;
case Dtor_Comdat:
llvm_unreachable("MS C++ ABI does not support comdat dtors");
}
llvm_unreachable("invalid dtor type");
}
void MicrosoftCXXABI::EmitCXXDestructors(const CXXDestructorDecl *D) {
CGM.EmitGlobal(GlobalDecl(D, Dtor_Base));
if (D->getParent()->getNumVBases() > 0 && D->hasAttr<DLLExportAttr>())
CGM.EmitGlobal(GlobalDecl(D, Dtor_Complete));
}
CharUnits
MicrosoftCXXABI::getVirtualFunctionPrologueThisAdjustment(GlobalDecl GD) {
const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
if (GD.getDtorType() == Dtor_Complete)
return CharUnits();
GD = GlobalDecl(DD, Dtor_Deleting);
}
MethodVFTableLocation ML =
CGM.getMicrosoftVTableContext().getMethodVFTableLocation(GD);
CharUnits Adjustment = ML.VFPtrOffset;
if (isa<CXXDestructorDecl>(MD))
Adjustment = CharUnits::Zero();
if (ML.VBase) {
const ASTRecordLayout &DerivedLayout =
getContext().getASTRecordLayout(MD->getParent());
Adjustment += DerivedLayout.getVBaseClassOffset(ML.VBase);
}
return Adjustment;
}
Address MicrosoftCXXABI::adjustThisArgumentForVirtualFunctionCall(
CodeGenFunction &CGF, GlobalDecl GD, Address This,
bool VirtualCall) {
if (!VirtualCall) {
CharUnits Adjustment = getVirtualFunctionPrologueThisAdjustment(GD);
if (Adjustment.isZero())
return This;
This = CGF.Builder.CreateElementBitCast(This, CGF.Int8Ty);
assert(Adjustment.isPositive());
return CGF.Builder.CreateConstByteGEP(This, Adjustment);
}
const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
GlobalDecl LookupGD = GD;
if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
if (GD.getDtorType() == Dtor_Complete)
return This;
LookupGD = GlobalDecl(DD, Dtor_Deleting);
}
MethodVFTableLocation ML =
CGM.getMicrosoftVTableContext().getMethodVFTableLocation(LookupGD);
CharUnits StaticOffset = ML.VFPtrOffset;
if (isa<CXXDestructorDecl>(MD) && GD.getDtorType() == Dtor_Base)
StaticOffset = CharUnits::Zero();
Address Result = This;
if (ML.VBase) {
Result = CGF.Builder.CreateElementBitCast(Result, CGF.Int8Ty);
const CXXRecordDecl *Derived = MD->getParent();
const CXXRecordDecl *VBase = ML.VBase;
llvm::Value *VBaseOffset =
GetVirtualBaseClassOffset(CGF, Result, Derived, VBase);
llvm::Value *VBasePtr = CGF.Builder.CreateInBoundsGEP(
Result.getElementType(), Result.getPointer(), VBaseOffset);
CharUnits VBaseAlign =
CGF.CGM.getVBaseAlignment(Result.getAlignment(), Derived, VBase);
Result = Address(VBasePtr, CGF.Int8Ty, VBaseAlign);
}
if (!StaticOffset.isZero()) {
assert(StaticOffset.isPositive());
Result = CGF.Builder.CreateElementBitCast(Result, CGF.Int8Ty);
if (ML.VBase) {
Result = CGF.Builder.CreateConstByteGEP(Result, StaticOffset);
} else {
Result = CGF.Builder.CreateConstInBoundsByteGEP(Result, StaticOffset);
}
}
return Result;
}
void MicrosoftCXXABI::addImplicitStructorParams(CodeGenFunction &CGF,
QualType &ResTy,
FunctionArgList &Params) {
ASTContext &Context = getContext();
const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
assert(isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD));
if (isa<CXXConstructorDecl>(MD) && MD->getParent()->getNumVBases()) {
auto *IsMostDerived = ImplicitParamDecl::Create(
Context, nullptr, CGF.CurGD.getDecl()->getLocation(),
&Context.Idents.get("is_most_derived"), Context.IntTy,
ImplicitParamDecl::Other);
const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
if (FPT->isVariadic())
Params.insert(Params.begin() + 1, IsMostDerived);
else
Params.push_back(IsMostDerived);
getStructorImplicitParamDecl(CGF) = IsMostDerived;
} else if (isDeletingDtor(CGF.CurGD)) {
auto *ShouldDelete = ImplicitParamDecl::Create(
Context, nullptr, CGF.CurGD.getDecl()->getLocation(),
&Context.Idents.get("should_call_delete"), Context.IntTy,
ImplicitParamDecl::Other);
Params.push_back(ShouldDelete);
getStructorImplicitParamDecl(CGF) = ShouldDelete;
}
}
void MicrosoftCXXABI::EmitInstanceFunctionProlog(CodeGenFunction &CGF) {
if (CGF.CurFuncDecl && CGF.CurFuncDecl->hasAttr<NakedAttr>())
return;
llvm::Value *This = loadIncomingCXXThis(CGF);
const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl());
if (!CGF.CurFuncIsThunk && MD->isVirtual()) {
CharUnits Adjustment = getVirtualFunctionPrologueThisAdjustment(CGF.CurGD);
if (!Adjustment.isZero()) {
unsigned AS = cast<llvm::PointerType>(This->getType())->getAddressSpace();
llvm::Type *charPtrTy = CGF.Int8Ty->getPointerTo(AS),
*thisTy = This->getType();
This = CGF.Builder.CreateBitCast(This, charPtrTy);
assert(Adjustment.isPositive());
This = CGF.Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, This,
-Adjustment.getQuantity());
This = CGF.Builder.CreateBitCast(This, thisTy, "this.adjusted");
}
}
setCXXABIThisValue(CGF, This);
if (HasThisReturn(CGF.CurGD))
CGF.Builder.CreateStore(getThisValue(CGF), CGF.ReturnValue);
else if (hasMostDerivedReturn(CGF.CurGD))
CGF.Builder.CreateStore(CGF.EmitCastToVoidPtr(getThisValue(CGF)),
CGF.ReturnValue);
if (isa<CXXConstructorDecl>(MD) && MD->getParent()->getNumVBases()) {
assert(getStructorImplicitParamDecl(CGF) &&
"no implicit parameter for a constructor with virtual bases?");
getStructorImplicitParamValue(CGF)
= CGF.Builder.CreateLoad(
CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)),
"is_most_derived");
}
if (isDeletingDtor(CGF.CurGD)) {
assert(getStructorImplicitParamDecl(CGF) &&
"no implicit parameter for a deleting destructor?");
getStructorImplicitParamValue(CGF)
= CGF.Builder.CreateLoad(
CGF.GetAddrOfLocalVar(getStructorImplicitParamDecl(CGF)),
"should_call_delete");
}
}
CGCXXABI::AddedStructorArgs MicrosoftCXXABI::getImplicitConstructorArgs(
CodeGenFunction &CGF, const CXXConstructorDecl *D, CXXCtorType Type,
bool ForVirtualBase, bool Delegating) {
assert(Type == Ctor_Complete || Type == Ctor_Base);
if (!D->getParent()->getNumVBases())
return AddedStructorArgs{};
const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>();
llvm::Value *MostDerivedArg;
if (Delegating) {
MostDerivedArg = getStructorImplicitParamValue(CGF);
} else {
MostDerivedArg = llvm::ConstantInt::get(CGM.Int32Ty, Type == Ctor_Complete);
}
if (FPT->isVariadic()) {
return AddedStructorArgs::prefix({{MostDerivedArg, getContext().IntTy}});
}
return AddedStructorArgs::suffix({{MostDerivedArg, getContext().IntTy}});
}
llvm::Value *MicrosoftCXXABI::getCXXDestructorImplicitParam(
CodeGenFunction &CGF, const CXXDestructorDecl *DD, CXXDtorType Type,
bool ForVirtualBase, bool Delegating) {
return nullptr;
}
void MicrosoftCXXABI::EmitDestructorCall(CodeGenFunction &CGF,
const CXXDestructorDecl *DD,
CXXDtorType Type, bool ForVirtualBase,
bool Delegating, Address This,
QualType ThisTy) {
if (Type == Dtor_Complete && DD->getParent()->getNumVBases() == 0)
Type = Dtor_Base;
GlobalDecl GD(DD, Type);
CGCallee Callee = CGCallee::forDirect(CGM.getAddrOfCXXStructor(GD), GD);
if (DD->isVirtual()) {
assert(Type != CXXDtorType::Dtor_Deleting &&
"The deleting destructor should only be called via a virtual call");
This = adjustThisArgumentForVirtualFunctionCall(CGF, GlobalDecl(DD, Type),
This, false);
}
llvm::BasicBlock *BaseDtorEndBB = nullptr;
if (ForVirtualBase && isa<CXXConstructorDecl>(CGF.CurCodeDecl)) {
BaseDtorEndBB = EmitDtorCompleteObjectHandler(CGF);
}
llvm::Value *Implicit =
getCXXDestructorImplicitParam(CGF, DD, Type, ForVirtualBase,
Delegating); CGF.EmitCXXDestructorCall(GD, Callee, This.getPointer(), ThisTy,
Implicit,
QualType(), nullptr);
if (BaseDtorEndBB) {
CGF.Builder.CreateBr(BaseDtorEndBB);
CGF.EmitBlock(BaseDtorEndBB);
}
}
void MicrosoftCXXABI::emitVTableTypeMetadata(const VPtrInfo &Info,
const CXXRecordDecl *RD,
llvm::GlobalVariable *VTable) {
if (!CGM.getCodeGenOpts().LTOUnit)
return;
if (CGM.getCodeGenOpts().WholeProgramVTables) {
llvm::DenseSet<const CXXRecordDecl *> Visited;
llvm::GlobalObject::VCallVisibility TypeVis =
CGM.GetVCallVisibilityLevel(RD, Visited);
if (TypeVis != llvm::GlobalObject::VCallVisibilityPublic)
VTable->setVCallVisibilityMetadata(TypeVis);
}
CharUnits AddressPoint =
getContext().getLangOpts().RTTIData
? getContext().toCharUnitsFromBits(
getContext().getTargetInfo().getPointerWidth(0))
: CharUnits::Zero();
if (Info.PathToIntroducingObject.empty()) {
CGM.AddVTableTypeMetadata(VTable, AddressPoint, RD);
return;
}
CGM.AddVTableTypeMetadata(VTable, AddressPoint,
Info.PathToIntroducingObject.back());
for (unsigned I = Info.PathToIntroducingObject.size() - 1; I != 0; --I) {
const CXXRecordDecl *DerivedRD = Info.PathToIntroducingObject[I - 1];
const CXXRecordDecl *BaseRD = Info.PathToIntroducingObject[I];
const ASTRecordLayout &Layout =
getContext().getASTRecordLayout(DerivedRD);
CharUnits Offset;
auto VBI = Layout.getVBaseOffsetsMap().find(BaseRD);
if (VBI == Layout.getVBaseOffsetsMap().end())
Offset = Layout.getBaseClassOffset(BaseRD);
else
Offset = VBI->second.VBaseOffset;
if (!Offset.isZero())
return;
CGM.AddVTableTypeMetadata(VTable, AddressPoint, DerivedRD);
}
if (Info.FullOffsetInMDC.isZero())
CGM.AddVTableTypeMetadata(VTable, AddressPoint, RD);
}
void MicrosoftCXXABI::emitVTableDefinitions(CodeGenVTables &CGVT,
const CXXRecordDecl *RD) {
MicrosoftVTableContext &VFTContext = CGM.getMicrosoftVTableContext();
const VPtrInfoVector &VFPtrs = VFTContext.getVFPtrOffsets(RD);
for (const std::unique_ptr<VPtrInfo>& Info : VFPtrs) {
llvm::GlobalVariable *VTable = getAddrOfVTable(RD, Info->FullOffsetInMDC);
if (VTable->hasInitializer())
continue;
const VTableLayout &VTLayout =
VFTContext.getVFTableLayout(RD, Info->FullOffsetInMDC);
llvm::Constant *RTTI = nullptr;
if (any_of(VTLayout.vtable_components(),
[](const VTableComponent &VTC) { return VTC.isRTTIKind(); }))
RTTI = getMSCompleteObjectLocator(RD, *Info);
ConstantInitBuilder builder(CGM);
auto components = builder.beginStruct();
CGVT.createVTableInitializer(components, VTLayout, RTTI,
VTable->hasLocalLinkage());
components.finishAndSetAsInitializer(VTable);
emitVTableTypeMetadata(*Info, RD, VTable);
}
}
bool MicrosoftCXXABI::isVirtualOffsetNeededForVTableField(
CodeGenFunction &CGF, CodeGenFunction::VPtr Vptr) {
return Vptr.NearestVBase != nullptr;
}
llvm::Value *MicrosoftCXXABI::getVTableAddressPointInStructor(
CodeGenFunction &CGF, const CXXRecordDecl *VTableClass, BaseSubobject Base,
const CXXRecordDecl *NearestVBase) {
llvm::Constant *VTableAddressPoint = getVTableAddressPoint(Base, VTableClass);
if (!VTableAddressPoint) {
assert(Base.getBase()->getNumVBases() &&
!getContext().getASTRecordLayout(Base.getBase()).hasOwnVFPtr());
}
return VTableAddressPoint;
}
static void mangleVFTableName(MicrosoftMangleContext &MangleContext,
const CXXRecordDecl *RD, const VPtrInfo &VFPtr,
SmallString<256> &Name) {
llvm::raw_svector_ostream Out(Name);
MangleContext.mangleCXXVFTable(RD, VFPtr.MangledPath, Out);
}
llvm::Constant *
MicrosoftCXXABI::getVTableAddressPoint(BaseSubobject Base,
const CXXRecordDecl *VTableClass) {
(void)getAddrOfVTable(VTableClass, Base.getBaseOffset());
VFTableIdTy ID(VTableClass, Base.getBaseOffset());
return VFTablesMap[ID];
}
llvm::Constant *MicrosoftCXXABI::getVTableAddressPointForConstExpr(
BaseSubobject Base, const CXXRecordDecl *VTableClass) {
llvm::Constant *VFTable = getVTableAddressPoint(Base, VTableClass);
assert(VFTable && "Couldn't find a vftable for the given base?");
return VFTable;
}
llvm::GlobalVariable *MicrosoftCXXABI::getAddrOfVTable(const CXXRecordDecl *RD,
CharUnits VPtrOffset) {
VFTableIdTy ID(RD, VPtrOffset);
VTablesMapTy::iterator I;
bool Inserted;
std::tie(I, Inserted) = VTablesMap.insert(std::make_pair(ID, nullptr));
if (!Inserted)
return I->second;
llvm::GlobalVariable *&VTable = I->second;
MicrosoftVTableContext &VTContext = CGM.getMicrosoftVTableContext();
const VPtrInfoVector &VFPtrs = VTContext.getVFPtrOffsets(RD);
if (DeferredVFTables.insert(RD).second) {
CGM.addDeferredVTable(RD);
#ifndef NDEBUG
llvm::StringSet<> ObservedMangledNames;
for (size_t J = 0, F = VFPtrs.size(); J != F; ++J) {
SmallString<256> Name;
mangleVFTableName(getMangleContext(), RD, *VFPtrs[J], Name);
if (!ObservedMangledNames.insert(Name.str()).second)
llvm_unreachable("Already saw this mangling before?");
}
#endif
}
const std::unique_ptr<VPtrInfo> *VFPtrI =
llvm::find_if(VFPtrs, [&](const std::unique_ptr<VPtrInfo> &VPI) {
return VPI->FullOffsetInMDC == VPtrOffset;
});
if (VFPtrI == VFPtrs.end()) {
VFTablesMap[ID] = nullptr;
return nullptr;
}
const std::unique_ptr<VPtrInfo> &VFPtr = *VFPtrI;
SmallString<256> VFTableName;
mangleVFTableName(getMangleContext(), RD, *VFPtr, VFTableName);
llvm::GlobalValue::LinkageTypes VFTableLinkage =
RD->hasAttr<DLLImportAttr>() ? llvm::GlobalValue::LinkOnceODRLinkage
: CGM.getVTableLinkage(RD);
bool VFTableComesFromAnotherTU =
llvm::GlobalValue::isAvailableExternallyLinkage(VFTableLinkage) ||
llvm::GlobalValue::isExternalLinkage(VFTableLinkage);
bool VTableAliasIsRequred =
!VFTableComesFromAnotherTU && getContext().getLangOpts().RTTIData;
if (llvm::GlobalValue *VFTable =
CGM.getModule().getNamedGlobal(VFTableName)) {
VFTablesMap[ID] = VFTable;
VTable = VTableAliasIsRequred
? cast<llvm::GlobalVariable>(
cast<llvm::GlobalAlias>(VFTable)->getAliaseeObject())
: cast<llvm::GlobalVariable>(VFTable);
return VTable;
}
const VTableLayout &VTLayout =
VTContext.getVFTableLayout(RD, VFPtr->FullOffsetInMDC);
llvm::GlobalValue::LinkageTypes VTableLinkage =
VTableAliasIsRequred ? llvm::GlobalValue::PrivateLinkage : VFTableLinkage;
StringRef VTableName = VTableAliasIsRequred ? StringRef() : VFTableName.str();
llvm::Type *VTableType = CGM.getVTables().getVTableType(VTLayout);
llvm::GlobalValue *VFTable;
VTable = new llvm::GlobalVariable(CGM.getModule(), VTableType,
true, VTableLinkage,
nullptr, VTableName);
VTable->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
llvm::Comdat *C = nullptr;
if (!VFTableComesFromAnotherTU &&
(llvm::GlobalValue::isWeakForLinker(VFTableLinkage) ||
(llvm::GlobalValue::isLocalLinkage(VFTableLinkage) &&
VTableAliasIsRequred)))
C = CGM.getModule().getOrInsertComdat(VFTableName.str());
if (VTableAliasIsRequred) {
llvm::Value *GEPIndices[] = {llvm::ConstantInt::get(CGM.Int32Ty, 0),
llvm::ConstantInt::get(CGM.Int32Ty, 0),
llvm::ConstantInt::get(CGM.Int32Ty, 1)};
llvm::Constant *VTableGEP = llvm::ConstantExpr::getInBoundsGetElementPtr(
VTable->getValueType(), VTable, GEPIndices);
if (llvm::GlobalValue::isWeakForLinker(VFTableLinkage)) {
VFTableLinkage = llvm::GlobalValue::ExternalLinkage;
if (C)
C->setSelectionKind(llvm::Comdat::Largest);
}
VFTable = llvm::GlobalAlias::create(CGM.Int8PtrTy,
0, VFTableLinkage,
VFTableName.str(), VTableGEP,
&CGM.getModule());
VFTable->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
} else {
VFTable = VTable;
}
if (C)
VTable->setComdat(C);
if (RD->hasAttr<DLLExportAttr>())
VFTable->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
VFTablesMap[ID] = VFTable;
return VTable;
}
CGCallee MicrosoftCXXABI::getVirtualFunctionPointer(CodeGenFunction &CGF,
GlobalDecl GD,
Address This,
llvm::Type *Ty,
SourceLocation Loc) {
CGBuilderTy &Builder = CGF.Builder;
Ty = Ty->getPointerTo();
Address VPtr =
adjustThisArgumentForVirtualFunctionCall(CGF, GD, This, true);
auto *MethodDecl = cast<CXXMethodDecl>(GD.getDecl());
llvm::Value *VTable = CGF.GetVTablePtr(VPtr, Ty->getPointerTo(),
MethodDecl->getParent());
MicrosoftVTableContext &VFTContext = CGM.getMicrosoftVTableContext();
MethodVFTableLocation ML = VFTContext.getMethodVFTableLocation(GD);
auto getObjectWithVPtr = [&] {
return llvm::find_if(VFTContext.getVFPtrOffsets(
ML.VBase ? ML.VBase : MethodDecl->getParent()),
[&](const std::unique_ptr<VPtrInfo> &Info) {
return Info->FullOffsetInMDC == ML.VFPtrOffset;
})
->get()
->ObjectWithVPtr;
};
llvm::Value *VFunc;
if (CGF.ShouldEmitVTableTypeCheckedLoad(MethodDecl->getParent())) {
VFunc = CGF.EmitVTableTypeCheckedLoad(
getObjectWithVPtr(), VTable, Ty,
ML.Index * CGM.getContext().getTargetInfo().getPointerWidth(0) / 8);
} else {
if (CGM.getCodeGenOpts().PrepareForLTO)
CGF.EmitTypeMetadataCodeForVCall(getObjectWithVPtr(), VTable, Loc);
llvm::Value *VFuncPtr =
Builder.CreateConstInBoundsGEP1_64(Ty, VTable, ML.Index, "vfn");
VFunc = Builder.CreateAlignedLoad(Ty, VFuncPtr, CGF.getPointerAlign());
}
CGCallee Callee(GD, VFunc);
return Callee;
}
llvm::Value *MicrosoftCXXABI::EmitVirtualDestructorCall(
CodeGenFunction &CGF, const CXXDestructorDecl *Dtor, CXXDtorType DtorType,
Address This, DeleteOrMemberCallExpr E) {
auto *CE = E.dyn_cast<const CXXMemberCallExpr *>();
auto *D = E.dyn_cast<const CXXDeleteExpr *>();
assert((CE != nullptr) ^ (D != nullptr));
assert(CE == nullptr || CE->arg_begin() == CE->arg_end());
assert(DtorType == Dtor_Deleting || DtorType == Dtor_Complete);
GlobalDecl GD(Dtor, Dtor_Deleting);
const CGFunctionInfo *FInfo =
&CGM.getTypes().arrangeCXXStructorDeclaration(GD);
llvm::FunctionType *Ty = CGF.CGM.getTypes().GetFunctionType(*FInfo);
CGCallee Callee = CGCallee::forVirtual(CE, GD, This, Ty);
ASTContext &Context = getContext();
llvm::Value *ImplicitParam = llvm::ConstantInt::get(
llvm::IntegerType::getInt32Ty(CGF.getLLVMContext()),
DtorType == Dtor_Deleting);
QualType ThisTy;
if (CE) {
ThisTy = CE->getObjectType();
} else {
ThisTy = D->getDestroyedType();
}
This = adjustThisArgumentForVirtualFunctionCall(CGF, GD, This, true);
RValue RV = CGF.EmitCXXDestructorCall(GD, Callee, This.getPointer(), ThisTy,
ImplicitParam, Context.IntTy, CE);
return RV.getScalarVal();
}
const VBTableGlobals &
MicrosoftCXXABI::enumerateVBTables(const CXXRecordDecl *RD) {
llvm::DenseMap<const CXXRecordDecl*, VBTableGlobals>::iterator Entry;
bool Added;
std::tie(Entry, Added) =
VBTablesMap.insert(std::make_pair(RD, VBTableGlobals()));
VBTableGlobals &VBGlobals = Entry->second;
if (!Added)
return VBGlobals;
MicrosoftVTableContext &Context = CGM.getMicrosoftVTableContext();
VBGlobals.VBTables = &Context.enumerateVBTables(RD);
llvm::GlobalVariable::LinkageTypes Linkage = CGM.getVTableLinkage(RD);
for (VPtrInfoVector::const_iterator I = VBGlobals.VBTables->begin(),
E = VBGlobals.VBTables->end();
I != E; ++I) {
VBGlobals.Globals.push_back(getAddrOfVBTable(**I, RD, Linkage));
}
return VBGlobals;
}
llvm::Function *
MicrosoftCXXABI::EmitVirtualMemPtrThunk(const CXXMethodDecl *MD,
const MethodVFTableLocation &ML) {
assert(!isa<CXXConstructorDecl>(MD) && !isa<CXXDestructorDecl>(MD) &&
"can't form pointers to ctors or virtual dtors");
SmallString<256> ThunkName;
llvm::raw_svector_ostream Out(ThunkName);
getMangleContext().mangleVirtualMemPtrThunk(MD, ML, Out);
if (llvm::GlobalValue *GV = CGM.getModule().getNamedValue(ThunkName))
return cast<llvm::Function>(GV);
const CGFunctionInfo &FnInfo =
CGM.getTypes().arrangeUnprototypedMustTailThunk(MD);
llvm::FunctionType *ThunkTy = CGM.getTypes().GetFunctionType(FnInfo);
llvm::Function *ThunkFn =
llvm::Function::Create(ThunkTy, llvm::Function::ExternalLinkage,
ThunkName.str(), &CGM.getModule());
assert(ThunkFn->getName() == ThunkName && "name was uniqued!");
ThunkFn->setLinkage(MD->isExternallyVisible()
? llvm::GlobalValue::LinkOnceODRLinkage
: llvm::GlobalValue::InternalLinkage);
if (MD->isExternallyVisible())
ThunkFn->setComdat(CGM.getModule().getOrInsertComdat(ThunkFn->getName()));
CGM.SetLLVMFunctionAttributes(MD, FnInfo, ThunkFn, false);
CGM.SetLLVMFunctionAttributesForDefinition(MD, ThunkFn);
ThunkFn->addFnAttr("thunk");
ThunkFn->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::None);
CodeGenFunction CGF(CGM);
CGF.CurGD = GlobalDecl(MD);
CGF.CurFuncIsThunk = true;
FunctionArgList FunctionArgs;
buildThisParam(CGF, FunctionArgs);
CGF.StartFunction(GlobalDecl(), FnInfo.getReturnType(), ThunkFn, FnInfo,
FunctionArgs, MD->getLocation(), SourceLocation());
setCXXABIThisValue(CGF, loadIncomingCXXThis(CGF));
llvm::Type *ThunkPtrTy = ThunkTy->getPointerTo();
llvm::Value *VTable = CGF.GetVTablePtr(
getThisAddress(CGF), ThunkPtrTy->getPointerTo(), MD->getParent());
llvm::Value *VFuncPtr = CGF.Builder.CreateConstInBoundsGEP1_64(
ThunkPtrTy, VTable, ML.Index, "vfn");
llvm::Value *Callee =
CGF.Builder.CreateAlignedLoad(ThunkPtrTy, VFuncPtr, CGF.getPointerAlign());
CGF.EmitMustTailThunk(MD, getThisValue(CGF), {ThunkTy, Callee});
return ThunkFn;
}
void MicrosoftCXXABI::emitVirtualInheritanceTables(const CXXRecordDecl *RD) {
const VBTableGlobals &VBGlobals = enumerateVBTables(RD);
for (unsigned I = 0, E = VBGlobals.VBTables->size(); I != E; ++I) {
const std::unique_ptr<VPtrInfo>& VBT = (*VBGlobals.VBTables)[I];
llvm::GlobalVariable *GV = VBGlobals.Globals[I];
if (GV->isDeclaration())
emitVBTableDefinition(*VBT, RD, GV);
}
}
llvm::GlobalVariable *
MicrosoftCXXABI::getAddrOfVBTable(const VPtrInfo &VBT, const CXXRecordDecl *RD,
llvm::GlobalVariable::LinkageTypes Linkage) {
SmallString<256> OutName;
llvm::raw_svector_ostream Out(OutName);
getMangleContext().mangleCXXVBTable(RD, VBT.MangledPath, Out);
StringRef Name = OutName.str();
llvm::ArrayType *VBTableType =
llvm::ArrayType::get(CGM.IntTy, 1 + VBT.ObjectWithVPtr->getNumVBases());
assert(!CGM.getModule().getNamedGlobal(Name) &&
"vbtable with this name already exists: mangling bug?");
CharUnits Alignment =
CGM.getContext().getTypeAlignInChars(CGM.getContext().IntTy);
llvm::GlobalVariable *GV = CGM.CreateOrReplaceCXXRuntimeVariable(
Name, VBTableType, Linkage, Alignment.getQuantity());
GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
if (RD->hasAttr<DLLImportAttr>())
GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
else if (RD->hasAttr<DLLExportAttr>())
GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
if (!GV->hasExternalLinkage())
emitVBTableDefinition(VBT, RD, GV);
return GV;
}
void MicrosoftCXXABI::emitVBTableDefinition(const VPtrInfo &VBT,
const CXXRecordDecl *RD,
llvm::GlobalVariable *GV) const {
const CXXRecordDecl *ObjectWithVPtr = VBT.ObjectWithVPtr;
assert(RD->getNumVBases() && ObjectWithVPtr->getNumVBases() &&
"should only emit vbtables for classes with vbtables");
const ASTRecordLayout &BaseLayout =
getContext().getASTRecordLayout(VBT.IntroducingObject);
const ASTRecordLayout &DerivedLayout = getContext().getASTRecordLayout(RD);
SmallVector<llvm::Constant *, 4> Offsets(1 + ObjectWithVPtr->getNumVBases(),
nullptr);
CharUnits VBPtrOffset = BaseLayout.getVBPtrOffset();
Offsets[0] = llvm::ConstantInt::get(CGM.IntTy, -VBPtrOffset.getQuantity());
MicrosoftVTableContext &Context = CGM.getMicrosoftVTableContext();
for (const auto &I : ObjectWithVPtr->vbases()) {
const CXXRecordDecl *VBase = I.getType()->getAsCXXRecordDecl();
CharUnits Offset = DerivedLayout.getVBaseClassOffset(VBase);
assert(!Offset.isNegative());
CharUnits CompleteVBPtrOffset = VBT.NonVirtualOffset + VBPtrOffset;
if (VBT.getVBaseWithVPtr())
CompleteVBPtrOffset +=
DerivedLayout.getVBaseClassOffset(VBT.getVBaseWithVPtr());
Offset -= CompleteVBPtrOffset;
unsigned VBIndex = Context.getVBTableIndex(ObjectWithVPtr, VBase);
assert(Offsets[VBIndex] == nullptr && "The same vbindex seen twice?");
Offsets[VBIndex] = llvm::ConstantInt::get(CGM.IntTy, Offset.getQuantity());
}
assert(Offsets.size() ==
cast<llvm::ArrayType>(GV->getValueType())->getNumElements());
llvm::ArrayType *VBTableType =
llvm::ArrayType::get(CGM.IntTy, Offsets.size());
llvm::Constant *Init = llvm::ConstantArray::get(VBTableType, Offsets);
GV->setInitializer(Init);
if (RD->hasAttr<DLLImportAttr>())
GV->setLinkage(llvm::GlobalVariable::AvailableExternallyLinkage);
}
llvm::Value *MicrosoftCXXABI::performThisAdjustment(CodeGenFunction &CGF,
Address This,
const ThisAdjustment &TA) {
if (TA.isEmpty())
return This.getPointer();
This = CGF.Builder.CreateElementBitCast(This, CGF.Int8Ty);
llvm::Value *V;
if (TA.Virtual.isEmpty()) {
V = This.getPointer();
} else {
assert(TA.Virtual.Microsoft.VtordispOffset < 0);
Address VtorDispPtr =
CGF.Builder.CreateConstInBoundsByteGEP(This,
CharUnits::fromQuantity(TA.Virtual.Microsoft.VtordispOffset));
VtorDispPtr = CGF.Builder.CreateElementBitCast(VtorDispPtr, CGF.Int32Ty);
llvm::Value *VtorDisp = CGF.Builder.CreateLoad(VtorDispPtr, "vtordisp");
V = CGF.Builder.CreateGEP(This.getElementType(), This.getPointer(),
CGF.Builder.CreateNeg(VtorDisp));
if (TA.Virtual.Microsoft.VBPtrOffset) {
assert(TA.Virtual.Microsoft.VBPtrOffset > 0);
assert(TA.Virtual.Microsoft.VBOffsetOffset >= 0);
llvm::Value *VBPtr;
llvm::Value *VBaseOffset = GetVBaseOffsetFromVBPtr(
CGF, Address(V, CGF.Int8Ty, CGF.getPointerAlign()),
-TA.Virtual.Microsoft.VBPtrOffset,
TA.Virtual.Microsoft.VBOffsetOffset, &VBPtr);
V = CGF.Builder.CreateInBoundsGEP(CGF.Int8Ty, VBPtr, VBaseOffset);
}
}
if (TA.NonVirtual) {
V = CGF.Builder.CreateConstGEP1_32(CGF.Int8Ty, V, TA.NonVirtual);
}
return V;
}
llvm::Value *
MicrosoftCXXABI::performReturnAdjustment(CodeGenFunction &CGF, Address Ret,
const ReturnAdjustment &RA) {
if (RA.isEmpty())
return Ret.getPointer();
auto OrigTy = Ret.getType();
Ret = CGF.Builder.CreateElementBitCast(Ret, CGF.Int8Ty);
llvm::Value *V = Ret.getPointer();
if (RA.Virtual.Microsoft.VBIndex) {
assert(RA.Virtual.Microsoft.VBIndex > 0);
int32_t IntSize = CGF.getIntSize().getQuantity();
llvm::Value *VBPtr;
llvm::Value *VBaseOffset =
GetVBaseOffsetFromVBPtr(CGF, Ret, RA.Virtual.Microsoft.VBPtrOffset,
IntSize * RA.Virtual.Microsoft.VBIndex, &VBPtr);
V = CGF.Builder.CreateInBoundsGEP(CGF.Int8Ty, VBPtr, VBaseOffset);
}
if (RA.NonVirtual)
V = CGF.Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, V, RA.NonVirtual);
return CGF.Builder.CreateBitCast(V, OrigTy);
}
bool MicrosoftCXXABI::requiresArrayCookie(const CXXDeleteExpr *expr,
QualType elementType) {
return elementType.isDestructedType();
}
bool MicrosoftCXXABI::requiresArrayCookie(const CXXNewExpr *expr) {
return expr->getAllocatedType().isDestructedType();
}
CharUnits MicrosoftCXXABI::getArrayCookieSizeImpl(QualType type) {
ASTContext &Ctx = getContext();
return std::max(Ctx.getTypeSizeInChars(Ctx.getSizeType()),
Ctx.getTypeAlignInChars(type));
}
llvm::Value *MicrosoftCXXABI::readArrayCookieImpl(CodeGenFunction &CGF,
Address allocPtr,
CharUnits cookieSize) {
Address numElementsPtr =
CGF.Builder.CreateElementBitCast(allocPtr, CGF.SizeTy);
return CGF.Builder.CreateLoad(numElementsPtr);
}
Address MicrosoftCXXABI::InitializeArrayCookie(CodeGenFunction &CGF,
Address newPtr,
llvm::Value *numElements,
const CXXNewExpr *expr,
QualType elementType) {
assert(requiresArrayCookie(expr));
CharUnits cookieSize = getArrayCookieSizeImpl(elementType);
Address cookiePtr = newPtr;
Address numElementsPtr
= CGF.Builder.CreateElementBitCast(cookiePtr, CGF.SizeTy);
CGF.Builder.CreateStore(numElements, numElementsPtr);
return CGF.Builder.CreateConstInBoundsByteGEP(newPtr, cookieSize);
}
static void emitGlobalDtorWithTLRegDtor(CodeGenFunction &CGF, const VarDecl &VD,
llvm::FunctionCallee Dtor,
llvm::Constant *Addr) {
llvm::Constant *DtorStub = CGF.createAtExitStub(VD, Dtor, Addr);
llvm::FunctionType *TLRegDtorTy = llvm::FunctionType::get(
CGF.IntTy, DtorStub->getType(), false);
llvm::FunctionCallee TLRegDtor = CGF.CGM.CreateRuntimeFunction(
TLRegDtorTy, "__tlregdtor", llvm::AttributeList(), true);
if (llvm::Function *TLRegDtorFn =
dyn_cast<llvm::Function>(TLRegDtor.getCallee()))
TLRegDtorFn->setDoesNotThrow();
CGF.EmitNounwindRuntimeCall(TLRegDtor, DtorStub);
}
void MicrosoftCXXABI::registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
llvm::FunctionCallee Dtor,
llvm::Constant *Addr) {
if (D.isNoDestroy(CGM.getContext()))
return;
if (D.getTLSKind())
return emitGlobalDtorWithTLRegDtor(CGF, D, Dtor, Addr);
CGF.registerGlobalDtorWithAtExit(D, Dtor, Addr);
}
void MicrosoftCXXABI::EmitThreadLocalInitFuncs(
CodeGenModule &CGM, ArrayRef<const VarDecl *> CXXThreadLocals,
ArrayRef<llvm::Function *> CXXThreadLocalInits,
ArrayRef<const VarDecl *> CXXThreadLocalInitVars) {
if (CXXThreadLocalInits.empty())
return;
CGM.AppendLinkerOptions(CGM.getTarget().getTriple().getArch() ==
llvm::Triple::x86
? "/include:___dyn_tls_init@12"
: "/include:__dyn_tls_init");
auto AddToXDU = [&CGM](llvm::Function *InitFunc) {
llvm::GlobalVariable *InitFuncPtr = new llvm::GlobalVariable(
CGM.getModule(), InitFunc->getType(), true,
llvm::GlobalVariable::InternalLinkage, InitFunc,
Twine(InitFunc->getName(), "$initializer$"));
InitFuncPtr->setSection(".CRT$XDU");
CGM.addUsedGlobal(InitFuncPtr);
return InitFuncPtr;
};
std::vector<llvm::Function *> NonComdatInits;
for (size_t I = 0, E = CXXThreadLocalInitVars.size(); I != E; ++I) {
llvm::GlobalVariable *GV = cast<llvm::GlobalVariable>(
CGM.GetGlobalValue(CGM.getMangledName(CXXThreadLocalInitVars[I])));
llvm::Function *F = CXXThreadLocalInits[I];
if (llvm::Comdat *C = GV->getComdat())
AddToXDU(F)->setComdat(C);
else
NonComdatInits.push_back(F);
}
if (!NonComdatInits.empty()) {
llvm::FunctionType *FTy =
llvm::FunctionType::get(CGM.VoidTy, false);
llvm::Function *InitFunc = CGM.CreateGlobalInitOrCleanUpFunction(
FTy, "__tls_init", CGM.getTypes().arrangeNullaryFunction(),
SourceLocation(), true);
CodeGenFunction(CGM).GenerateCXXGlobalInitFunc(InitFunc, NonComdatInits);
AddToXDU(InitFunc);
}
}
static llvm::GlobalValue *getTlsGuardVar(CodeGenModule &CGM) {
llvm::Type *VTy = llvm::Type::getInt8Ty(CGM.getLLVMContext());
llvm::Constant *TlsGuardConstant =
CGM.CreateRuntimeVariable(VTy, "__tls_guard");
llvm::GlobalValue *TlsGuard = cast<llvm::GlobalValue>(TlsGuardConstant);
TlsGuard->setThreadLocal(true);
return TlsGuard;
}
static llvm::FunctionCallee getDynTlsOnDemandInitFn(CodeGenModule &CGM) {
llvm::FunctionType *FTy =
llvm::FunctionType::get(llvm::Type::getVoidTy(CGM.getLLVMContext()), {},
false);
return CGM.CreateRuntimeFunction(
FTy, "__dyn_tls_on_demand_init",
llvm::AttributeList::get(CGM.getLLVMContext(),
llvm::AttributeList::FunctionIndex,
llvm::Attribute::NoUnwind),
true);
}
static void emitTlsGuardCheck(CodeGenFunction &CGF, llvm::GlobalValue *TlsGuard,
llvm::BasicBlock *DynInitBB,
llvm::BasicBlock *ContinueBB) {
llvm::LoadInst *TlsGuardValue =
CGF.Builder.CreateLoad(Address(TlsGuard, CGF.Int8Ty, CharUnits::One()));
llvm::Value *CmpResult =
CGF.Builder.CreateICmpEQ(TlsGuardValue, CGF.Builder.getInt8(0));
CGF.Builder.CreateCondBr(CmpResult, DynInitBB, ContinueBB);
}
static void emitDynamicTlsInitializationCall(CodeGenFunction &CGF,
llvm::GlobalValue *TlsGuard,
llvm::BasicBlock *ContinueBB) {
llvm::FunctionCallee Initializer = getDynTlsOnDemandInitFn(CGF.CGM);
llvm::Function *InitializerFunction =
cast<llvm::Function>(Initializer.getCallee());
llvm::CallInst *CallVal = CGF.Builder.CreateCall(InitializerFunction);
CallVal->setCallingConv(InitializerFunction->getCallingConv());
CGF.Builder.CreateBr(ContinueBB);
}
static void emitDynamicTlsInitialization(CodeGenFunction &CGF) {
llvm::BasicBlock *DynInitBB =
CGF.createBasicBlock("dyntls.dyn_init", CGF.CurFn);
llvm::BasicBlock *ContinueBB =
CGF.createBasicBlock("dyntls.continue", CGF.CurFn);
llvm::GlobalValue *TlsGuard = getTlsGuardVar(CGF.CGM);
emitTlsGuardCheck(CGF, TlsGuard, DynInitBB, ContinueBB);
CGF.Builder.SetInsertPoint(DynInitBB);
emitDynamicTlsInitializationCall(CGF, TlsGuard, ContinueBB);
CGF.Builder.SetInsertPoint(ContinueBB);
}
LValue MicrosoftCXXABI::EmitThreadLocalVarDeclLValue(CodeGenFunction &CGF,
const VarDecl *VD,
QualType LValType) {
emitDynamicTlsInitialization(CGF);
llvm::Value *V = CGF.CGM.GetAddrOfGlobalVar(VD);
llvm::Type *RealVarTy = CGF.getTypes().ConvertTypeForMem(VD->getType());
unsigned AS = cast<llvm::PointerType>(V->getType())->getAddressSpace();
V = CGF.Builder.CreateBitCast(V, RealVarTy->getPointerTo(AS));
CharUnits Alignment = CGF.getContext().getDeclAlign(VD);
Address Addr(V, RealVarTy, Alignment);
LValue LV = VD->getType()->isReferenceType()
? CGF.EmitLoadOfReferenceLValue(Addr, VD->getType(),
AlignmentSource::Decl)
: CGF.MakeAddrLValue(Addr, LValType, AlignmentSource::Decl);
return LV;
}
static ConstantAddress getInitThreadEpochPtr(CodeGenModule &CGM) {
StringRef VarName("_Init_thread_epoch");
CharUnits Align = CGM.getIntAlign();
if (auto *GV = CGM.getModule().getNamedGlobal(VarName))
return ConstantAddress(GV, GV->getValueType(), Align);
auto *GV = new llvm::GlobalVariable(
CGM.getModule(), CGM.IntTy,
false, llvm::GlobalVariable::ExternalLinkage,
nullptr, VarName,
nullptr, llvm::GlobalVariable::GeneralDynamicTLSModel);
GV->setAlignment(Align.getAsAlign());
return ConstantAddress(GV, GV->getValueType(), Align);
}
static llvm::FunctionCallee getInitThreadHeaderFn(CodeGenModule &CGM) {
llvm::FunctionType *FTy =
llvm::FunctionType::get(llvm::Type::getVoidTy(CGM.getLLVMContext()),
CGM.IntTy->getPointerTo(), false);
return CGM.CreateRuntimeFunction(
FTy, "_Init_thread_header",
llvm::AttributeList::get(CGM.getLLVMContext(),
llvm::AttributeList::FunctionIndex,
llvm::Attribute::NoUnwind),
true);
}
static llvm::FunctionCallee getInitThreadFooterFn(CodeGenModule &CGM) {
llvm::FunctionType *FTy =
llvm::FunctionType::get(llvm::Type::getVoidTy(CGM.getLLVMContext()),
CGM.IntTy->getPointerTo(), false);
return CGM.CreateRuntimeFunction(
FTy, "_Init_thread_footer",
llvm::AttributeList::get(CGM.getLLVMContext(),
llvm::AttributeList::FunctionIndex,
llvm::Attribute::NoUnwind),
true);
}
static llvm::FunctionCallee getInitThreadAbortFn(CodeGenModule &CGM) {
llvm::FunctionType *FTy =
llvm::FunctionType::get(llvm::Type::getVoidTy(CGM.getLLVMContext()),
CGM.IntTy->getPointerTo(), false);
return CGM.CreateRuntimeFunction(
FTy, "_Init_thread_abort",
llvm::AttributeList::get(CGM.getLLVMContext(),
llvm::AttributeList::FunctionIndex,
llvm::Attribute::NoUnwind),
true);
}
namespace {
struct ResetGuardBit final : EHScopeStack::Cleanup {
Address Guard;
unsigned GuardNum;
ResetGuardBit(Address Guard, unsigned GuardNum)
: Guard(Guard), GuardNum(GuardNum) {}
void Emit(CodeGenFunction &CGF, Flags flags) override {
CGBuilderTy &Builder = CGF.Builder;
llvm::LoadInst *LI = Builder.CreateLoad(Guard);
llvm::ConstantInt *Mask =
llvm::ConstantInt::get(CGF.IntTy, ~(1ULL << GuardNum));
Builder.CreateStore(Builder.CreateAnd(LI, Mask), Guard);
}
};
struct CallInitThreadAbort final : EHScopeStack::Cleanup {
llvm::Value *Guard;
CallInitThreadAbort(Address Guard) : Guard(Guard.getPointer()) {}
void Emit(CodeGenFunction &CGF, Flags flags) override {
CGF.EmitNounwindRuntimeCall(getInitThreadAbortFn(CGF.CGM), Guard);
}
};
}
void MicrosoftCXXABI::EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
llvm::GlobalVariable *GV,
bool PerformInit) {
if (!D.isStaticLocal()) {
assert(GV->hasWeakLinkage() || GV->hasLinkOnceLinkage());
llvm::Function *F = CGF.CurFn;
F->setLinkage(llvm::GlobalValue::LinkOnceODRLinkage);
F->setComdat(CGM.getModule().getOrInsertComdat(F->getName()));
CGF.EmitCXXGlobalVarDeclInit(D, GV, PerformInit);
return;
}
bool ThreadlocalStatic = D.getTLSKind();
bool ThreadsafeStatic = getContext().getLangOpts().ThreadsafeStatics;
bool HasPerVariableGuard = ThreadsafeStatic && !ThreadlocalStatic;
CGBuilderTy &Builder = CGF.Builder;
llvm::IntegerType *GuardTy = CGF.Int32Ty;
llvm::ConstantInt *Zero = llvm::ConstantInt::get(GuardTy, 0);
CharUnits GuardAlign = CharUnits::fromQuantity(4);
GuardInfo *GI = nullptr;
if (ThreadlocalStatic)
GI = &ThreadLocalGuardVariableMap[D.getDeclContext()];
else if (!ThreadsafeStatic)
GI = &GuardVariableMap[D.getDeclContext()];
llvm::GlobalVariable *GuardVar = GI ? GI->Guard : nullptr;
unsigned GuardNum;
if (D.isExternallyVisible()) {
GuardNum = getContext().getStaticLocalNumber(&D);
assert(GuardNum > 0);
GuardNum--;
} else if (HasPerVariableGuard) {
GuardNum = ThreadSafeGuardNumMap[D.getDeclContext()]++;
} else {
GuardNum = GI->BitIndex++;
}
if (!HasPerVariableGuard && GuardNum >= 32) {
if (D.isExternallyVisible())
ErrorUnsupportedABI(CGF, "more than 32 guarded initializations");
GuardNum %= 32;
GuardVar = nullptr;
}
if (!GuardVar) {
SmallString<256> GuardName;
{
llvm::raw_svector_ostream Out(GuardName);
if (HasPerVariableGuard)
getMangleContext().mangleThreadSafeStaticGuardVariable(&D, GuardNum,
Out);
else
getMangleContext().mangleStaticGuardVariable(&D, Out);
}
GuardVar =
new llvm::GlobalVariable(CGM.getModule(), GuardTy, false,
GV->getLinkage(), Zero, GuardName.str());
GuardVar->setVisibility(GV->getVisibility());
GuardVar->setDLLStorageClass(GV->getDLLStorageClass());
GuardVar->setAlignment(GuardAlign.getAsAlign());
if (GuardVar->isWeakForLinker())
GuardVar->setComdat(
CGM.getModule().getOrInsertComdat(GuardVar->getName()));
if (D.getTLSKind())
CGM.setTLSMode(GuardVar, D);
if (GI && !HasPerVariableGuard)
GI->Guard = GuardVar;
}
ConstantAddress GuardAddr(GuardVar, GuardTy, GuardAlign);
assert(GuardVar->getLinkage() == GV->getLinkage() &&
"static local from the same function had different linkage");
if (!HasPerVariableGuard) {
llvm::ConstantInt *Bit = llvm::ConstantInt::get(GuardTy, 1ULL << GuardNum);
llvm::LoadInst *LI = Builder.CreateLoad(GuardAddr);
llvm::Value *NeedsInit =
Builder.CreateICmpEQ(Builder.CreateAnd(LI, Bit), Zero);
llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
CGF.EmitCXXGuardedInitBranch(NeedsInit, InitBlock, EndBlock,
CodeGenFunction::GuardKind::VariableGuard, &D);
CGF.EmitBlock(InitBlock);
Builder.CreateStore(Builder.CreateOr(LI, Bit), GuardAddr);
CGF.EHStack.pushCleanup<ResetGuardBit>(EHCleanup, GuardAddr, GuardNum);
CGF.EmitCXXGlobalVarDeclInit(D, GV, PerformInit);
CGF.PopCleanupBlock();
Builder.CreateBr(EndBlock);
CGF.EmitBlock(EndBlock);
} else {
llvm::LoadInst *FirstGuardLoad = Builder.CreateLoad(GuardAddr);
FirstGuardLoad->setOrdering(llvm::AtomicOrdering::Unordered);
llvm::LoadInst *InitThreadEpoch =
Builder.CreateLoad(getInitThreadEpochPtr(CGM));
llvm::Value *IsUninitialized =
Builder.CreateICmpSGT(FirstGuardLoad, InitThreadEpoch);
llvm::BasicBlock *AttemptInitBlock = CGF.createBasicBlock("init.attempt");
llvm::BasicBlock *EndBlock = CGF.createBasicBlock("init.end");
CGF.EmitCXXGuardedInitBranch(IsUninitialized, AttemptInitBlock, EndBlock,
CodeGenFunction::GuardKind::VariableGuard, &D);
CGF.EmitBlock(AttemptInitBlock);
CGF.EmitNounwindRuntimeCall(getInitThreadHeaderFn(CGM),
GuardAddr.getPointer());
llvm::LoadInst *SecondGuardLoad = Builder.CreateLoad(GuardAddr);
SecondGuardLoad->setOrdering(llvm::AtomicOrdering::Unordered);
llvm::Value *ShouldDoInit =
Builder.CreateICmpEQ(SecondGuardLoad, getAllOnesInt());
llvm::BasicBlock *InitBlock = CGF.createBasicBlock("init");
Builder.CreateCondBr(ShouldDoInit, InitBlock, EndBlock);
CGF.EmitBlock(InitBlock);
CGF.EHStack.pushCleanup<CallInitThreadAbort>(EHCleanup, GuardAddr);
CGF.EmitCXXGlobalVarDeclInit(D, GV, PerformInit);
CGF.PopCleanupBlock();
CGF.EmitNounwindRuntimeCall(getInitThreadFooterFn(CGM),
GuardAddr.getPointer());
Builder.CreateBr(EndBlock);
CGF.EmitBlock(EndBlock);
}
}
bool MicrosoftCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
if (MPT->isMemberFunctionPointer())
return true;
const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
return (!inheritanceModelHasVBTableOffsetField(Inheritance) &&
RD->nullFieldOffsetIsZero());
}
llvm::Type *
MicrosoftCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
llvm::SmallVector<llvm::Type *, 4> fields;
if (MPT->isMemberFunctionPointer())
fields.push_back(CGM.VoidPtrTy); else
fields.push_back(CGM.IntTy);
if (inheritanceModelHasNVOffsetField(MPT->isMemberFunctionPointer(),
Inheritance))
fields.push_back(CGM.IntTy);
if (inheritanceModelHasVBPtrOffsetField(Inheritance))
fields.push_back(CGM.IntTy);
if (inheritanceModelHasVBTableOffsetField(Inheritance))
fields.push_back(CGM.IntTy);
if (fields.size() == 1)
return fields[0];
return llvm::StructType::get(CGM.getLLVMContext(), fields);
}
void MicrosoftCXXABI::
GetNullMemberPointerFields(const MemberPointerType *MPT,
llvm::SmallVectorImpl<llvm::Constant *> &fields) {
assert(fields.empty());
const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
if (MPT->isMemberFunctionPointer()) {
fields.push_back(llvm::Constant::getNullValue(CGM.VoidPtrTy));
} else {
if (RD->nullFieldOffsetIsZero())
fields.push_back(getZeroInt()); else
fields.push_back(getAllOnesInt()); }
if (inheritanceModelHasNVOffsetField(MPT->isMemberFunctionPointer(),
Inheritance))
fields.push_back(getZeroInt());
if (inheritanceModelHasVBPtrOffsetField(Inheritance))
fields.push_back(getZeroInt());
if (inheritanceModelHasVBTableOffsetField(Inheritance))
fields.push_back(getAllOnesInt());
}
llvm::Constant *
MicrosoftCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
llvm::SmallVector<llvm::Constant *, 4> fields;
GetNullMemberPointerFields(MPT, fields);
if (fields.size() == 1)
return fields[0];
llvm::Constant *Res = llvm::ConstantStruct::getAnon(fields);
assert(Res->getType() == ConvertMemberPointerType(MPT));
return Res;
}
llvm::Constant *
MicrosoftCXXABI::EmitFullMemberPointer(llvm::Constant *FirstField,
bool IsMemberFunction,
const CXXRecordDecl *RD,
CharUnits NonVirtualBaseAdjustment,
unsigned VBTableIndex) {
MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
if (inheritanceModelHasOnlyOneField(IsMemberFunction, Inheritance))
return FirstField;
llvm::SmallVector<llvm::Constant *, 4> fields;
fields.push_back(FirstField);
if (inheritanceModelHasNVOffsetField(IsMemberFunction, Inheritance))
fields.push_back(llvm::ConstantInt::get(
CGM.IntTy, NonVirtualBaseAdjustment.getQuantity()));
if (inheritanceModelHasVBPtrOffsetField(Inheritance)) {
CharUnits Offs = CharUnits::Zero();
if (VBTableIndex)
Offs = getContext().getASTRecordLayout(RD).getVBPtrOffset();
fields.push_back(llvm::ConstantInt::get(CGM.IntTy, Offs.getQuantity()));
}
if (inheritanceModelHasVBTableOffsetField(Inheritance))
fields.push_back(llvm::ConstantInt::get(CGM.IntTy, VBTableIndex));
return llvm::ConstantStruct::getAnon(fields);
}
llvm::Constant *
MicrosoftCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
CharUnits offset) {
return EmitMemberDataPointer(MPT->getMostRecentCXXRecordDecl(), offset);
}
llvm::Constant *MicrosoftCXXABI::EmitMemberDataPointer(const CXXRecordDecl *RD,
CharUnits offset) {
if (RD->getMSInheritanceModel() ==
MSInheritanceModel::Virtual)
offset -= getContext().getOffsetOfBaseWithVBPtr(RD);
llvm::Constant *FirstField =
llvm::ConstantInt::get(CGM.IntTy, offset.getQuantity());
return EmitFullMemberPointer(FirstField, false, RD,
CharUnits::Zero(), 0);
}
llvm::Constant *MicrosoftCXXABI::EmitMemberPointer(const APValue &MP,
QualType MPType) {
const MemberPointerType *DstTy = MPType->castAs<MemberPointerType>();
const ValueDecl *MPD = MP.getMemberPointerDecl();
if (!MPD)
return EmitNullMemberPointer(DstTy);
ASTContext &Ctx = getContext();
ArrayRef<const CXXRecordDecl *> MemberPointerPath = MP.getMemberPointerPath();
llvm::Constant *C;
if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MPD)) {
C = EmitMemberFunctionPointer(MD);
} else {
CharUnits FieldOffset = Ctx.toCharUnitsFromBits(Ctx.getFieldOffset(MPD));
const FieldDecl *FD = dyn_cast<FieldDecl>(MPD);
if (!FD)
FD = cast<FieldDecl>(*cast<IndirectFieldDecl>(MPD)->chain_begin());
const CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getParent());
RD = RD->getMostRecentNonInjectedDecl();
C = EmitMemberDataPointer(RD, FieldOffset);
}
if (!MemberPointerPath.empty()) {
const CXXRecordDecl *SrcRD = cast<CXXRecordDecl>(MPD->getDeclContext());
const Type *SrcRecTy = Ctx.getTypeDeclType(SrcRD).getTypePtr();
const MemberPointerType *SrcTy =
Ctx.getMemberPointerType(DstTy->getPointeeType(), SrcRecTy)
->castAs<MemberPointerType>();
bool DerivedMember = MP.isMemberPointerToDerivedMember();
SmallVector<const CXXBaseSpecifier *, 4> DerivedToBasePath;
const CXXRecordDecl *PrevRD = SrcRD;
for (const CXXRecordDecl *PathElem : MemberPointerPath) {
const CXXRecordDecl *Base = nullptr;
const CXXRecordDecl *Derived = nullptr;
if (DerivedMember) {
Base = PathElem;
Derived = PrevRD;
} else {
Base = PrevRD;
Derived = PathElem;
}
for (const CXXBaseSpecifier &BS : Derived->bases())
if (BS.getType()->getAsCXXRecordDecl()->getCanonicalDecl() ==
Base->getCanonicalDecl())
DerivedToBasePath.push_back(&BS);
PrevRD = PathElem;
}
assert(DerivedToBasePath.size() == MemberPointerPath.size());
CastKind CK = DerivedMember ? CK_DerivedToBaseMemberPointer
: CK_BaseToDerivedMemberPointer;
C = EmitMemberPointerConversion(SrcTy, DstTy, CK, DerivedToBasePath.begin(),
DerivedToBasePath.end(), C);
}
return C;
}
llvm::Constant *
MicrosoftCXXABI::EmitMemberFunctionPointer(const CXXMethodDecl *MD) {
assert(MD->isInstance() && "Member function must not be static!");
CharUnits NonVirtualBaseAdjustment = CharUnits::Zero();
const CXXRecordDecl *RD = MD->getParent()->getMostRecentNonInjectedDecl();
CodeGenTypes &Types = CGM.getTypes();
unsigned VBTableIndex = 0;
llvm::Constant *FirstField;
const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
if (!MD->isVirtual()) {
llvm::Type *Ty;
if (Types.isFuncTypeConvertible(FPT)) {
Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
} else {
Ty = CGM.PtrDiffTy;
}
FirstField = CGM.GetAddrOfFunction(MD, Ty);
} else {
auto &VTableContext = CGM.getMicrosoftVTableContext();
MethodVFTableLocation ML = VTableContext.getMethodVFTableLocation(MD);
FirstField = EmitVirtualMemPtrThunk(MD, ML);
NonVirtualBaseAdjustment += ML.VFPtrOffset;
if (ML.VBase)
VBTableIndex = VTableContext.getVBTableIndex(RD, ML.VBase) * 4;
}
if (VBTableIndex == 0 &&
RD->getMSInheritanceModel() ==
MSInheritanceModel::Virtual)
NonVirtualBaseAdjustment -= getContext().getOffsetOfBaseWithVBPtr(RD);
FirstField = llvm::ConstantExpr::getBitCast(FirstField, CGM.VoidPtrTy);
return EmitFullMemberPointer(FirstField, true, RD,
NonVirtualBaseAdjustment, VBTableIndex);
}
llvm::Value *
MicrosoftCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
llvm::Value *L,
llvm::Value *R,
const MemberPointerType *MPT,
bool Inequality) {
CGBuilderTy &Builder = CGF.Builder;
llvm::ICmpInst::Predicate Eq;
llvm::Instruction::BinaryOps And, Or;
if (Inequality) {
Eq = llvm::ICmpInst::ICMP_NE;
And = llvm::Instruction::Or;
Or = llvm::Instruction::And;
} else {
Eq = llvm::ICmpInst::ICMP_EQ;
And = llvm::Instruction::And;
Or = llvm::Instruction::Or;
}
const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
if (inheritanceModelHasOnlyOneField(MPT->isMemberFunctionPointer(),
Inheritance))
return Builder.CreateICmp(Eq, L, R);
llvm::Value *L0 = Builder.CreateExtractValue(L, 0, "lhs.0");
llvm::Value *R0 = Builder.CreateExtractValue(R, 0, "rhs.0");
llvm::Value *Cmp0 = Builder.CreateICmp(Eq, L0, R0, "memptr.cmp.first");
llvm::Value *Res = nullptr;
llvm::StructType *LType = cast<llvm::StructType>(L->getType());
for (unsigned I = 1, E = LType->getNumElements(); I != E; ++I) {
llvm::Value *LF = Builder.CreateExtractValue(L, I);
llvm::Value *RF = Builder.CreateExtractValue(R, I);
llvm::Value *Cmp = Builder.CreateICmp(Eq, LF, RF, "memptr.cmp.rest");
if (Res)
Res = Builder.CreateBinOp(And, Res, Cmp);
else
Res = Cmp;
}
if (MPT->isMemberFunctionPointer()) {
llvm::Value *Zero = llvm::Constant::getNullValue(L0->getType());
llvm::Value *IsZero = Builder.CreateICmp(Eq, L0, Zero, "memptr.cmp.iszero");
Res = Builder.CreateBinOp(Or, Res, IsZero);
}
return Builder.CreateBinOp(And, Res, Cmp0, "memptr.cmp");
}
llvm::Value *
MicrosoftCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
llvm::Value *MemPtr,
const MemberPointerType *MPT) {
CGBuilderTy &Builder = CGF.Builder;
llvm::SmallVector<llvm::Constant *, 4> fields;
if (MPT->isMemberFunctionPointer())
fields.push_back(llvm::Constant::getNullValue(CGM.VoidPtrTy));
else
GetNullMemberPointerFields(MPT, fields);
assert(!fields.empty());
llvm::Value *FirstField = MemPtr;
if (MemPtr->getType()->isStructTy())
FirstField = Builder.CreateExtractValue(MemPtr, 0);
llvm::Value *Res = Builder.CreateICmpNE(FirstField, fields[0], "memptr.cmp0");
if (MPT->isMemberFunctionPointer())
return Res;
for (int I = 1, E = fields.size(); I < E; ++I) {
llvm::Value *Field = Builder.CreateExtractValue(MemPtr, I);
llvm::Value *Next = Builder.CreateICmpNE(Field, fields[I], "memptr.cmp");
Res = Builder.CreateOr(Res, Next, "memptr.tobool");
}
return Res;
}
bool MicrosoftCXXABI::MemberPointerConstantIsNull(const MemberPointerType *MPT,
llvm::Constant *Val) {
if (MPT->isMemberFunctionPointer()) {
llvm::Constant *FirstField = Val->getType()->isStructTy() ?
Val->getAggregateElement(0U) : Val;
return FirstField->isNullValue();
}
if (isZeroInitializable(MPT) && Val->isNullValue())
return true;
llvm::SmallVector<llvm::Constant *, 4> Fields;
GetNullMemberPointerFields(MPT, Fields);
if (Fields.size() == 1) {
assert(Val->getType()->isIntegerTy());
return Val == Fields[0];
}
unsigned I, E;
for (I = 0, E = Fields.size(); I != E; ++I) {
if (Val->getAggregateElement(I) != Fields[I])
break;
}
return I == E;
}
llvm::Value *
MicrosoftCXXABI::GetVBaseOffsetFromVBPtr(CodeGenFunction &CGF,
Address This,
llvm::Value *VBPtrOffset,
llvm::Value *VBTableOffset,
llvm::Value **VBPtrOut) {
CGBuilderTy &Builder = CGF.Builder;
This = Builder.CreateElementBitCast(This, CGM.Int8Ty);
llvm::Value *VBPtr = Builder.CreateInBoundsGEP(
This.getElementType(), This.getPointer(), VBPtrOffset, "vbptr");
if (VBPtrOut) *VBPtrOut = VBPtr;
VBPtr = Builder.CreateBitCast(VBPtr,
CGM.Int32Ty->getPointerTo(0)->getPointerTo(This.getAddressSpace()));
CharUnits VBPtrAlign;
if (auto CI = dyn_cast<llvm::ConstantInt>(VBPtrOffset)) {
VBPtrAlign = This.getAlignment().alignmentAtOffset(
CharUnits::fromQuantity(CI->getSExtValue()));
} else {
VBPtrAlign = CGF.getPointerAlign();
}
llvm::Value *VBTable = Builder.CreateAlignedLoad(
CGM.Int32Ty->getPointerTo(0), VBPtr, VBPtrAlign, "vbtable");
llvm::Value *VBTableIndex = Builder.CreateAShr(
VBTableOffset, llvm::ConstantInt::get(VBTableOffset->getType(), 2),
"vbtindex", true);
llvm::Value *VBaseOffs =
Builder.CreateInBoundsGEP(CGM.Int32Ty, VBTable, VBTableIndex);
VBaseOffs = Builder.CreateBitCast(VBaseOffs, CGM.Int32Ty->getPointerTo(0));
return Builder.CreateAlignedLoad(CGM.Int32Ty, VBaseOffs,
CharUnits::fromQuantity(4), "vbase_offs");
}
llvm::Value *MicrosoftCXXABI::AdjustVirtualBase(
CodeGenFunction &CGF, const Expr *E, const CXXRecordDecl *RD,
Address Base, llvm::Value *VBTableOffset, llvm::Value *VBPtrOffset) {
CGBuilderTy &Builder = CGF.Builder;
Base = Builder.CreateElementBitCast(Base, CGM.Int8Ty);
llvm::BasicBlock *OriginalBB = nullptr;
llvm::BasicBlock *SkipAdjustBB = nullptr;
llvm::BasicBlock *VBaseAdjustBB = nullptr;
if (VBPtrOffset) {
OriginalBB = Builder.GetInsertBlock();
VBaseAdjustBB = CGF.createBasicBlock("memptr.vadjust");
SkipAdjustBB = CGF.createBasicBlock("memptr.skip_vadjust");
llvm::Value *IsVirtual =
Builder.CreateICmpNE(VBTableOffset, getZeroInt(),
"memptr.is_vbase");
Builder.CreateCondBr(IsVirtual, VBaseAdjustBB, SkipAdjustBB);
CGF.EmitBlock(VBaseAdjustBB);
}
if (!VBPtrOffset) {
CharUnits offs = CharUnits::Zero();
if (!RD->hasDefinition()) {
DiagnosticsEngine &Diags = CGF.CGM.getDiags();
unsigned DiagID = Diags.getCustomDiagID(
DiagnosticsEngine::Error,
"member pointer representation requires a "
"complete class type for %0 to perform this expression");
Diags.Report(E->getExprLoc(), DiagID) << RD << E->getSourceRange();
} else if (RD->getNumVBases())
offs = getContext().getASTRecordLayout(RD).getVBPtrOffset();
VBPtrOffset = llvm::ConstantInt::get(CGM.IntTy, offs.getQuantity());
}
llvm::Value *VBPtr = nullptr;
llvm::Value *VBaseOffs =
GetVBaseOffsetFromVBPtr(CGF, Base, VBPtrOffset, VBTableOffset, &VBPtr);
llvm::Value *AdjustedBase =
Builder.CreateInBoundsGEP(CGM.Int8Ty, VBPtr, VBaseOffs);
if (VBaseAdjustBB) {
Builder.CreateBr(SkipAdjustBB);
CGF.EmitBlock(SkipAdjustBB);
llvm::PHINode *Phi = Builder.CreatePHI(CGM.Int8PtrTy, 2, "memptr.base");
Phi->addIncoming(Base.getPointer(), OriginalBB);
Phi->addIncoming(AdjustedBase, VBaseAdjustBB);
return Phi;
}
return AdjustedBase;
}
llvm::Value *MicrosoftCXXABI::EmitMemberDataPointerAddress(
CodeGenFunction &CGF, const Expr *E, Address Base, llvm::Value *MemPtr,
const MemberPointerType *MPT) {
assert(MPT->isMemberDataPointer());
unsigned AS = Base.getAddressSpace();
llvm::Type *PType =
CGF.ConvertTypeForMem(MPT->getPointeeType())->getPointerTo(AS);
CGBuilderTy &Builder = CGF.Builder;
const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
llvm::Value *FieldOffset = MemPtr;
llvm::Value *VirtualBaseAdjustmentOffset = nullptr;
llvm::Value *VBPtrOffset = nullptr;
if (MemPtr->getType()->isStructTy()) {
unsigned I = 0;
FieldOffset = Builder.CreateExtractValue(MemPtr, I++);
if (inheritanceModelHasVBPtrOffsetField(Inheritance))
VBPtrOffset = Builder.CreateExtractValue(MemPtr, I++);
if (inheritanceModelHasVBTableOffsetField(Inheritance))
VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(MemPtr, I++);
}
llvm::Value *Addr;
if (VirtualBaseAdjustmentOffset) {
Addr = AdjustVirtualBase(CGF, E, RD, Base, VirtualBaseAdjustmentOffset,
VBPtrOffset);
} else {
Addr = Base.getPointer();
}
Addr = Builder.CreateBitCast(Addr, CGF.Int8Ty->getPointerTo(AS));
Addr = Builder.CreateInBoundsGEP(CGF.Int8Ty, Addr, FieldOffset,
"memptr.offset");
return Builder.CreateBitCast(Addr, PType);
}
llvm::Value *
MicrosoftCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF,
const CastExpr *E,
llvm::Value *Src) {
assert(E->getCastKind() == CK_DerivedToBaseMemberPointer ||
E->getCastKind() == CK_BaseToDerivedMemberPointer ||
E->getCastKind() == CK_ReinterpretMemberPointer);
if (isa<llvm::Constant>(Src))
return EmitMemberPointerConversion(E, cast<llvm::Constant>(Src));
const MemberPointerType *SrcTy =
E->getSubExpr()->getType()->castAs<MemberPointerType>();
const MemberPointerType *DstTy = E->getType()->castAs<MemberPointerType>();
bool IsFunc = SrcTy->isMemberFunctionPointer();
bool IsReinterpret = E->getCastKind() == CK_ReinterpretMemberPointer;
if (IsReinterpret && IsFunc)
return Src;
CXXRecordDecl *SrcRD = SrcTy->getMostRecentCXXRecordDecl();
CXXRecordDecl *DstRD = DstTy->getMostRecentCXXRecordDecl();
if (IsReinterpret &&
SrcRD->nullFieldOffsetIsZero() == DstRD->nullFieldOffsetIsZero())
return Src;
CGBuilderTy &Builder = CGF.Builder;
llvm::Value *IsNotNull = EmitMemberPointerIsNotNull(CGF, Src, SrcTy);
llvm::Constant *DstNull = EmitNullMemberPointer(DstTy);
if (IsReinterpret) {
assert(Src->getType() == DstNull->getType());
return Builder.CreateSelect(IsNotNull, Src, DstNull);
}
llvm::BasicBlock *OriginalBB = Builder.GetInsertBlock();
llvm::BasicBlock *ConvertBB = CGF.createBasicBlock("memptr.convert");
llvm::BasicBlock *ContinueBB = CGF.createBasicBlock("memptr.converted");
Builder.CreateCondBr(IsNotNull, ConvertBB, ContinueBB);
CGF.EmitBlock(ConvertBB);
llvm::Value *Dst = EmitNonNullMemberPointerConversion(
SrcTy, DstTy, E->getCastKind(), E->path_begin(), E->path_end(), Src,
Builder);
Builder.CreateBr(ContinueBB);
CGF.EmitBlock(ContinueBB);
llvm::PHINode *Phi = Builder.CreatePHI(DstNull->getType(), 2, "memptr.converted");
Phi->addIncoming(DstNull, OriginalBB);
Phi->addIncoming(Dst, ConvertBB);
return Phi;
}
llvm::Value *MicrosoftCXXABI::EmitNonNullMemberPointerConversion(
const MemberPointerType *SrcTy, const MemberPointerType *DstTy, CastKind CK,
CastExpr::path_const_iterator PathBegin,
CastExpr::path_const_iterator PathEnd, llvm::Value *Src,
CGBuilderTy &Builder) {
const CXXRecordDecl *SrcRD = SrcTy->getMostRecentCXXRecordDecl();
const CXXRecordDecl *DstRD = DstTy->getMostRecentCXXRecordDecl();
MSInheritanceModel SrcInheritance = SrcRD->getMSInheritanceModel();
MSInheritanceModel DstInheritance = DstRD->getMSInheritanceModel();
bool IsFunc = SrcTy->isMemberFunctionPointer();
bool IsConstant = isa<llvm::Constant>(Src);
llvm::Value *FirstField = Src;
llvm::Value *NonVirtualBaseAdjustment = getZeroInt();
llvm::Value *VirtualBaseAdjustmentOffset = getZeroInt();
llvm::Value *VBPtrOffset = getZeroInt();
if (!inheritanceModelHasOnlyOneField(IsFunc, SrcInheritance)) {
unsigned I = 0;
FirstField = Builder.CreateExtractValue(Src, I++);
if (inheritanceModelHasNVOffsetField(IsFunc, SrcInheritance))
NonVirtualBaseAdjustment = Builder.CreateExtractValue(Src, I++);
if (inheritanceModelHasVBPtrOffsetField(SrcInheritance))
VBPtrOffset = Builder.CreateExtractValue(Src, I++);
if (inheritanceModelHasVBTableOffsetField(SrcInheritance))
VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(Src, I++);
}
bool IsDerivedToBase = (CK == CK_DerivedToBaseMemberPointer);
const MemberPointerType *DerivedTy = IsDerivedToBase ? SrcTy : DstTy;
const CXXRecordDecl *DerivedClass = DerivedTy->getMostRecentCXXRecordDecl();
llvm::Value *&NVAdjustField = IsFunc ? NonVirtualBaseAdjustment : FirstField;
llvm::Value *SrcVBIndexEqZero =
Builder.CreateICmpEQ(VirtualBaseAdjustmentOffset, getZeroInt());
if (SrcInheritance == MSInheritanceModel::Virtual) {
if (int64_t SrcOffsetToFirstVBase =
getContext().getOffsetOfBaseWithVBPtr(SrcRD).getQuantity()) {
llvm::Value *UndoSrcAdjustment = Builder.CreateSelect(
SrcVBIndexEqZero,
llvm::ConstantInt::get(CGM.IntTy, SrcOffsetToFirstVBase),
getZeroInt());
NVAdjustField = Builder.CreateNSWAdd(NVAdjustField, UndoSrcAdjustment);
}
}
llvm::Constant *BaseClassOffset = llvm::ConstantInt::get(
CGM.IntTy,
CGM.computeNonVirtualBaseClassOffset(DerivedClass, PathBegin, PathEnd)
.getQuantity());
llvm::Value *NVDisp;
if (IsDerivedToBase)
NVDisp = Builder.CreateNSWSub(NVAdjustField, BaseClassOffset, "adj");
else
NVDisp = Builder.CreateNSWAdd(NVAdjustField, BaseClassOffset, "adj");
NVAdjustField = Builder.CreateSelect(SrcVBIndexEqZero, NVDisp, getZeroInt());
llvm::Value *DstVBIndexEqZero = SrcVBIndexEqZero;
if (inheritanceModelHasVBTableOffsetField(DstInheritance) &&
inheritanceModelHasVBTableOffsetField(SrcInheritance)) {
if (llvm::GlobalVariable *VDispMap =
getAddrOfVirtualDisplacementMap(SrcRD, DstRD)) {
llvm::Value *VBIndex = Builder.CreateExactUDiv(
VirtualBaseAdjustmentOffset, llvm::ConstantInt::get(CGM.IntTy, 4));
if (IsConstant) {
llvm::Constant *Mapping = VDispMap->getInitializer();
VirtualBaseAdjustmentOffset =
Mapping->getAggregateElement(cast<llvm::Constant>(VBIndex));
} else {
llvm::Value *Idxs[] = {getZeroInt(), VBIndex};
VirtualBaseAdjustmentOffset = Builder.CreateAlignedLoad(
CGM.IntTy, Builder.CreateInBoundsGEP(VDispMap->getValueType(),
VDispMap, Idxs),
CharUnits::fromQuantity(4));
}
DstVBIndexEqZero =
Builder.CreateICmpEQ(VirtualBaseAdjustmentOffset, getZeroInt());
}
}
if (inheritanceModelHasVBPtrOffsetField(DstInheritance)) {
llvm::Value *DstVBPtrOffset = llvm::ConstantInt::get(
CGM.IntTy,
getContext().getASTRecordLayout(DstRD).getVBPtrOffset().getQuantity());
VBPtrOffset =
Builder.CreateSelect(DstVBIndexEqZero, getZeroInt(), DstVBPtrOffset);
}
if (DstInheritance == MSInheritanceModel::Virtual) {
if (int64_t DstOffsetToFirstVBase =
getContext().getOffsetOfBaseWithVBPtr(DstRD).getQuantity()) {
llvm::Value *DoDstAdjustment = Builder.CreateSelect(
DstVBIndexEqZero,
llvm::ConstantInt::get(CGM.IntTy, DstOffsetToFirstVBase),
getZeroInt());
NVAdjustField = Builder.CreateNSWSub(NVAdjustField, DoDstAdjustment);
}
}
llvm::Value *Dst;
if (inheritanceModelHasOnlyOneField(IsFunc, DstInheritance)) {
Dst = FirstField;
} else {
Dst = llvm::UndefValue::get(ConvertMemberPointerType(DstTy));
unsigned Idx = 0;
Dst = Builder.CreateInsertValue(Dst, FirstField, Idx++);
if (inheritanceModelHasNVOffsetField(IsFunc, DstInheritance))
Dst = Builder.CreateInsertValue(Dst, NonVirtualBaseAdjustment, Idx++);
if (inheritanceModelHasVBPtrOffsetField(DstInheritance))
Dst = Builder.CreateInsertValue(Dst, VBPtrOffset, Idx++);
if (inheritanceModelHasVBTableOffsetField(DstInheritance))
Dst = Builder.CreateInsertValue(Dst, VirtualBaseAdjustmentOffset, Idx++);
}
return Dst;
}
llvm::Constant *
MicrosoftCXXABI::EmitMemberPointerConversion(const CastExpr *E,
llvm::Constant *Src) {
const MemberPointerType *SrcTy =
E->getSubExpr()->getType()->castAs<MemberPointerType>();
const MemberPointerType *DstTy = E->getType()->castAs<MemberPointerType>();
CastKind CK = E->getCastKind();
return EmitMemberPointerConversion(SrcTy, DstTy, CK, E->path_begin(),
E->path_end(), Src);
}
llvm::Constant *MicrosoftCXXABI::EmitMemberPointerConversion(
const MemberPointerType *SrcTy, const MemberPointerType *DstTy, CastKind CK,
CastExpr::path_const_iterator PathBegin,
CastExpr::path_const_iterator PathEnd, llvm::Constant *Src) {
assert(CK == CK_DerivedToBaseMemberPointer ||
CK == CK_BaseToDerivedMemberPointer ||
CK == CK_ReinterpretMemberPointer);
if (MemberPointerConstantIsNull(SrcTy, Src))
return EmitNullMemberPointer(DstTy);
if (CK == CK_ReinterpretMemberPointer)
return Src;
CGBuilderTy Builder(CGM, CGM.getLLVMContext());
auto *Dst = cast<llvm::Constant>(EmitNonNullMemberPointerConversion(
SrcTy, DstTy, CK, PathBegin, PathEnd, Src, Builder));
return Dst;
}
CGCallee MicrosoftCXXABI::EmitLoadOfMemberFunctionPointer(
CodeGenFunction &CGF, const Expr *E, Address This,
llvm::Value *&ThisPtrForCall, llvm::Value *MemPtr,
const MemberPointerType *MPT) {
assert(MPT->isMemberFunctionPointer());
const FunctionProtoType *FPT =
MPT->getPointeeType()->castAs<FunctionProtoType>();
const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(
CGM.getTypes().arrangeCXXMethodType(RD, FPT, nullptr));
CGBuilderTy &Builder = CGF.Builder;
MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
llvm::Value *FunctionPointer = MemPtr;
llvm::Value *NonVirtualBaseAdjustment = nullptr;
llvm::Value *VirtualBaseAdjustmentOffset = nullptr;
llvm::Value *VBPtrOffset = nullptr;
if (MemPtr->getType()->isStructTy()) {
unsigned I = 0;
FunctionPointer = Builder.CreateExtractValue(MemPtr, I++);
if (inheritanceModelHasNVOffsetField(MPT, Inheritance))
NonVirtualBaseAdjustment = Builder.CreateExtractValue(MemPtr, I++);
if (inheritanceModelHasVBPtrOffsetField(Inheritance))
VBPtrOffset = Builder.CreateExtractValue(MemPtr, I++);
if (inheritanceModelHasVBTableOffsetField(Inheritance))
VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(MemPtr, I++);
}
if (VirtualBaseAdjustmentOffset) {
ThisPtrForCall = AdjustVirtualBase(CGF, E, RD, This,
VirtualBaseAdjustmentOffset, VBPtrOffset);
} else {
ThisPtrForCall = This.getPointer();
}
if (NonVirtualBaseAdjustment) {
llvm::Value *Ptr = Builder.CreateBitCast(ThisPtrForCall, CGF.Int8PtrTy);
Ptr = Builder.CreateInBoundsGEP(CGF.Int8Ty, Ptr, NonVirtualBaseAdjustment);
ThisPtrForCall = Builder.CreateBitCast(Ptr, ThisPtrForCall->getType(),
"this.adjusted");
}
FunctionPointer =
Builder.CreateBitCast(FunctionPointer, FTy->getPointerTo());
CGCallee Callee(FPT, FunctionPointer);
return Callee;
}
CGCXXABI *clang::CodeGen::CreateMicrosoftCXXABI(CodeGenModule &CGM) {
return new MicrosoftCXXABI(CGM);
}
static llvm::GlobalVariable *getTypeInfoVTable(CodeGenModule &CGM) {
StringRef MangledName("??_7type_info@@6B@");
if (auto VTable = CGM.getModule().getNamedGlobal(MangledName))
return VTable;
return new llvm::GlobalVariable(CGM.getModule(), CGM.Int8PtrTy,
true,
llvm::GlobalVariable::ExternalLinkage,
nullptr, MangledName);
}
namespace {
struct MSRTTIClass {
enum {
IsPrivateOnPath = 1 | 8,
IsAmbiguous = 2,
IsPrivate = 4,
IsVirtual = 16,
HasHierarchyDescriptor = 64
};
MSRTTIClass(const CXXRecordDecl *RD) : RD(RD) {}
uint32_t initialize(const MSRTTIClass *Parent,
const CXXBaseSpecifier *Specifier);
MSRTTIClass *getFirstChild() { return this + 1; }
static MSRTTIClass *getNextChild(MSRTTIClass *Child) {
return Child + 1 + Child->NumBases;
}
const CXXRecordDecl *RD, *VirtualRoot;
uint32_t Flags, NumBases, OffsetInVBase;
};
uint32_t MSRTTIClass::initialize(const MSRTTIClass *Parent,
const CXXBaseSpecifier *Specifier) {
Flags = HasHierarchyDescriptor;
if (!Parent) {
VirtualRoot = nullptr;
OffsetInVBase = 0;
} else {
if (Specifier->getAccessSpecifier() != AS_public)
Flags |= IsPrivate | IsPrivateOnPath;
if (Specifier->isVirtual()) {
Flags |= IsVirtual;
VirtualRoot = RD;
OffsetInVBase = 0;
} else {
if (Parent->Flags & IsPrivateOnPath)
Flags |= IsPrivateOnPath;
VirtualRoot = Parent->VirtualRoot;
OffsetInVBase = Parent->OffsetInVBase + RD->getASTContext()
.getASTRecordLayout(Parent->RD).getBaseClassOffset(RD).getQuantity();
}
}
NumBases = 0;
MSRTTIClass *Child = getFirstChild();
for (const CXXBaseSpecifier &Base : RD->bases()) {
NumBases += Child->initialize(this, &Base) + 1;
Child = getNextChild(Child);
}
return NumBases;
}
static llvm::GlobalValue::LinkageTypes getLinkageForRTTI(QualType Ty) {
switch (Ty->getLinkage()) {
case NoLinkage:
case InternalLinkage:
case UniqueExternalLinkage:
return llvm::GlobalValue::InternalLinkage;
case VisibleNoLinkage:
case ModuleInternalLinkage:
case ModuleLinkage:
case ExternalLinkage:
return llvm::GlobalValue::LinkOnceODRLinkage;
}
llvm_unreachable("Invalid linkage!");
}
struct MSRTTIBuilder {
enum {
HasBranchingHierarchy = 1,
HasVirtualBranchingHierarchy = 2,
HasAmbiguousBases = 4
};
MSRTTIBuilder(MicrosoftCXXABI &ABI, const CXXRecordDecl *RD)
: CGM(ABI.CGM), Context(CGM.getContext()),
VMContext(CGM.getLLVMContext()), Module(CGM.getModule()), RD(RD),
Linkage(getLinkageForRTTI(CGM.getContext().getTagDeclType(RD))),
ABI(ABI) {}
llvm::GlobalVariable *getBaseClassDescriptor(const MSRTTIClass &Classes);
llvm::GlobalVariable *
getBaseClassArray(SmallVectorImpl<MSRTTIClass> &Classes);
llvm::GlobalVariable *getClassHierarchyDescriptor();
llvm::GlobalVariable *getCompleteObjectLocator(const VPtrInfo &Info);
CodeGenModule &CGM;
ASTContext &Context;
llvm::LLVMContext &VMContext;
llvm::Module &Module;
const CXXRecordDecl *RD;
llvm::GlobalVariable::LinkageTypes Linkage;
MicrosoftCXXABI &ABI;
};
}
static void serializeClassHierarchy(SmallVectorImpl<MSRTTIClass> &Classes,
const CXXRecordDecl *RD) {
Classes.push_back(MSRTTIClass(RD));
for (const CXXBaseSpecifier &Base : RD->bases())
serializeClassHierarchy(Classes, Base.getType()->getAsCXXRecordDecl());
}
static void
detectAmbiguousBases(SmallVectorImpl<MSRTTIClass> &Classes) {
llvm::SmallPtrSet<const CXXRecordDecl *, 8> VirtualBases;
llvm::SmallPtrSet<const CXXRecordDecl *, 8> UniqueBases;
llvm::SmallPtrSet<const CXXRecordDecl *, 8> AmbiguousBases;
for (MSRTTIClass *Class = &Classes.front(); Class <= &Classes.back();) {
if ((Class->Flags & MSRTTIClass::IsVirtual) &&
!VirtualBases.insert(Class->RD).second) {
Class = MSRTTIClass::getNextChild(Class);
continue;
}
if (!UniqueBases.insert(Class->RD).second)
AmbiguousBases.insert(Class->RD);
Class++;
}
if (AmbiguousBases.empty())
return;
for (MSRTTIClass &Class : Classes)
if (AmbiguousBases.count(Class.RD))
Class.Flags |= MSRTTIClass::IsAmbiguous;
}
llvm::GlobalVariable *MSRTTIBuilder::getClassHierarchyDescriptor() {
SmallString<256> MangledName;
{
llvm::raw_svector_ostream Out(MangledName);
ABI.getMangleContext().mangleCXXRTTIClassHierarchyDescriptor(RD, Out);
}
if (auto CHD = Module.getNamedGlobal(MangledName))
return CHD;
SmallVector<MSRTTIClass, 8> Classes;
serializeClassHierarchy(Classes, RD);
Classes.front().initialize(nullptr, nullptr);
detectAmbiguousBases(Classes);
int Flags = 0;
for (auto Class : Classes) {
if (Class.RD->getNumBases() > 1)
Flags |= HasBranchingHierarchy;
if (Class.Flags & MSRTTIClass::IsAmbiguous)
Flags |= HasAmbiguousBases;
}
if ((Flags & HasBranchingHierarchy) && RD->getNumVBases() != 0)
Flags |= HasVirtualBranchingHierarchy;
llvm::Value *GEPIndices[] = {llvm::ConstantInt::get(CGM.IntTy, 0),
llvm::ConstantInt::get(CGM.IntTy, 0)};
auto Type = ABI.getClassHierarchyDescriptorType();
auto CHD = new llvm::GlobalVariable(Module, Type, true, Linkage,
nullptr,
MangledName);
if (CHD->isWeakForLinker())
CHD->setComdat(CGM.getModule().getOrInsertComdat(CHD->getName()));
auto *Bases = getBaseClassArray(Classes);
llvm::Constant *Fields[] = {
llvm::ConstantInt::get(CGM.IntTy, 0), llvm::ConstantInt::get(CGM.IntTy, Flags),
llvm::ConstantInt::get(CGM.IntTy, Classes.size()),
ABI.getImageRelativeConstant(llvm::ConstantExpr::getInBoundsGetElementPtr(
Bases->getValueType(), Bases,
llvm::ArrayRef<llvm::Value *>(GEPIndices))),
};
CHD->setInitializer(llvm::ConstantStruct::get(Type, Fields));
return CHD;
}
llvm::GlobalVariable *
MSRTTIBuilder::getBaseClassArray(SmallVectorImpl<MSRTTIClass> &Classes) {
SmallString<256> MangledName;
{
llvm::raw_svector_ostream Out(MangledName);
ABI.getMangleContext().mangleCXXRTTIBaseClassArray(RD, Out);
}
llvm::Type *PtrType = ABI.getImageRelativeType(
ABI.getBaseClassDescriptorType()->getPointerTo());
auto *ArrType = llvm::ArrayType::get(PtrType, Classes.size() + 1);
auto *BCA =
new llvm::GlobalVariable(Module, ArrType,
true, Linkage,
nullptr, MangledName);
if (BCA->isWeakForLinker())
BCA->setComdat(CGM.getModule().getOrInsertComdat(BCA->getName()));
SmallVector<llvm::Constant *, 8> BaseClassArrayData;
for (MSRTTIClass &Class : Classes)
BaseClassArrayData.push_back(
ABI.getImageRelativeConstant(getBaseClassDescriptor(Class)));
BaseClassArrayData.push_back(llvm::Constant::getNullValue(PtrType));
BCA->setInitializer(llvm::ConstantArray::get(ArrType, BaseClassArrayData));
return BCA;
}
llvm::GlobalVariable *
MSRTTIBuilder::getBaseClassDescriptor(const MSRTTIClass &Class) {
uint32_t OffsetInVBTable = 0;
int32_t VBPtrOffset = -1;
if (Class.VirtualRoot) {
auto &VTableContext = CGM.getMicrosoftVTableContext();
OffsetInVBTable = VTableContext.getVBTableIndex(RD, Class.VirtualRoot) * 4;
VBPtrOffset = Context.getASTRecordLayout(RD).getVBPtrOffset().getQuantity();
}
SmallString<256> MangledName;
{
llvm::raw_svector_ostream Out(MangledName);
ABI.getMangleContext().mangleCXXRTTIBaseClassDescriptor(
Class.RD, Class.OffsetInVBase, VBPtrOffset, OffsetInVBTable,
Class.Flags, Out);
}
if (auto BCD = Module.getNamedGlobal(MangledName))
return BCD;
auto Type = ABI.getBaseClassDescriptorType();
auto BCD =
new llvm::GlobalVariable(Module, Type, true, Linkage,
nullptr, MangledName);
if (BCD->isWeakForLinker())
BCD->setComdat(CGM.getModule().getOrInsertComdat(BCD->getName()));
llvm::Constant *Fields[] = {
ABI.getImageRelativeConstant(
ABI.getAddrOfRTTIDescriptor(Context.getTypeDeclType(Class.RD))),
llvm::ConstantInt::get(CGM.IntTy, Class.NumBases),
llvm::ConstantInt::get(CGM.IntTy, Class.OffsetInVBase),
llvm::ConstantInt::get(CGM.IntTy, VBPtrOffset),
llvm::ConstantInt::get(CGM.IntTy, OffsetInVBTable),
llvm::ConstantInt::get(CGM.IntTy, Class.Flags),
ABI.getImageRelativeConstant(
MSRTTIBuilder(ABI, Class.RD).getClassHierarchyDescriptor()),
};
BCD->setInitializer(llvm::ConstantStruct::get(Type, Fields));
return BCD;
}
llvm::GlobalVariable *
MSRTTIBuilder::getCompleteObjectLocator(const VPtrInfo &Info) {
SmallString<256> MangledName;
{
llvm::raw_svector_ostream Out(MangledName);
ABI.getMangleContext().mangleCXXRTTICompleteObjectLocator(RD, Info.MangledPath, Out);
}
if (auto COL = Module.getNamedGlobal(MangledName))
return COL;
int OffsetToTop = Info.FullOffsetInMDC.getQuantity();
int VFPtrOffset = 0;
if (const CXXRecordDecl *VBase = Info.getVBaseWithVPtr())
if (Context.getASTRecordLayout(RD)
.getVBaseOffsetsMap()
.find(VBase)
->second.hasVtorDisp())
VFPtrOffset = Info.NonVirtualOffset.getQuantity() + 4;
llvm::StructType *Type = ABI.getCompleteObjectLocatorType();
auto COL = new llvm::GlobalVariable(Module, Type, true, Linkage,
nullptr, MangledName);
llvm::Constant *Fields[] = {
llvm::ConstantInt::get(CGM.IntTy, ABI.isImageRelative()),
llvm::ConstantInt::get(CGM.IntTy, OffsetToTop),
llvm::ConstantInt::get(CGM.IntTy, VFPtrOffset),
ABI.getImageRelativeConstant(
CGM.GetAddrOfRTTIDescriptor(Context.getTypeDeclType(RD))),
ABI.getImageRelativeConstant(getClassHierarchyDescriptor()),
ABI.getImageRelativeConstant(COL),
};
llvm::ArrayRef<llvm::Constant *> FieldsRef(Fields);
if (!ABI.isImageRelative())
FieldsRef = FieldsRef.drop_back();
COL->setInitializer(llvm::ConstantStruct::get(Type, FieldsRef));
if (COL->isWeakForLinker())
COL->setComdat(CGM.getModule().getOrInsertComdat(COL->getName()));
return COL;
}
static QualType decomposeTypeForEH(ASTContext &Context, QualType T,
bool &IsConst, bool &IsVolatile,
bool &IsUnaligned) {
T = Context.getExceptionObjectType(T);
IsConst = false;
IsVolatile = false;
IsUnaligned = false;
QualType PointeeType = T->getPointeeType();
if (!PointeeType.isNull()) {
IsConst = PointeeType.isConstQualified();
IsVolatile = PointeeType.isVolatileQualified();
IsUnaligned = PointeeType.getQualifiers().hasUnaligned();
}
if (const auto *MPTy = T->getAs<MemberPointerType>())
T = Context.getMemberPointerType(PointeeType.getUnqualifiedType(),
MPTy->getClass());
if (T->isPointerType())
T = Context.getPointerType(PointeeType.getUnqualifiedType());
return T;
}
CatchTypeInfo
MicrosoftCXXABI::getAddrOfCXXCatchHandlerType(QualType Type,
QualType CatchHandlerType) {
bool IsConst, IsVolatile, IsUnaligned;
Type =
decomposeTypeForEH(getContext(), Type, IsConst, IsVolatile, IsUnaligned);
bool IsReference = CatchHandlerType->isReferenceType();
uint32_t Flags = 0;
if (IsConst)
Flags |= 1;
if (IsVolatile)
Flags |= 2;
if (IsUnaligned)
Flags |= 4;
if (IsReference)
Flags |= 8;
return CatchTypeInfo{getAddrOfRTTIDescriptor(Type)->stripPointerCasts(),
Flags};
}
llvm::Constant *MicrosoftCXXABI::getAddrOfRTTIDescriptor(QualType Type) {
SmallString<256> MangledName;
{
llvm::raw_svector_ostream Out(MangledName);
getMangleContext().mangleCXXRTTI(Type, Out);
}
if (llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(MangledName))
return llvm::ConstantExpr::getBitCast(GV, CGM.Int8PtrTy);
SmallString<256> TypeInfoString;
{
llvm::raw_svector_ostream Out(TypeInfoString);
getMangleContext().mangleCXXRTTIName(Type, Out);
}
llvm::Constant *Fields[] = {
getTypeInfoVTable(CGM), llvm::ConstantPointerNull::get(CGM.Int8PtrTy), llvm::ConstantDataArray::getString(CGM.getLLVMContext(), TypeInfoString)};
llvm::StructType *TypeDescriptorType =
getTypeDescriptorType(TypeInfoString);
auto *Var = new llvm::GlobalVariable(
CGM.getModule(), TypeDescriptorType, false,
getLinkageForRTTI(Type),
llvm::ConstantStruct::get(TypeDescriptorType, Fields),
MangledName);
if (Var->isWeakForLinker())
Var->setComdat(CGM.getModule().getOrInsertComdat(Var->getName()));
return llvm::ConstantExpr::getBitCast(Var, CGM.Int8PtrTy);
}
llvm::GlobalVariable *
MicrosoftCXXABI::getMSCompleteObjectLocator(const CXXRecordDecl *RD,
const VPtrInfo &Info) {
return MSRTTIBuilder(*this, RD).getCompleteObjectLocator(Info);
}
void MicrosoftCXXABI::emitCXXStructor(GlobalDecl GD) {
if (auto *ctor = dyn_cast<CXXConstructorDecl>(GD.getDecl())) {
llvm::Function *Fn =
CGM.codegenCXXStructor(GD.getWithCtorType(Ctor_Complete));
CGM.maybeSetTrivialComdat(*ctor, *Fn);
return;
}
auto *dtor = cast<CXXDestructorDecl>(GD.getDecl());
if (GD.getDtorType() == Dtor_Complete &&
dtor->getParent()->getNumVBases() == 0)
GD = GD.getWithDtorType(Dtor_Base);
if (GD.getDtorType() == Dtor_Base && !CGM.TryEmitBaseDestructorAsAlias(dtor))
return;
llvm::Function *Fn = CGM.codegenCXXStructor(GD);
if (Fn->isWeakForLinker())
Fn->setComdat(CGM.getModule().getOrInsertComdat(Fn->getName()));
}
llvm::Function *
MicrosoftCXXABI::getAddrOfCXXCtorClosure(const CXXConstructorDecl *CD,
CXXCtorType CT) {
assert(CT == Ctor_CopyingClosure || CT == Ctor_DefaultClosure);
SmallString<256> ThunkName;
llvm::raw_svector_ostream Out(ThunkName);
getMangleContext().mangleName(GlobalDecl(CD, CT), Out);
if (llvm::GlobalValue *GV = CGM.getModule().getNamedValue(ThunkName))
return cast<llvm::Function>(GV);
const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeMSCtorClosure(CD, CT);
llvm::FunctionType *ThunkTy = CGM.getTypes().GetFunctionType(FnInfo);
const CXXRecordDecl *RD = CD->getParent();
QualType RecordTy = getContext().getRecordType(RD);
llvm::Function *ThunkFn = llvm::Function::Create(
ThunkTy, getLinkageForRTTI(RecordTy), ThunkName.str(), &CGM.getModule());
ThunkFn->setCallingConv(static_cast<llvm::CallingConv::ID>(
FnInfo.getEffectiveCallingConvention()));
if (ThunkFn->isWeakForLinker())
ThunkFn->setComdat(CGM.getModule().getOrInsertComdat(ThunkFn->getName()));
bool IsCopy = CT == Ctor_CopyingClosure;
CodeGenFunction CGF(CGM);
CGF.CurGD = GlobalDecl(CD, Ctor_Complete);
FunctionArgList FunctionArgs;
buildThisParam(CGF, FunctionArgs);
ImplicitParamDecl SrcParam(
getContext(), nullptr, SourceLocation(),
&getContext().Idents.get("src"),
getContext().getLValueReferenceType(RecordTy,
true),
ImplicitParamDecl::Other);
if (IsCopy)
FunctionArgs.push_back(&SrcParam);
ImplicitParamDecl IsMostDerived(getContext(), nullptr,
SourceLocation(),
&getContext().Idents.get("is_most_derived"),
getContext().IntTy, ImplicitParamDecl::Other);
if (RD->getNumVBases() > 0)
FunctionArgs.push_back(&IsMostDerived);
auto NL = ApplyDebugLocation::CreateEmpty(CGF);
CGF.StartFunction(GlobalDecl(), FnInfo.getReturnType(), ThunkFn, FnInfo,
FunctionArgs, CD->getLocation(), SourceLocation());
auto AL = ApplyDebugLocation::CreateArtificial(CGF);
setCXXABIThisValue(CGF, loadIncomingCXXThis(CGF));
llvm::Value *This = getThisValue(CGF);
llvm::Value *SrcVal =
IsCopy ? CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(&SrcParam), "src")
: nullptr;
CallArgList Args;
Args.add(RValue::get(This), CD->getThisType());
if (SrcVal)
Args.add(RValue::get(SrcVal), SrcParam.getType());
SmallVector<const Stmt *, 4> ArgVec;
ArrayRef<ParmVarDecl *> params = CD->parameters().drop_front(IsCopy ? 1 : 0);
for (const ParmVarDecl *PD : params) {
assert(PD->hasDefaultArg() && "ctor closure lacks default args");
ArgVec.push_back(PD->getDefaultArg());
}
CodeGenFunction::RunCleanupsScope Cleanups(CGF);
const auto *FPT = CD->getType()->castAs<FunctionProtoType>();
CGF.EmitCallArgs(Args, FPT, llvm::makeArrayRef(ArgVec), CD, IsCopy ? 1 : 0);
AddedStructorArgCounts ExtraArgs =
addImplicitConstructorArgs(CGF, CD, Ctor_Complete,
false,
false, Args);
llvm::Constant *CalleePtr =
CGM.getAddrOfCXXStructor(GlobalDecl(CD, Ctor_Complete));
CGCallee Callee =
CGCallee::forDirect(CalleePtr, GlobalDecl(CD, Ctor_Complete));
const CGFunctionInfo &CalleeInfo = CGM.getTypes().arrangeCXXConstructorCall(
Args, CD, Ctor_Complete, ExtraArgs.Prefix, ExtraArgs.Suffix);
CGF.EmitCall(CalleeInfo, Callee, ReturnValueSlot(), Args);
Cleanups.ForceCleanup();
CGF.FinishFunction(SourceLocation());
return ThunkFn;
}
llvm::Constant *MicrosoftCXXABI::getCatchableType(QualType T,
uint32_t NVOffset,
int32_t VBPtrOffset,
uint32_t VBIndex) {
assert(!T->isReferenceType());
CXXRecordDecl *RD = T->getAsCXXRecordDecl();
const CXXConstructorDecl *CD =
RD ? CGM.getContext().getCopyConstructorForExceptionObject(RD) : nullptr;
CXXCtorType CT = Ctor_Complete;
if (CD)
if (!hasDefaultCXXMethodCC(getContext(), CD) || CD->getNumParams() != 1)
CT = Ctor_CopyingClosure;
uint32_t Size = getContext().getTypeSizeInChars(T).getQuantity();
SmallString<256> MangledName;
{
llvm::raw_svector_ostream Out(MangledName);
getMangleContext().mangleCXXCatchableType(T, CD, CT, Size, NVOffset,
VBPtrOffset, VBIndex, Out);
}
if (llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(MangledName))
return getImageRelativeConstant(GV);
llvm::Constant *TD = getImageRelativeConstant(getAddrOfRTTIDescriptor(T));
llvm::Constant *CopyCtor;
if (CD) {
if (CT == Ctor_CopyingClosure)
CopyCtor = getAddrOfCXXCtorClosure(CD, Ctor_CopyingClosure);
else
CopyCtor = CGM.getAddrOfCXXStructor(GlobalDecl(CD, Ctor_Complete));
CopyCtor = llvm::ConstantExpr::getBitCast(CopyCtor, CGM.Int8PtrTy);
} else {
CopyCtor = llvm::Constant::getNullValue(CGM.Int8PtrTy);
}
CopyCtor = getImageRelativeConstant(CopyCtor);
bool IsScalar = !RD;
bool HasVirtualBases = false;
bool IsStdBadAlloc = false; QualType PointeeType = T;
if (T->isPointerType())
PointeeType = T->getPointeeType();
if (const CXXRecordDecl *RD = PointeeType->getAsCXXRecordDecl()) {
HasVirtualBases = RD->getNumVBases() > 0;
if (IdentifierInfo *II = RD->getIdentifier())
IsStdBadAlloc = II->isStr("bad_alloc") && RD->isInStdNamespace();
}
uint32_t Flags = 0;
if (IsScalar)
Flags |= 1;
if (HasVirtualBases)
Flags |= 4;
if (IsStdBadAlloc)
Flags |= 16;
llvm::Constant *Fields[] = {
llvm::ConstantInt::get(CGM.IntTy, Flags), TD, llvm::ConstantInt::get(CGM.IntTy, NVOffset), llvm::ConstantInt::get(CGM.IntTy, VBPtrOffset), llvm::ConstantInt::get(CGM.IntTy, VBIndex), llvm::ConstantInt::get(CGM.IntTy, Size), CopyCtor };
llvm::StructType *CTType = getCatchableTypeType();
auto *GV = new llvm::GlobalVariable(
CGM.getModule(), CTType, true, getLinkageForRTTI(T),
llvm::ConstantStruct::get(CTType, Fields), MangledName);
GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
GV->setSection(".xdata");
if (GV->isWeakForLinker())
GV->setComdat(CGM.getModule().getOrInsertComdat(GV->getName()));
return getImageRelativeConstant(GV);
}
llvm::GlobalVariable *MicrosoftCXXABI::getCatchableTypeArray(QualType T) {
assert(!T->isReferenceType());
llvm::GlobalVariable *&CTA = CatchableTypeArrays[T];
if (CTA)
return CTA;
llvm::SmallSetVector<llvm::Constant *, 2> CatchableTypes;
const CXXRecordDecl *MostDerivedClass = nullptr;
bool IsPointer = T->isPointerType();
if (IsPointer)
MostDerivedClass = T->getPointeeType()->getAsCXXRecordDecl();
else
MostDerivedClass = T->getAsCXXRecordDecl();
if (MostDerivedClass) {
const ASTContext &Context = getContext();
const ASTRecordLayout &MostDerivedLayout =
Context.getASTRecordLayout(MostDerivedClass);
MicrosoftVTableContext &VTableContext = CGM.getMicrosoftVTableContext();
SmallVector<MSRTTIClass, 8> Classes;
serializeClassHierarchy(Classes, MostDerivedClass);
Classes.front().initialize(nullptr, nullptr);
detectAmbiguousBases(Classes);
for (const MSRTTIClass &Class : Classes) {
if (Class.Flags &
(MSRTTIClass::IsPrivateOnPath | MSRTTIClass::IsAmbiguous))
continue;
uint32_t OffsetInVBTable = 0;
int32_t VBPtrOffset = -1;
if (Class.VirtualRoot) {
OffsetInVBTable =
VTableContext.getVBTableIndex(MostDerivedClass, Class.VirtualRoot)*4;
VBPtrOffset = MostDerivedLayout.getVBPtrOffset().getQuantity();
}
QualType RTTITy = QualType(Class.RD->getTypeForDecl(), 0);
if (IsPointer)
RTTITy = Context.getPointerType(RTTITy);
CatchableTypes.insert(getCatchableType(RTTITy, Class.OffsetInVBase,
VBPtrOffset, OffsetInVBTable));
}
}
CatchableTypes.insert(getCatchableType(T));
if (IsPointer && T->getPointeeType()->isObjectType())
CatchableTypes.insert(getCatchableType(getContext().VoidPtrTy));
if (T->isNullPtrType())
CatchableTypes.insert(getCatchableType(getContext().VoidPtrTy));
uint32_t NumEntries = CatchableTypes.size();
llvm::Type *CTType =
getImageRelativeType(getCatchableTypeType()->getPointerTo());
llvm::ArrayType *AT = llvm::ArrayType::get(CTType, NumEntries);
llvm::StructType *CTAType = getCatchableTypeArrayType(NumEntries);
llvm::Constant *Fields[] = {
llvm::ConstantInt::get(CGM.IntTy, NumEntries), llvm::ConstantArray::get(
AT, llvm::makeArrayRef(CatchableTypes.begin(),
CatchableTypes.end())) };
SmallString<256> MangledName;
{
llvm::raw_svector_ostream Out(MangledName);
getMangleContext().mangleCXXCatchableTypeArray(T, NumEntries, Out);
}
CTA = new llvm::GlobalVariable(
CGM.getModule(), CTAType, true, getLinkageForRTTI(T),
llvm::ConstantStruct::get(CTAType, Fields), MangledName);
CTA->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
CTA->setSection(".xdata");
if (CTA->isWeakForLinker())
CTA->setComdat(CGM.getModule().getOrInsertComdat(CTA->getName()));
return CTA;
}
llvm::GlobalVariable *MicrosoftCXXABI::getThrowInfo(QualType T) {
bool IsConst, IsVolatile, IsUnaligned;
T = decomposeTypeForEH(getContext(), T, IsConst, IsVolatile, IsUnaligned);
llvm::GlobalVariable *CTA = getCatchableTypeArray(T);
uint32_t NumEntries =
cast<llvm::ConstantInt>(CTA->getInitializer()->getAggregateElement(0U))
->getLimitedValue();
SmallString<256> MangledName;
{
llvm::raw_svector_ostream Out(MangledName);
getMangleContext().mangleCXXThrowInfo(T, IsConst, IsVolatile, IsUnaligned,
NumEntries, Out);
}
if (llvm::GlobalVariable *GV = CGM.getModule().getNamedGlobal(MangledName))
return GV;
uint32_t Flags = 0;
if (IsConst)
Flags |= 1;
if (IsVolatile)
Flags |= 2;
if (IsUnaligned)
Flags |= 4;
llvm::Constant *CleanupFn = llvm::Constant::getNullValue(CGM.Int8PtrTy);
if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
if (CXXDestructorDecl *DtorD = RD->getDestructor())
if (!DtorD->isTrivial())
CleanupFn = llvm::ConstantExpr::getBitCast(
CGM.getAddrOfCXXStructor(GlobalDecl(DtorD, Dtor_Complete)),
CGM.Int8PtrTy);
llvm::Constant *ForwardCompat =
getImageRelativeConstant(llvm::Constant::getNullValue(CGM.Int8PtrTy));
llvm::Constant *PointerToCatchableTypes = getImageRelativeConstant(
llvm::ConstantExpr::getBitCast(CTA, CGM.Int8PtrTy));
llvm::StructType *TIType = getThrowInfoType();
llvm::Constant *Fields[] = {
llvm::ConstantInt::get(CGM.IntTy, Flags), getImageRelativeConstant(CleanupFn), ForwardCompat, PointerToCatchableTypes };
auto *GV = new llvm::GlobalVariable(
CGM.getModule(), TIType, true, getLinkageForRTTI(T),
llvm::ConstantStruct::get(TIType, Fields), MangledName.str());
GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
GV->setSection(".xdata");
if (GV->isWeakForLinker())
GV->setComdat(CGM.getModule().getOrInsertComdat(GV->getName()));
return GV;
}
void MicrosoftCXXABI::emitThrow(CodeGenFunction &CGF, const CXXThrowExpr *E) {
const Expr *SubExpr = E->getSubExpr();
assert(SubExpr && "SubExpr cannot be null");
QualType ThrowType = SubExpr->getType();
Address AI = CGF.CreateMemTemp(ThrowType);
CGF.EmitAnyExprToMem(SubExpr, AI, ThrowType.getQualifiers(),
true);
llvm::GlobalVariable *TI = getThrowInfo(ThrowType);
llvm::Value *Args[] = {
CGF.Builder.CreateBitCast(AI.getPointer(), CGM.Int8PtrTy),
TI
};
CGF.EmitNoreturnRuntimeCallOrInvoke(getThrowFn(), Args);
}
std::pair<llvm::Value *, const CXXRecordDecl *>
MicrosoftCXXABI::LoadVTablePtr(CodeGenFunction &CGF, Address This,
const CXXRecordDecl *RD) {
std::tie(This, std::ignore, RD) =
performBaseAdjustment(CGF, This, QualType(RD->getTypeForDecl(), 0));
return {CGF.GetVTablePtr(This, CGM.Int8PtrTy, RD), RD};
}
bool MicrosoftCXXABI::isPermittedToBeHomogeneousAggregate(
const CXXRecordDecl *CXXRD) const {
return !CGM.getTarget().getTriple().isAArch64() ||
isTrivialForAArch64MSVC(CXXRD);
}