#include "clang/AST/VTableBuilder.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/ASTDiagnostic.h"
#include "clang/AST/CXXInheritance.h"
#include "clang/AST/RecordLayout.h"
#include "clang/Basic/TargetInfo.h"
#include "llvm/ADT/SetOperations.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/Support/Format.h"
#include "llvm/Support/raw_ostream.h"
#include <algorithm>
#include <cstdio>
using namespace clang;
#define DUMP_OVERRIDERS 0
namespace {
struct BaseOffset {
const CXXRecordDecl *DerivedClass;
const CXXRecordDecl *VirtualBase;
CharUnits NonVirtualOffset;
BaseOffset() : DerivedClass(nullptr), VirtualBase(nullptr),
NonVirtualOffset(CharUnits::Zero()) { }
BaseOffset(const CXXRecordDecl *DerivedClass,
const CXXRecordDecl *VirtualBase, CharUnits NonVirtualOffset)
: DerivedClass(DerivedClass), VirtualBase(VirtualBase),
NonVirtualOffset(NonVirtualOffset) { }
bool isEmpty() const { return NonVirtualOffset.isZero() && !VirtualBase; }
};
class FinalOverriders {
public:
struct OverriderInfo {
const CXXMethodDecl *Method;
const CXXRecordDecl *VirtualBase;
CharUnits Offset;
OverriderInfo() : Method(nullptr), VirtualBase(nullptr),
Offset(CharUnits::Zero()) { }
};
private:
const CXXRecordDecl *MostDerivedClass;
const CharUnits MostDerivedClassOffset;
const CXXRecordDecl *LayoutClass;
ASTContext &Context;
const ASTRecordLayout &MostDerivedClassLayout;
typedef std::pair<const CXXMethodDecl *, CharUnits> MethodBaseOffsetPairTy;
typedef llvm::DenseMap<MethodBaseOffsetPairTy,
OverriderInfo> OverridersMapTy;
OverridersMapTy OverridersMap;
typedef llvm::DenseMap<std::pair<const CXXRecordDecl *, unsigned>,
CharUnits> SubobjectOffsetMapTy;
typedef llvm::DenseMap<const CXXRecordDecl *, unsigned> SubobjectCountMapTy;
void ComputeBaseOffsets(BaseSubobject Base, bool IsVirtual,
CharUnits OffsetInLayoutClass,
SubobjectOffsetMapTy &SubobjectOffsets,
SubobjectOffsetMapTy &SubobjectLayoutClassOffsets,
SubobjectCountMapTy &SubobjectCounts);
typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy;
void dump(raw_ostream &Out, BaseSubobject Base,
VisitedVirtualBasesSetTy& VisitedVirtualBases);
public:
FinalOverriders(const CXXRecordDecl *MostDerivedClass,
CharUnits MostDerivedClassOffset,
const CXXRecordDecl *LayoutClass);
OverriderInfo getOverrider(const CXXMethodDecl *MD,
CharUnits BaseOffset) const {
assert(OverridersMap.count(std::make_pair(MD, BaseOffset)) &&
"Did not find overrider!");
return OverridersMap.lookup(std::make_pair(MD, BaseOffset));
}
void dump() {
VisitedVirtualBasesSetTy VisitedVirtualBases;
dump(llvm::errs(), BaseSubobject(MostDerivedClass, CharUnits::Zero()),
VisitedVirtualBases);
}
};
FinalOverriders::FinalOverriders(const CXXRecordDecl *MostDerivedClass,
CharUnits MostDerivedClassOffset,
const CXXRecordDecl *LayoutClass)
: MostDerivedClass(MostDerivedClass),
MostDerivedClassOffset(MostDerivedClassOffset), LayoutClass(LayoutClass),
Context(MostDerivedClass->getASTContext()),
MostDerivedClassLayout(Context.getASTRecordLayout(MostDerivedClass)) {
SubobjectOffsetMapTy SubobjectOffsets;
SubobjectOffsetMapTy SubobjectLayoutClassOffsets;
SubobjectCountMapTy SubobjectCounts;
ComputeBaseOffsets(BaseSubobject(MostDerivedClass, CharUnits::Zero()),
false,
MostDerivedClassOffset,
SubobjectOffsets, SubobjectLayoutClassOffsets,
SubobjectCounts);
CXXFinalOverriderMap FinalOverriders;
MostDerivedClass->getFinalOverriders(FinalOverriders);
for (const auto &Overrider : FinalOverriders) {
const CXXMethodDecl *MD = Overrider.first;
const OverridingMethods &Methods = Overrider.second;
for (const auto &M : Methods) {
unsigned SubobjectNumber = M.first;
assert(SubobjectOffsets.count(std::make_pair(MD->getParent(),
SubobjectNumber)) &&
"Did not find subobject offset!");
CharUnits BaseOffset = SubobjectOffsets[std::make_pair(MD->getParent(),
SubobjectNumber)];
assert(M.second.size() == 1 && "Final overrider is not unique!");
const UniqueVirtualMethod &Method = M.second.front();
const CXXRecordDecl *OverriderRD = Method.Method->getParent();
assert(SubobjectLayoutClassOffsets.count(
std::make_pair(OverriderRD, Method.Subobject))
&& "Did not find subobject offset!");
CharUnits OverriderOffset =
SubobjectLayoutClassOffsets[std::make_pair(OverriderRD,
Method.Subobject)];
OverriderInfo& Overrider = OverridersMap[std::make_pair(MD, BaseOffset)];
assert(!Overrider.Method && "Overrider should not exist yet!");
Overrider.Offset = OverriderOffset;
Overrider.Method = Method.Method;
Overrider.VirtualBase = Method.InVirtualSubobject;
}
}
#if DUMP_OVERRIDERS
dump();
#endif
}
static BaseOffset ComputeBaseOffset(const ASTContext &Context,
const CXXRecordDecl *DerivedRD,
const CXXBasePath &Path) {
CharUnits NonVirtualOffset = CharUnits::Zero();
unsigned NonVirtualStart = 0;
const CXXRecordDecl *VirtualBase = nullptr;
for (int I = Path.size(), E = 0; I != E; --I) {
const CXXBasePathElement &Element = Path[I - 1];
if (Element.Base->isVirtual()) {
NonVirtualStart = I;
QualType VBaseType = Element.Base->getType();
VirtualBase = VBaseType->getAsCXXRecordDecl();
break;
}
}
for (unsigned I = NonVirtualStart, E = Path.size(); I != E; ++I) {
const CXXBasePathElement &Element = Path[I];
const ASTRecordLayout &Layout = Context.getASTRecordLayout(Element.Class);
const CXXRecordDecl *Base = Element.Base->getType()->getAsCXXRecordDecl();
NonVirtualOffset += Layout.getBaseClassOffset(Base);
}
return BaseOffset(DerivedRD, VirtualBase, NonVirtualOffset);
}
static BaseOffset ComputeBaseOffset(const ASTContext &Context,
const CXXRecordDecl *BaseRD,
const CXXRecordDecl *DerivedRD) {
CXXBasePaths Paths(false,
true, false);
if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
llvm_unreachable("Class must be derived from the passed in base class!");
return ComputeBaseOffset(Context, DerivedRD, Paths.front());
}
static BaseOffset
ComputeReturnAdjustmentBaseOffset(ASTContext &Context,
const CXXMethodDecl *DerivedMD,
const CXXMethodDecl *BaseMD) {
const auto *BaseFT = BaseMD->getType()->castAs<FunctionType>();
const auto *DerivedFT = DerivedMD->getType()->castAs<FunctionType>();
CanQualType CanDerivedReturnType =
Context.getCanonicalType(DerivedFT->getReturnType());
CanQualType CanBaseReturnType =
Context.getCanonicalType(BaseFT->getReturnType());
assert(CanDerivedReturnType->getTypeClass() ==
CanBaseReturnType->getTypeClass() &&
"Types must have same type class!");
if (CanDerivedReturnType == CanBaseReturnType) {
return BaseOffset();
}
if (isa<ReferenceType>(CanDerivedReturnType)) {
CanDerivedReturnType =
CanDerivedReturnType->getAs<ReferenceType>()->getPointeeType();
CanBaseReturnType =
CanBaseReturnType->getAs<ReferenceType>()->getPointeeType();
} else if (isa<PointerType>(CanDerivedReturnType)) {
CanDerivedReturnType =
CanDerivedReturnType->getAs<PointerType>()->getPointeeType();
CanBaseReturnType =
CanBaseReturnType->getAs<PointerType>()->getPointeeType();
} else {
llvm_unreachable("Unexpected return type!");
}
if (CanDerivedReturnType.getUnqualifiedType() ==
CanBaseReturnType.getUnqualifiedType()) {
return BaseOffset();
}
const CXXRecordDecl *DerivedRD =
cast<CXXRecordDecl>(cast<RecordType>(CanDerivedReturnType)->getDecl());
const CXXRecordDecl *BaseRD =
cast<CXXRecordDecl>(cast<RecordType>(CanBaseReturnType)->getDecl());
return ComputeBaseOffset(Context, BaseRD, DerivedRD);
}
void
FinalOverriders::ComputeBaseOffsets(BaseSubobject Base, bool IsVirtual,
CharUnits OffsetInLayoutClass,
SubobjectOffsetMapTy &SubobjectOffsets,
SubobjectOffsetMapTy &SubobjectLayoutClassOffsets,
SubobjectCountMapTy &SubobjectCounts) {
const CXXRecordDecl *RD = Base.getBase();
unsigned SubobjectNumber = 0;
if (!IsVirtual)
SubobjectNumber = ++SubobjectCounts[RD];
assert(!SubobjectOffsets.count(std::make_pair(RD, SubobjectNumber))
&& "Subobject offset already exists!");
assert(!SubobjectLayoutClassOffsets.count(std::make_pair(RD, SubobjectNumber))
&& "Subobject offset already exists!");
SubobjectOffsets[std::make_pair(RD, SubobjectNumber)] = Base.getBaseOffset();
SubobjectLayoutClassOffsets[std::make_pair(RD, SubobjectNumber)] =
OffsetInLayoutClass;
for (const auto &B : RD->bases()) {
const CXXRecordDecl *BaseDecl = B.getType()->getAsCXXRecordDecl();
CharUnits BaseOffset;
CharUnits BaseOffsetInLayoutClass;
if (B.isVirtual()) {
if (SubobjectOffsets.count(std::make_pair(BaseDecl, 0)))
continue;
const ASTRecordLayout &LayoutClassLayout =
Context.getASTRecordLayout(LayoutClass);
BaseOffset = MostDerivedClassLayout.getVBaseClassOffset(BaseDecl);
BaseOffsetInLayoutClass =
LayoutClassLayout.getVBaseClassOffset(BaseDecl);
} else {
const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
CharUnits Offset = Layout.getBaseClassOffset(BaseDecl);
BaseOffset = Base.getBaseOffset() + Offset;
BaseOffsetInLayoutClass = OffsetInLayoutClass + Offset;
}
ComputeBaseOffsets(BaseSubobject(BaseDecl, BaseOffset),
B.isVirtual(), BaseOffsetInLayoutClass,
SubobjectOffsets, SubobjectLayoutClassOffsets,
SubobjectCounts);
}
}
void FinalOverriders::dump(raw_ostream &Out, BaseSubobject Base,
VisitedVirtualBasesSetTy &VisitedVirtualBases) {
const CXXRecordDecl *RD = Base.getBase();
const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
for (const auto &B : RD->bases()) {
const CXXRecordDecl *BaseDecl = B.getType()->getAsCXXRecordDecl();
if (!BaseDecl->isPolymorphic())
continue;
CharUnits BaseOffset;
if (B.isVirtual()) {
if (!VisitedVirtualBases.insert(BaseDecl).second) {
continue;
}
BaseOffset = MostDerivedClassLayout.getVBaseClassOffset(BaseDecl);
} else {
BaseOffset = Layout.getBaseClassOffset(BaseDecl) + Base.getBaseOffset();
}
dump(Out, BaseSubobject(BaseDecl, BaseOffset), VisitedVirtualBases);
}
Out << "Final overriders for (";
RD->printQualifiedName(Out);
Out << ", ";
Out << Base.getBaseOffset().getQuantity() << ")\n";
for (const auto *MD : RD->methods()) {
if (!VTableContextBase::hasVtableSlot(MD))
continue;
MD = MD->getCanonicalDecl();
OverriderInfo Overrider = getOverrider(MD, Base.getBaseOffset());
Out << " ";
MD->printQualifiedName(Out);
Out << " - (";
Overrider.Method->printQualifiedName(Out);
Out << ", " << Overrider.Offset.getQuantity() << ')';
BaseOffset Offset;
if (!Overrider.Method->isPure())
Offset = ComputeReturnAdjustmentBaseOffset(Context, Overrider.Method, MD);
if (!Offset.isEmpty()) {
Out << " [ret-adj: ";
if (Offset.VirtualBase) {
Offset.VirtualBase->printQualifiedName(Out);
Out << " vbase, ";
}
Out << Offset.NonVirtualOffset.getQuantity() << " nv]";
}
Out << "\n";
}
}
struct VCallOffsetMap {
typedef std::pair<const CXXMethodDecl *, CharUnits> MethodAndOffsetPairTy;
SmallVector<MethodAndOffsetPairTy, 16> Offsets;
static bool MethodsCanShareVCallOffset(const CXXMethodDecl *LHS,
const CXXMethodDecl *RHS);
public:
bool AddVCallOffset(const CXXMethodDecl *MD, CharUnits OffsetOffset);
CharUnits getVCallOffsetOffset(const CXXMethodDecl *MD);
bool empty() const { return Offsets.empty(); }
};
static bool HasSameVirtualSignature(const CXXMethodDecl *LHS,
const CXXMethodDecl *RHS) {
const FunctionProtoType *LT =
cast<FunctionProtoType>(LHS->getType().getCanonicalType());
const FunctionProtoType *RT =
cast<FunctionProtoType>(RHS->getType().getCanonicalType());
if (LT == RT) return true;
if (LT->getMethodQuals() != RT->getMethodQuals())
return false;
return LT->getParamTypes() == RT->getParamTypes();
}
bool VCallOffsetMap::MethodsCanShareVCallOffset(const CXXMethodDecl *LHS,
const CXXMethodDecl *RHS) {
assert(VTableContextBase::hasVtableSlot(LHS) && "LHS must be virtual!");
assert(VTableContextBase::hasVtableSlot(RHS) && "RHS must be virtual!");
if (isa<CXXDestructorDecl>(LHS))
return isa<CXXDestructorDecl>(RHS);
DeclarationName LHSName = LHS->getDeclName();
DeclarationName RHSName = RHS->getDeclName();
if (LHSName != RHSName)
return false;
return HasSameVirtualSignature(LHS, RHS);
}
bool VCallOffsetMap::AddVCallOffset(const CXXMethodDecl *MD,
CharUnits OffsetOffset) {
for (const auto &OffsetPair : Offsets) {
if (MethodsCanShareVCallOffset(OffsetPair.first, MD))
return false;
}
Offsets.push_back(MethodAndOffsetPairTy(MD, OffsetOffset));
return true;
}
CharUnits VCallOffsetMap::getVCallOffsetOffset(const CXXMethodDecl *MD) {
for (const auto &OffsetPair : Offsets) {
if (MethodsCanShareVCallOffset(OffsetPair.first, MD))
return OffsetPair.second;
}
llvm_unreachable("Should always find a vcall offset offset!");
}
class VCallAndVBaseOffsetBuilder {
public:
typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits>
VBaseOffsetOffsetsMapTy;
private:
const ItaniumVTableContext &VTables;
const CXXRecordDecl *MostDerivedClass;
const CXXRecordDecl *LayoutClass;
ASTContext &Context;
typedef SmallVector<VTableComponent, 64> VTableComponentVectorTy;
VTableComponentVectorTy Components;
llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBases;
VCallOffsetMap VCallOffsets;
VBaseOffsetOffsetsMapTy VBaseOffsetOffsets;
const FinalOverriders *Overriders;
void AddVCallAndVBaseOffsets(BaseSubobject Base, bool BaseIsVirtual,
CharUnits RealBaseOffset);
void AddVCallOffsets(BaseSubobject Base, CharUnits VBaseOffset);
void AddVBaseOffsets(const CXXRecordDecl *Base,
CharUnits OffsetInLayoutClass);
CharUnits getCurrentOffsetOffset() const;
public:
VCallAndVBaseOffsetBuilder(const ItaniumVTableContext &VTables,
const CXXRecordDecl *MostDerivedClass,
const CXXRecordDecl *LayoutClass,
const FinalOverriders *Overriders,
BaseSubobject Base, bool BaseIsVirtual,
CharUnits OffsetInLayoutClass)
: VTables(VTables), MostDerivedClass(MostDerivedClass),
LayoutClass(LayoutClass), Context(MostDerivedClass->getASTContext()),
Overriders(Overriders) {
AddVCallAndVBaseOffsets(Base, BaseIsVirtual, OffsetInLayoutClass);
}
typedef VTableComponentVectorTy::const_reverse_iterator const_iterator;
const_iterator components_begin() const { return Components.rbegin(); }
const_iterator components_end() const { return Components.rend(); }
const VCallOffsetMap &getVCallOffsets() const { return VCallOffsets; }
const VBaseOffsetOffsetsMapTy &getVBaseOffsetOffsets() const {
return VBaseOffsetOffsets;
}
};
void
VCallAndVBaseOffsetBuilder::AddVCallAndVBaseOffsets(BaseSubobject Base,
bool BaseIsVirtual,
CharUnits RealBaseOffset) {
const ASTRecordLayout &Layout = Context.getASTRecordLayout(Base.getBase());
if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
bool PrimaryBaseIsVirtual = Layout.isPrimaryBaseVirtual();
CharUnits PrimaryBaseOffset;
if (PrimaryBaseIsVirtual) {
assert(Layout.getVBaseClassOffset(PrimaryBase).isZero() &&
"Primary vbase should have a zero offset!");
const ASTRecordLayout &MostDerivedClassLayout =
Context.getASTRecordLayout(MostDerivedClass);
PrimaryBaseOffset =
MostDerivedClassLayout.getVBaseClassOffset(PrimaryBase);
} else {
assert(Layout.getBaseClassOffset(PrimaryBase).isZero() &&
"Primary base should have a zero offset!");
PrimaryBaseOffset = Base.getBaseOffset();
}
AddVCallAndVBaseOffsets(
BaseSubobject(PrimaryBase,PrimaryBaseOffset),
PrimaryBaseIsVirtual, RealBaseOffset);
}
AddVBaseOffsets(Base.getBase(), RealBaseOffset);
if (BaseIsVirtual)
AddVCallOffsets(Base, RealBaseOffset);
}
CharUnits VCallAndVBaseOffsetBuilder::getCurrentOffsetOffset() const {
int64_t OffsetIndex = -(int64_t)(3 + Components.size());
CharUnits OffsetWidth = Context.toCharUnitsFromBits(
VTables.isRelativeLayout() ? 32
: Context.getTargetInfo().getPointerWidth(0));
CharUnits OffsetOffset = OffsetWidth * OffsetIndex;
return OffsetOffset;
}
void VCallAndVBaseOffsetBuilder::AddVCallOffsets(BaseSubobject Base,
CharUnits VBaseOffset) {
const CXXRecordDecl *RD = Base.getBase();
const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
if (PrimaryBase && !Layout.isPrimaryBaseVirtual()) {
assert(Layout.getBaseClassOffset(PrimaryBase).isZero() &&
"Primary base should have a zero offset!");
AddVCallOffsets(BaseSubobject(PrimaryBase, Base.getBaseOffset()),
VBaseOffset);
}
for (const auto *MD : RD->methods()) {
if (!VTableContextBase::hasVtableSlot(MD))
continue;
MD = MD->getCanonicalDecl();
CharUnits OffsetOffset = getCurrentOffsetOffset();
if (!VCallOffsets.AddVCallOffset(MD, OffsetOffset))
continue;
CharUnits Offset = CharUnits::Zero();
if (Overriders) {
FinalOverriders::OverriderInfo Overrider =
Overriders->getOverrider(MD, Base.getBaseOffset());
Offset = Overrider.Offset - VBaseOffset;
}
Components.push_back(
VTableComponent::MakeVCallOffset(Offset));
}
for (const auto &B : RD->bases()) {
if (B.isVirtual())
continue;
const CXXRecordDecl *BaseDecl = B.getType()->getAsCXXRecordDecl();
if (BaseDecl == PrimaryBase)
continue;
CharUnits BaseOffset = Base.getBaseOffset() +
Layout.getBaseClassOffset(BaseDecl);
AddVCallOffsets(BaseSubobject(BaseDecl, BaseOffset),
VBaseOffset);
}
}
void
VCallAndVBaseOffsetBuilder::AddVBaseOffsets(const CXXRecordDecl *RD,
CharUnits OffsetInLayoutClass) {
const ASTRecordLayout &LayoutClassLayout =
Context.getASTRecordLayout(LayoutClass);
for (const auto &B : RD->bases()) {
const CXXRecordDecl *BaseDecl = B.getType()->getAsCXXRecordDecl();
if (B.isVirtual() && VisitedVirtualBases.insert(BaseDecl).second) {
CharUnits Offset =
LayoutClassLayout.getVBaseClassOffset(BaseDecl) - OffsetInLayoutClass;
assert(!VBaseOffsetOffsets.count(BaseDecl) &&
"vbase offset offset already exists!");
CharUnits VBaseOffsetOffset = getCurrentOffsetOffset();
VBaseOffsetOffsets.insert(
std::make_pair(BaseDecl, VBaseOffsetOffset));
Components.push_back(
VTableComponent::MakeVBaseOffset(Offset));
}
AddVBaseOffsets(BaseDecl, OffsetInLayoutClass);
}
}
class ItaniumVTableBuilder {
public:
typedef llvm::SmallSetVector<const CXXRecordDecl *, 8>
PrimaryBasesSetVectorTy;
typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits>
VBaseOffsetOffsetsMapTy;
typedef VTableLayout::AddressPointsMapTy AddressPointsMapTy;
typedef llvm::DenseMap<GlobalDecl, int64_t> MethodVTableIndicesTy;
private:
ItaniumVTableContext &VTables;
const CXXRecordDecl *MostDerivedClass;
const CharUnits MostDerivedClassOffset;
bool MostDerivedClassIsVirtual;
const CXXRecordDecl *LayoutClass;
ASTContext &Context;
const FinalOverriders Overriders;
llvm::DenseMap<const CXXRecordDecl *, VCallOffsetMap> VCallOffsetsForVBases;
VBaseOffsetOffsetsMapTy VBaseOffsetOffsets;
SmallVector<VTableComponent, 64> Components;
AddressPointsMapTy AddressPoints;
struct MethodInfo {
const CharUnits BaseOffset;
const CharUnits BaseOffsetInLayoutClass;
const uint64_t VTableIndex;
MethodInfo(CharUnits BaseOffset, CharUnits BaseOffsetInLayoutClass,
uint64_t VTableIndex)
: BaseOffset(BaseOffset),
BaseOffsetInLayoutClass(BaseOffsetInLayoutClass),
VTableIndex(VTableIndex) { }
MethodInfo()
: BaseOffset(CharUnits::Zero()),
BaseOffsetInLayoutClass(CharUnits::Zero()),
VTableIndex(0) { }
MethodInfo(MethodInfo const&) = default;
};
typedef llvm::DenseMap<const CXXMethodDecl *, MethodInfo> MethodInfoMapTy;
MethodInfoMapTy MethodInfoMap;
MethodVTableIndicesTy MethodVTableIndices;
typedef llvm::DenseMap<uint64_t, ThunkInfo> VTableThunksMapTy;
VTableThunksMapTy VTableThunks;
typedef SmallVector<ThunkInfo, 1> ThunkInfoVectorTy;
typedef llvm::DenseMap<const CXXMethodDecl *, ThunkInfoVectorTy> ThunksMapTy;
ThunksMapTy Thunks;
void AddThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk);
void ComputeThisAdjustments();
typedef llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBasesSetTy;
VisitedVirtualBasesSetTy PrimaryVirtualBases;
ReturnAdjustment ComputeReturnAdjustment(BaseOffset Offset);
BaseOffset ComputeThisAdjustmentBaseOffset(BaseSubobject Base,
BaseSubobject Derived) const;
ThisAdjustment
ComputeThisAdjustment(const CXXMethodDecl *MD,
CharUnits BaseOffsetInLayoutClass,
FinalOverriders::OverriderInfo Overrider);
void AddMethod(const CXXMethodDecl *MD, ReturnAdjustment ReturnAdjustment);
bool IsOverriderUsed(const CXXMethodDecl *Overrider,
CharUnits BaseOffsetInLayoutClass,
const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
CharUnits FirstBaseOffsetInLayoutClass) const;
void AddMethods(BaseSubobject Base, CharUnits BaseOffsetInLayoutClass,
const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
CharUnits FirstBaseOffsetInLayoutClass,
PrimaryBasesSetVectorTy &PrimaryBases);
void LayoutVTable();
void LayoutPrimaryAndSecondaryVTables(BaseSubobject Base,
bool BaseIsMorallyVirtual,
bool BaseIsVirtualInLayoutClass,
CharUnits OffsetInLayoutClass);
void LayoutSecondaryVTables(BaseSubobject Base, bool BaseIsMorallyVirtual,
CharUnits OffsetInLayoutClass);
void DeterminePrimaryVirtualBases(const CXXRecordDecl *RD,
CharUnits OffsetInLayoutClass,
VisitedVirtualBasesSetTy &VBases);
void LayoutVTablesForVirtualBases(const CXXRecordDecl *RD,
VisitedVirtualBasesSetTy &VBases);
bool isBuildingConstructorVTable() const {
return MostDerivedClass != LayoutClass;
}
public:
SmallVector<size_t, 4> VTableIndices;
ItaniumVTableBuilder(ItaniumVTableContext &VTables,
const CXXRecordDecl *MostDerivedClass,
CharUnits MostDerivedClassOffset,
bool MostDerivedClassIsVirtual,
const CXXRecordDecl *LayoutClass)
: VTables(VTables), MostDerivedClass(MostDerivedClass),
MostDerivedClassOffset(MostDerivedClassOffset),
MostDerivedClassIsVirtual(MostDerivedClassIsVirtual),
LayoutClass(LayoutClass), Context(MostDerivedClass->getASTContext()),
Overriders(MostDerivedClass, MostDerivedClassOffset, LayoutClass) {
assert(!Context.getTargetInfo().getCXXABI().isMicrosoft());
LayoutVTable();
if (Context.getLangOpts().DumpVTableLayouts)
dumpLayout(llvm::outs());
}
uint64_t getNumThunks() const {
return Thunks.size();
}
ThunksMapTy::const_iterator thunks_begin() const {
return Thunks.begin();
}
ThunksMapTy::const_iterator thunks_end() const {
return Thunks.end();
}
const VBaseOffsetOffsetsMapTy &getVBaseOffsetOffsets() const {
return VBaseOffsetOffsets;
}
const AddressPointsMapTy &getAddressPoints() const {
return AddressPoints;
}
MethodVTableIndicesTy::const_iterator vtable_indices_begin() const {
return MethodVTableIndices.begin();
}
MethodVTableIndicesTy::const_iterator vtable_indices_end() const {
return MethodVTableIndices.end();
}
ArrayRef<VTableComponent> vtable_components() const { return Components; }
AddressPointsMapTy::const_iterator address_points_begin() const {
return AddressPoints.begin();
}
AddressPointsMapTy::const_iterator address_points_end() const {
return AddressPoints.end();
}
VTableThunksMapTy::const_iterator vtable_thunks_begin() const {
return VTableThunks.begin();
}
VTableThunksMapTy::const_iterator vtable_thunks_end() const {
return VTableThunks.end();
}
void dumpLayout(raw_ostream&);
};
void ItaniumVTableBuilder::AddThunk(const CXXMethodDecl *MD,
const ThunkInfo &Thunk) {
assert(!isBuildingConstructorVTable() &&
"Can't add thunks for construction vtable");
SmallVectorImpl<ThunkInfo> &ThunksVector = Thunks[MD];
if (llvm::is_contained(ThunksVector, Thunk))
return;
ThunksVector.push_back(Thunk);
}
typedef llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverriddenMethodsSetTy;
template <class VisitorTy>
static void
visitAllOverriddenMethods(const CXXMethodDecl *MD, VisitorTy &Visitor) {
assert(VTableContextBase::hasVtableSlot(MD) && "Method is not virtual!");
for (const CXXMethodDecl *OverriddenMD : MD->overridden_methods()) {
if (!Visitor(OverriddenMD))
continue;
visitAllOverriddenMethods(OverriddenMD, Visitor);
}
}
static void
ComputeAllOverriddenMethods(const CXXMethodDecl *MD,
OverriddenMethodsSetTy& OverriddenMethods) {
auto OverriddenMethodsCollector = [&](const CXXMethodDecl *MD) {
return OverriddenMethods.insert(MD).second;
};
visitAllOverriddenMethods(MD, OverriddenMethodsCollector);
}
void ItaniumVTableBuilder::ComputeThisAdjustments() {
for (const auto &MI : MethodInfoMap) {
const CXXMethodDecl *MD = MI.first;
const MethodInfo &MethodInfo = MI.second;
uint64_t VTableIndex = MethodInfo.VTableIndex;
if (Components[VTableIndex].getKind() ==
VTableComponent::CK_UnusedFunctionPointer)
continue;
FinalOverriders::OverriderInfo Overrider =
Overriders.getOverrider(MD, MethodInfo.BaseOffset);
if (MethodInfo.BaseOffsetInLayoutClass == Overrider.Offset) {
if (VTableThunks.lookup(VTableIndex).Return.isEmpty())
continue;
}
ThisAdjustment ThisAdjustment =
ComputeThisAdjustment(MD, MethodInfo.BaseOffsetInLayoutClass, Overrider);
if (ThisAdjustment.isEmpty())
continue;
VTableThunks[VTableIndex].This = ThisAdjustment;
if (isa<CXXDestructorDecl>(MD)) {
VTableThunks[VTableIndex + 1].This = ThisAdjustment;
}
}
MethodInfoMap.clear();
if (isBuildingConstructorVTable()) {
return;
}
for (const auto &TI : VTableThunks) {
const VTableComponent &Component = Components[TI.first];
const ThunkInfo &Thunk = TI.second;
const CXXMethodDecl *MD;
switch (Component.getKind()) {
default:
llvm_unreachable("Unexpected vtable component kind!");
case VTableComponent::CK_FunctionPointer:
MD = Component.getFunctionDecl();
break;
case VTableComponent::CK_CompleteDtorPointer:
MD = Component.getDestructorDecl();
break;
case VTableComponent::CK_DeletingDtorPointer:
continue;
}
if (MD->getParent() == MostDerivedClass)
AddThunk(MD, Thunk);
}
}
ReturnAdjustment
ItaniumVTableBuilder::ComputeReturnAdjustment(BaseOffset Offset) {
ReturnAdjustment Adjustment;
if (!Offset.isEmpty()) {
if (Offset.VirtualBase) {
if (Offset.DerivedClass == MostDerivedClass) {
Adjustment.Virtual.Itanium.VBaseOffsetOffset =
VBaseOffsetOffsets.lookup(Offset.VirtualBase).getQuantity();
} else {
Adjustment.Virtual.Itanium.VBaseOffsetOffset =
VTables.getVirtualBaseOffsetOffset(Offset.DerivedClass,
Offset.VirtualBase).getQuantity();
}
}
Adjustment.NonVirtual = Offset.NonVirtualOffset.getQuantity();
}
return Adjustment;
}
BaseOffset ItaniumVTableBuilder::ComputeThisAdjustmentBaseOffset(
BaseSubobject Base, BaseSubobject Derived) const {
const CXXRecordDecl *BaseRD = Base.getBase();
const CXXRecordDecl *DerivedRD = Derived.getBase();
CXXBasePaths Paths(true,
true, true);
if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
llvm_unreachable("Class must be derived from the passed in base class!");
for (const CXXBasePath &Path : Paths) {
BaseOffset Offset = ComputeBaseOffset(Context, DerivedRD, Path);
CharUnits OffsetToBaseSubobject = Offset.NonVirtualOffset;
if (Offset.VirtualBase) {
const ASTRecordLayout &LayoutClassLayout =
Context.getASTRecordLayout(LayoutClass);
OffsetToBaseSubobject +=
LayoutClassLayout.getVBaseClassOffset(Offset.VirtualBase);
} else {
OffsetToBaseSubobject += Derived.getBaseOffset();
}
if (OffsetToBaseSubobject == Base.getBaseOffset()) {
Offset.NonVirtualOffset = -Offset.NonVirtualOffset;
return Offset;
}
}
return BaseOffset();
}
ThisAdjustment ItaniumVTableBuilder::ComputeThisAdjustment(
const CXXMethodDecl *MD, CharUnits BaseOffsetInLayoutClass,
FinalOverriders::OverriderInfo Overrider) {
if (Overrider.Method->isPure())
return ThisAdjustment();
BaseSubobject OverriddenBaseSubobject(MD->getParent(),
BaseOffsetInLayoutClass);
BaseSubobject OverriderBaseSubobject(Overrider.Method->getParent(),
Overrider.Offset);
BaseOffset Offset = ComputeThisAdjustmentBaseOffset(OverriddenBaseSubobject,
OverriderBaseSubobject);
if (Offset.isEmpty())
return ThisAdjustment();
ThisAdjustment Adjustment;
if (Offset.VirtualBase) {
VCallOffsetMap &VCallOffsets = VCallOffsetsForVBases[Offset.VirtualBase];
if (VCallOffsets.empty()) {
VCallAndVBaseOffsetBuilder Builder(
VTables, MostDerivedClass, MostDerivedClass,
nullptr,
BaseSubobject(Offset.VirtualBase, CharUnits::Zero()),
true,
CharUnits::Zero());
VCallOffsets = Builder.getVCallOffsets();
}
Adjustment.Virtual.Itanium.VCallOffsetOffset =
VCallOffsets.getVCallOffsetOffset(MD).getQuantity();
}
Adjustment.NonVirtual = Offset.NonVirtualOffset.getQuantity();
return Adjustment;
}
void ItaniumVTableBuilder::AddMethod(const CXXMethodDecl *MD,
ReturnAdjustment ReturnAdjustment) {
if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
assert(ReturnAdjustment.isEmpty() &&
"Destructor can't have return adjustment!");
Components.push_back(VTableComponent::MakeCompleteDtor(DD));
Components.push_back(VTableComponent::MakeDeletingDtor(DD));
} else {
if (!ReturnAdjustment.isEmpty())
VTableThunks[Components.size()].Return = ReturnAdjustment;
Components.push_back(VTableComponent::MakeFunction(MD));
}
}
static bool OverridesIndirectMethodInBases(
const CXXMethodDecl *MD,
ItaniumVTableBuilder::PrimaryBasesSetVectorTy &Bases) {
if (Bases.count(MD->getParent()))
return true;
for (const CXXMethodDecl *OverriddenMD : MD->overridden_methods()) {
if (OverridesIndirectMethodInBases(OverriddenMD, Bases))
return true;
}
return false;
}
bool ItaniumVTableBuilder::IsOverriderUsed(
const CXXMethodDecl *Overrider, CharUnits BaseOffsetInLayoutClass,
const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
CharUnits FirstBaseOffsetInLayoutClass) const {
if (BaseOffsetInLayoutClass == FirstBaseOffsetInLayoutClass)
return true;
if (Overrider->getParent() == FirstBaseInPrimaryBaseChain)
return true;
ItaniumVTableBuilder::PrimaryBasesSetVectorTy PrimaryBases;
const CXXRecordDecl *RD = FirstBaseInPrimaryBaseChain;
PrimaryBases.insert(RD);
while (true) {
const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
if (!PrimaryBase)
break;
if (Layout.isPrimaryBaseVirtual()) {
assert(Layout.getVBaseClassOffset(PrimaryBase).isZero() &&
"Primary base should always be at offset 0!");
const ASTRecordLayout &LayoutClassLayout =
Context.getASTRecordLayout(LayoutClass);
if (LayoutClassLayout.getVBaseClassOffset(PrimaryBase) !=
FirstBaseOffsetInLayoutClass) {
break;
}
} else {
assert(Layout.getBaseClassOffset(PrimaryBase).isZero() &&
"Primary base should always be at offset 0!");
}
if (!PrimaryBases.insert(PrimaryBase))
llvm_unreachable("Found a duplicate primary base!");
RD = PrimaryBase;
}
return OverridesIndirectMethodInBases(Overrider, PrimaryBases);
}
typedef llvm::SmallSetVector<const CXXRecordDecl *, 8> BasesSetVectorTy;
static const CXXMethodDecl *
FindNearestOverriddenMethod(const CXXMethodDecl *MD,
BasesSetVectorTy &Bases) {
OverriddenMethodsSetTy OverriddenMethods;
ComputeAllOverriddenMethods(MD, OverriddenMethods);
for (const CXXRecordDecl *PrimaryBase : llvm::reverse(Bases)) {
for (const CXXMethodDecl *OverriddenMD : OverriddenMethods) {
if (OverriddenMD->getParent() == PrimaryBase)
return OverriddenMD;
}
}
return nullptr;
}
void ItaniumVTableBuilder::AddMethods(
BaseSubobject Base, CharUnits BaseOffsetInLayoutClass,
const CXXRecordDecl *FirstBaseInPrimaryBaseChain,
CharUnits FirstBaseOffsetInLayoutClass,
PrimaryBasesSetVectorTy &PrimaryBases) {
const CXXRecordDecl *RD = Base.getBase();
const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
CharUnits PrimaryBaseOffset;
CharUnits PrimaryBaseOffsetInLayoutClass;
if (Layout.isPrimaryBaseVirtual()) {
assert(Layout.getVBaseClassOffset(PrimaryBase).isZero() &&
"Primary vbase should have a zero offset!");
const ASTRecordLayout &MostDerivedClassLayout =
Context.getASTRecordLayout(MostDerivedClass);
PrimaryBaseOffset =
MostDerivedClassLayout.getVBaseClassOffset(PrimaryBase);
const ASTRecordLayout &LayoutClassLayout =
Context.getASTRecordLayout(LayoutClass);
PrimaryBaseOffsetInLayoutClass =
LayoutClassLayout.getVBaseClassOffset(PrimaryBase);
} else {
assert(Layout.getBaseClassOffset(PrimaryBase).isZero() &&
"Primary base should have a zero offset!");
PrimaryBaseOffset = Base.getBaseOffset();
PrimaryBaseOffsetInLayoutClass = BaseOffsetInLayoutClass;
}
AddMethods(BaseSubobject(PrimaryBase, PrimaryBaseOffset),
PrimaryBaseOffsetInLayoutClass, FirstBaseInPrimaryBaseChain,
FirstBaseOffsetInLayoutClass, PrimaryBases);
if (!PrimaryBases.insert(PrimaryBase))
llvm_unreachable("Found a duplicate primary base!");
}
typedef llvm::SmallVector<const CXXMethodDecl *, 8> NewVirtualFunctionsTy;
NewVirtualFunctionsTy NewVirtualFunctions;
llvm::SmallVector<const CXXMethodDecl*, 4> NewImplicitVirtualFunctions;
for (const auto *MD : RD->methods()) {
if (!ItaniumVTableContext::hasVtableSlot(MD))
continue;
MD = MD->getCanonicalDecl();
FinalOverriders::OverriderInfo Overrider =
Overriders.getOverrider(MD, Base.getBaseOffset());
if (const CXXMethodDecl *OverriddenMD =
FindNearestOverriddenMethod(MD, PrimaryBases)) {
if (ComputeReturnAdjustmentBaseOffset(Context, MD,
OverriddenMD).isEmpty()) {
assert(MethodInfoMap.count(OverriddenMD) &&
"Did not find the overridden method!");
MethodInfo &OverriddenMethodInfo = MethodInfoMap[OverriddenMD];
MethodInfo MethodInfo(Base.getBaseOffset(), BaseOffsetInLayoutClass,
OverriddenMethodInfo.VTableIndex);
assert(!MethodInfoMap.count(MD) &&
"Should not have method info for this method yet!");
MethodInfoMap.insert(std::make_pair(MD, MethodInfo));
MethodInfoMap.erase(OverriddenMD);
if (!isBuildingConstructorVTable() && OverriddenMD != MD) {
ThisAdjustment ThisAdjustment =
ComputeThisAdjustment(OverriddenMD, BaseOffsetInLayoutClass,
Overrider);
if (ThisAdjustment.Virtual.Itanium.VCallOffsetOffset &&
Overrider.Method->getParent() == MostDerivedClass) {
BaseOffset ReturnAdjustmentOffset =
ComputeReturnAdjustmentBaseOffset(Context, Overrider.Method, MD);
ReturnAdjustment ReturnAdjustment =
ComputeReturnAdjustment(ReturnAdjustmentOffset);
AddThunk(Overrider.Method,
ThunkInfo(ThisAdjustment, ReturnAdjustment));
}
}
continue;
}
}
if (MD->isImplicit())
NewImplicitVirtualFunctions.push_back(MD);
else
NewVirtualFunctions.push_back(MD);
}
std::stable_sort(
NewImplicitVirtualFunctions.begin(), NewImplicitVirtualFunctions.end(),
[](const CXXMethodDecl *A, const CXXMethodDecl *B) {
if (A->isCopyAssignmentOperator() != B->isCopyAssignmentOperator())
return A->isCopyAssignmentOperator();
if (A->isMoveAssignmentOperator() != B->isMoveAssignmentOperator())
return A->isMoveAssignmentOperator();
if (isa<CXXDestructorDecl>(A) != isa<CXXDestructorDecl>(B))
return isa<CXXDestructorDecl>(A);
assert(A->getOverloadedOperator() == OO_EqualEqual &&
B->getOverloadedOperator() == OO_EqualEqual &&
"unexpected or duplicate implicit virtual function");
return false;
});
NewVirtualFunctions.append(NewImplicitVirtualFunctions.begin(),
NewImplicitVirtualFunctions.end());
for (const CXXMethodDecl *MD : NewVirtualFunctions) {
FinalOverriders::OverriderInfo Overrider =
Overriders.getOverrider(MD, Base.getBaseOffset());
MethodInfo MethodInfo(Base.getBaseOffset(), BaseOffsetInLayoutClass,
Components.size());
assert(!MethodInfoMap.count(MD) &&
"Should not have method info for this method yet!");
MethodInfoMap.insert(std::make_pair(MD, MethodInfo));
const CXXMethodDecl *OverriderMD = Overrider.Method;
if (!IsOverriderUsed(OverriderMD, BaseOffsetInLayoutClass,
FirstBaseInPrimaryBaseChain,
FirstBaseOffsetInLayoutClass)) {
Components.push_back(VTableComponent::MakeUnusedFunction(OverriderMD));
continue;
}
BaseOffset ReturnAdjustmentOffset;
if (!OverriderMD->isPure()) {
ReturnAdjustmentOffset =
ComputeReturnAdjustmentBaseOffset(Context, OverriderMD, MD);
}
ReturnAdjustment ReturnAdjustment =
ComputeReturnAdjustment(ReturnAdjustmentOffset);
AddMethod(Overrider.Method, ReturnAdjustment);
}
}
void ItaniumVTableBuilder::LayoutVTable() {
LayoutPrimaryAndSecondaryVTables(BaseSubobject(MostDerivedClass,
CharUnits::Zero()),
false,
MostDerivedClassIsVirtual,
MostDerivedClassOffset);
VisitedVirtualBasesSetTy VBases;
DeterminePrimaryVirtualBases(MostDerivedClass, MostDerivedClassOffset,
VBases);
VBases.clear();
LayoutVTablesForVirtualBases(MostDerivedClass, VBases);
bool IsAppleKext = Context.getLangOpts().AppleKext;
if (IsAppleKext)
Components.push_back(VTableComponent::MakeVCallOffset(CharUnits::Zero()));
}
void ItaniumVTableBuilder::LayoutPrimaryAndSecondaryVTables(
BaseSubobject Base, bool BaseIsMorallyVirtual,
bool BaseIsVirtualInLayoutClass, CharUnits OffsetInLayoutClass) {
assert(Base.getBase()->isDynamicClass() && "class does not have a vtable!");
unsigned VTableIndex = Components.size();
VTableIndices.push_back(VTableIndex);
VCallAndVBaseOffsetBuilder Builder(
VTables, MostDerivedClass, LayoutClass, &Overriders, Base,
BaseIsVirtualInLayoutClass, OffsetInLayoutClass);
Components.append(Builder.components_begin(), Builder.components_end());
if (BaseIsVirtualInLayoutClass && !Builder.getVCallOffsets().empty()) {
VCallOffsetMap &VCallOffsets = VCallOffsetsForVBases[Base.getBase()];
if (VCallOffsets.empty())
VCallOffsets = Builder.getVCallOffsets();
}
if (Base.getBase() == MostDerivedClass)
VBaseOffsetOffsets = Builder.getVBaseOffsetOffsets();
CharUnits OffsetToTop = MostDerivedClassOffset - OffsetInLayoutClass;
Components.push_back(VTableComponent::MakeOffsetToTop(OffsetToTop));
Components.push_back(VTableComponent::MakeRTTI(MostDerivedClass));
uint64_t AddressPoint = Components.size();
PrimaryBasesSetVectorTy PrimaryBases;
AddMethods(Base, OffsetInLayoutClass,
Base.getBase(), OffsetInLayoutClass,
PrimaryBases);
const CXXRecordDecl *RD = Base.getBase();
if (RD == MostDerivedClass) {
assert(MethodVTableIndices.empty());
for (const auto &I : MethodInfoMap) {
const CXXMethodDecl *MD = I.first;
const MethodInfo &MI = I.second;
if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
MethodVTableIndices[GlobalDecl(DD, Dtor_Complete)]
= MI.VTableIndex - AddressPoint;
MethodVTableIndices[GlobalDecl(DD, Dtor_Deleting)]
= MI.VTableIndex + 1 - AddressPoint;
} else {
MethodVTableIndices[MD] = MI.VTableIndex - AddressPoint;
}
}
}
ComputeThisAdjustments();
while (true) {
AddressPoints.insert(
std::make_pair(BaseSubobject(RD, OffsetInLayoutClass),
VTableLayout::AddressPointLocation{
unsigned(VTableIndices.size() - 1),
unsigned(AddressPoint - VTableIndex)}));
const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
if (!PrimaryBase)
break;
if (Layout.isPrimaryBaseVirtual()) {
const ASTRecordLayout &LayoutClassLayout =
Context.getASTRecordLayout(LayoutClass);
if (LayoutClassLayout.getVBaseClassOffset(PrimaryBase) !=
OffsetInLayoutClass) {
break;
}
}
RD = PrimaryBase;
}
LayoutSecondaryVTables(Base, BaseIsMorallyVirtual, OffsetInLayoutClass);
}
void
ItaniumVTableBuilder::LayoutSecondaryVTables(BaseSubobject Base,
bool BaseIsMorallyVirtual,
CharUnits OffsetInLayoutClass) {
const CXXRecordDecl *RD = Base.getBase();
const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
for (const auto &B : RD->bases()) {
if (B.isVirtual())
continue;
const CXXRecordDecl *BaseDecl = B.getType()->getAsCXXRecordDecl();
if (!BaseDecl->isDynamicClass())
continue;
if (isBuildingConstructorVTable()) {
if (!BaseIsMorallyVirtual && !BaseDecl->getNumVBases())
continue;
}
CharUnits RelativeBaseOffset = Layout.getBaseClassOffset(BaseDecl);
CharUnits BaseOffset = Base.getBaseOffset() + RelativeBaseOffset;
CharUnits BaseOffsetInLayoutClass =
OffsetInLayoutClass + RelativeBaseOffset;
if (BaseDecl == PrimaryBase) {
LayoutSecondaryVTables(BaseSubobject(BaseDecl, BaseOffset),
BaseIsMorallyVirtual, BaseOffsetInLayoutClass);
continue;
}
LayoutPrimaryAndSecondaryVTables(
BaseSubobject(BaseDecl, BaseOffset),
BaseIsMorallyVirtual,
false,
BaseOffsetInLayoutClass);
}
}
void ItaniumVTableBuilder::DeterminePrimaryVirtualBases(
const CXXRecordDecl *RD, CharUnits OffsetInLayoutClass,
VisitedVirtualBasesSetTy &VBases) {
const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
if (Layout.isPrimaryBaseVirtual()) {
bool IsPrimaryVirtualBase = true;
if (isBuildingConstructorVTable()) {
const ASTRecordLayout &LayoutClassLayout =
Context.getASTRecordLayout(LayoutClass);
CharUnits PrimaryBaseOffsetInLayoutClass =
LayoutClassLayout.getVBaseClassOffset(PrimaryBase);
if (PrimaryBaseOffsetInLayoutClass != OffsetInLayoutClass)
IsPrimaryVirtualBase = false;
}
if (IsPrimaryVirtualBase)
PrimaryVirtualBases.insert(PrimaryBase);
}
}
for (const auto &B : RD->bases()) {
const CXXRecordDecl *BaseDecl = B.getType()->getAsCXXRecordDecl();
CharUnits BaseOffsetInLayoutClass;
if (B.isVirtual()) {
if (!VBases.insert(BaseDecl).second)
continue;
const ASTRecordLayout &LayoutClassLayout =
Context.getASTRecordLayout(LayoutClass);
BaseOffsetInLayoutClass =
LayoutClassLayout.getVBaseClassOffset(BaseDecl);
} else {
BaseOffsetInLayoutClass =
OffsetInLayoutClass + Layout.getBaseClassOffset(BaseDecl);
}
DeterminePrimaryVirtualBases(BaseDecl, BaseOffsetInLayoutClass, VBases);
}
}
void ItaniumVTableBuilder::LayoutVTablesForVirtualBases(
const CXXRecordDecl *RD, VisitedVirtualBasesSetTy &VBases) {
for (const auto &B : RD->bases()) {
const CXXRecordDecl *BaseDecl = B.getType()->getAsCXXRecordDecl();
if (B.isVirtual() && BaseDecl->isDynamicClass() &&
!PrimaryVirtualBases.count(BaseDecl) &&
VBases.insert(BaseDecl).second) {
const ASTRecordLayout &MostDerivedClassLayout =
Context.getASTRecordLayout(MostDerivedClass);
CharUnits BaseOffset =
MostDerivedClassLayout.getVBaseClassOffset(BaseDecl);
const ASTRecordLayout &LayoutClassLayout =
Context.getASTRecordLayout(LayoutClass);
CharUnits BaseOffsetInLayoutClass =
LayoutClassLayout.getVBaseClassOffset(BaseDecl);
LayoutPrimaryAndSecondaryVTables(
BaseSubobject(BaseDecl, BaseOffset),
true,
true,
BaseOffsetInLayoutClass);
}
if (BaseDecl->getNumVBases())
LayoutVTablesForVirtualBases(BaseDecl, VBases);
}
}
void ItaniumVTableBuilder::dumpLayout(raw_ostream &Out) {
if (isBuildingConstructorVTable()) {
Out << "Construction vtable for ('";
MostDerivedClass->printQualifiedName(Out);
Out << "', ";
Out << MostDerivedClassOffset.getQuantity() << ") in '";
LayoutClass->printQualifiedName(Out);
} else {
Out << "Vtable for '";
MostDerivedClass->printQualifiedName(Out);
}
Out << "' (" << Components.size() << " entries).\n";
std::multimap<uint64_t, BaseSubobject> AddressPointsByIndex;
for (const auto &AP : AddressPoints) {
const BaseSubobject &Base = AP.first;
uint64_t Index =
VTableIndices[AP.second.VTableIndex] + AP.second.AddressPointIndex;
AddressPointsByIndex.insert(std::make_pair(Index, Base));
}
for (unsigned I = 0, E = Components.size(); I != E; ++I) {
uint64_t Index = I;
Out << llvm::format("%4d | ", I);
const VTableComponent &Component = Components[I];
switch (Component.getKind()) {
case VTableComponent::CK_VCallOffset:
Out << "vcall_offset ("
<< Component.getVCallOffset().getQuantity()
<< ")";
break;
case VTableComponent::CK_VBaseOffset:
Out << "vbase_offset ("
<< Component.getVBaseOffset().getQuantity()
<< ")";
break;
case VTableComponent::CK_OffsetToTop:
Out << "offset_to_top ("
<< Component.getOffsetToTop().getQuantity()
<< ")";
break;
case VTableComponent::CK_RTTI:
Component.getRTTIDecl()->printQualifiedName(Out);
Out << " RTTI";
break;
case VTableComponent::CK_FunctionPointer: {
const CXXMethodDecl *MD = Component.getFunctionDecl();
std::string Str =
PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
MD);
Out << Str;
if (MD->isPure())
Out << " [pure]";
if (MD->isDeleted())
Out << " [deleted]";
ThunkInfo Thunk = VTableThunks.lookup(I);
if (!Thunk.isEmpty()) {
if (!Thunk.Return.isEmpty()) {
Out << "\n [return adjustment: ";
Out << Thunk.Return.NonVirtual << " non-virtual";
if (Thunk.Return.Virtual.Itanium.VBaseOffsetOffset) {
Out << ", " << Thunk.Return.Virtual.Itanium.VBaseOffsetOffset;
Out << " vbase offset offset";
}
Out << ']';
}
if (!Thunk.This.isEmpty()) {
Out << "\n [this adjustment: ";
Out << Thunk.This.NonVirtual << " non-virtual";
if (Thunk.This.Virtual.Itanium.VCallOffsetOffset) {
Out << ", " << Thunk.This.Virtual.Itanium.VCallOffsetOffset;
Out << " vcall offset offset";
}
Out << ']';
}
}
break;
}
case VTableComponent::CK_CompleteDtorPointer:
case VTableComponent::CK_DeletingDtorPointer: {
bool IsComplete =
Component.getKind() == VTableComponent::CK_CompleteDtorPointer;
const CXXDestructorDecl *DD = Component.getDestructorDecl();
DD->printQualifiedName(Out);
if (IsComplete)
Out << "() [complete]";
else
Out << "() [deleting]";
if (DD->isPure())
Out << " [pure]";
ThunkInfo Thunk = VTableThunks.lookup(I);
if (!Thunk.isEmpty()) {
if (!Thunk.This.isEmpty()) {
Out << "\n [this adjustment: ";
Out << Thunk.This.NonVirtual << " non-virtual";
if (Thunk.This.Virtual.Itanium.VCallOffsetOffset) {
Out << ", " << Thunk.This.Virtual.Itanium.VCallOffsetOffset;
Out << " vcall offset offset";
}
Out << ']';
}
}
break;
}
case VTableComponent::CK_UnusedFunctionPointer: {
const CXXMethodDecl *MD = Component.getUnusedFunctionDecl();
std::string Str =
PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
MD);
Out << "[unused] " << Str;
if (MD->isPure())
Out << " [pure]";
}
}
Out << '\n';
uint64_t NextIndex = Index + 1;
if (AddressPointsByIndex.count(NextIndex)) {
if (AddressPointsByIndex.count(NextIndex) == 1) {
const BaseSubobject &Base =
AddressPointsByIndex.find(NextIndex)->second;
Out << " -- (";
Base.getBase()->printQualifiedName(Out);
Out << ", " << Base.getBaseOffset().getQuantity();
Out << ") vtable address --\n";
} else {
CharUnits BaseOffset =
AddressPointsByIndex.lower_bound(NextIndex)->second.getBaseOffset();
std::set<std::string> ClassNames;
for (const auto &I :
llvm::make_range(AddressPointsByIndex.equal_range(NextIndex))) {
assert(I.second.getBaseOffset() == BaseOffset &&
"Invalid base offset!");
const CXXRecordDecl *RD = I.second.getBase();
ClassNames.insert(RD->getQualifiedNameAsString());
}
for (const std::string &Name : ClassNames) {
Out << " -- (" << Name;
Out << ", " << BaseOffset.getQuantity() << ") vtable address --\n";
}
}
}
}
Out << '\n';
if (isBuildingConstructorVTable())
return;
if (MostDerivedClass->getNumVBases()) {
std::map<std::string, CharUnits> ClassNamesAndOffsets;
for (const auto &I : VBaseOffsetOffsets) {
std::string ClassName = I.first->getQualifiedNameAsString();
CharUnits OffsetOffset = I.second;
ClassNamesAndOffsets.insert(std::make_pair(ClassName, OffsetOffset));
}
Out << "Virtual base offset offsets for '";
MostDerivedClass->printQualifiedName(Out);
Out << "' (";
Out << ClassNamesAndOffsets.size();
Out << (ClassNamesAndOffsets.size() == 1 ? " entry" : " entries") << ").\n";
for (const auto &I : ClassNamesAndOffsets)
Out << " " << I.first << " | " << I.second.getQuantity() << '\n';
Out << "\n";
}
if (!Thunks.empty()) {
std::map<std::string, const CXXMethodDecl *> MethodNamesAndDecls;
for (const auto &I : Thunks) {
const CXXMethodDecl *MD = I.first;
std::string MethodName =
PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
MD);
MethodNamesAndDecls.insert(std::make_pair(MethodName, MD));
}
for (const auto &I : MethodNamesAndDecls) {
const std::string &MethodName = I.first;
const CXXMethodDecl *MD = I.second;
ThunkInfoVectorTy ThunksVector = Thunks[MD];
llvm::sort(ThunksVector, [](const ThunkInfo &LHS, const ThunkInfo &RHS) {
assert(LHS.Method == nullptr && RHS.Method == nullptr);
return std::tie(LHS.This, LHS.Return) < std::tie(RHS.This, RHS.Return);
});
Out << "Thunks for '" << MethodName << "' (" << ThunksVector.size();
Out << (ThunksVector.size() == 1 ? " entry" : " entries") << ").\n";
for (unsigned I = 0, E = ThunksVector.size(); I != E; ++I) {
const ThunkInfo &Thunk = ThunksVector[I];
Out << llvm::format("%4d | ", I);
if (!Thunk.Return.isEmpty()) {
Out << "return adjustment: " << Thunk.Return.NonVirtual;
Out << " non-virtual";
if (Thunk.Return.Virtual.Itanium.VBaseOffsetOffset) {
Out << ", " << Thunk.Return.Virtual.Itanium.VBaseOffsetOffset;
Out << " vbase offset offset";
}
if (!Thunk.This.isEmpty())
Out << "\n ";
}
if (!Thunk.This.isEmpty()) {
Out << "this adjustment: ";
Out << Thunk.This.NonVirtual << " non-virtual";
if (Thunk.This.Virtual.Itanium.VCallOffsetOffset) {
Out << ", " << Thunk.This.Virtual.Itanium.VCallOffsetOffset;
Out << " vcall offset offset";
}
}
Out << '\n';
}
Out << '\n';
}
}
std::map<uint64_t, std::string> IndicesMap;
for (const auto *MD : MostDerivedClass->methods()) {
if (!ItaniumVTableContext::hasVtableSlot(MD))
continue;
MD = MD->getCanonicalDecl();
std::string MethodName =
PredefinedExpr::ComputeName(PredefinedExpr::PrettyFunctionNoVirtual,
MD);
if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
GlobalDecl GD(DD, Dtor_Complete);
assert(MethodVTableIndices.count(GD));
uint64_t VTableIndex = MethodVTableIndices[GD];
IndicesMap[VTableIndex] = MethodName + " [complete]";
IndicesMap[VTableIndex + 1] = MethodName + " [deleting]";
} else {
assert(MethodVTableIndices.count(MD));
IndicesMap[MethodVTableIndices[MD]] = MethodName;
}
}
if (!IndicesMap.empty()) {
Out << "VTable indices for '";
MostDerivedClass->printQualifiedName(Out);
Out << "' (" << IndicesMap.size() << " entries).\n";
for (const auto &I : IndicesMap) {
uint64_t VTableIndex = I.first;
const std::string &MethodName = I.second;
Out << llvm::format("%4" PRIu64 " | ", VTableIndex) << MethodName
<< '\n';
}
}
Out << '\n';
}
}
static VTableLayout::AddressPointsIndexMapTy
MakeAddressPointIndices(const VTableLayout::AddressPointsMapTy &addressPoints,
unsigned numVTables) {
VTableLayout::AddressPointsIndexMapTy indexMap(numVTables);
for (auto it = addressPoints.begin(); it != addressPoints.end(); ++it) {
const auto &addressPointLoc = it->second;
unsigned vtableIndex = addressPointLoc.VTableIndex;
unsigned addressPoint = addressPointLoc.AddressPointIndex;
if (indexMap[vtableIndex]) {
assert(indexMap[vtableIndex] == addressPoint &&
"Every vtable index should have a unique address point. Found a "
"vtable that has two different address points.");
} else {
indexMap[vtableIndex] = addressPoint;
}
}
return indexMap;
}
VTableLayout::VTableLayout(ArrayRef<size_t> VTableIndices,
ArrayRef<VTableComponent> VTableComponents,
ArrayRef<VTableThunkTy> VTableThunks,
const AddressPointsMapTy &AddressPoints)
: VTableComponents(VTableComponents), VTableThunks(VTableThunks),
AddressPoints(AddressPoints), AddressPointIndices(MakeAddressPointIndices(
AddressPoints, VTableIndices.size())) {
if (VTableIndices.size() <= 1)
assert(VTableIndices.size() == 1 && VTableIndices[0] == 0);
else
this->VTableIndices = OwningArrayRef<size_t>(VTableIndices);
llvm::sort(this->VTableThunks, [](const VTableLayout::VTableThunkTy &LHS,
const VTableLayout::VTableThunkTy &RHS) {
assert((LHS.first != RHS.first || LHS.second == RHS.second) &&
"Different thunks should have unique indices!");
return LHS.first < RHS.first;
});
}
VTableLayout::~VTableLayout() { }
bool VTableContextBase::hasVtableSlot(const CXXMethodDecl *MD) {
return MD->isVirtual() && !MD->isConsteval();
}
ItaniumVTableContext::ItaniumVTableContext(
ASTContext &Context, VTableComponentLayout ComponentLayout)
: VTableContextBase(false), ComponentLayout(ComponentLayout) {}
ItaniumVTableContext::~ItaniumVTableContext() {}
uint64_t ItaniumVTableContext::getMethodVTableIndex(GlobalDecl GD) {
GD = GD.getCanonicalDecl();
MethodVTableIndicesTy::iterator I = MethodVTableIndices.find(GD);
if (I != MethodVTableIndices.end())
return I->second;
const CXXRecordDecl *RD = cast<CXXMethodDecl>(GD.getDecl())->getParent();
computeVTableRelatedInformation(RD);
I = MethodVTableIndices.find(GD);
assert(I != MethodVTableIndices.end() && "Did not find index!");
return I->second;
}
CharUnits
ItaniumVTableContext::getVirtualBaseOffsetOffset(const CXXRecordDecl *RD,
const CXXRecordDecl *VBase) {
ClassPairTy ClassPair(RD, VBase);
VirtualBaseClassOffsetOffsetsMapTy::iterator I =
VirtualBaseClassOffsetOffsets.find(ClassPair);
if (I != VirtualBaseClassOffsetOffsets.end())
return I->second;
VCallAndVBaseOffsetBuilder Builder(*this, RD, RD, nullptr,
BaseSubobject(RD, CharUnits::Zero()),
false,
CharUnits::Zero());
for (const auto &I : Builder.getVBaseOffsetOffsets()) {
ClassPairTy ClassPair(RD, I.first);
VirtualBaseClassOffsetOffsets.insert(std::make_pair(ClassPair, I.second));
}
I = VirtualBaseClassOffsetOffsets.find(ClassPair);
assert(I != VirtualBaseClassOffsetOffsets.end() && "Did not find index!");
return I->second;
}
static std::unique_ptr<VTableLayout>
CreateVTableLayout(const ItaniumVTableBuilder &Builder) {
SmallVector<VTableLayout::VTableThunkTy, 1>
VTableThunks(Builder.vtable_thunks_begin(), Builder.vtable_thunks_end());
return std::make_unique<VTableLayout>(
Builder.VTableIndices, Builder.vtable_components(), VTableThunks,
Builder.getAddressPoints());
}
void
ItaniumVTableContext::computeVTableRelatedInformation(const CXXRecordDecl *RD) {
std::unique_ptr<const VTableLayout> &Entry = VTableLayouts[RD];
if (Entry)
return;
ItaniumVTableBuilder Builder(*this, RD, CharUnits::Zero(),
false, RD);
Entry = CreateVTableLayout(Builder);
MethodVTableIndices.insert(Builder.vtable_indices_begin(),
Builder.vtable_indices_end());
Thunks.insert(Builder.thunks_begin(), Builder.thunks_end());
if (!RD->getNumVBases())
return;
const CXXRecordDecl *VBase =
RD->vbases_begin()->getType()->getAsCXXRecordDecl();
if (VirtualBaseClassOffsetOffsets.count(std::make_pair(RD, VBase)))
return;
for (const auto &I : Builder.getVBaseOffsetOffsets()) {
ClassPairTy ClassPair(RD, I.first);
VirtualBaseClassOffsetOffsets.insert(std::make_pair(ClassPair, I.second));
}
}
std::unique_ptr<VTableLayout>
ItaniumVTableContext::createConstructionVTableLayout(
const CXXRecordDecl *MostDerivedClass, CharUnits MostDerivedClassOffset,
bool MostDerivedClassIsVirtual, const CXXRecordDecl *LayoutClass) {
ItaniumVTableBuilder Builder(*this, MostDerivedClass, MostDerivedClassOffset,
MostDerivedClassIsVirtual, LayoutClass);
return CreateVTableLayout(Builder);
}
namespace {
class VFTableBuilder {
public:
typedef llvm::DenseMap<GlobalDecl, MethodVFTableLocation>
MethodVFTableLocationsTy;
typedef llvm::iterator_range<MethodVFTableLocationsTy::const_iterator>
method_locations_range;
private:
MicrosoftVTableContext &VTables;
ASTContext &Context;
const CXXRecordDecl *MostDerivedClass;
const ASTRecordLayout &MostDerivedClassLayout;
const VPtrInfo &WhichVFPtr;
const FinalOverriders Overriders;
SmallVector<VTableComponent, 64> Components;
MethodVFTableLocationsTy MethodVFTableLocations;
bool HasRTTIComponent = false;
struct MethodInfo {
const uint64_t VBTableIndex;
const uint64_t VFTableIndex;
bool Shadowed;
bool UsesExtraSlot;
MethodInfo(uint64_t VBTableIndex, uint64_t VFTableIndex,
bool UsesExtraSlot = false)
: VBTableIndex(VBTableIndex), VFTableIndex(VFTableIndex),
Shadowed(false), UsesExtraSlot(UsesExtraSlot) {}
MethodInfo()
: VBTableIndex(0), VFTableIndex(0), Shadowed(false),
UsesExtraSlot(false) {}
};
typedef llvm::DenseMap<const CXXMethodDecl *, MethodInfo> MethodInfoMapTy;
MethodInfoMapTy MethodInfoMap;
typedef llvm::DenseMap<uint64_t, ThunkInfo> VTableThunksMapTy;
VTableThunksMapTy VTableThunks;
typedef SmallVector<ThunkInfo, 1> ThunkInfoVectorTy;
typedef llvm::DenseMap<const CXXMethodDecl *, ThunkInfoVectorTy> ThunksMapTy;
ThunksMapTy Thunks;
void AddThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk) {
SmallVector<ThunkInfo, 1> &ThunksVector = Thunks[MD];
if (llvm::is_contained(ThunksVector, Thunk))
return;
ThunksVector.push_back(Thunk);
}
CharUnits ComputeThisOffset(FinalOverriders::OverriderInfo Overrider);
void CalculateVtordispAdjustment(FinalOverriders::OverriderInfo Overrider,
CharUnits ThisOffset, ThisAdjustment &TA);
void AddMethod(const CXXMethodDecl *MD, ThunkInfo TI) {
if (!TI.isEmpty()) {
VTableThunks[Components.size()] = TI;
AddThunk(MD, TI);
}
if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
assert(TI.Return.isEmpty() &&
"Destructor can't have return adjustment!");
Components.push_back(VTableComponent::MakeDeletingDtor(DD));
} else {
Components.push_back(VTableComponent::MakeFunction(MD));
}
}
void AddMethods(BaseSubobject Base, unsigned BaseDepth,
const CXXRecordDecl *LastVBase,
BasesSetVectorTy &VisitedBases);
void LayoutVFTable() {
if (HasRTTIComponent)
Components.push_back(VTableComponent::MakeRTTI(MostDerivedClass));
BasesSetVectorTy VisitedBases;
AddMethods(BaseSubobject(MostDerivedClass, CharUnits::Zero()), 0, nullptr,
VisitedBases);
assert(!Components.empty() && "vftable can't be empty");
assert(MethodVFTableLocations.empty());
for (const auto &I : MethodInfoMap) {
const CXXMethodDecl *MD = I.first;
const MethodInfo &MI = I.second;
assert(MD == MD->getCanonicalDecl());
if (MD->getParent() != MostDerivedClass || MI.Shadowed)
continue;
MethodVFTableLocation Loc(MI.VBTableIndex, WhichVFPtr.getVBaseWithVPtr(),
WhichVFPtr.NonVirtualOffset, MI.VFTableIndex);
if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD)) {
MethodVFTableLocations[GlobalDecl(DD, Dtor_Deleting)] = Loc;
} else {
MethodVFTableLocations[MD] = Loc;
}
}
}
public:
VFTableBuilder(MicrosoftVTableContext &VTables,
const CXXRecordDecl *MostDerivedClass, const VPtrInfo &Which)
: VTables(VTables),
Context(MostDerivedClass->getASTContext()),
MostDerivedClass(MostDerivedClass),
MostDerivedClassLayout(Context.getASTRecordLayout(MostDerivedClass)),
WhichVFPtr(Which),
Overriders(MostDerivedClass, CharUnits(), MostDerivedClass) {
if (Context.getLangOpts().RTTIData)
HasRTTIComponent = true;
LayoutVFTable();
if (Context.getLangOpts().DumpVTableLayouts)
dumpLayout(llvm::outs());
}
uint64_t getNumThunks() const { return Thunks.size(); }
ThunksMapTy::const_iterator thunks_begin() const { return Thunks.begin(); }
ThunksMapTy::const_iterator thunks_end() const { return Thunks.end(); }
method_locations_range vtable_locations() const {
return method_locations_range(MethodVFTableLocations.begin(),
MethodVFTableLocations.end());
}
ArrayRef<VTableComponent> vtable_components() const { return Components; }
VTableThunksMapTy::const_iterator vtable_thunks_begin() const {
return VTableThunks.begin();
}
VTableThunksMapTy::const_iterator vtable_thunks_end() const {
return VTableThunks.end();
}
void dumpLayout(raw_ostream &);
};
}
CharUnits
VFTableBuilder::ComputeThisOffset(FinalOverriders::OverriderInfo Overrider) {
BasesSetVectorTy Bases;
{
OverriddenMethodsSetTy VisitedOverriddenMethods;
auto InitialOverriddenDefinitionCollector = [&](
const CXXMethodDecl *OverriddenMD) {
if (OverriddenMD->size_overridden_methods() == 0)
Bases.insert(OverriddenMD->getParent());
return VisitedOverriddenMethods.insert(OverriddenMD).second;
};
visitAllOverriddenMethods(Overrider.Method,
InitialOverriddenDefinitionCollector);
}
if (Bases.size() == 0)
return Overrider.Offset;
CXXBasePaths Paths;
Overrider.Method->getParent()->lookupInBases(
[&Bases](const CXXBaseSpecifier *Specifier, CXXBasePath &) {
return Bases.count(Specifier->getType()->getAsCXXRecordDecl());
},
Paths);
CharUnits Ret;
bool First = true;
const ASTRecordLayout &OverriderRDLayout =
Context.getASTRecordLayout(Overrider.Method->getParent());
for (const CXXBasePath &Path : Paths) {
CharUnits ThisOffset = Overrider.Offset;
CharUnits LastVBaseOffset;
for (const CXXBasePathElement &Element : Path) {
QualType CurTy = Element.Base->getType();
const CXXRecordDecl *PrevRD = Element.Class,
*CurRD = CurTy->getAsCXXRecordDecl();
const ASTRecordLayout &Layout = Context.getASTRecordLayout(PrevRD);
if (Element.Base->isVirtual()) {
LastVBaseOffset = ThisOffset =
Overrider.Offset + OverriderRDLayout.getVBaseClassOffset(CurRD);
} else {
ThisOffset += Layout.getBaseClassOffset(CurRD);
}
}
if (isa<CXXDestructorDecl>(Overrider.Method)) {
if (LastVBaseOffset.isZero()) {
ThisOffset = Overrider.Offset;
} else {
ThisOffset = LastVBaseOffset;
}
}
if (Ret > ThisOffset || First) {
First = false;
Ret = ThisOffset;
}
}
assert(!First && "Method not found in the given subobject?");
return Ret;
}
void VFTableBuilder::CalculateVtordispAdjustment(
FinalOverriders::OverriderInfo Overrider, CharUnits ThisOffset,
ThisAdjustment &TA) {
const ASTRecordLayout::VBaseOffsetsMapTy &VBaseMap =
MostDerivedClassLayout.getVBaseOffsetsMap();
const ASTRecordLayout::VBaseOffsetsMapTy::const_iterator &VBaseMapEntry =
VBaseMap.find(WhichVFPtr.getVBaseWithVPtr());
assert(VBaseMapEntry != VBaseMap.end());
if (!VBaseMapEntry->second.hasVtorDisp() ||
Overrider.VirtualBase == WhichVFPtr.getVBaseWithVPtr())
return;
CharUnits OffsetOfVBaseWithVFPtr = VBaseMapEntry->second.VBaseOffset;
TA.Virtual.Microsoft.VtordispOffset =
(OffsetOfVBaseWithVFPtr - WhichVFPtr.FullOffsetInMDC).getQuantity() - 4;
if (Overrider.Method->getParent() == MostDerivedClass ||
!Overrider.VirtualBase)
return;
TA.Virtual.Microsoft.VBPtrOffset =
(OffsetOfVBaseWithVFPtr + WhichVFPtr.NonVirtualOffset -
MostDerivedClassLayout.getVBPtrOffset()).getQuantity();
TA.Virtual.Microsoft.VBOffsetOffset =
Context.getTypeSizeInChars(Context.IntTy).getQuantity() *
VTables.getVBTableIndex(MostDerivedClass, Overrider.VirtualBase);
TA.NonVirtual = (ThisOffset - Overrider.Offset).getQuantity();
}
static void GroupNewVirtualOverloads(
const CXXRecordDecl *RD,
SmallVector<const CXXMethodDecl *, 10> &VirtualMethods) {
typedef SmallVector<const CXXMethodDecl *, 1> MethodGroup;
SmallVector<MethodGroup, 10> Groups;
typedef llvm::DenseMap<DeclarationName, unsigned> VisitedGroupIndicesTy;
VisitedGroupIndicesTy VisitedGroupIndices;
for (const auto *D : RD->decls()) {
const auto *ND = dyn_cast<NamedDecl>(D);
if (!ND)
continue;
VisitedGroupIndicesTy::iterator J;
bool Inserted;
std::tie(J, Inserted) = VisitedGroupIndices.insert(
std::make_pair(ND->getDeclName(), Groups.size()));
if (Inserted)
Groups.push_back(MethodGroup());
if (const auto *MD = dyn_cast<CXXMethodDecl>(ND))
if (MicrosoftVTableContext::hasVtableSlot(MD))
Groups[J->second].push_back(MD->getCanonicalDecl());
}
for (const MethodGroup &Group : Groups)
VirtualMethods.append(Group.rbegin(), Group.rend());
}
static bool isDirectVBase(const CXXRecordDecl *Base, const CXXRecordDecl *RD) {
for (const auto &B : RD->bases()) {
if (B.isVirtual() && B.getType()->getAsCXXRecordDecl() == Base)
return true;
}
return false;
}
void VFTableBuilder::AddMethods(BaseSubobject Base, unsigned BaseDepth,
const CXXRecordDecl *LastVBase,
BasesSetVectorTy &VisitedBases) {
const CXXRecordDecl *RD = Base.getBase();
if (!RD->isPolymorphic())
return;
const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
const CXXRecordDecl *NextBase = nullptr, *NextLastVBase = LastVBase;
CharUnits NextBaseOffset;
if (BaseDepth < WhichVFPtr.PathToIntroducingObject.size()) {
NextBase = WhichVFPtr.PathToIntroducingObject[BaseDepth];
if (isDirectVBase(NextBase, RD)) {
NextLastVBase = NextBase;
NextBaseOffset = MostDerivedClassLayout.getVBaseClassOffset(NextBase);
} else {
NextBaseOffset =
Base.getBaseOffset() + Layout.getBaseClassOffset(NextBase);
}
} else if (const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase()) {
assert(!Layout.isPrimaryBaseVirtual() &&
"No primary virtual bases in this ABI");
NextBase = PrimaryBase;
NextBaseOffset = Base.getBaseOffset();
}
if (NextBase) {
AddMethods(BaseSubobject(NextBase, NextBaseOffset), BaseDepth + 1,
NextLastVBase, VisitedBases);
if (!VisitedBases.insert(NextBase))
llvm_unreachable("Found a duplicate primary base!");
}
SmallVector<const CXXMethodDecl*, 10> VirtualMethods;
GroupNewVirtualOverloads(RD, VirtualMethods);
for (const CXXMethodDecl *MD : VirtualMethods) {
FinalOverriders::OverriderInfo FinalOverrider =
Overriders.getOverrider(MD, Base.getBaseOffset());
const CXXMethodDecl *FinalOverriderMD = FinalOverrider.Method;
const CXXMethodDecl *OverriddenMD =
FindNearestOverriddenMethod(MD, VisitedBases);
ThisAdjustment ThisAdjustmentOffset;
bool ReturnAdjustingThunk = false, ForceReturnAdjustmentMangling = false;
CharUnits ThisOffset = ComputeThisOffset(FinalOverrider);
ThisAdjustmentOffset.NonVirtual =
(ThisOffset - WhichVFPtr.FullOffsetInMDC).getQuantity();
if ((OverriddenMD || FinalOverriderMD != MD) &&
WhichVFPtr.getVBaseWithVPtr())
CalculateVtordispAdjustment(FinalOverrider, ThisOffset,
ThisAdjustmentOffset);
unsigned VBIndex =
LastVBase ? VTables.getVBTableIndex(MostDerivedClass, LastVBase) : 0;
if (OverriddenMD) {
MethodInfoMapTy::iterator OverriddenMDIterator =
MethodInfoMap.find(OverriddenMD);
if (OverriddenMDIterator == MethodInfoMap.end())
continue;
MethodInfo &OverriddenMethodInfo = OverriddenMDIterator->second;
VBIndex = OverriddenMethodInfo.VBTableIndex;
ReturnAdjustingThunk = !ComputeReturnAdjustmentBaseOffset(
Context, MD, OverriddenMD).isEmpty() ||
OverriddenMethodInfo.UsesExtraSlot;
if (!ReturnAdjustingThunk) {
MethodInfo MI(VBIndex, OverriddenMethodInfo.VFTableIndex);
MethodInfoMap.erase(OverriddenMDIterator);
assert(!MethodInfoMap.count(MD) &&
"Should not have method info for this method yet!");
MethodInfoMap.insert(std::make_pair(MD, MI));
continue;
}
OverriddenMethodInfo.Shadowed = true;
ForceReturnAdjustmentMangling =
!(MD == FinalOverriderMD && ThisAdjustmentOffset.isEmpty());
} else if (Base.getBaseOffset() != WhichVFPtr.FullOffsetInMDC ||
MD->size_overridden_methods()) {
continue;
}
MethodInfo MI(VBIndex,
HasRTTIComponent ? Components.size() - 1 : Components.size(),
ReturnAdjustingThunk);
assert(!MethodInfoMap.count(MD) &&
"Should not have method info for this method yet!");
MethodInfoMap.insert(std::make_pair(MD, MI));
BaseOffset ReturnAdjustmentOffset;
ReturnAdjustment ReturnAdjustment;
if (!FinalOverriderMD->isPure()) {
ReturnAdjustmentOffset =
ComputeReturnAdjustmentBaseOffset(Context, FinalOverriderMD, MD);
}
if (!ReturnAdjustmentOffset.isEmpty()) {
ForceReturnAdjustmentMangling = true;
ReturnAdjustment.NonVirtual =
ReturnAdjustmentOffset.NonVirtualOffset.getQuantity();
if (ReturnAdjustmentOffset.VirtualBase) {
const ASTRecordLayout &DerivedLayout =
Context.getASTRecordLayout(ReturnAdjustmentOffset.DerivedClass);
ReturnAdjustment.Virtual.Microsoft.VBPtrOffset =
DerivedLayout.getVBPtrOffset().getQuantity();
ReturnAdjustment.Virtual.Microsoft.VBIndex =
VTables.getVBTableIndex(ReturnAdjustmentOffset.DerivedClass,
ReturnAdjustmentOffset.VirtualBase);
}
}
AddMethod(FinalOverriderMD,
ThunkInfo(ThisAdjustmentOffset, ReturnAdjustment,
ForceReturnAdjustmentMangling ? MD : nullptr));
}
}
static void PrintBasePath(const VPtrInfo::BasePath &Path, raw_ostream &Out) {
for (const CXXRecordDecl *Elem : llvm::reverse(Path)) {
Out << "'";
Elem->printQualifiedName(Out);
Out << "' in ";
}
}
static void dumpMicrosoftThunkAdjustment(const ThunkInfo &TI, raw_ostream &Out,
bool ContinueFirstLine) {
const ReturnAdjustment &R = TI.Return;
bool Multiline = false;
const char *LinePrefix = "\n ";
if (!R.isEmpty() || TI.Method) {
if (!ContinueFirstLine)
Out << LinePrefix;
Out << "[return adjustment (to type '"
<< TI.Method->getReturnType().getCanonicalType() << "'): ";
if (R.Virtual.Microsoft.VBPtrOffset)
Out << "vbptr at offset " << R.Virtual.Microsoft.VBPtrOffset << ", ";
if (R.Virtual.Microsoft.VBIndex)
Out << "vbase #" << R.Virtual.Microsoft.VBIndex << ", ";
Out << R.NonVirtual << " non-virtual]";
Multiline = true;
}
const ThisAdjustment &T = TI.This;
if (!T.isEmpty()) {
if (Multiline || !ContinueFirstLine)
Out << LinePrefix;
Out << "[this adjustment: ";
if (!TI.This.Virtual.isEmpty()) {
assert(T.Virtual.Microsoft.VtordispOffset < 0);
Out << "vtordisp at " << T.Virtual.Microsoft.VtordispOffset << ", ";
if (T.Virtual.Microsoft.VBPtrOffset) {
Out << "vbptr at " << T.Virtual.Microsoft.VBPtrOffset
<< " to the left,";
assert(T.Virtual.Microsoft.VBOffsetOffset > 0);
Out << LinePrefix << " vboffset at "
<< T.Virtual.Microsoft.VBOffsetOffset << " in the vbtable, ";
}
}
Out << T.NonVirtual << " non-virtual]";
}
}
void VFTableBuilder::dumpLayout(raw_ostream &Out) {
Out << "VFTable for ";
PrintBasePath(WhichVFPtr.PathToIntroducingObject, Out);
Out << "'";
MostDerivedClass->printQualifiedName(Out);
Out << "' (" << Components.size()
<< (Components.size() == 1 ? " entry" : " entries") << ").\n";
for (unsigned I = 0, E = Components.size(); I != E; ++I) {
Out << llvm::format("%4d | ", I);
const VTableComponent &Component = Components[I];
switch (Component.getKind()) {
case VTableComponent::CK_RTTI:
Component.getRTTIDecl()->printQualifiedName(Out);
Out << " RTTI";
break;
case VTableComponent::CK_FunctionPointer: {
const CXXMethodDecl *MD = Component.getFunctionDecl();
std::string Str = PredefinedExpr::ComputeName(
PredefinedExpr::PrettyFunctionNoVirtual, MD);
Out << Str;
if (MD->isPure())
Out << " [pure]";
if (MD->isDeleted())
Out << " [deleted]";
ThunkInfo Thunk = VTableThunks.lookup(I);
if (!Thunk.isEmpty())
dumpMicrosoftThunkAdjustment(Thunk, Out, false);
break;
}
case VTableComponent::CK_DeletingDtorPointer: {
const CXXDestructorDecl *DD = Component.getDestructorDecl();
DD->printQualifiedName(Out);
Out << "() [scalar deleting]";
if (DD->isPure())
Out << " [pure]";
ThunkInfo Thunk = VTableThunks.lookup(I);
if (!Thunk.isEmpty()) {
assert(Thunk.Return.isEmpty() &&
"No return adjustment needed for destructors!");
dumpMicrosoftThunkAdjustment(Thunk, Out, false);
}
break;
}
default:
DiagnosticsEngine &Diags = Context.getDiagnostics();
unsigned DiagID = Diags.getCustomDiagID(
DiagnosticsEngine::Error,
"Unexpected vftable component type %0 for component number %1");
Diags.Report(MostDerivedClass->getLocation(), DiagID)
<< I << Component.getKind();
}
Out << '\n';
}
Out << '\n';
if (!Thunks.empty()) {
std::map<std::string, const CXXMethodDecl *> MethodNamesAndDecls;
for (const auto &I : Thunks) {
const CXXMethodDecl *MD = I.first;
std::string MethodName = PredefinedExpr::ComputeName(
PredefinedExpr::PrettyFunctionNoVirtual, MD);
MethodNamesAndDecls.insert(std::make_pair(MethodName, MD));
}
for (const auto &MethodNameAndDecl : MethodNamesAndDecls) {
const std::string &MethodName = MethodNameAndDecl.first;
const CXXMethodDecl *MD = MethodNameAndDecl.second;
ThunkInfoVectorTy ThunksVector = Thunks[MD];
llvm::stable_sort(ThunksVector, [](const ThunkInfo &LHS,
const ThunkInfo &RHS) {
return std::tie(LHS.This, LHS.Return) < std::tie(RHS.This, RHS.Return);
});
Out << "Thunks for '" << MethodName << "' (" << ThunksVector.size();
Out << (ThunksVector.size() == 1 ? " entry" : " entries") << ").\n";
for (unsigned I = 0, E = ThunksVector.size(); I != E; ++I) {
const ThunkInfo &Thunk = ThunksVector[I];
Out << llvm::format("%4d | ", I);
dumpMicrosoftThunkAdjustment(Thunk, Out, true);
Out << '\n';
}
Out << '\n';
}
}
Out.flush();
}
static bool setsIntersect(const llvm::SmallPtrSet<const CXXRecordDecl *, 4> &A,
ArrayRef<const CXXRecordDecl *> B) {
for (const CXXRecordDecl *Decl : B) {
if (A.count(Decl))
return true;
}
return false;
}
static bool rebucketPaths(VPtrInfoVector &Paths);
void MicrosoftVTableContext::computeVTablePaths(bool ForVBTables,
const CXXRecordDecl *RD,
VPtrInfoVector &Paths) {
assert(Paths.empty());
const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
if (ForVBTables ? Layout.hasOwnVBPtr() : Layout.hasOwnVFPtr())
Paths.push_back(std::make_unique<VPtrInfo>(RD));
llvm::SmallPtrSet<const CXXRecordDecl*, 4> VBasesSeen;
for (const auto &B : RD->bases()) {
const CXXRecordDecl *Base = B.getType()->getAsCXXRecordDecl();
if (B.isVirtual() && VBasesSeen.count(Base))
continue;
if (!Base->isDynamicClass())
continue;
const VPtrInfoVector &BasePaths =
ForVBTables ? enumerateVBTables(Base) : getVFPtrOffsets(Base);
for (const std::unique_ptr<VPtrInfo> &BaseInfo : BasePaths) {
if (setsIntersect(VBasesSeen, BaseInfo->ContainingVBases))
continue;
auto P = std::make_unique<VPtrInfo>(*BaseInfo);
if (P->MangledPath.empty() || P->MangledPath.back() != Base)
P->NextBaseToMangle = Base;
if (P->ObjectWithVPtr == Base &&
Base == (ForVBTables ? Layout.getBaseSharingVBPtr()
: Layout.getPrimaryBase()))
P->ObjectWithVPtr = RD;
if (B.isVirtual())
P->ContainingVBases.push_back(Base);
else if (P->ContainingVBases.empty())
P->NonVirtualOffset += Layout.getBaseClassOffset(Base);
P->FullOffsetInMDC = P->NonVirtualOffset;
if (const CXXRecordDecl *VB = P->getVBaseWithVPtr())
P->FullOffsetInMDC += Layout.getVBaseClassOffset(VB);
Paths.push_back(std::move(P));
}
if (B.isVirtual())
VBasesSeen.insert(Base);
for (const auto &VB : Base->vbases())
VBasesSeen.insert(VB.getType()->getAsCXXRecordDecl());
}
bool Changed = true;
while (Changed)
Changed = rebucketPaths(Paths);
}
static bool extendPath(VPtrInfo &P) {
if (P.NextBaseToMangle) {
P.MangledPath.push_back(P.NextBaseToMangle);
P.NextBaseToMangle = nullptr; return true;
}
return false;
}
static bool rebucketPaths(VPtrInfoVector &Paths) {
llvm::SmallVector<std::reference_wrapper<VPtrInfo>, 2> PathsSorted(
llvm::make_pointee_range(Paths));
llvm::sort(PathsSorted, [](const VPtrInfo &LHS, const VPtrInfo &RHS) {
return LHS.MangledPath < RHS.MangledPath;
});
bool Changed = false;
for (size_t I = 0, E = PathsSorted.size(); I != E;) {
size_t BucketStart = I;
do {
++I;
} while (I != E &&
PathsSorted[BucketStart].get().MangledPath ==
PathsSorted[I].get().MangledPath);
if (I - BucketStart > 1) {
for (size_t II = BucketStart; II != I; ++II)
Changed |= extendPath(PathsSorted[II]);
assert(Changed && "no paths were extended to fix ambiguity");
}
}
return Changed;
}
MicrosoftVTableContext::~MicrosoftVTableContext() {}
namespace {
typedef llvm::SetVector<BaseSubobject, std::vector<BaseSubobject>,
llvm::DenseSet<BaseSubobject>> FullPathTy;
}
static void findPathsToSubobject(ASTContext &Context,
const ASTRecordLayout &MostDerivedLayout,
const CXXRecordDecl *RD, CharUnits Offset,
BaseSubobject IntroducingObject,
FullPathTy &FullPath,
std::list<FullPathTy> &Paths) {
if (BaseSubobject(RD, Offset) == IntroducingObject) {
Paths.push_back(FullPath);
return;
}
const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
for (const CXXBaseSpecifier &BS : RD->bases()) {
const CXXRecordDecl *Base = BS.getType()->getAsCXXRecordDecl();
CharUnits NewOffset = BS.isVirtual()
? MostDerivedLayout.getVBaseClassOffset(Base)
: Offset + Layout.getBaseClassOffset(Base);
FullPath.insert(BaseSubobject(Base, NewOffset));
findPathsToSubobject(Context, MostDerivedLayout, Base, NewOffset,
IntroducingObject, FullPath, Paths);
FullPath.pop_back();
}
}
static void removeRedundantPaths(std::list<FullPathTy> &FullPaths) {
FullPaths.remove_if([&](const FullPathTy &SpecificPath) {
for (const FullPathTy &OtherPath : FullPaths) {
if (&SpecificPath == &OtherPath)
continue;
if (llvm::all_of(SpecificPath, [&](const BaseSubobject &BSO) {
return OtherPath.contains(BSO);
})) {
return true;
}
}
return false;
});
}
static CharUnits getOffsetOfFullPath(ASTContext &Context,
const CXXRecordDecl *RD,
const FullPathTy &FullPath) {
const ASTRecordLayout &MostDerivedLayout =
Context.getASTRecordLayout(RD);
CharUnits Offset = CharUnits::fromQuantity(-1);
for (const BaseSubobject &BSO : FullPath) {
const CXXRecordDecl *Base = BSO.getBase();
if (Base == RD) {
assert(Offset.getQuantity() == -1);
Offset = CharUnits::Zero();
continue;
}
assert(Offset.getQuantity() != -1);
const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
const CXXBaseSpecifier *BaseBS = std::find_if(
RD->bases_begin(), RD->bases_end(), [&](const CXXBaseSpecifier &BS) {
return BS.getType()->getAsCXXRecordDecl() == Base;
});
Offset = BaseBS->isVirtual() ? MostDerivedLayout.getVBaseClassOffset(Base)
: Offset + Layout.getBaseClassOffset(Base);
RD = Base;
}
return Offset;
}
static const FullPathTy *selectBestPath(ASTContext &Context,
const CXXRecordDecl *RD,
const VPtrInfo &Info,
std::list<FullPathTy> &FullPaths) {
if (FullPaths.empty())
return nullptr;
if (FullPaths.size() == 1)
return &FullPaths.front();
const FullPathTy *BestPath = nullptr;
typedef std::set<const CXXMethodDecl *> OverriderSetTy;
OverriderSetTy LastOverrides;
for (const FullPathTy &SpecificPath : FullPaths) {
assert(!SpecificPath.empty());
OverriderSetTy CurrentOverrides;
const CXXRecordDecl *TopLevelRD = SpecificPath.begin()->getBase();
CharUnits BaseOffset =
getOffsetOfFullPath(Context, TopLevelRD, SpecificPath);
FinalOverriders Overriders(TopLevelRD, CharUnits::Zero(), TopLevelRD);
for (const CXXMethodDecl *MD : Info.IntroducingObject->methods()) {
if (!MicrosoftVTableContext::hasVtableSlot(MD))
continue;
FinalOverriders::OverriderInfo OI =
Overriders.getOverrider(MD->getCanonicalDecl(), BaseOffset);
const CXXMethodDecl *OverridingMethod = OI.Method;
if (ComputeReturnAdjustmentBaseOffset(Context, OverridingMethod, MD)
.isEmpty())
continue;
const CXXRecordDecl *OverridingParent = OverridingMethod->getParent();
if (llvm::none_of(SpecificPath, [&](const BaseSubobject &BSO) {
return BSO.getBase() == OverridingParent;
}))
continue;
CurrentOverrides.insert(OverridingMethod);
}
OverriderSetTy NewOverrides =
llvm::set_difference(CurrentOverrides, LastOverrides);
if (NewOverrides.empty())
continue;
OverriderSetTy MissingOverrides =
llvm::set_difference(LastOverrides, CurrentOverrides);
if (MissingOverrides.empty()) {
BestPath = &SpecificPath;
std::swap(CurrentOverrides, LastOverrides);
} else {
DiagnosticsEngine &Diags = Context.getDiagnostics();
const CXXMethodDecl *CovariantMD = *NewOverrides.begin();
const CXXMethodDecl *ConflictMD = *MissingOverrides.begin();
Diags.Report(RD->getLocation(), diag::err_vftable_ambiguous_component)
<< RD;
Diags.Report(CovariantMD->getLocation(), diag::note_covariant_thunk)
<< CovariantMD;
Diags.Report(ConflictMD->getLocation(), diag::note_covariant_thunk)
<< ConflictMD;
}
}
return BestPath ? BestPath : &FullPaths.front();
}
static void computeFullPathsForVFTables(ASTContext &Context,
const CXXRecordDecl *RD,
VPtrInfoVector &Paths) {
const ASTRecordLayout &MostDerivedLayout = Context.getASTRecordLayout(RD);
FullPathTy FullPath;
std::list<FullPathTy> FullPaths;
for (const std::unique_ptr<VPtrInfo>& Info : Paths) {
findPathsToSubobject(
Context, MostDerivedLayout, RD, CharUnits::Zero(),
BaseSubobject(Info->IntroducingObject, Info->FullOffsetInMDC), FullPath,
FullPaths);
FullPath.clear();
removeRedundantPaths(FullPaths);
Info->PathToIntroducingObject.clear();
if (const FullPathTy *BestPath =
selectBestPath(Context, RD, *Info, FullPaths))
for (const BaseSubobject &BSO : *BestPath)
Info->PathToIntroducingObject.push_back(BSO.getBase());
FullPaths.clear();
}
}
static bool vfptrIsEarlierInMDC(const ASTRecordLayout &Layout,
const MethodVFTableLocation &LHS,
const MethodVFTableLocation &RHS) {
CharUnits L = LHS.VFPtrOffset;
CharUnits R = RHS.VFPtrOffset;
if (LHS.VBase)
L += Layout.getVBaseClassOffset(LHS.VBase);
if (RHS.VBase)
R += Layout.getVBaseClassOffset(RHS.VBase);
return L < R;
}
void MicrosoftVTableContext::computeVTableRelatedInformation(
const CXXRecordDecl *RD) {
assert(RD->isDynamicClass());
if (VFPtrLocations.count(RD))
return;
const VTableLayout::AddressPointsMapTy EmptyAddressPointsMap;
{
auto VFPtrs = std::make_unique<VPtrInfoVector>();
computeVTablePaths(false, RD, *VFPtrs);
computeFullPathsForVFTables(Context, RD, *VFPtrs);
VFPtrLocations[RD] = std::move(VFPtrs);
}
MethodVFTableLocationsTy NewMethodLocations;
for (const std::unique_ptr<VPtrInfo> &VFPtr : *VFPtrLocations[RD]) {
VFTableBuilder Builder(*this, RD, *VFPtr);
VFTableIdTy id(RD, VFPtr->FullOffsetInMDC);
assert(VFTableLayouts.count(id) == 0);
SmallVector<VTableLayout::VTableThunkTy, 1> VTableThunks(
Builder.vtable_thunks_begin(), Builder.vtable_thunks_end());
VFTableLayouts[id] = std::make_unique<VTableLayout>(
ArrayRef<size_t>{0}, Builder.vtable_components(), VTableThunks,
EmptyAddressPointsMap);
Thunks.insert(Builder.thunks_begin(), Builder.thunks_end());
const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
for (const auto &Loc : Builder.vtable_locations()) {
auto Insert = NewMethodLocations.insert(Loc);
if (!Insert.second) {
const MethodVFTableLocation &NewLoc = Loc.second;
MethodVFTableLocation &OldLoc = Insert.first->second;
if (vfptrIsEarlierInMDC(Layout, NewLoc, OldLoc))
OldLoc = NewLoc;
}
}
}
MethodVFTableLocations.insert(NewMethodLocations.begin(),
NewMethodLocations.end());
if (Context.getLangOpts().DumpVTableLayouts)
dumpMethodLocations(RD, NewMethodLocations, llvm::outs());
}
void MicrosoftVTableContext::dumpMethodLocations(
const CXXRecordDecl *RD, const MethodVFTableLocationsTy &NewMethods,
raw_ostream &Out) {
std::map<MethodVFTableLocation, std::string> IndicesMap;
bool HasNonzeroOffset = false;
for (const auto &I : NewMethods) {
const CXXMethodDecl *MD = cast<const CXXMethodDecl>(I.first.getDecl());
assert(hasVtableSlot(MD));
std::string MethodName = PredefinedExpr::ComputeName(
PredefinedExpr::PrettyFunctionNoVirtual, MD);
if (isa<CXXDestructorDecl>(MD)) {
IndicesMap[I.second] = MethodName + " [scalar deleting]";
} else {
IndicesMap[I.second] = MethodName;
}
if (!I.second.VFPtrOffset.isZero() || I.second.VBTableIndex != 0)
HasNonzeroOffset = true;
}
if (!IndicesMap.empty()) {
Out << "VFTable indices for ";
Out << "'";
RD->printQualifiedName(Out);
Out << "' (" << IndicesMap.size()
<< (IndicesMap.size() == 1 ? " entry" : " entries") << ").\n";
CharUnits LastVFPtrOffset = CharUnits::fromQuantity(-1);
uint64_t LastVBIndex = 0;
for (const auto &I : IndicesMap) {
CharUnits VFPtrOffset = I.first.VFPtrOffset;
uint64_t VBIndex = I.first.VBTableIndex;
if (HasNonzeroOffset &&
(VFPtrOffset != LastVFPtrOffset || VBIndex != LastVBIndex)) {
assert(VBIndex > LastVBIndex || VFPtrOffset > LastVFPtrOffset);
Out << " -- accessible via ";
if (VBIndex)
Out << "vbtable index " << VBIndex << ", ";
Out << "vfptr at offset " << VFPtrOffset.getQuantity() << " --\n";
LastVFPtrOffset = VFPtrOffset;
LastVBIndex = VBIndex;
}
uint64_t VTableIndex = I.first.Index;
const std::string &MethodName = I.second;
Out << llvm::format("%4" PRIu64 " | ", VTableIndex) << MethodName << '\n';
}
Out << '\n';
}
Out.flush();
}
const VirtualBaseInfo &MicrosoftVTableContext::computeVBTableRelatedInformation(
const CXXRecordDecl *RD) {
VirtualBaseInfo *VBI;
{
std::unique_ptr<VirtualBaseInfo> &Entry = VBaseInfo[RD];
if (Entry)
return *Entry;
Entry = std::make_unique<VirtualBaseInfo>();
VBI = Entry.get();
}
computeVTablePaths(true, RD, VBI->VBPtrPaths);
const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
if (const CXXRecordDecl *VBPtrBase = Layout.getBaseSharingVBPtr()) {
const VirtualBaseInfo &BaseInfo =
computeVBTableRelatedInformation(VBPtrBase);
VBI->VBTableIndices.insert(BaseInfo.VBTableIndices.begin(),
BaseInfo.VBTableIndices.end());
}
unsigned VBTableIndex = 1 + VBI->VBTableIndices.size();
for (const auto &VB : RD->vbases()) {
const CXXRecordDecl *CurVBase = VB.getType()->getAsCXXRecordDecl();
if (!VBI->VBTableIndices.count(CurVBase))
VBI->VBTableIndices[CurVBase] = VBTableIndex++;
}
return *VBI;
}
unsigned MicrosoftVTableContext::getVBTableIndex(const CXXRecordDecl *Derived,
const CXXRecordDecl *VBase) {
const VirtualBaseInfo &VBInfo = computeVBTableRelatedInformation(Derived);
assert(VBInfo.VBTableIndices.count(VBase));
return VBInfo.VBTableIndices.find(VBase)->second;
}
const VPtrInfoVector &
MicrosoftVTableContext::enumerateVBTables(const CXXRecordDecl *RD) {
return computeVBTableRelatedInformation(RD).VBPtrPaths;
}
const VPtrInfoVector &
MicrosoftVTableContext::getVFPtrOffsets(const CXXRecordDecl *RD) {
computeVTableRelatedInformation(RD);
assert(VFPtrLocations.count(RD) && "Couldn't find vfptr locations");
return *VFPtrLocations[RD];
}
const VTableLayout &
MicrosoftVTableContext::getVFTableLayout(const CXXRecordDecl *RD,
CharUnits VFPtrOffset) {
computeVTableRelatedInformation(RD);
VFTableIdTy id(RD, VFPtrOffset);
assert(VFTableLayouts.count(id) && "Couldn't find a VFTable at this offset");
return *VFTableLayouts[id];
}
MethodVFTableLocation
MicrosoftVTableContext::getMethodVFTableLocation(GlobalDecl GD) {
assert(hasVtableSlot(cast<CXXMethodDecl>(GD.getDecl())) &&
"Only use this method for virtual methods or dtors");
if (isa<CXXDestructorDecl>(GD.getDecl()))
assert(GD.getDtorType() == Dtor_Deleting);
GD = GD.getCanonicalDecl();
MethodVFTableLocationsTy::iterator I = MethodVFTableLocations.find(GD);
if (I != MethodVFTableLocations.end())
return I->second;
const CXXRecordDecl *RD = cast<CXXMethodDecl>(GD.getDecl())->getParent();
computeVTableRelatedInformation(RD);
I = MethodVFTableLocations.find(GD);
assert(I != MethodVFTableLocations.end() && "Did not find index!");
return I->second;
}