#include "clang/AST/CXXInheritance.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/Decl.h"
#include "clang/AST/DeclBase.h"
#include "clang/AST/DeclCXX.h"
#include "clang/AST/DeclTemplate.h"
#include "clang/AST/RecordLayout.h"
#include "clang/AST/TemplateName.h"
#include "clang/AST/Type.h"
#include "clang/Basic/LLVM.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/iterator_range.h"
#include "llvm/Support/Casting.h"
#include <algorithm>
#include <utility>
#include <cassert>
#include <vector>
using namespace clang;
bool CXXBasePaths::isAmbiguous(CanQualType BaseType) {
BaseType = BaseType.getUnqualifiedType();
IsVirtBaseAndNumberNonVirtBases Subobjects = ClassSubobjects[BaseType];
return Subobjects.NumberOfNonVirtBases + (Subobjects.IsVirtBase ? 1 : 0) > 1;
}
void CXXBasePaths::clear() {
Paths.clear();
ClassSubobjects.clear();
VisitedDependentRecords.clear();
ScratchPath.clear();
DetectedVirtual = nullptr;
}
void CXXBasePaths::swap(CXXBasePaths &Other) {
std::swap(Origin, Other.Origin);
Paths.swap(Other.Paths);
ClassSubobjects.swap(Other.ClassSubobjects);
VisitedDependentRecords.swap(Other.VisitedDependentRecords);
std::swap(FindAmbiguities, Other.FindAmbiguities);
std::swap(RecordPaths, Other.RecordPaths);
std::swap(DetectVirtual, Other.DetectVirtual);
std::swap(DetectedVirtual, Other.DetectedVirtual);
}
bool CXXRecordDecl::isDerivedFrom(const CXXRecordDecl *Base) const {
CXXBasePaths Paths(false, false,
false);
return isDerivedFrom(Base, Paths);
}
bool CXXRecordDecl::isDerivedFrom(const CXXRecordDecl *Base,
CXXBasePaths &Paths) const {
if (getCanonicalDecl() == Base->getCanonicalDecl())
return false;
Paths.setOrigin(const_cast<CXXRecordDecl*>(this));
const CXXRecordDecl *BaseDecl = Base->getCanonicalDecl();
return lookupInBases(
[BaseDecl](const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
return FindBaseClass(Specifier, Path, BaseDecl);
},
Paths);
}
bool CXXRecordDecl::isVirtuallyDerivedFrom(const CXXRecordDecl *Base) const {
if (!getNumVBases())
return false;
CXXBasePaths Paths(false, false,
false);
if (getCanonicalDecl() == Base->getCanonicalDecl())
return false;
Paths.setOrigin(const_cast<CXXRecordDecl*>(this));
const CXXRecordDecl *BaseDecl = Base->getCanonicalDecl();
return lookupInBases(
[BaseDecl](const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
return FindVirtualBaseClass(Specifier, Path, BaseDecl);
},
Paths);
}
bool CXXRecordDecl::isProvablyNotDerivedFrom(const CXXRecordDecl *Base) const {
const CXXRecordDecl *TargetDecl = Base->getCanonicalDecl();
return forallBases([TargetDecl](const CXXRecordDecl *Base) {
return Base->getCanonicalDecl() != TargetDecl;
});
}
bool
CXXRecordDecl::isCurrentInstantiation(const DeclContext *CurContext) const {
assert(isDependentContext());
for (; !CurContext->isFileContext(); CurContext = CurContext->getParent())
if (CurContext->Equals(this))
return true;
return false;
}
bool CXXRecordDecl::forallBases(ForallBasesCallback BaseMatches) const {
SmallVector<const CXXRecordDecl*, 8> Queue;
const CXXRecordDecl *Record = this;
while (true) {
for (const auto &I : Record->bases()) {
const RecordType *Ty = I.getType()->getAs<RecordType>();
if (!Ty)
return false;
CXXRecordDecl *Base =
cast_or_null<CXXRecordDecl>(Ty->getDecl()->getDefinition());
if (!Base ||
(Base->isDependentContext() &&
!Base->isCurrentInstantiation(Record))) {
return false;
}
Queue.push_back(Base);
if (!BaseMatches(Base))
return false;
}
if (Queue.empty())
break;
Record = Queue.pop_back_val(); }
return true;
}
bool CXXBasePaths::lookupInBases(ASTContext &Context,
const CXXRecordDecl *Record,
CXXRecordDecl::BaseMatchesCallback BaseMatches,
bool LookupInDependent) {
bool FoundPath = false;
AccessSpecifier AccessToHere = ScratchPath.Access;
bool IsFirstStep = ScratchPath.empty();
for (const auto &BaseSpec : Record->bases()) {
QualType BaseType =
Context.getCanonicalType(BaseSpec.getType()).getUnqualifiedType();
if (!LookupInDependent && BaseType->isDependentType())
continue;
IsVirtBaseAndNumberNonVirtBases &Subobjects = ClassSubobjects[BaseType];
bool VisitBase = true;
bool SetVirtual = false;
if (BaseSpec.isVirtual()) {
VisitBase = !Subobjects.IsVirtBase;
Subobjects.IsVirtBase = true;
if (isDetectingVirtual() && DetectedVirtual == nullptr) {
DetectedVirtual = BaseType->getAs<RecordType>();
SetVirtual = true;
}
} else {
++Subobjects.NumberOfNonVirtBases;
}
if (isRecordingPaths()) {
CXXBasePathElement Element;
Element.Base = &BaseSpec;
Element.Class = Record;
if (BaseSpec.isVirtual())
Element.SubobjectNumber = 0;
else
Element.SubobjectNumber = Subobjects.NumberOfNonVirtBases;
ScratchPath.push_back(Element);
if (IsFirstStep)
ScratchPath.Access = BaseSpec.getAccessSpecifier();
else
ScratchPath.Access = CXXRecordDecl::MergeAccess(AccessToHere,
BaseSpec.getAccessSpecifier());
}
bool FoundPathThroughBase = false;
if (BaseMatches(&BaseSpec, ScratchPath)) {
FoundPath = FoundPathThroughBase = true;
if (isRecordingPaths()) {
Paths.push_back(ScratchPath);
} else if (!isFindingAmbiguities()) {
return FoundPath;
}
} else if (VisitBase) {
CXXRecordDecl *BaseRecord;
if (LookupInDependent) {
BaseRecord = nullptr;
const TemplateSpecializationType *TST =
BaseSpec.getType()->getAs<TemplateSpecializationType>();
if (!TST) {
if (auto *RT = BaseSpec.getType()->getAs<RecordType>())
BaseRecord = cast<CXXRecordDecl>(RT->getDecl());
} else {
TemplateName TN = TST->getTemplateName();
if (auto *TD =
dyn_cast_or_null<ClassTemplateDecl>(TN.getAsTemplateDecl()))
BaseRecord = TD->getTemplatedDecl();
}
if (BaseRecord) {
if (!BaseRecord->hasDefinition() ||
VisitedDependentRecords.count(BaseRecord)) {
BaseRecord = nullptr;
} else {
VisitedDependentRecords.insert(BaseRecord);
}
}
} else {
BaseRecord = cast<CXXRecordDecl>(
BaseSpec.getType()->castAs<RecordType>()->getDecl());
}
if (BaseRecord &&
lookupInBases(Context, BaseRecord, BaseMatches, LookupInDependent)) {
FoundPath = FoundPathThroughBase = true;
if (!isFindingAmbiguities())
return FoundPath;
}
}
if (isRecordingPaths()) {
ScratchPath.pop_back();
}
if (SetVirtual && !FoundPathThroughBase) {
DetectedVirtual = nullptr;
}
}
ScratchPath.Access = AccessToHere;
return FoundPath;
}
bool CXXRecordDecl::lookupInBases(BaseMatchesCallback BaseMatches,
CXXBasePaths &Paths,
bool LookupInDependent) const {
if (!Paths.lookupInBases(getASTContext(), this, BaseMatches,
LookupInDependent))
return false;
if (!Paths.isRecordingPaths() || !Paths.isFindingAmbiguities())
return true;
Paths.Paths.remove_if([&Paths](const CXXBasePath &Path) {
for (const CXXBasePathElement &PE : Path) {
if (!PE.Base->isVirtual())
continue;
CXXRecordDecl *VBase = nullptr;
if (const RecordType *Record = PE.Base->getType()->getAs<RecordType>())
VBase = cast<CXXRecordDecl>(Record->getDecl());
if (!VBase)
break;
for (const CXXBasePath &HidingP : Paths) {
CXXRecordDecl *HidingClass = nullptr;
if (const RecordType *Record =
HidingP.back().Base->getType()->getAs<RecordType>())
HidingClass = cast<CXXRecordDecl>(Record->getDecl());
if (!HidingClass)
break;
if (HidingClass->isVirtuallyDerivedFrom(VBase))
return true;
}
}
return false;
});
return true;
}
bool CXXRecordDecl::FindBaseClass(const CXXBaseSpecifier *Specifier,
CXXBasePath &Path,
const CXXRecordDecl *BaseRecord) {
assert(BaseRecord->getCanonicalDecl() == BaseRecord &&
"User data for FindBaseClass is not canonical!");
return Specifier->getType()->castAs<RecordType>()->getDecl()
->getCanonicalDecl() == BaseRecord;
}
bool CXXRecordDecl::FindVirtualBaseClass(const CXXBaseSpecifier *Specifier,
CXXBasePath &Path,
const CXXRecordDecl *BaseRecord) {
assert(BaseRecord->getCanonicalDecl() == BaseRecord &&
"User data for FindBaseClass is not canonical!");
return Specifier->isVirtual() &&
Specifier->getType()->castAs<RecordType>()->getDecl()
->getCanonicalDecl() == BaseRecord;
}
static bool isOrdinaryMember(const NamedDecl *ND) {
return ND->isInIdentifierNamespace(Decl::IDNS_Ordinary | Decl::IDNS_Tag |
Decl::IDNS_Member);
}
static bool findOrdinaryMember(const CXXRecordDecl *RD, CXXBasePath &Path,
DeclarationName Name) {
Path.Decls = RD->lookup(Name).begin();
for (DeclContext::lookup_iterator I = Path.Decls, E = I.end(); I != E; ++I)
if (isOrdinaryMember(*I))
return true;
return false;
}
bool CXXRecordDecl::hasMemberName(DeclarationName Name) const {
CXXBasePath P;
if (findOrdinaryMember(this, P, Name))
return true;
CXXBasePaths Paths(false, false, false);
return lookupInBases(
[Name](const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
return findOrdinaryMember(Specifier->getType()->getAsCXXRecordDecl(),
Path, Name);
},
Paths);
}
static bool
findOrdinaryMemberInDependentClasses(const CXXBaseSpecifier *Specifier,
CXXBasePath &Path, DeclarationName Name) {
const TemplateSpecializationType *TST =
Specifier->getType()->getAs<TemplateSpecializationType>();
if (!TST) {
auto *RT = Specifier->getType()->getAs<RecordType>();
if (!RT)
return false;
return findOrdinaryMember(cast<CXXRecordDecl>(RT->getDecl()), Path, Name);
}
TemplateName TN = TST->getTemplateName();
const auto *TD = dyn_cast_or_null<ClassTemplateDecl>(TN.getAsTemplateDecl());
if (!TD)
return false;
CXXRecordDecl *RD = TD->getTemplatedDecl();
if (!RD)
return false;
return findOrdinaryMember(RD, Path, Name);
}
std::vector<const NamedDecl *> CXXRecordDecl::lookupDependentName(
DeclarationName Name,
llvm::function_ref<bool(const NamedDecl *ND)> Filter) {
std::vector<const NamedDecl *> Results;
bool AnyOrdinaryMembers = false;
for (const NamedDecl *ND : lookup(Name)) {
if (isOrdinaryMember(ND))
AnyOrdinaryMembers = true;
if (Filter(ND))
Results.push_back(ND);
}
if (AnyOrdinaryMembers)
return Results;
CXXBasePaths Paths;
Paths.setOrigin(this);
if (!lookupInBases(
[&](const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
return findOrdinaryMemberInDependentClasses(Specifier, Path, Name);
},
Paths, true))
return Results;
for (DeclContext::lookup_iterator I = Paths.front().Decls, E = I.end();
I != E; ++I) {
if (isOrdinaryMember(*I) && Filter(*I))
Results.push_back(*I);
}
return Results;
}
void OverridingMethods::add(unsigned OverriddenSubobject,
UniqueVirtualMethod Overriding) {
SmallVectorImpl<UniqueVirtualMethod> &SubobjectOverrides
= Overrides[OverriddenSubobject];
if (!llvm::is_contained(SubobjectOverrides, Overriding))
SubobjectOverrides.push_back(Overriding);
}
void OverridingMethods::add(const OverridingMethods &Other) {
for (const_iterator I = Other.begin(), IE = Other.end(); I != IE; ++I) {
for (overriding_const_iterator M = I->second.begin(),
MEnd = I->second.end();
M != MEnd;
++M)
add(I->first, *M);
}
}
void OverridingMethods::replaceAll(UniqueVirtualMethod Overriding) {
for (iterator I = begin(), IEnd = end(); I != IEnd; ++I) {
I->second.clear();
I->second.push_back(Overriding);
}
}
namespace {
class FinalOverriderCollector {
llvm::DenseMap<const CXXRecordDecl *, unsigned> SubobjectCount;
llvm::DenseMap<const CXXRecordDecl *, CXXFinalOverriderMap *> VirtualOverriders;
CXXFinalOverriderMap FinalOverriders;
public:
~FinalOverriderCollector();
void Collect(const CXXRecordDecl *RD, bool VirtualBase,
const CXXRecordDecl *InVirtualSubobject,
CXXFinalOverriderMap &Overriders);
};
}
void FinalOverriderCollector::Collect(const CXXRecordDecl *RD,
bool VirtualBase,
const CXXRecordDecl *InVirtualSubobject,
CXXFinalOverriderMap &Overriders) {
unsigned SubobjectNumber = 0;
if (!VirtualBase)
SubobjectNumber
= ++SubobjectCount[cast<CXXRecordDecl>(RD->getCanonicalDecl())];
for (const auto &Base : RD->bases()) {
if (const RecordType *RT = Base.getType()->getAs<RecordType>()) {
const CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(RT->getDecl());
if (!BaseDecl->isPolymorphic())
continue;
if (Overriders.empty() && !Base.isVirtual()) {
Collect(BaseDecl, false, InVirtualSubobject, Overriders);
continue;
}
CXXFinalOverriderMap ComputedBaseOverriders;
CXXFinalOverriderMap *BaseOverriders = &ComputedBaseOverriders;
if (Base.isVirtual()) {
CXXFinalOverriderMap *&MyVirtualOverriders = VirtualOverriders[BaseDecl];
BaseOverriders = MyVirtualOverriders;
if (!MyVirtualOverriders) {
MyVirtualOverriders = new CXXFinalOverriderMap;
BaseOverriders = MyVirtualOverriders;
Collect(BaseDecl, true, BaseDecl, *MyVirtualOverriders);
}
} else
Collect(BaseDecl, false, InVirtualSubobject, ComputedBaseOverriders);
for (CXXFinalOverriderMap::iterator OM = BaseOverriders->begin(),
OMEnd = BaseOverriders->end();
OM != OMEnd;
++OM) {
const CXXMethodDecl *CanonOM = OM->first->getCanonicalDecl();
Overriders[CanonOM].add(OM->second);
}
}
}
for (auto *M : RD->methods()) {
if (!M->isVirtual())
continue;
CXXMethodDecl *CanonM = M->getCanonicalDecl();
using OverriddenMethodsRange =
llvm::iterator_range<CXXMethodDecl::method_iterator>;
OverriddenMethodsRange OverriddenMethods = CanonM->overridden_methods();
if (OverriddenMethods.begin() == OverriddenMethods.end()) {
Overriders[CanonM].add(SubobjectNumber,
UniqueVirtualMethod(CanonM, SubobjectNumber,
InVirtualSubobject));
continue;
}
SmallVector<OverriddenMethodsRange, 4> Stack(1, OverriddenMethods);
while (!Stack.empty()) {
for (const CXXMethodDecl *OM : Stack.pop_back_val()) {
const CXXMethodDecl *CanonOM = OM->getCanonicalDecl();
Overriders[CanonOM].replaceAll(
UniqueVirtualMethod(CanonM, SubobjectNumber,
InVirtualSubobject));
auto OverriddenMethods = CanonOM->overridden_methods();
if (OverriddenMethods.begin() == OverriddenMethods.end())
continue;
Stack.push_back(OverriddenMethods);
}
}
Overriders[CanonM].add(SubobjectNumber,
UniqueVirtualMethod(CanonM, SubobjectNumber,
InVirtualSubobject));
}
}
FinalOverriderCollector::~FinalOverriderCollector() {
for (llvm::DenseMap<const CXXRecordDecl *, CXXFinalOverriderMap *>::iterator
VO = VirtualOverriders.begin(), VOEnd = VirtualOverriders.end();
VO != VOEnd;
++VO)
delete VO->second;
}
void
CXXRecordDecl::getFinalOverriders(CXXFinalOverriderMap &FinalOverriders) const {
FinalOverriderCollector Collector;
Collector.Collect(this, false, nullptr, FinalOverriders);
for (auto &OM : FinalOverriders) {
for (auto &SO : OM.second) {
SmallVectorImpl<UniqueVirtualMethod> &Overriding = SO.second;
if (Overriding.size() < 2)
continue;
auto IsHidden = [&Overriding](const UniqueVirtualMethod &M) {
if (!M.InVirtualSubobject)
return false;
for (const UniqueVirtualMethod &OP : Overriding)
if (&M != &OP &&
OP.Method->getParent()->isVirtuallyDerivedFrom(
M.InVirtualSubobject))
return true;
return false;
};
llvm::erase_if(Overriding, IsHidden);
}
}
}
static void
AddIndirectPrimaryBases(const CXXRecordDecl *RD, ASTContext &Context,
CXXIndirectPrimaryBaseSet& Bases) {
const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
if (Layout.isPrimaryBaseVirtual())
Bases.insert(Layout.getPrimaryBase());
for (const auto &I : RD->bases()) {
assert(!I.getType()->isDependentType() &&
"Cannot get indirect primary bases for class with dependent bases.");
const CXXRecordDecl *BaseDecl =
cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
if (BaseDecl->getNumVBases())
AddIndirectPrimaryBases(BaseDecl, Context, Bases);
}
}
void
CXXRecordDecl::getIndirectPrimaryBases(CXXIndirectPrimaryBaseSet& Bases) const {
ASTContext &Context = getASTContext();
if (!getNumVBases())
return;
for (const auto &I : bases()) {
assert(!I.getType()->isDependentType() &&
"Cannot get indirect primary bases for class with dependent bases.");
const CXXRecordDecl *BaseDecl =
cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
if (BaseDecl->getNumVBases())
AddIndirectPrimaryBases(BaseDecl, Context, Bases);
}
}