Path: blob/main/contrib/llvm-project/clang/lib/AST/DeclCXX.cpp
35259 views
//===- DeclCXX.cpp - C++ Declaration AST Node Implementation --------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This file implements the C++ related Decl classes.9//10//===----------------------------------------------------------------------===//1112#include "clang/AST/DeclCXX.h"13#include "clang/AST/ASTContext.h"14#include "clang/AST/ASTLambda.h"15#include "clang/AST/ASTMutationListener.h"16#include "clang/AST/ASTUnresolvedSet.h"17#include "clang/AST/Attr.h"18#include "clang/AST/CXXInheritance.h"19#include "clang/AST/DeclBase.h"20#include "clang/AST/DeclTemplate.h"21#include "clang/AST/DeclarationName.h"22#include "clang/AST/Expr.h"23#include "clang/AST/ExprCXX.h"24#include "clang/AST/LambdaCapture.h"25#include "clang/AST/NestedNameSpecifier.h"26#include "clang/AST/ODRHash.h"27#include "clang/AST/Type.h"28#include "clang/AST/TypeLoc.h"29#include "clang/AST/UnresolvedSet.h"30#include "clang/Basic/Diagnostic.h"31#include "clang/Basic/IdentifierTable.h"32#include "clang/Basic/LLVM.h"33#include "clang/Basic/LangOptions.h"34#include "clang/Basic/OperatorKinds.h"35#include "clang/Basic/PartialDiagnostic.h"36#include "clang/Basic/SourceLocation.h"37#include "clang/Basic/Specifiers.h"38#include "clang/Basic/TargetInfo.h"39#include "llvm/ADT/SmallPtrSet.h"40#include "llvm/ADT/SmallVector.h"41#include "llvm/ADT/iterator_range.h"42#include "llvm/Support/Casting.h"43#include "llvm/Support/ErrorHandling.h"44#include "llvm/Support/Format.h"45#include "llvm/Support/raw_ostream.h"46#include <algorithm>47#include <cassert>48#include <cstddef>49#include <cstdint>5051using namespace clang;5253//===----------------------------------------------------------------------===//54// Decl Allocation/Deallocation Method Implementations55//===----------------------------------------------------------------------===//5657void AccessSpecDecl::anchor() {}5859AccessSpecDecl *AccessSpecDecl::CreateDeserialized(ASTContext &C,60GlobalDeclID ID) {61return new (C, ID) AccessSpecDecl(EmptyShell());62}6364void LazyASTUnresolvedSet::getFromExternalSource(ASTContext &C) const {65ExternalASTSource *Source = C.getExternalSource();66assert(Impl.Decls.isLazy() && "getFromExternalSource for non-lazy set");67assert(Source && "getFromExternalSource with no external source");6869for (ASTUnresolvedSet::iterator I = Impl.begin(); I != Impl.end(); ++I)70I.setDecl(71cast<NamedDecl>(Source->GetExternalDecl(GlobalDeclID(I.getDeclID()))));72Impl.Decls.setLazy(false);73}7475CXXRecordDecl::DefinitionData::DefinitionData(CXXRecordDecl *D)76: UserDeclaredConstructor(false), UserDeclaredSpecialMembers(0),77Aggregate(true), PlainOldData(true), Empty(true), Polymorphic(false),78Abstract(false), IsStandardLayout(true), IsCXX11StandardLayout(true),79HasBasesWithFields(false), HasBasesWithNonStaticDataMembers(false),80HasPrivateFields(false), HasProtectedFields(false),81HasPublicFields(false), HasMutableFields(false), HasVariantMembers(false),82HasOnlyCMembers(true), HasInitMethod(false), HasInClassInitializer(false),83HasUninitializedReferenceMember(false), HasUninitializedFields(false),84HasInheritedConstructor(false), HasInheritedDefaultConstructor(false),85HasInheritedAssignment(false),86NeedOverloadResolutionForCopyConstructor(false),87NeedOverloadResolutionForMoveConstructor(false),88NeedOverloadResolutionForCopyAssignment(false),89NeedOverloadResolutionForMoveAssignment(false),90NeedOverloadResolutionForDestructor(false),91DefaultedCopyConstructorIsDeleted(false),92DefaultedMoveConstructorIsDeleted(false),93DefaultedCopyAssignmentIsDeleted(false),94DefaultedMoveAssignmentIsDeleted(false),95DefaultedDestructorIsDeleted(false), HasTrivialSpecialMembers(SMF_All),96HasTrivialSpecialMembersForCall(SMF_All),97DeclaredNonTrivialSpecialMembers(0),98DeclaredNonTrivialSpecialMembersForCall(0), HasIrrelevantDestructor(true),99HasConstexprNonCopyMoveConstructor(false),100HasDefaultedDefaultConstructor(false),101DefaultedDefaultConstructorIsConstexpr(true),102HasConstexprDefaultConstructor(false),103DefaultedDestructorIsConstexpr(true),104HasNonLiteralTypeFieldsOrBases(false), StructuralIfLiteral(true),105UserProvidedDefaultConstructor(false), DeclaredSpecialMembers(0),106ImplicitCopyConstructorCanHaveConstParamForVBase(true),107ImplicitCopyConstructorCanHaveConstParamForNonVBase(true),108ImplicitCopyAssignmentHasConstParam(true),109HasDeclaredCopyConstructorWithConstParam(false),110HasDeclaredCopyAssignmentWithConstParam(false),111IsAnyDestructorNoReturn(false), IsLambda(false),112IsParsingBaseSpecifiers(false), ComputedVisibleConversions(false),113HasODRHash(false), Definition(D) {}114115CXXBaseSpecifier *CXXRecordDecl::DefinitionData::getBasesSlowCase() const {116return Bases.get(Definition->getASTContext().getExternalSource());117}118119CXXBaseSpecifier *CXXRecordDecl::DefinitionData::getVBasesSlowCase() const {120return VBases.get(Definition->getASTContext().getExternalSource());121}122123CXXRecordDecl::CXXRecordDecl(Kind K, TagKind TK, const ASTContext &C,124DeclContext *DC, SourceLocation StartLoc,125SourceLocation IdLoc, IdentifierInfo *Id,126CXXRecordDecl *PrevDecl)127: RecordDecl(K, TK, C, DC, StartLoc, IdLoc, Id, PrevDecl),128DefinitionData(PrevDecl ? PrevDecl->DefinitionData129: nullptr) {}130131CXXRecordDecl *CXXRecordDecl::Create(const ASTContext &C, TagKind TK,132DeclContext *DC, SourceLocation StartLoc,133SourceLocation IdLoc, IdentifierInfo *Id,134CXXRecordDecl *PrevDecl,135bool DelayTypeCreation) {136auto *R = new (C, DC) CXXRecordDecl(CXXRecord, TK, C, DC, StartLoc, IdLoc, Id,137PrevDecl);138R->setMayHaveOutOfDateDef(C.getLangOpts().Modules);139140// FIXME: DelayTypeCreation seems like such a hack141if (!DelayTypeCreation)142C.getTypeDeclType(R, PrevDecl);143return R;144}145146CXXRecordDecl *147CXXRecordDecl::CreateLambda(const ASTContext &C, DeclContext *DC,148TypeSourceInfo *Info, SourceLocation Loc,149unsigned DependencyKind, bool IsGeneric,150LambdaCaptureDefault CaptureDefault) {151auto *R = new (C, DC) CXXRecordDecl(CXXRecord, TagTypeKind::Class, C, DC, Loc,152Loc, nullptr, nullptr);153R->setBeingDefined(true);154R->DefinitionData = new (C) struct LambdaDefinitionData(155R, Info, DependencyKind, IsGeneric, CaptureDefault);156R->setMayHaveOutOfDateDef(false);157R->setImplicit(true);158159C.getTypeDeclType(R, /*PrevDecl=*/nullptr);160return R;161}162163CXXRecordDecl *CXXRecordDecl::CreateDeserialized(const ASTContext &C,164GlobalDeclID ID) {165auto *R = new (C, ID)166CXXRecordDecl(CXXRecord, TagTypeKind::Struct, C, nullptr,167SourceLocation(), SourceLocation(), nullptr, nullptr);168R->setMayHaveOutOfDateDef(false);169return R;170}171172/// Determine whether a class has a repeated base class. This is intended for173/// use when determining if a class is standard-layout, so makes no attempt to174/// handle virtual bases.175static bool hasRepeatedBaseClass(const CXXRecordDecl *StartRD) {176llvm::SmallPtrSet<const CXXRecordDecl*, 8> SeenBaseTypes;177SmallVector<const CXXRecordDecl*, 8> WorkList = {StartRD};178while (!WorkList.empty()) {179const CXXRecordDecl *RD = WorkList.pop_back_val();180if (RD->getTypeForDecl()->isDependentType())181continue;182for (const CXXBaseSpecifier &BaseSpec : RD->bases()) {183if (const CXXRecordDecl *B = BaseSpec.getType()->getAsCXXRecordDecl()) {184if (!SeenBaseTypes.insert(B).second)185return true;186WorkList.push_back(B);187}188}189}190return false;191}192193void194CXXRecordDecl::setBases(CXXBaseSpecifier const * const *Bases,195unsigned NumBases) {196ASTContext &C = getASTContext();197198if (!data().Bases.isOffset() && data().NumBases > 0)199C.Deallocate(data().getBases());200201if (NumBases) {202if (!C.getLangOpts().CPlusPlus17) {203// C++ [dcl.init.aggr]p1:204// An aggregate is [...] a class with [...] no base classes [...].205data().Aggregate = false;206}207208// C++ [class]p4:209// A POD-struct is an aggregate class...210data().PlainOldData = false;211}212213// The set of seen virtual base types.214llvm::SmallPtrSet<CanQualType, 8> SeenVBaseTypes;215216// The virtual bases of this class.217SmallVector<const CXXBaseSpecifier *, 8> VBases;218219data().Bases = new(C) CXXBaseSpecifier [NumBases];220data().NumBases = NumBases;221for (unsigned i = 0; i < NumBases; ++i) {222data().getBases()[i] = *Bases[i];223// Keep track of inherited vbases for this base class.224const CXXBaseSpecifier *Base = Bases[i];225QualType BaseType = Base->getType();226// Skip dependent types; we can't do any checking on them now.227if (BaseType->isDependentType())228continue;229auto *BaseClassDecl =230cast<CXXRecordDecl>(BaseType->castAs<RecordType>()->getDecl());231232// C++2a [class]p7:233// A standard-layout class is a class that:234// [...]235// -- has all non-static data members and bit-fields in the class and236// its base classes first declared in the same class237if (BaseClassDecl->data().HasBasesWithFields ||238!BaseClassDecl->field_empty()) {239if (data().HasBasesWithFields)240// Two bases have members or bit-fields: not standard-layout.241data().IsStandardLayout = false;242data().HasBasesWithFields = true;243}244245// C++11 [class]p7:246// A standard-layout class is a class that:247// -- [...] has [...] at most one base class with non-static data248// members249if (BaseClassDecl->data().HasBasesWithNonStaticDataMembers ||250BaseClassDecl->hasDirectFields()) {251if (data().HasBasesWithNonStaticDataMembers)252data().IsCXX11StandardLayout = false;253data().HasBasesWithNonStaticDataMembers = true;254}255256if (!BaseClassDecl->isEmpty()) {257// C++14 [meta.unary.prop]p4:258// T is a class type [...] with [...] no base class B for which259// is_empty<B>::value is false.260data().Empty = false;261}262263// C++1z [dcl.init.agg]p1:264// An aggregate is a class with [...] no private or protected base classes265if (Base->getAccessSpecifier() != AS_public) {266data().Aggregate = false;267268// C++20 [temp.param]p7:269// A structural type is [...] a literal class type with [...] all base270// classes [...] public271data().StructuralIfLiteral = false;272}273274// C++ [class.virtual]p1:275// A class that declares or inherits a virtual function is called a276// polymorphic class.277if (BaseClassDecl->isPolymorphic()) {278data().Polymorphic = true;279280// An aggregate is a class with [...] no virtual functions.281data().Aggregate = false;282}283284// C++0x [class]p7:285// A standard-layout class is a class that: [...]286// -- has no non-standard-layout base classes287if (!BaseClassDecl->isStandardLayout())288data().IsStandardLayout = false;289if (!BaseClassDecl->isCXX11StandardLayout())290data().IsCXX11StandardLayout = false;291292// Record if this base is the first non-literal field or base.293if (!hasNonLiteralTypeFieldsOrBases() && !BaseType->isLiteralType(C))294data().HasNonLiteralTypeFieldsOrBases = true;295296// Now go through all virtual bases of this base and add them.297for (const auto &VBase : BaseClassDecl->vbases()) {298// Add this base if it's not already in the list.299if (SeenVBaseTypes.insert(C.getCanonicalType(VBase.getType())).second) {300VBases.push_back(&VBase);301302// C++11 [class.copy]p8:303// The implicitly-declared copy constructor for a class X will have304// the form 'X::X(const X&)' if each [...] virtual base class B of X305// has a copy constructor whose first parameter is of type306// 'const B&' or 'const volatile B&' [...]307if (CXXRecordDecl *VBaseDecl = VBase.getType()->getAsCXXRecordDecl())308if (!VBaseDecl->hasCopyConstructorWithConstParam())309data().ImplicitCopyConstructorCanHaveConstParamForVBase = false;310311// C++1z [dcl.init.agg]p1:312// An aggregate is a class with [...] no virtual base classes313data().Aggregate = false;314}315}316317if (Base->isVirtual()) {318// Add this base if it's not already in the list.319if (SeenVBaseTypes.insert(C.getCanonicalType(BaseType)).second)320VBases.push_back(Base);321322// C++14 [meta.unary.prop] is_empty:323// T is a class type, but not a union type, with ... no virtual base324// classes325data().Empty = false;326327// C++1z [dcl.init.agg]p1:328// An aggregate is a class with [...] no virtual base classes329data().Aggregate = false;330331// C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:332// A [default constructor, copy/move constructor, or copy/move assignment333// operator for a class X] is trivial [...] if:334// -- class X has [...] no virtual base classes335data().HasTrivialSpecialMembers &= SMF_Destructor;336data().HasTrivialSpecialMembersForCall &= SMF_Destructor;337338// C++0x [class]p7:339// A standard-layout class is a class that: [...]340// -- has [...] no virtual base classes341data().IsStandardLayout = false;342data().IsCXX11StandardLayout = false;343344// C++20 [dcl.constexpr]p3:345// In the definition of a constexpr function [...]346// -- if the function is a constructor or destructor,347// its class shall not have any virtual base classes348data().DefaultedDefaultConstructorIsConstexpr = false;349data().DefaultedDestructorIsConstexpr = false;350351// C++1z [class.copy]p8:352// The implicitly-declared copy constructor for a class X will have353// the form 'X::X(const X&)' if each potentially constructed subobject354// has a copy constructor whose first parameter is of type355// 'const B&' or 'const volatile B&' [...]356if (!BaseClassDecl->hasCopyConstructorWithConstParam())357data().ImplicitCopyConstructorCanHaveConstParamForVBase = false;358} else {359// C++ [class.ctor]p5:360// A default constructor is trivial [...] if:361// -- all the direct base classes of its class have trivial default362// constructors.363if (!BaseClassDecl->hasTrivialDefaultConstructor())364data().HasTrivialSpecialMembers &= ~SMF_DefaultConstructor;365366// C++0x [class.copy]p13:367// A copy/move constructor for class X is trivial if [...]368// [...]369// -- the constructor selected to copy/move each direct base class370// subobject is trivial, and371if (!BaseClassDecl->hasTrivialCopyConstructor())372data().HasTrivialSpecialMembers &= ~SMF_CopyConstructor;373374if (!BaseClassDecl->hasTrivialCopyConstructorForCall())375data().HasTrivialSpecialMembersForCall &= ~SMF_CopyConstructor;376377// If the base class doesn't have a simple move constructor, we'll eagerly378// declare it and perform overload resolution to determine which function379// it actually calls. If it does have a simple move constructor, this380// check is correct.381if (!BaseClassDecl->hasTrivialMoveConstructor())382data().HasTrivialSpecialMembers &= ~SMF_MoveConstructor;383384if (!BaseClassDecl->hasTrivialMoveConstructorForCall())385data().HasTrivialSpecialMembersForCall &= ~SMF_MoveConstructor;386387// C++0x [class.copy]p27:388// A copy/move assignment operator for class X is trivial if [...]389// [...]390// -- the assignment operator selected to copy/move each direct base391// class subobject is trivial, and392if (!BaseClassDecl->hasTrivialCopyAssignment())393data().HasTrivialSpecialMembers &= ~SMF_CopyAssignment;394// If the base class doesn't have a simple move assignment, we'll eagerly395// declare it and perform overload resolution to determine which function396// it actually calls. If it does have a simple move assignment, this397// check is correct.398if (!BaseClassDecl->hasTrivialMoveAssignment())399data().HasTrivialSpecialMembers &= ~SMF_MoveAssignment;400401// C++11 [class.ctor]p6:402// If that user-written default constructor would satisfy the403// requirements of a constexpr constructor/function(C++23), the404// implicitly-defined default constructor is constexpr.405if (!BaseClassDecl->hasConstexprDefaultConstructor())406data().DefaultedDefaultConstructorIsConstexpr =407C.getLangOpts().CPlusPlus23;408409// C++1z [class.copy]p8:410// The implicitly-declared copy constructor for a class X will have411// the form 'X::X(const X&)' if each potentially constructed subobject412// has a copy constructor whose first parameter is of type413// 'const B&' or 'const volatile B&' [...]414if (!BaseClassDecl->hasCopyConstructorWithConstParam())415data().ImplicitCopyConstructorCanHaveConstParamForNonVBase = false;416}417418// C++ [class.ctor]p3:419// A destructor is trivial if all the direct base classes of its class420// have trivial destructors.421if (!BaseClassDecl->hasTrivialDestructor())422data().HasTrivialSpecialMembers &= ~SMF_Destructor;423424if (!BaseClassDecl->hasTrivialDestructorForCall())425data().HasTrivialSpecialMembersForCall &= ~SMF_Destructor;426427if (!BaseClassDecl->hasIrrelevantDestructor())428data().HasIrrelevantDestructor = false;429430if (BaseClassDecl->isAnyDestructorNoReturn())431data().IsAnyDestructorNoReturn = true;432433// C++11 [class.copy]p18:434// The implicitly-declared copy assignment operator for a class X will435// have the form 'X& X::operator=(const X&)' if each direct base class B436// of X has a copy assignment operator whose parameter is of type 'const437// B&', 'const volatile B&', or 'B' [...]438if (!BaseClassDecl->hasCopyAssignmentWithConstParam())439data().ImplicitCopyAssignmentHasConstParam = false;440441// A class has an Objective-C object member if... or any of its bases442// has an Objective-C object member.443if (BaseClassDecl->hasObjectMember())444setHasObjectMember(true);445446if (BaseClassDecl->hasVolatileMember())447setHasVolatileMember(true);448449if (BaseClassDecl->getArgPassingRestrictions() ==450RecordArgPassingKind::CanNeverPassInRegs)451setArgPassingRestrictions(RecordArgPassingKind::CanNeverPassInRegs);452453// Keep track of the presence of mutable fields.454if (BaseClassDecl->hasMutableFields())455data().HasMutableFields = true;456457if (BaseClassDecl->hasUninitializedReferenceMember())458data().HasUninitializedReferenceMember = true;459460if (!BaseClassDecl->allowConstDefaultInit())461data().HasUninitializedFields = true;462463addedClassSubobject(BaseClassDecl);464}465466// C++2a [class]p7:467// A class S is a standard-layout class if it:468// -- has at most one base class subobject of any given type469//470// Note that we only need to check this for classes with more than one base471// class. If there's only one base class, and it's standard layout, then472// we know there are no repeated base classes.473if (data().IsStandardLayout && NumBases > 1 && hasRepeatedBaseClass(this))474data().IsStandardLayout = false;475476if (VBases.empty()) {477data().IsParsingBaseSpecifiers = false;478return;479}480481// Create base specifier for any direct or indirect virtual bases.482data().VBases = new (C) CXXBaseSpecifier[VBases.size()];483data().NumVBases = VBases.size();484for (int I = 0, E = VBases.size(); I != E; ++I) {485QualType Type = VBases[I]->getType();486if (!Type->isDependentType())487addedClassSubobject(Type->getAsCXXRecordDecl());488data().getVBases()[I] = *VBases[I];489}490491data().IsParsingBaseSpecifiers = false;492}493494unsigned CXXRecordDecl::getODRHash() const {495assert(hasDefinition() && "ODRHash only for records with definitions");496497// Previously calculated hash is stored in DefinitionData.498if (DefinitionData->HasODRHash)499return DefinitionData->ODRHash;500501// Only calculate hash on first call of getODRHash per record.502ODRHash Hash;503Hash.AddCXXRecordDecl(getDefinition());504DefinitionData->HasODRHash = true;505DefinitionData->ODRHash = Hash.CalculateHash();506507return DefinitionData->ODRHash;508}509510void CXXRecordDecl::addedClassSubobject(CXXRecordDecl *Subobj) {511// C++11 [class.copy]p11:512// A defaulted copy/move constructor for a class X is defined as513// deleted if X has:514// -- a direct or virtual base class B that cannot be copied/moved [...]515// -- a non-static data member of class type M (or array thereof)516// that cannot be copied or moved [...]517if (!Subobj->hasSimpleCopyConstructor())518data().NeedOverloadResolutionForCopyConstructor = true;519if (!Subobj->hasSimpleMoveConstructor())520data().NeedOverloadResolutionForMoveConstructor = true;521522// C++11 [class.copy]p23:523// A defaulted copy/move assignment operator for a class X is defined as524// deleted if X has:525// -- a direct or virtual base class B that cannot be copied/moved [...]526// -- a non-static data member of class type M (or array thereof)527// that cannot be copied or moved [...]528if (!Subobj->hasSimpleCopyAssignment())529data().NeedOverloadResolutionForCopyAssignment = true;530if (!Subobj->hasSimpleMoveAssignment())531data().NeedOverloadResolutionForMoveAssignment = true;532533// C++11 [class.ctor]p5, C++11 [class.copy]p11, C++11 [class.dtor]p5:534// A defaulted [ctor or dtor] for a class X is defined as535// deleted if X has:536// -- any direct or virtual base class [...] has a type with a destructor537// that is deleted or inaccessible from the defaulted [ctor or dtor].538// -- any non-static data member has a type with a destructor539// that is deleted or inaccessible from the defaulted [ctor or dtor].540if (!Subobj->hasSimpleDestructor()) {541data().NeedOverloadResolutionForCopyConstructor = true;542data().NeedOverloadResolutionForMoveConstructor = true;543data().NeedOverloadResolutionForDestructor = true;544}545546// C++2a [dcl.constexpr]p4:547// The definition of a constexpr destructor [shall] satisfy the548// following requirement:549// -- for every subobject of class type or (possibly multi-dimensional)550// array thereof, that class type shall have a constexpr destructor551if (!Subobj->hasConstexprDestructor())552data().DefaultedDestructorIsConstexpr =553getASTContext().getLangOpts().CPlusPlus23;554555// C++20 [temp.param]p7:556// A structural type is [...] a literal class type [for which] the types557// of all base classes and non-static data members are structural types or558// (possibly multi-dimensional) array thereof559if (!Subobj->data().StructuralIfLiteral)560data().StructuralIfLiteral = false;561}562563const CXXRecordDecl *CXXRecordDecl::getStandardLayoutBaseWithFields() const {564assert(565isStandardLayout() &&566"getStandardLayoutBaseWithFields called on a non-standard-layout type");567#ifdef EXPENSIVE_CHECKS568{569unsigned NumberOfBasesWithFields = 0;570if (!field_empty())571++NumberOfBasesWithFields;572llvm::SmallPtrSet<const CXXRecordDecl *, 8> UniqueBases;573forallBases([&](const CXXRecordDecl *Base) -> bool {574if (!Base->field_empty())575++NumberOfBasesWithFields;576assert(577UniqueBases.insert(Base->getCanonicalDecl()).second &&578"Standard layout struct has multiple base classes of the same type");579return true;580});581assert(NumberOfBasesWithFields <= 1 &&582"Standard layout struct has fields declared in more than one class");583}584#endif585if (!field_empty())586return this;587const CXXRecordDecl *Result = this;588forallBases([&](const CXXRecordDecl *Base) -> bool {589if (!Base->field_empty()) {590// This is the base where the fields are declared; return early591Result = Base;592return false;593}594return true;595});596return Result;597}598599bool CXXRecordDecl::hasConstexprDestructor() const {600auto *Dtor = getDestructor();601return Dtor ? Dtor->isConstexpr() : defaultedDestructorIsConstexpr();602}603604bool CXXRecordDecl::hasAnyDependentBases() const {605if (!isDependentContext())606return false;607608return !forallBases([](const CXXRecordDecl *) { return true; });609}610611bool CXXRecordDecl::isTriviallyCopyable() const {612// C++0x [class]p5:613// A trivially copyable class is a class that:614// -- has no non-trivial copy constructors,615if (hasNonTrivialCopyConstructor()) return false;616// -- has no non-trivial move constructors,617if (hasNonTrivialMoveConstructor()) return false;618// -- has no non-trivial copy assignment operators,619if (hasNonTrivialCopyAssignment()) return false;620// -- has no non-trivial move assignment operators, and621if (hasNonTrivialMoveAssignment()) return false;622// -- has a trivial destructor.623if (!hasTrivialDestructor()) return false;624625return true;626}627628bool CXXRecordDecl::isTriviallyCopyConstructible() const {629630// A trivially copy constructible class is a class that:631// -- has no non-trivial copy constructors,632if (hasNonTrivialCopyConstructor())633return false;634// -- has a trivial destructor.635if (!hasTrivialDestructor())636return false;637638return true;639}640641void CXXRecordDecl::markedVirtualFunctionPure() {642// C++ [class.abstract]p2:643// A class is abstract if it has at least one pure virtual function.644data().Abstract = true;645}646647bool CXXRecordDecl::hasSubobjectAtOffsetZeroOfEmptyBaseType(648ASTContext &Ctx, const CXXRecordDecl *XFirst) {649if (!getNumBases())650return false;651652llvm::SmallPtrSet<const CXXRecordDecl*, 8> Bases;653llvm::SmallPtrSet<const CXXRecordDecl*, 8> M;654SmallVector<const CXXRecordDecl*, 8> WorkList;655656// Visit a type that we have determined is an element of M(S).657auto Visit = [&](const CXXRecordDecl *RD) -> bool {658RD = RD->getCanonicalDecl();659660// C++2a [class]p8:661// A class S is a standard-layout class if it [...] has no element of the662// set M(S) of types as a base class.663//664// If we find a subobject of an empty type, it might also be a base class,665// so we'll need to walk the base classes to check.666if (!RD->data().HasBasesWithFields) {667// Walk the bases the first time, stopping if we find the type. Build a668// set of them so we don't need to walk them again.669if (Bases.empty()) {670bool RDIsBase = !forallBases([&](const CXXRecordDecl *Base) -> bool {671Base = Base->getCanonicalDecl();672if (RD == Base)673return false;674Bases.insert(Base);675return true;676});677if (RDIsBase)678return true;679} else {680if (Bases.count(RD))681return true;682}683}684685if (M.insert(RD).second)686WorkList.push_back(RD);687return false;688};689690if (Visit(XFirst))691return true;692693while (!WorkList.empty()) {694const CXXRecordDecl *X = WorkList.pop_back_val();695696// FIXME: We don't check the bases of X. That matches the standard, but697// that sure looks like a wording bug.698699// -- If X is a non-union class type with a non-static data member700// [recurse to each field] that is either of zero size or is the701// first non-static data member of X702// -- If X is a union type, [recurse to union members]703bool IsFirstField = true;704for (auto *FD : X->fields()) {705// FIXME: Should we really care about the type of the first non-static706// data member of a non-union if there are preceding unnamed bit-fields?707if (FD->isUnnamedBitField())708continue;709710if (!IsFirstField && !FD->isZeroSize(Ctx))711continue;712713if (FD->isInvalidDecl())714continue;715716// -- If X is n array type, [visit the element type]717QualType T = Ctx.getBaseElementType(FD->getType());718if (auto *RD = T->getAsCXXRecordDecl())719if (Visit(RD))720return true;721722if (!X->isUnion())723IsFirstField = false;724}725}726727return false;728}729730bool CXXRecordDecl::lambdaIsDefaultConstructibleAndAssignable() const {731assert(isLambda() && "not a lambda");732733// C++2a [expr.prim.lambda.capture]p11:734// The closure type associated with a lambda-expression has no default735// constructor if the lambda-expression has a lambda-capture and a736// defaulted default constructor otherwise. It has a deleted copy737// assignment operator if the lambda-expression has a lambda-capture and738// defaulted copy and move assignment operators otherwise.739//740// C++17 [expr.prim.lambda]p21:741// The closure type associated with a lambda-expression has no default742// constructor and a deleted copy assignment operator.743if (!isCapturelessLambda())744return false;745return getASTContext().getLangOpts().CPlusPlus20;746}747748void CXXRecordDecl::addedMember(Decl *D) {749if (!D->isImplicit() && !isa<FieldDecl>(D) && !isa<IndirectFieldDecl>(D) &&750(!isa<TagDecl>(D) ||751cast<TagDecl>(D)->getTagKind() == TagTypeKind::Class ||752cast<TagDecl>(D)->getTagKind() == TagTypeKind::Interface))753data().HasOnlyCMembers = false;754755// Ignore friends and invalid declarations.756if (D->getFriendObjectKind() || D->isInvalidDecl())757return;758759auto *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);760if (FunTmpl)761D = FunTmpl->getTemplatedDecl();762763// FIXME: Pass NamedDecl* to addedMember?764Decl *DUnderlying = D;765if (auto *ND = dyn_cast<NamedDecl>(DUnderlying)) {766DUnderlying = ND->getUnderlyingDecl();767if (auto *UnderlyingFunTmpl = dyn_cast<FunctionTemplateDecl>(DUnderlying))768DUnderlying = UnderlyingFunTmpl->getTemplatedDecl();769}770771if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) {772if (Method->isVirtual()) {773// C++ [dcl.init.aggr]p1:774// An aggregate is an array or a class with [...] no virtual functions.775data().Aggregate = false;776777// C++ [class]p4:778// A POD-struct is an aggregate class...779data().PlainOldData = false;780781// C++14 [meta.unary.prop]p4:782// T is a class type [...] with [...] no virtual member functions...783data().Empty = false;784785// C++ [class.virtual]p1:786// A class that declares or inherits a virtual function is called a787// polymorphic class.788data().Polymorphic = true;789790// C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:791// A [default constructor, copy/move constructor, or copy/move792// assignment operator for a class X] is trivial [...] if:793// -- class X has no virtual functions [...]794data().HasTrivialSpecialMembers &= SMF_Destructor;795data().HasTrivialSpecialMembersForCall &= SMF_Destructor;796797// C++0x [class]p7:798// A standard-layout class is a class that: [...]799// -- has no virtual functions800data().IsStandardLayout = false;801data().IsCXX11StandardLayout = false;802}803}804805// Notify the listener if an implicit member was added after the definition806// was completed.807if (!isBeingDefined() && D->isImplicit())808if (ASTMutationListener *L = getASTMutationListener())809L->AddedCXXImplicitMember(data().Definition, D);810811// The kind of special member this declaration is, if any.812unsigned SMKind = 0;813814// Handle constructors.815if (const auto *Constructor = dyn_cast<CXXConstructorDecl>(D)) {816if (Constructor->isInheritingConstructor()) {817// Ignore constructor shadow declarations. They are lazily created and818// so shouldn't affect any properties of the class.819} else {820if (!Constructor->isImplicit()) {821// Note that we have a user-declared constructor.822data().UserDeclaredConstructor = true;823824const TargetInfo &TI = getASTContext().getTargetInfo();825if ((!Constructor->isDeleted() && !Constructor->isDefaulted()) ||826!TI.areDefaultedSMFStillPOD(getLangOpts())) {827// C++ [class]p4:828// A POD-struct is an aggregate class [...]829// Since the POD bit is meant to be C++03 POD-ness, clear it even if830// the type is technically an aggregate in C++0x since it wouldn't be831// in 03.832data().PlainOldData = false;833}834}835836if (Constructor->isDefaultConstructor()) {837SMKind |= SMF_DefaultConstructor;838839if (Constructor->isUserProvided())840data().UserProvidedDefaultConstructor = true;841if (Constructor->isConstexpr())842data().HasConstexprDefaultConstructor = true;843if (Constructor->isDefaulted())844data().HasDefaultedDefaultConstructor = true;845}846847if (!FunTmpl) {848unsigned Quals;849if (Constructor->isCopyConstructor(Quals)) {850SMKind |= SMF_CopyConstructor;851852if (Quals & Qualifiers::Const)853data().HasDeclaredCopyConstructorWithConstParam = true;854} else if (Constructor->isMoveConstructor())855SMKind |= SMF_MoveConstructor;856}857858// C++11 [dcl.init.aggr]p1: DR1518859// An aggregate is an array or a class with no user-provided [or]860// explicit [...] constructors861// C++20 [dcl.init.aggr]p1:862// An aggregate is an array or a class with no user-declared [...]863// constructors864if (getASTContext().getLangOpts().CPlusPlus20865? !Constructor->isImplicit()866: (Constructor->isUserProvided() || Constructor->isExplicit()))867data().Aggregate = false;868}869}870871// Handle constructors, including those inherited from base classes.872if (const auto *Constructor = dyn_cast<CXXConstructorDecl>(DUnderlying)) {873// Record if we see any constexpr constructors which are neither copy874// nor move constructors.875// C++1z [basic.types]p10:876// [...] has at least one constexpr constructor or constructor template877// (possibly inherited from a base class) that is not a copy or move878// constructor [...]879if (Constructor->isConstexpr() && !Constructor->isCopyOrMoveConstructor())880data().HasConstexprNonCopyMoveConstructor = true;881if (!isa<CXXConstructorDecl>(D) && Constructor->isDefaultConstructor())882data().HasInheritedDefaultConstructor = true;883}884885// Handle member functions.886if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) {887if (isa<CXXDestructorDecl>(D))888SMKind |= SMF_Destructor;889890if (Method->isCopyAssignmentOperator()) {891SMKind |= SMF_CopyAssignment;892893const auto *ParamTy =894Method->getNonObjectParameter(0)->getType()->getAs<ReferenceType>();895if (!ParamTy || ParamTy->getPointeeType().isConstQualified())896data().HasDeclaredCopyAssignmentWithConstParam = true;897}898899if (Method->isMoveAssignmentOperator())900SMKind |= SMF_MoveAssignment;901902// Keep the list of conversion functions up-to-date.903if (auto *Conversion = dyn_cast<CXXConversionDecl>(D)) {904// FIXME: We use the 'unsafe' accessor for the access specifier here,905// because Sema may not have set it yet. That's really just a misdesign906// in Sema. However, LLDB *will* have set the access specifier correctly,907// and adds declarations after the class is technically completed,908// so completeDefinition()'s overriding of the access specifiers doesn't909// work.910AccessSpecifier AS = Conversion->getAccessUnsafe();911912if (Conversion->getPrimaryTemplate()) {913// We don't record specializations.914} else {915ASTContext &Ctx = getASTContext();916ASTUnresolvedSet &Conversions = data().Conversions.get(Ctx);917NamedDecl *Primary =918FunTmpl ? cast<NamedDecl>(FunTmpl) : cast<NamedDecl>(Conversion);919if (Primary->getPreviousDecl())920Conversions.replace(cast<NamedDecl>(Primary->getPreviousDecl()),921Primary, AS);922else923Conversions.addDecl(Ctx, Primary, AS);924}925}926927if (SMKind) {928// If this is the first declaration of a special member, we no longer have929// an implicit trivial special member.930data().HasTrivialSpecialMembers &=931data().DeclaredSpecialMembers | ~SMKind;932data().HasTrivialSpecialMembersForCall &=933data().DeclaredSpecialMembers | ~SMKind;934935// Note when we have declared a declared special member, and suppress the936// implicit declaration of this special member.937data().DeclaredSpecialMembers |= SMKind;938if (!Method->isImplicit()) {939data().UserDeclaredSpecialMembers |= SMKind;940941const TargetInfo &TI = getASTContext().getTargetInfo();942if ((!Method->isDeleted() && !Method->isDefaulted() &&943SMKind != SMF_MoveAssignment) ||944!TI.areDefaultedSMFStillPOD(getLangOpts())) {945// C++03 [class]p4:946// A POD-struct is an aggregate class that has [...] no user-defined947// copy assignment operator and no user-defined destructor.948//949// Since the POD bit is meant to be C++03 POD-ness, and in C++03,950// aggregates could not have any constructors, clear it even for an951// explicitly defaulted or deleted constructor.952// type is technically an aggregate in C++0x since it wouldn't be in953// 03.954//955// Also, a user-declared move assignment operator makes a class956// non-POD. This is an extension in C++03.957data().PlainOldData = false;958}959}960// When instantiating a class, we delay updating the destructor and961// triviality properties of the class until selecting a destructor and962// computing the eligibility of its special member functions. This is963// because there might be function constraints that we need to evaluate964// and compare later in the instantiation.965if (!Method->isIneligibleOrNotSelected()) {966addedEligibleSpecialMemberFunction(Method, SMKind);967}968}969970return;971}972973// Handle non-static data members.974if (const auto *Field = dyn_cast<FieldDecl>(D)) {975ASTContext &Context = getASTContext();976977// C++2a [class]p7:978// A standard-layout class is a class that:979// [...]980// -- has all non-static data members and bit-fields in the class and981// its base classes first declared in the same class982if (data().HasBasesWithFields)983data().IsStandardLayout = false;984985// C++ [class.bit]p2:986// A declaration for a bit-field that omits the identifier declares an987// unnamed bit-field. Unnamed bit-fields are not members and cannot be988// initialized.989if (Field->isUnnamedBitField()) {990// C++ [meta.unary.prop]p4: [LWG2358]991// T is a class type [...] with [...] no unnamed bit-fields of non-zero992// length993if (data().Empty && !Field->isZeroLengthBitField(Context) &&994Context.getLangOpts().getClangABICompat() >995LangOptions::ClangABI::Ver6)996data().Empty = false;997return;998}9991000// C++11 [class]p7:1001// A standard-layout class is a class that:1002// -- either has no non-static data members in the most derived class1003// [...] or has no base classes with non-static data members1004if (data().HasBasesWithNonStaticDataMembers)1005data().IsCXX11StandardLayout = false;10061007// C++ [dcl.init.aggr]p1:1008// An aggregate is an array or a class (clause 9) with [...] no1009// private or protected non-static data members (clause 11).1010//1011// A POD must be an aggregate.1012if (D->getAccess() == AS_private || D->getAccess() == AS_protected) {1013data().Aggregate = false;1014data().PlainOldData = false;10151016// C++20 [temp.param]p7:1017// A structural type is [...] a literal class type [for which] all1018// non-static data members are public1019data().StructuralIfLiteral = false;1020}10211022// Track whether this is the first field. We use this when checking1023// whether the class is standard-layout below.1024bool IsFirstField = !data().HasPrivateFields &&1025!data().HasProtectedFields && !data().HasPublicFields;10261027// C++0x [class]p7:1028// A standard-layout class is a class that:1029// [...]1030// -- has the same access control for all non-static data members,1031switch (D->getAccess()) {1032case AS_private: data().HasPrivateFields = true; break;1033case AS_protected: data().HasProtectedFields = true; break;1034case AS_public: data().HasPublicFields = true; break;1035case AS_none: llvm_unreachable("Invalid access specifier");1036};1037if ((data().HasPrivateFields + data().HasProtectedFields +1038data().HasPublicFields) > 1) {1039data().IsStandardLayout = false;1040data().IsCXX11StandardLayout = false;1041}10421043// Keep track of the presence of mutable fields.1044if (Field->isMutable()) {1045data().HasMutableFields = true;10461047// C++20 [temp.param]p7:1048// A structural type is [...] a literal class type [for which] all1049// non-static data members are public1050data().StructuralIfLiteral = false;1051}10521053// C++11 [class.union]p8, DR1460:1054// If X is a union, a non-static data member of X that is not an anonymous1055// union is a variant member of X.1056if (isUnion() && !Field->isAnonymousStructOrUnion())1057data().HasVariantMembers = true;10581059// C++0x [class]p9:1060// A POD struct is a class that is both a trivial class and a1061// standard-layout class, and has no non-static data members of type1062// non-POD struct, non-POD union (or array of such types).1063//1064// Automatic Reference Counting: the presence of a member of Objective-C pointer type1065// that does not explicitly have no lifetime makes the class a non-POD.1066QualType T = Context.getBaseElementType(Field->getType());1067if (T->isObjCRetainableType() || T.isObjCGCStrong()) {1068if (T.hasNonTrivialObjCLifetime()) {1069// Objective-C Automatic Reference Counting:1070// If a class has a non-static data member of Objective-C pointer1071// type (or array thereof), it is a non-POD type and its1072// default constructor (if any), copy constructor, move constructor,1073// copy assignment operator, move assignment operator, and destructor are1074// non-trivial.1075setHasObjectMember(true);1076struct DefinitionData &Data = data();1077Data.PlainOldData = false;1078Data.HasTrivialSpecialMembers = 0;10791080// __strong or __weak fields do not make special functions non-trivial1081// for the purpose of calls.1082Qualifiers::ObjCLifetime LT = T.getQualifiers().getObjCLifetime();1083if (LT != Qualifiers::OCL_Strong && LT != Qualifiers::OCL_Weak)1084data().HasTrivialSpecialMembersForCall = 0;10851086// Structs with __weak fields should never be passed directly.1087if (LT == Qualifiers::OCL_Weak)1088setArgPassingRestrictions(RecordArgPassingKind::CanNeverPassInRegs);10891090Data.HasIrrelevantDestructor = false;10911092if (isUnion()) {1093data().DefaultedCopyConstructorIsDeleted = true;1094data().DefaultedMoveConstructorIsDeleted = true;1095data().DefaultedCopyAssignmentIsDeleted = true;1096data().DefaultedMoveAssignmentIsDeleted = true;1097data().DefaultedDestructorIsDeleted = true;1098data().NeedOverloadResolutionForCopyConstructor = true;1099data().NeedOverloadResolutionForMoveConstructor = true;1100data().NeedOverloadResolutionForCopyAssignment = true;1101data().NeedOverloadResolutionForMoveAssignment = true;1102data().NeedOverloadResolutionForDestructor = true;1103}1104} else if (!Context.getLangOpts().ObjCAutoRefCount) {1105setHasObjectMember(true);1106}1107} else if (!T.isCXX98PODType(Context))1108data().PlainOldData = false;11091110if (T->isReferenceType()) {1111if (!Field->hasInClassInitializer())1112data().HasUninitializedReferenceMember = true;11131114// C++0x [class]p7:1115// A standard-layout class is a class that:1116// -- has no non-static data members of type [...] reference,1117data().IsStandardLayout = false;1118data().IsCXX11StandardLayout = false;11191120// C++1z [class.copy.ctor]p10:1121// A defaulted copy constructor for a class X is defined as deleted if X has:1122// -- a non-static data member of rvalue reference type1123if (T->isRValueReferenceType())1124data().DefaultedCopyConstructorIsDeleted = true;1125}11261127if (!Field->hasInClassInitializer() && !Field->isMutable()) {1128if (CXXRecordDecl *FieldType = T->getAsCXXRecordDecl()) {1129if (FieldType->hasDefinition() && !FieldType->allowConstDefaultInit())1130data().HasUninitializedFields = true;1131} else {1132data().HasUninitializedFields = true;1133}1134}11351136// Record if this field is the first non-literal or volatile field or base.1137if (!T->isLiteralType(Context) || T.isVolatileQualified())1138data().HasNonLiteralTypeFieldsOrBases = true;11391140if (Field->hasInClassInitializer() ||1141(Field->isAnonymousStructOrUnion() &&1142Field->getType()->getAsCXXRecordDecl()->hasInClassInitializer())) {1143data().HasInClassInitializer = true;11441145// C++11 [class]p5:1146// A default constructor is trivial if [...] no non-static data member1147// of its class has a brace-or-equal-initializer.1148data().HasTrivialSpecialMembers &= ~SMF_DefaultConstructor;11491150// C++11 [dcl.init.aggr]p1:1151// An aggregate is a [...] class with [...] no1152// brace-or-equal-initializers for non-static data members.1153//1154// This rule was removed in C++14.1155if (!getASTContext().getLangOpts().CPlusPlus14)1156data().Aggregate = false;11571158// C++11 [class]p10:1159// A POD struct is [...] a trivial class.1160data().PlainOldData = false;1161}11621163// C++11 [class.copy]p23:1164// A defaulted copy/move assignment operator for a class X is defined1165// as deleted if X has:1166// -- a non-static data member of reference type1167if (T->isReferenceType()) {1168data().DefaultedCopyAssignmentIsDeleted = true;1169data().DefaultedMoveAssignmentIsDeleted = true;1170}11711172// Bitfields of length 0 are also zero-sized, but we already bailed out for1173// those because they are always unnamed.1174bool IsZeroSize = Field->isZeroSize(Context);11751176if (const auto *RecordTy = T->getAs<RecordType>()) {1177auto *FieldRec = cast<CXXRecordDecl>(RecordTy->getDecl());1178if (FieldRec->getDefinition()) {1179addedClassSubobject(FieldRec);11801181// We may need to perform overload resolution to determine whether a1182// field can be moved if it's const or volatile qualified.1183if (T.getCVRQualifiers() & (Qualifiers::Const | Qualifiers::Volatile)) {1184// We need to care about 'const' for the copy constructor because an1185// implicit copy constructor might be declared with a non-const1186// parameter.1187data().NeedOverloadResolutionForCopyConstructor = true;1188data().NeedOverloadResolutionForMoveConstructor = true;1189data().NeedOverloadResolutionForCopyAssignment = true;1190data().NeedOverloadResolutionForMoveAssignment = true;1191}11921193// C++11 [class.ctor]p5, C++11 [class.copy]p11:1194// A defaulted [special member] for a class X is defined as1195// deleted if:1196// -- X is a union-like class that has a variant member with a1197// non-trivial [corresponding special member]1198if (isUnion()) {1199if (FieldRec->hasNonTrivialCopyConstructor())1200data().DefaultedCopyConstructorIsDeleted = true;1201if (FieldRec->hasNonTrivialMoveConstructor())1202data().DefaultedMoveConstructorIsDeleted = true;1203if (FieldRec->hasNonTrivialCopyAssignment())1204data().DefaultedCopyAssignmentIsDeleted = true;1205if (FieldRec->hasNonTrivialMoveAssignment())1206data().DefaultedMoveAssignmentIsDeleted = true;1207if (FieldRec->hasNonTrivialDestructor())1208data().DefaultedDestructorIsDeleted = true;1209}12101211// For an anonymous union member, our overload resolution will perform1212// overload resolution for its members.1213if (Field->isAnonymousStructOrUnion()) {1214data().NeedOverloadResolutionForCopyConstructor |=1215FieldRec->data().NeedOverloadResolutionForCopyConstructor;1216data().NeedOverloadResolutionForMoveConstructor |=1217FieldRec->data().NeedOverloadResolutionForMoveConstructor;1218data().NeedOverloadResolutionForCopyAssignment |=1219FieldRec->data().NeedOverloadResolutionForCopyAssignment;1220data().NeedOverloadResolutionForMoveAssignment |=1221FieldRec->data().NeedOverloadResolutionForMoveAssignment;1222data().NeedOverloadResolutionForDestructor |=1223FieldRec->data().NeedOverloadResolutionForDestructor;1224}12251226// C++0x [class.ctor]p5:1227// A default constructor is trivial [...] if:1228// -- for all the non-static data members of its class that are of1229// class type (or array thereof), each such class has a trivial1230// default constructor.1231if (!FieldRec->hasTrivialDefaultConstructor())1232data().HasTrivialSpecialMembers &= ~SMF_DefaultConstructor;12331234// C++0x [class.copy]p13:1235// A copy/move constructor for class X is trivial if [...]1236// [...]1237// -- for each non-static data member of X that is of class type (or1238// an array thereof), the constructor selected to copy/move that1239// member is trivial;1240if (!FieldRec->hasTrivialCopyConstructor())1241data().HasTrivialSpecialMembers &= ~SMF_CopyConstructor;12421243if (!FieldRec->hasTrivialCopyConstructorForCall())1244data().HasTrivialSpecialMembersForCall &= ~SMF_CopyConstructor;12451246// If the field doesn't have a simple move constructor, we'll eagerly1247// declare the move constructor for this class and we'll decide whether1248// it's trivial then.1249if (!FieldRec->hasTrivialMoveConstructor())1250data().HasTrivialSpecialMembers &= ~SMF_MoveConstructor;12511252if (!FieldRec->hasTrivialMoveConstructorForCall())1253data().HasTrivialSpecialMembersForCall &= ~SMF_MoveConstructor;12541255// C++0x [class.copy]p27:1256// A copy/move assignment operator for class X is trivial if [...]1257// [...]1258// -- for each non-static data member of X that is of class type (or1259// an array thereof), the assignment operator selected to1260// copy/move that member is trivial;1261if (!FieldRec->hasTrivialCopyAssignment())1262data().HasTrivialSpecialMembers &= ~SMF_CopyAssignment;1263// If the field doesn't have a simple move assignment, we'll eagerly1264// declare the move assignment for this class and we'll decide whether1265// it's trivial then.1266if (!FieldRec->hasTrivialMoveAssignment())1267data().HasTrivialSpecialMembers &= ~SMF_MoveAssignment;12681269if (!FieldRec->hasTrivialDestructor())1270data().HasTrivialSpecialMembers &= ~SMF_Destructor;1271if (!FieldRec->hasTrivialDestructorForCall())1272data().HasTrivialSpecialMembersForCall &= ~SMF_Destructor;1273if (!FieldRec->hasIrrelevantDestructor())1274data().HasIrrelevantDestructor = false;1275if (FieldRec->isAnyDestructorNoReturn())1276data().IsAnyDestructorNoReturn = true;1277if (FieldRec->hasObjectMember())1278setHasObjectMember(true);1279if (FieldRec->hasVolatileMember())1280setHasVolatileMember(true);1281if (FieldRec->getArgPassingRestrictions() ==1282RecordArgPassingKind::CanNeverPassInRegs)1283setArgPassingRestrictions(RecordArgPassingKind::CanNeverPassInRegs);12841285// C++0x [class]p7:1286// A standard-layout class is a class that:1287// -- has no non-static data members of type non-standard-layout1288// class (or array of such types) [...]1289if (!FieldRec->isStandardLayout())1290data().IsStandardLayout = false;1291if (!FieldRec->isCXX11StandardLayout())1292data().IsCXX11StandardLayout = false;12931294// C++2a [class]p7:1295// A standard-layout class is a class that:1296// [...]1297// -- has no element of the set M(S) of types as a base class.1298if (data().IsStandardLayout &&1299(isUnion() || IsFirstField || IsZeroSize) &&1300hasSubobjectAtOffsetZeroOfEmptyBaseType(Context, FieldRec))1301data().IsStandardLayout = false;13021303// C++11 [class]p7:1304// A standard-layout class is a class that:1305// -- has no base classes of the same type as the first non-static1306// data member1307if (data().IsCXX11StandardLayout && IsFirstField) {1308// FIXME: We should check all base classes here, not just direct1309// base classes.1310for (const auto &BI : bases()) {1311if (Context.hasSameUnqualifiedType(BI.getType(), T)) {1312data().IsCXX11StandardLayout = false;1313break;1314}1315}1316}13171318// Keep track of the presence of mutable fields.1319if (FieldRec->hasMutableFields())1320data().HasMutableFields = true;13211322if (Field->isMutable()) {1323// Our copy constructor/assignment might call something other than1324// the subobject's copy constructor/assignment if it's mutable and of1325// class type.1326data().NeedOverloadResolutionForCopyConstructor = true;1327data().NeedOverloadResolutionForCopyAssignment = true;1328}13291330// C++11 [class.copy]p13:1331// If the implicitly-defined constructor would satisfy the1332// requirements of a constexpr constructor, the implicitly-defined1333// constructor is constexpr.1334// C++11 [dcl.constexpr]p4:1335// -- every constructor involved in initializing non-static data1336// members [...] shall be a constexpr constructor1337if (!Field->hasInClassInitializer() &&1338!FieldRec->hasConstexprDefaultConstructor() && !isUnion())1339// The standard requires any in-class initializer to be a constant1340// expression. We consider this to be a defect.1341data().DefaultedDefaultConstructorIsConstexpr =1342Context.getLangOpts().CPlusPlus23;13431344// C++11 [class.copy]p8:1345// The implicitly-declared copy constructor for a class X will have1346// the form 'X::X(const X&)' if each potentially constructed subobject1347// of a class type M (or array thereof) has a copy constructor whose1348// first parameter is of type 'const M&' or 'const volatile M&'.1349if (!FieldRec->hasCopyConstructorWithConstParam())1350data().ImplicitCopyConstructorCanHaveConstParamForNonVBase = false;13511352// C++11 [class.copy]p18:1353// The implicitly-declared copy assignment oeprator for a class X will1354// have the form 'X& X::operator=(const X&)' if [...] for all the1355// non-static data members of X that are of a class type M (or array1356// thereof), each such class type has a copy assignment operator whose1357// parameter is of type 'const M&', 'const volatile M&' or 'M'.1358if (!FieldRec->hasCopyAssignmentWithConstParam())1359data().ImplicitCopyAssignmentHasConstParam = false;13601361if (FieldRec->hasUninitializedReferenceMember() &&1362!Field->hasInClassInitializer())1363data().HasUninitializedReferenceMember = true;13641365// C++11 [class.union]p8, DR1460:1366// a non-static data member of an anonymous union that is a member of1367// X is also a variant member of X.1368if (FieldRec->hasVariantMembers() &&1369Field->isAnonymousStructOrUnion())1370data().HasVariantMembers = true;1371}1372} else {1373// Base element type of field is a non-class type.1374if (!T->isLiteralType(Context) ||1375(!Field->hasInClassInitializer() && !isUnion() &&1376!Context.getLangOpts().CPlusPlus20))1377data().DefaultedDefaultConstructorIsConstexpr = false;13781379// C++11 [class.copy]p23:1380// A defaulted copy/move assignment operator for a class X is defined1381// as deleted if X has:1382// -- a non-static data member of const non-class type (or array1383// thereof)1384if (T.isConstQualified()) {1385data().DefaultedCopyAssignmentIsDeleted = true;1386data().DefaultedMoveAssignmentIsDeleted = true;1387}13881389// C++20 [temp.param]p7:1390// A structural type is [...] a literal class type [for which] the1391// types of all non-static data members are structural types or1392// (possibly multidimensional) array thereof1393// We deal with class types elsewhere.1394if (!T->isStructuralType())1395data().StructuralIfLiteral = false;1396}13971398// C++14 [meta.unary.prop]p4:1399// T is a class type [...] with [...] no non-static data members other1400// than subobjects of zero size1401if (data().Empty && !IsZeroSize)1402data().Empty = false;1403}14041405// Handle using declarations of conversion functions.1406if (auto *Shadow = dyn_cast<UsingShadowDecl>(D)) {1407if (Shadow->getDeclName().getNameKind()1408== DeclarationName::CXXConversionFunctionName) {1409ASTContext &Ctx = getASTContext();1410data().Conversions.get(Ctx).addDecl(Ctx, Shadow, Shadow->getAccess());1411}1412}14131414if (const auto *Using = dyn_cast<UsingDecl>(D)) {1415if (Using->getDeclName().getNameKind() ==1416DeclarationName::CXXConstructorName) {1417data().HasInheritedConstructor = true;1418// C++1z [dcl.init.aggr]p1:1419// An aggregate is [...] a class [...] with no inherited constructors1420data().Aggregate = false;1421}14221423if (Using->getDeclName().getCXXOverloadedOperator() == OO_Equal)1424data().HasInheritedAssignment = true;1425}1426}14271428bool CXXRecordDecl::isLiteral() const {1429const LangOptions &LangOpts = getLangOpts();1430if (!(LangOpts.CPlusPlus20 ? hasConstexprDestructor()1431: hasTrivialDestructor()))1432return false;14331434if (hasNonLiteralTypeFieldsOrBases()) {1435// CWG25981436// is an aggregate union type that has either no variant1437// members or at least one variant member of non-volatile literal type,1438if (!isUnion())1439return false;1440bool HasAtLeastOneLiteralMember =1441fields().empty() || any_of(fields(), [this](const FieldDecl *D) {1442return !D->getType().isVolatileQualified() &&1443D->getType()->isLiteralType(getASTContext());1444});1445if (!HasAtLeastOneLiteralMember)1446return false;1447}14481449return isAggregate() || (isLambda() && LangOpts.CPlusPlus17) ||1450hasConstexprNonCopyMoveConstructor() || hasTrivialDefaultConstructor();1451}14521453void CXXRecordDecl::addedSelectedDestructor(CXXDestructorDecl *DD) {1454DD->setIneligibleOrNotSelected(false);1455addedEligibleSpecialMemberFunction(DD, SMF_Destructor);1456}14571458void CXXRecordDecl::addedEligibleSpecialMemberFunction(const CXXMethodDecl *MD,1459unsigned SMKind) {1460// FIXME: We shouldn't change DeclaredNonTrivialSpecialMembers if `MD` is1461// a function template, but this needs CWG attention before we break ABI.1462// See https://github.com/llvm/llvm-project/issues/5920614631464if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD)) {1465if (DD->isUserProvided())1466data().HasIrrelevantDestructor = false;1467// If the destructor is explicitly defaulted and not trivial or not public1468// or if the destructor is deleted, we clear HasIrrelevantDestructor in1469// finishedDefaultedOrDeletedMember.14701471// C++11 [class.dtor]p5:1472// A destructor is trivial if [...] the destructor is not virtual.1473if (DD->isVirtual()) {1474data().HasTrivialSpecialMembers &= ~SMF_Destructor;1475data().HasTrivialSpecialMembersForCall &= ~SMF_Destructor;1476}14771478if (DD->isNoReturn())1479data().IsAnyDestructorNoReturn = true;1480}14811482if (!MD->isImplicit() && !MD->isUserProvided()) {1483// This method is user-declared but not user-provided. We can't work1484// out whether it's trivial yet (not until we get to the end of the1485// class). We'll handle this method in1486// finishedDefaultedOrDeletedMember.1487} else if (MD->isTrivial()) {1488data().HasTrivialSpecialMembers |= SMKind;1489data().HasTrivialSpecialMembersForCall |= SMKind;1490} else if (MD->isTrivialForCall()) {1491data().HasTrivialSpecialMembersForCall |= SMKind;1492data().DeclaredNonTrivialSpecialMembers |= SMKind;1493} else {1494data().DeclaredNonTrivialSpecialMembers |= SMKind;1495// If this is a user-provided function, do not set1496// DeclaredNonTrivialSpecialMembersForCall here since we don't know1497// yet whether the method would be considered non-trivial for the1498// purpose of calls (attribute "trivial_abi" can be dropped from the1499// class later, which can change the special method's triviality).1500if (!MD->isUserProvided())1501data().DeclaredNonTrivialSpecialMembersForCall |= SMKind;1502}1503}15041505void CXXRecordDecl::finishedDefaultedOrDeletedMember(CXXMethodDecl *D) {1506assert(!D->isImplicit() && !D->isUserProvided());15071508// The kind of special member this declaration is, if any.1509unsigned SMKind = 0;15101511if (const auto *Constructor = dyn_cast<CXXConstructorDecl>(D)) {1512if (Constructor->isDefaultConstructor()) {1513SMKind |= SMF_DefaultConstructor;1514if (Constructor->isConstexpr())1515data().HasConstexprDefaultConstructor = true;1516}1517if (Constructor->isCopyConstructor())1518SMKind |= SMF_CopyConstructor;1519else if (Constructor->isMoveConstructor())1520SMKind |= SMF_MoveConstructor;1521else if (Constructor->isConstexpr())1522// We may now know that the constructor is constexpr.1523data().HasConstexprNonCopyMoveConstructor = true;1524} else if (isa<CXXDestructorDecl>(D)) {1525SMKind |= SMF_Destructor;1526if (!D->isTrivial() || D->getAccess() != AS_public || D->isDeleted())1527data().HasIrrelevantDestructor = false;1528} else if (D->isCopyAssignmentOperator())1529SMKind |= SMF_CopyAssignment;1530else if (D->isMoveAssignmentOperator())1531SMKind |= SMF_MoveAssignment;15321533// Update which trivial / non-trivial special members we have.1534// addedMember will have skipped this step for this member.1535if (!D->isIneligibleOrNotSelected()) {1536if (D->isTrivial())1537data().HasTrivialSpecialMembers |= SMKind;1538else1539data().DeclaredNonTrivialSpecialMembers |= SMKind;1540}1541}15421543void CXXRecordDecl::LambdaDefinitionData::AddCaptureList(ASTContext &Ctx,1544Capture *CaptureList) {1545Captures.push_back(CaptureList);1546if (Captures.size() == 2) {1547// The TinyPtrVector member now needs destruction.1548Ctx.addDestruction(&Captures);1549}1550}15511552void CXXRecordDecl::setCaptures(ASTContext &Context,1553ArrayRef<LambdaCapture> Captures) {1554CXXRecordDecl::LambdaDefinitionData &Data = getLambdaData();15551556// Copy captures.1557Data.NumCaptures = Captures.size();1558Data.NumExplicitCaptures = 0;1559auto *ToCapture = (LambdaCapture *)Context.Allocate(sizeof(LambdaCapture) *1560Captures.size());1561Data.AddCaptureList(Context, ToCapture);1562for (const LambdaCapture &C : Captures) {1563if (C.isExplicit())1564++Data.NumExplicitCaptures;15651566new (ToCapture) LambdaCapture(C);1567ToCapture++;1568}15691570if (!lambdaIsDefaultConstructibleAndAssignable())1571Data.DefaultedCopyAssignmentIsDeleted = true;1572}15731574void CXXRecordDecl::setTrivialForCallFlags(CXXMethodDecl *D) {1575unsigned SMKind = 0;15761577if (const auto *Constructor = dyn_cast<CXXConstructorDecl>(D)) {1578if (Constructor->isCopyConstructor())1579SMKind = SMF_CopyConstructor;1580else if (Constructor->isMoveConstructor())1581SMKind = SMF_MoveConstructor;1582} else if (isa<CXXDestructorDecl>(D))1583SMKind = SMF_Destructor;15841585if (D->isTrivialForCall())1586data().HasTrivialSpecialMembersForCall |= SMKind;1587else1588data().DeclaredNonTrivialSpecialMembersForCall |= SMKind;1589}15901591bool CXXRecordDecl::isCLike() const {1592if (getTagKind() == TagTypeKind::Class ||1593getTagKind() == TagTypeKind::Interface ||1594!TemplateOrInstantiation.isNull())1595return false;1596if (!hasDefinition())1597return true;15981599return isPOD() && data().HasOnlyCMembers;1600}16011602bool CXXRecordDecl::isGenericLambda() const {1603if (!isLambda()) return false;1604return getLambdaData().IsGenericLambda;1605}16061607#ifndef NDEBUG1608static bool allLookupResultsAreTheSame(const DeclContext::lookup_result &R) {1609return llvm::all_of(R, [&](NamedDecl *D) {1610return D->isInvalidDecl() || declaresSameEntity(D, R.front());1611});1612}1613#endif16141615static NamedDecl* getLambdaCallOperatorHelper(const CXXRecordDecl &RD) {1616if (!RD.isLambda()) return nullptr;1617DeclarationName Name =1618RD.getASTContext().DeclarationNames.getCXXOperatorName(OO_Call);1619DeclContext::lookup_result Calls = RD.lookup(Name);16201621assert(!Calls.empty() && "Missing lambda call operator!");1622assert(allLookupResultsAreTheSame(Calls) &&1623"More than one lambda call operator!");1624return Calls.front();1625}16261627FunctionTemplateDecl* CXXRecordDecl::getDependentLambdaCallOperator() const {1628NamedDecl *CallOp = getLambdaCallOperatorHelper(*this);1629return dyn_cast_or_null<FunctionTemplateDecl>(CallOp);1630}16311632CXXMethodDecl *CXXRecordDecl::getLambdaCallOperator() const {1633NamedDecl *CallOp = getLambdaCallOperatorHelper(*this);16341635if (CallOp == nullptr)1636return nullptr;16371638if (const auto *CallOpTmpl = dyn_cast<FunctionTemplateDecl>(CallOp))1639return cast<CXXMethodDecl>(CallOpTmpl->getTemplatedDecl());16401641return cast<CXXMethodDecl>(CallOp);1642}16431644CXXMethodDecl* CXXRecordDecl::getLambdaStaticInvoker() const {1645CXXMethodDecl *CallOp = getLambdaCallOperator();1646CallingConv CC = CallOp->getType()->castAs<FunctionType>()->getCallConv();1647return getLambdaStaticInvoker(CC);1648}16491650static DeclContext::lookup_result1651getLambdaStaticInvokers(const CXXRecordDecl &RD) {1652assert(RD.isLambda() && "Must be a lambda");1653DeclarationName Name =1654&RD.getASTContext().Idents.get(getLambdaStaticInvokerName());1655return RD.lookup(Name);1656}16571658static CXXMethodDecl *getInvokerAsMethod(NamedDecl *ND) {1659if (const auto *InvokerTemplate = dyn_cast<FunctionTemplateDecl>(ND))1660return cast<CXXMethodDecl>(InvokerTemplate->getTemplatedDecl());1661return cast<CXXMethodDecl>(ND);1662}16631664CXXMethodDecl *CXXRecordDecl::getLambdaStaticInvoker(CallingConv CC) const {1665if (!isLambda())1666return nullptr;1667DeclContext::lookup_result Invoker = getLambdaStaticInvokers(*this);16681669for (NamedDecl *ND : Invoker) {1670const auto *FTy =1671cast<ValueDecl>(ND->getAsFunction())->getType()->castAs<FunctionType>();1672if (FTy->getCallConv() == CC)1673return getInvokerAsMethod(ND);1674}16751676return nullptr;1677}16781679void CXXRecordDecl::getCaptureFields(1680llvm::DenseMap<const ValueDecl *, FieldDecl *> &Captures,1681FieldDecl *&ThisCapture) const {1682Captures.clear();1683ThisCapture = nullptr;16841685LambdaDefinitionData &Lambda = getLambdaData();1686for (const LambdaCapture *List : Lambda.Captures) {1687RecordDecl::field_iterator Field = field_begin();1688for (const LambdaCapture *C = List, *CEnd = C + Lambda.NumCaptures;1689C != CEnd; ++C, ++Field) {1690if (C->capturesThis())1691ThisCapture = *Field;1692else if (C->capturesVariable())1693Captures[C->getCapturedVar()] = *Field;1694}1695assert(Field == field_end());1696}1697}16981699TemplateParameterList *1700CXXRecordDecl::getGenericLambdaTemplateParameterList() const {1701if (!isGenericLambda()) return nullptr;1702CXXMethodDecl *CallOp = getLambdaCallOperator();1703if (FunctionTemplateDecl *Tmpl = CallOp->getDescribedFunctionTemplate())1704return Tmpl->getTemplateParameters();1705return nullptr;1706}17071708ArrayRef<NamedDecl *>1709CXXRecordDecl::getLambdaExplicitTemplateParameters() const {1710TemplateParameterList *List = getGenericLambdaTemplateParameterList();1711if (!List)1712return {};17131714assert(std::is_partitioned(List->begin(), List->end(),1715[](const NamedDecl *D) { return !D->isImplicit(); })1716&& "Explicit template params should be ordered before implicit ones");17171718const auto ExplicitEnd = llvm::partition_point(1719*List, [](const NamedDecl *D) { return !D->isImplicit(); });1720return llvm::ArrayRef(List->begin(), ExplicitEnd);1721}17221723Decl *CXXRecordDecl::getLambdaContextDecl() const {1724assert(isLambda() && "Not a lambda closure type!");1725ExternalASTSource *Source = getParentASTContext().getExternalSource();1726return getLambdaData().ContextDecl.get(Source);1727}17281729void CXXRecordDecl::setLambdaNumbering(LambdaNumbering Numbering) {1730assert(isLambda() && "Not a lambda closure type!");1731getLambdaData().ManglingNumber = Numbering.ManglingNumber;1732if (Numbering.DeviceManglingNumber)1733getASTContext().DeviceLambdaManglingNumbers[this] =1734Numbering.DeviceManglingNumber;1735getLambdaData().IndexInContext = Numbering.IndexInContext;1736getLambdaData().ContextDecl = Numbering.ContextDecl;1737getLambdaData().HasKnownInternalLinkage = Numbering.HasKnownInternalLinkage;1738}17391740unsigned CXXRecordDecl::getDeviceLambdaManglingNumber() const {1741assert(isLambda() && "Not a lambda closure type!");1742return getASTContext().DeviceLambdaManglingNumbers.lookup(this);1743}17441745static CanQualType GetConversionType(ASTContext &Context, NamedDecl *Conv) {1746QualType T =1747cast<CXXConversionDecl>(Conv->getUnderlyingDecl()->getAsFunction())1748->getConversionType();1749return Context.getCanonicalType(T);1750}17511752/// Collect the visible conversions of a base class.1753///1754/// \param Record a base class of the class we're considering1755/// \param InVirtual whether this base class is a virtual base (or a base1756/// of a virtual base)1757/// \param Access the access along the inheritance path to this base1758/// \param ParentHiddenTypes the conversions provided by the inheritors1759/// of this base1760/// \param Output the set to which to add conversions from non-virtual bases1761/// \param VOutput the set to which to add conversions from virtual bases1762/// \param HiddenVBaseCs the set of conversions which were hidden in a1763/// virtual base along some inheritance path1764static void CollectVisibleConversions(1765ASTContext &Context, const CXXRecordDecl *Record, bool InVirtual,1766AccessSpecifier Access,1767const llvm::SmallPtrSet<CanQualType, 8> &ParentHiddenTypes,1768ASTUnresolvedSet &Output, UnresolvedSetImpl &VOutput,1769llvm::SmallPtrSet<NamedDecl *, 8> &HiddenVBaseCs) {1770// The set of types which have conversions in this class or its1771// subclasses. As an optimization, we don't copy the derived set1772// unless it might change.1773const llvm::SmallPtrSet<CanQualType, 8> *HiddenTypes = &ParentHiddenTypes;1774llvm::SmallPtrSet<CanQualType, 8> HiddenTypesBuffer;17751776// Collect the direct conversions and figure out which conversions1777// will be hidden in the subclasses.1778CXXRecordDecl::conversion_iterator ConvI = Record->conversion_begin();1779CXXRecordDecl::conversion_iterator ConvE = Record->conversion_end();1780if (ConvI != ConvE) {1781HiddenTypesBuffer = ParentHiddenTypes;1782HiddenTypes = &HiddenTypesBuffer;17831784for (CXXRecordDecl::conversion_iterator I = ConvI; I != ConvE; ++I) {1785CanQualType ConvType(GetConversionType(Context, I.getDecl()));1786bool Hidden = ParentHiddenTypes.count(ConvType);1787if (!Hidden)1788HiddenTypesBuffer.insert(ConvType);17891790// If this conversion is hidden and we're in a virtual base,1791// remember that it's hidden along some inheritance path.1792if (Hidden && InVirtual)1793HiddenVBaseCs.insert(cast<NamedDecl>(I.getDecl()->getCanonicalDecl()));17941795// If this conversion isn't hidden, add it to the appropriate output.1796else if (!Hidden) {1797AccessSpecifier IAccess1798= CXXRecordDecl::MergeAccess(Access, I.getAccess());17991800if (InVirtual)1801VOutput.addDecl(I.getDecl(), IAccess);1802else1803Output.addDecl(Context, I.getDecl(), IAccess);1804}1805}1806}18071808// Collect information recursively from any base classes.1809for (const auto &I : Record->bases()) {1810const auto *RT = I.getType()->getAs<RecordType>();1811if (!RT) continue;18121813AccessSpecifier BaseAccess1814= CXXRecordDecl::MergeAccess(Access, I.getAccessSpecifier());1815bool BaseInVirtual = InVirtual || I.isVirtual();18161817auto *Base = cast<CXXRecordDecl>(RT->getDecl());1818CollectVisibleConversions(Context, Base, BaseInVirtual, BaseAccess,1819*HiddenTypes, Output, VOutput, HiddenVBaseCs);1820}1821}18221823/// Collect the visible conversions of a class.1824///1825/// This would be extremely straightforward if it weren't for virtual1826/// bases. It might be worth special-casing that, really.1827static void CollectVisibleConversions(ASTContext &Context,1828const CXXRecordDecl *Record,1829ASTUnresolvedSet &Output) {1830// The collection of all conversions in virtual bases that we've1831// found. These will be added to the output as long as they don't1832// appear in the hidden-conversions set.1833UnresolvedSet<8> VBaseCs;18341835// The set of conversions in virtual bases that we've determined to1836// be hidden.1837llvm::SmallPtrSet<NamedDecl*, 8> HiddenVBaseCs;18381839// The set of types hidden by classes derived from this one.1840llvm::SmallPtrSet<CanQualType, 8> HiddenTypes;18411842// Go ahead and collect the direct conversions and add them to the1843// hidden-types set.1844CXXRecordDecl::conversion_iterator ConvI = Record->conversion_begin();1845CXXRecordDecl::conversion_iterator ConvE = Record->conversion_end();1846Output.append(Context, ConvI, ConvE);1847for (; ConvI != ConvE; ++ConvI)1848HiddenTypes.insert(GetConversionType(Context, ConvI.getDecl()));18491850// Recursively collect conversions from base classes.1851for (const auto &I : Record->bases()) {1852const auto *RT = I.getType()->getAs<RecordType>();1853if (!RT) continue;18541855CollectVisibleConversions(Context, cast<CXXRecordDecl>(RT->getDecl()),1856I.isVirtual(), I.getAccessSpecifier(),1857HiddenTypes, Output, VBaseCs, HiddenVBaseCs);1858}18591860// Add any unhidden conversions provided by virtual bases.1861for (UnresolvedSetIterator I = VBaseCs.begin(), E = VBaseCs.end();1862I != E; ++I) {1863if (!HiddenVBaseCs.count(cast<NamedDecl>(I.getDecl()->getCanonicalDecl())))1864Output.addDecl(Context, I.getDecl(), I.getAccess());1865}1866}18671868/// getVisibleConversionFunctions - get all conversion functions visible1869/// in current class; including conversion function templates.1870llvm::iterator_range<CXXRecordDecl::conversion_iterator>1871CXXRecordDecl::getVisibleConversionFunctions() const {1872ASTContext &Ctx = getASTContext();18731874ASTUnresolvedSet *Set;1875if (bases_begin() == bases_end()) {1876// If root class, all conversions are visible.1877Set = &data().Conversions.get(Ctx);1878} else {1879Set = &data().VisibleConversions.get(Ctx);1880// If visible conversion list is not evaluated, evaluate it.1881if (!data().ComputedVisibleConversions) {1882CollectVisibleConversions(Ctx, this, *Set);1883data().ComputedVisibleConversions = true;1884}1885}1886return llvm::make_range(Set->begin(), Set->end());1887}18881889void CXXRecordDecl::removeConversion(const NamedDecl *ConvDecl) {1890// This operation is O(N) but extremely rare. Sema only uses it to1891// remove UsingShadowDecls in a class that were followed by a direct1892// declaration, e.g.:1893// class A : B {1894// using B::operator int;1895// operator int();1896// };1897// This is uncommon by itself and even more uncommon in conjunction1898// with sufficiently large numbers of directly-declared conversions1899// that asymptotic behavior matters.19001901ASTUnresolvedSet &Convs = data().Conversions.get(getASTContext());1902for (unsigned I = 0, E = Convs.size(); I != E; ++I) {1903if (Convs[I].getDecl() == ConvDecl) {1904Convs.erase(I);1905assert(!llvm::is_contained(Convs, ConvDecl) &&1906"conversion was found multiple times in unresolved set");1907return;1908}1909}19101911llvm_unreachable("conversion not found in set!");1912}19131914CXXRecordDecl *CXXRecordDecl::getInstantiatedFromMemberClass() const {1915if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo())1916return cast<CXXRecordDecl>(MSInfo->getInstantiatedFrom());19171918return nullptr;1919}19201921MemberSpecializationInfo *CXXRecordDecl::getMemberSpecializationInfo() const {1922return TemplateOrInstantiation.dyn_cast<MemberSpecializationInfo *>();1923}19241925void1926CXXRecordDecl::setInstantiationOfMemberClass(CXXRecordDecl *RD,1927TemplateSpecializationKind TSK) {1928assert(TemplateOrInstantiation.isNull() &&1929"Previous template or instantiation?");1930assert(!isa<ClassTemplatePartialSpecializationDecl>(this));1931TemplateOrInstantiation1932= new (getASTContext()) MemberSpecializationInfo(RD, TSK);1933}19341935ClassTemplateDecl *CXXRecordDecl::getDescribedClassTemplate() const {1936return TemplateOrInstantiation.dyn_cast<ClassTemplateDecl *>();1937}19381939void CXXRecordDecl::setDescribedClassTemplate(ClassTemplateDecl *Template) {1940TemplateOrInstantiation = Template;1941}19421943TemplateSpecializationKind CXXRecordDecl::getTemplateSpecializationKind() const{1944if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(this))1945return Spec->getSpecializationKind();19461947if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo())1948return MSInfo->getTemplateSpecializationKind();19491950return TSK_Undeclared;1951}19521953void1954CXXRecordDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK) {1955if (auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(this)) {1956Spec->setSpecializationKind(TSK);1957return;1958}19591960if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo()) {1961MSInfo->setTemplateSpecializationKind(TSK);1962return;1963}19641965llvm_unreachable("Not a class template or member class specialization");1966}19671968const CXXRecordDecl *CXXRecordDecl::getTemplateInstantiationPattern() const {1969auto GetDefinitionOrSelf =1970[](const CXXRecordDecl *D) -> const CXXRecordDecl * {1971if (auto *Def = D->getDefinition())1972return Def;1973return D;1974};19751976// If it's a class template specialization, find the template or partial1977// specialization from which it was instantiated.1978if (auto *TD = dyn_cast<ClassTemplateSpecializationDecl>(this)) {1979auto From = TD->getInstantiatedFrom();1980if (auto *CTD = From.dyn_cast<ClassTemplateDecl *>()) {1981while (auto *NewCTD = CTD->getInstantiatedFromMemberTemplate()) {1982if (NewCTD->isMemberSpecialization())1983break;1984CTD = NewCTD;1985}1986return GetDefinitionOrSelf(CTD->getTemplatedDecl());1987}1988if (auto *CTPSD =1989From.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {1990while (auto *NewCTPSD = CTPSD->getInstantiatedFromMember()) {1991if (NewCTPSD->isMemberSpecialization())1992break;1993CTPSD = NewCTPSD;1994}1995return GetDefinitionOrSelf(CTPSD);1996}1997}19981999if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo()) {2000if (isTemplateInstantiation(MSInfo->getTemplateSpecializationKind())) {2001const CXXRecordDecl *RD = this;2002while (auto *NewRD = RD->getInstantiatedFromMemberClass())2003RD = NewRD;2004return GetDefinitionOrSelf(RD);2005}2006}20072008assert(!isTemplateInstantiation(this->getTemplateSpecializationKind()) &&2009"couldn't find pattern for class template instantiation");2010return nullptr;2011}20122013CXXDestructorDecl *CXXRecordDecl::getDestructor() const {2014ASTContext &Context = getASTContext();2015QualType ClassType = Context.getTypeDeclType(this);20162017DeclarationName Name2018= Context.DeclarationNames.getCXXDestructorName(2019Context.getCanonicalType(ClassType));20202021DeclContext::lookup_result R = lookup(Name);20222023// If a destructor was marked as not selected, we skip it. We don't always2024// have a selected destructor: dependent types, unnamed structs.2025for (auto *Decl : R) {2026auto* DD = dyn_cast<CXXDestructorDecl>(Decl);2027if (DD && !DD->isIneligibleOrNotSelected())2028return DD;2029}2030return nullptr;2031}20322033static bool isDeclContextInNamespace(const DeclContext *DC) {2034while (!DC->isTranslationUnit()) {2035if (DC->isNamespace())2036return true;2037DC = DC->getParent();2038}2039return false;2040}20412042bool CXXRecordDecl::isInterfaceLike() const {2043assert(hasDefinition() && "checking for interface-like without a definition");2044// All __interfaces are inheritently interface-like.2045if (isInterface())2046return true;20472048// Interface-like types cannot have a user declared constructor, destructor,2049// friends, VBases, conversion functions, or fields. Additionally, lambdas2050// cannot be interface types.2051if (isLambda() || hasUserDeclaredConstructor() ||2052hasUserDeclaredDestructor() || !field_empty() || hasFriends() ||2053getNumVBases() > 0 || conversion_end() - conversion_begin() > 0)2054return false;20552056// No interface-like type can have a method with a definition.2057for (const auto *const Method : methods())2058if (Method->isDefined() && !Method->isImplicit())2059return false;20602061// Check "Special" types.2062const auto *Uuid = getAttr<UuidAttr>();2063// MS SDK declares IUnknown/IDispatch both in the root of a TU, or in an2064// extern C++ block directly in the TU. These are only valid if in one2065// of these two situations.2066if (Uuid && isStruct() && !getDeclContext()->isExternCContext() &&2067!isDeclContextInNamespace(getDeclContext()) &&2068((getName() == "IUnknown" &&2069Uuid->getGuid() == "00000000-0000-0000-C000-000000000046") ||2070(getName() == "IDispatch" &&2071Uuid->getGuid() == "00020400-0000-0000-C000-000000000046"))) {2072if (getNumBases() > 0)2073return false;2074return true;2075}20762077// FIXME: Any access specifiers is supposed to make this no longer interface2078// like.20792080// If this isn't a 'special' type, it must have a single interface-like base.2081if (getNumBases() != 1)2082return false;20832084const auto BaseSpec = *bases_begin();2085if (BaseSpec.isVirtual() || BaseSpec.getAccessSpecifier() != AS_public)2086return false;2087const auto *Base = BaseSpec.getType()->getAsCXXRecordDecl();2088if (Base->isInterface() || !Base->isInterfaceLike())2089return false;2090return true;2091}20922093void CXXRecordDecl::completeDefinition() {2094completeDefinition(nullptr);2095}20962097static bool hasPureVirtualFinalOverrider(2098const CXXRecordDecl &RD, const CXXFinalOverriderMap *FinalOverriders) {2099if (!FinalOverriders) {2100CXXFinalOverriderMap MyFinalOverriders;2101RD.getFinalOverriders(MyFinalOverriders);2102return hasPureVirtualFinalOverrider(RD, &MyFinalOverriders);2103}21042105for (const CXXFinalOverriderMap::value_type &2106OverridingMethodsEntry : *FinalOverriders) {2107for (const auto &[_, SubobjOverrides] : OverridingMethodsEntry.second) {2108assert(SubobjOverrides.size() > 0 &&2109"All virtual functions have overriding virtual functions");21102111if (SubobjOverrides.front().Method->isPureVirtual())2112return true;2113}2114}2115return false;2116}21172118void CXXRecordDecl::completeDefinition(CXXFinalOverriderMap *FinalOverriders) {2119RecordDecl::completeDefinition();21202121// If the class may be abstract (but hasn't been marked as such), check for2122// any pure final overriders.2123//2124// C++ [class.abstract]p4:2125// A class is abstract if it contains or inherits at least one2126// pure virtual function for which the final overrider is pure2127// virtual.2128if (mayBeAbstract() && hasPureVirtualFinalOverrider(*this, FinalOverriders))2129markAbstract();21302131// Set access bits correctly on the directly-declared conversions.2132for (conversion_iterator I = conversion_begin(), E = conversion_end();2133I != E; ++I)2134I.setAccess((*I)->getAccess());2135}21362137bool CXXRecordDecl::mayBeAbstract() const {2138if (data().Abstract || isInvalidDecl() || !data().Polymorphic ||2139isDependentContext())2140return false;21412142for (const auto &B : bases()) {2143const auto *BaseDecl =2144cast<CXXRecordDecl>(B.getType()->castAs<RecordType>()->getDecl());2145if (BaseDecl->isAbstract())2146return true;2147}21482149return false;2150}21512152bool CXXRecordDecl::isEffectivelyFinal() const {2153auto *Def = getDefinition();2154if (!Def)2155return false;2156if (Def->hasAttr<FinalAttr>())2157return true;2158if (const auto *Dtor = Def->getDestructor())2159if (Dtor->hasAttr<FinalAttr>())2160return true;2161return false;2162}21632164void CXXDeductionGuideDecl::anchor() {}21652166bool ExplicitSpecifier::isEquivalent(const ExplicitSpecifier Other) const {2167if ((getKind() != Other.getKind() ||2168getKind() == ExplicitSpecKind::Unresolved)) {2169if (getKind() == ExplicitSpecKind::Unresolved &&2170Other.getKind() == ExplicitSpecKind::Unresolved) {2171ODRHash SelfHash, OtherHash;2172SelfHash.AddStmt(getExpr());2173OtherHash.AddStmt(Other.getExpr());2174return SelfHash.CalculateHash() == OtherHash.CalculateHash();2175} else2176return false;2177}2178return true;2179}21802181ExplicitSpecifier ExplicitSpecifier::getFromDecl(FunctionDecl *Function) {2182switch (Function->getDeclKind()) {2183case Decl::Kind::CXXConstructor:2184return cast<CXXConstructorDecl>(Function)->getExplicitSpecifier();2185case Decl::Kind::CXXConversion:2186return cast<CXXConversionDecl>(Function)->getExplicitSpecifier();2187case Decl::Kind::CXXDeductionGuide:2188return cast<CXXDeductionGuideDecl>(Function)->getExplicitSpecifier();2189default:2190return {};2191}2192}21932194CXXDeductionGuideDecl *CXXDeductionGuideDecl::Create(2195ASTContext &C, DeclContext *DC, SourceLocation StartLoc,2196ExplicitSpecifier ES, const DeclarationNameInfo &NameInfo, QualType T,2197TypeSourceInfo *TInfo, SourceLocation EndLocation, CXXConstructorDecl *Ctor,2198DeductionCandidate Kind) {2199return new (C, DC) CXXDeductionGuideDecl(C, DC, StartLoc, ES, NameInfo, T,2200TInfo, EndLocation, Ctor, Kind);2201}22022203CXXDeductionGuideDecl *2204CXXDeductionGuideDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID) {2205return new (C, ID) CXXDeductionGuideDecl(2206C, nullptr, SourceLocation(), ExplicitSpecifier(), DeclarationNameInfo(),2207QualType(), nullptr, SourceLocation(), nullptr,2208DeductionCandidate::Normal);2209}22102211RequiresExprBodyDecl *RequiresExprBodyDecl::Create(2212ASTContext &C, DeclContext *DC, SourceLocation StartLoc) {2213return new (C, DC) RequiresExprBodyDecl(C, DC, StartLoc);2214}22152216RequiresExprBodyDecl *2217RequiresExprBodyDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID) {2218return new (C, ID) RequiresExprBodyDecl(C, nullptr, SourceLocation());2219}22202221void CXXMethodDecl::anchor() {}22222223bool CXXMethodDecl::isStatic() const {2224const CXXMethodDecl *MD = getCanonicalDecl();22252226if (MD->getStorageClass() == SC_Static)2227return true;22282229OverloadedOperatorKind OOK = getDeclName().getCXXOverloadedOperator();2230return isStaticOverloadedOperator(OOK);2231}22322233static bool recursivelyOverrides(const CXXMethodDecl *DerivedMD,2234const CXXMethodDecl *BaseMD) {2235for (const CXXMethodDecl *MD : DerivedMD->overridden_methods()) {2236if (MD->getCanonicalDecl() == BaseMD->getCanonicalDecl())2237return true;2238if (recursivelyOverrides(MD, BaseMD))2239return true;2240}2241return false;2242}22432244CXXMethodDecl *2245CXXMethodDecl::getCorrespondingMethodDeclaredInClass(const CXXRecordDecl *RD,2246bool MayBeBase) {2247if (this->getParent()->getCanonicalDecl() == RD->getCanonicalDecl())2248return this;22492250// Lookup doesn't work for destructors, so handle them separately.2251if (isa<CXXDestructorDecl>(this)) {2252CXXMethodDecl *MD = RD->getDestructor();2253if (MD) {2254if (recursivelyOverrides(MD, this))2255return MD;2256if (MayBeBase && recursivelyOverrides(this, MD))2257return MD;2258}2259return nullptr;2260}22612262for (auto *ND : RD->lookup(getDeclName())) {2263auto *MD = dyn_cast<CXXMethodDecl>(ND);2264if (!MD)2265continue;2266if (recursivelyOverrides(MD, this))2267return MD;2268if (MayBeBase && recursivelyOverrides(this, MD))2269return MD;2270}22712272return nullptr;2273}22742275CXXMethodDecl *2276CXXMethodDecl::getCorrespondingMethodInClass(const CXXRecordDecl *RD,2277bool MayBeBase) {2278if (auto *MD = getCorrespondingMethodDeclaredInClass(RD, MayBeBase))2279return MD;22802281llvm::SmallVector<CXXMethodDecl*, 4> FinalOverriders;2282auto AddFinalOverrider = [&](CXXMethodDecl *D) {2283// If this function is overridden by a candidate final overrider, it is not2284// a final overrider.2285for (CXXMethodDecl *OtherD : FinalOverriders) {2286if (declaresSameEntity(D, OtherD) || recursivelyOverrides(OtherD, D))2287return;2288}22892290// Other candidate final overriders might be overridden by this function.2291llvm::erase_if(FinalOverriders, [&](CXXMethodDecl *OtherD) {2292return recursivelyOverrides(D, OtherD);2293});22942295FinalOverriders.push_back(D);2296};22972298for (const auto &I : RD->bases()) {2299const RecordType *RT = I.getType()->getAs<RecordType>();2300if (!RT)2301continue;2302const auto *Base = cast<CXXRecordDecl>(RT->getDecl());2303if (CXXMethodDecl *D = this->getCorrespondingMethodInClass(Base))2304AddFinalOverrider(D);2305}23062307return FinalOverriders.size() == 1 ? FinalOverriders.front() : nullptr;2308}23092310CXXMethodDecl *2311CXXMethodDecl::Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc,2312const DeclarationNameInfo &NameInfo, QualType T,2313TypeSourceInfo *TInfo, StorageClass SC, bool UsesFPIntrin,2314bool isInline, ConstexprSpecKind ConstexprKind,2315SourceLocation EndLocation,2316Expr *TrailingRequiresClause) {2317return new (C, RD) CXXMethodDecl(2318CXXMethod, C, RD, StartLoc, NameInfo, T, TInfo, SC, UsesFPIntrin,2319isInline, ConstexprKind, EndLocation, TrailingRequiresClause);2320}23212322CXXMethodDecl *CXXMethodDecl::CreateDeserialized(ASTContext &C,2323GlobalDeclID ID) {2324return new (C, ID) CXXMethodDecl(2325CXXMethod, C, nullptr, SourceLocation(), DeclarationNameInfo(),2326QualType(), nullptr, SC_None, false, false,2327ConstexprSpecKind::Unspecified, SourceLocation(), nullptr);2328}23292330CXXMethodDecl *CXXMethodDecl::getDevirtualizedMethod(const Expr *Base,2331bool IsAppleKext) {2332assert(isVirtual() && "this method is expected to be virtual");23332334// When building with -fapple-kext, all calls must go through the vtable since2335// the kernel linker can do runtime patching of vtables.2336if (IsAppleKext)2337return nullptr;23382339// If the member function is marked 'final', we know that it can't be2340// overridden and can therefore devirtualize it unless it's pure virtual.2341if (hasAttr<FinalAttr>())2342return isPureVirtual() ? nullptr : this;23432344// If Base is unknown, we cannot devirtualize.2345if (!Base)2346return nullptr;23472348// If the base expression (after skipping derived-to-base conversions) is a2349// class prvalue, then we can devirtualize.2350Base = Base->getBestDynamicClassTypeExpr();2351if (Base->isPRValue() && Base->getType()->isRecordType())2352return this;23532354// If we don't even know what we would call, we can't devirtualize.2355const CXXRecordDecl *BestDynamicDecl = Base->getBestDynamicClassType();2356if (!BestDynamicDecl)2357return nullptr;23582359// There may be a method corresponding to MD in a derived class.2360CXXMethodDecl *DevirtualizedMethod =2361getCorrespondingMethodInClass(BestDynamicDecl);23622363// If there final overrider in the dynamic type is ambiguous, we can't2364// devirtualize this call.2365if (!DevirtualizedMethod)2366return nullptr;23672368// If that method is pure virtual, we can't devirtualize. If this code is2369// reached, the result would be UB, not a direct call to the derived class2370// function, and we can't assume the derived class function is defined.2371if (DevirtualizedMethod->isPureVirtual())2372return nullptr;23732374// If that method is marked final, we can devirtualize it.2375if (DevirtualizedMethod->hasAttr<FinalAttr>())2376return DevirtualizedMethod;23772378// Similarly, if the class itself or its destructor is marked 'final',2379// the class can't be derived from and we can therefore devirtualize the2380// member function call.2381if (BestDynamicDecl->isEffectivelyFinal())2382return DevirtualizedMethod;23832384if (const auto *DRE = dyn_cast<DeclRefExpr>(Base)) {2385if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))2386if (VD->getType()->isRecordType())2387// This is a record decl. We know the type and can devirtualize it.2388return DevirtualizedMethod;23892390return nullptr;2391}23922393// We can devirtualize calls on an object accessed by a class member access2394// expression, since by C++11 [basic.life]p6 we know that it can't refer to2395// a derived class object constructed in the same location.2396if (const auto *ME = dyn_cast<MemberExpr>(Base)) {2397const ValueDecl *VD = ME->getMemberDecl();2398return VD->getType()->isRecordType() ? DevirtualizedMethod : nullptr;2399}24002401// Likewise for calls on an object accessed by a (non-reference) pointer to2402// member access.2403if (auto *BO = dyn_cast<BinaryOperator>(Base)) {2404if (BO->isPtrMemOp()) {2405auto *MPT = BO->getRHS()->getType()->castAs<MemberPointerType>();2406if (MPT->getPointeeType()->isRecordType())2407return DevirtualizedMethod;2408}2409}24102411// We can't devirtualize the call.2412return nullptr;2413}24142415bool CXXMethodDecl::isUsualDeallocationFunction(2416SmallVectorImpl<const FunctionDecl *> &PreventedBy) const {2417assert(PreventedBy.empty() && "PreventedBy is expected to be empty");2418if (getOverloadedOperator() != OO_Delete &&2419getOverloadedOperator() != OO_Array_Delete)2420return false;24212422// C++ [basic.stc.dynamic.deallocation]p2:2423// A template instance is never a usual deallocation function,2424// regardless of its signature.2425if (getPrimaryTemplate())2426return false;24272428// C++ [basic.stc.dynamic.deallocation]p2:2429// If a class T has a member deallocation function named operator delete2430// with exactly one parameter, then that function is a usual (non-placement)2431// deallocation function. [...]2432if (getNumParams() == 1)2433return true;2434unsigned UsualParams = 1;24352436// C++ P0722:2437// A destroying operator delete is a usual deallocation function if2438// removing the std::destroying_delete_t parameter and changing the2439// first parameter type from T* to void* results in the signature of2440// a usual deallocation function.2441if (isDestroyingOperatorDelete())2442++UsualParams;24432444// C++ <=14 [basic.stc.dynamic.deallocation]p2:2445// [...] If class T does not declare such an operator delete but does2446// declare a member deallocation function named operator delete with2447// exactly two parameters, the second of which has type std::size_t (18.1),2448// then this function is a usual deallocation function.2449//2450// C++17 says a usual deallocation function is one with the signature2451// (void* [, size_t] [, std::align_val_t] [, ...])2452// and all such functions are usual deallocation functions. It's not clear2453// that allowing varargs functions was intentional.2454ASTContext &Context = getASTContext();2455if (UsualParams < getNumParams() &&2456Context.hasSameUnqualifiedType(getParamDecl(UsualParams)->getType(),2457Context.getSizeType()))2458++UsualParams;24592460if (UsualParams < getNumParams() &&2461getParamDecl(UsualParams)->getType()->isAlignValT())2462++UsualParams;24632464if (UsualParams != getNumParams())2465return false;24662467// In C++17 onwards, all potential usual deallocation functions are actual2468// usual deallocation functions. Honor this behavior when post-C++142469// deallocation functions are offered as extensions too.2470// FIXME(EricWF): Destroying Delete should be a language option. How do we2471// handle when destroying delete is used prior to C++17?2472if (Context.getLangOpts().CPlusPlus17 ||2473Context.getLangOpts().AlignedAllocation ||2474isDestroyingOperatorDelete())2475return true;24762477// This function is a usual deallocation function if there are no2478// single-parameter deallocation functions of the same kind.2479DeclContext::lookup_result R = getDeclContext()->lookup(getDeclName());2480bool Result = true;2481for (const auto *D : R) {2482if (const auto *FD = dyn_cast<FunctionDecl>(D)) {2483if (FD->getNumParams() == 1) {2484PreventedBy.push_back(FD);2485Result = false;2486}2487}2488}2489return Result;2490}24912492bool CXXMethodDecl::isExplicitObjectMemberFunction() const {2493// C++2b [dcl.fct]p6:2494// An explicit object member function is a non-static member2495// function with an explicit object parameter2496return !isStatic() && hasCXXExplicitFunctionObjectParameter();2497}24982499bool CXXMethodDecl::isImplicitObjectMemberFunction() const {2500return !isStatic() && !hasCXXExplicitFunctionObjectParameter();2501}25022503bool CXXMethodDecl::isCopyAssignmentOperator() const {2504// C++0x [class.copy]p17:2505// A user-declared copy assignment operator X::operator= is a non-static2506// non-template member function of class X with exactly one parameter of2507// type X, X&, const X&, volatile X& or const volatile X&.2508if (/*operator=*/getOverloadedOperator() != OO_Equal ||2509/*non-static*/ isStatic() ||25102511/*non-template*/ getPrimaryTemplate() || getDescribedFunctionTemplate() ||2512getNumExplicitParams() != 1)2513return false;25142515QualType ParamType = getNonObjectParameter(0)->getType();2516if (const auto *Ref = ParamType->getAs<LValueReferenceType>())2517ParamType = Ref->getPointeeType();25182519ASTContext &Context = getASTContext();2520QualType ClassType2521= Context.getCanonicalType(Context.getTypeDeclType(getParent()));2522return Context.hasSameUnqualifiedType(ClassType, ParamType);2523}25242525bool CXXMethodDecl::isMoveAssignmentOperator() const {2526// C++0x [class.copy]p19:2527// A user-declared move assignment operator X::operator= is a non-static2528// non-template member function of class X with exactly one parameter of type2529// X&&, const X&&, volatile X&&, or const volatile X&&.2530if (getOverloadedOperator() != OO_Equal || isStatic() ||2531getPrimaryTemplate() || getDescribedFunctionTemplate() ||2532getNumExplicitParams() != 1)2533return false;25342535QualType ParamType = getNonObjectParameter(0)->getType();2536if (!ParamType->isRValueReferenceType())2537return false;2538ParamType = ParamType->getPointeeType();25392540ASTContext &Context = getASTContext();2541QualType ClassType2542= Context.getCanonicalType(Context.getTypeDeclType(getParent()));2543return Context.hasSameUnqualifiedType(ClassType, ParamType);2544}25452546void CXXMethodDecl::addOverriddenMethod(const CXXMethodDecl *MD) {2547assert(MD->isCanonicalDecl() && "Method is not canonical!");2548assert(!MD->getParent()->isDependentContext() &&2549"Can't add an overridden method to a class template!");2550assert(MD->isVirtual() && "Method is not virtual!");25512552getASTContext().addOverriddenMethod(this, MD);2553}25542555CXXMethodDecl::method_iterator CXXMethodDecl::begin_overridden_methods() const {2556if (isa<CXXConstructorDecl>(this)) return nullptr;2557return getASTContext().overridden_methods_begin(this);2558}25592560CXXMethodDecl::method_iterator CXXMethodDecl::end_overridden_methods() const {2561if (isa<CXXConstructorDecl>(this)) return nullptr;2562return getASTContext().overridden_methods_end(this);2563}25642565unsigned CXXMethodDecl::size_overridden_methods() const {2566if (isa<CXXConstructorDecl>(this)) return 0;2567return getASTContext().overridden_methods_size(this);2568}25692570CXXMethodDecl::overridden_method_range2571CXXMethodDecl::overridden_methods() const {2572if (isa<CXXConstructorDecl>(this))2573return overridden_method_range(nullptr, nullptr);2574return getASTContext().overridden_methods(this);2575}25762577static QualType getThisObjectType(ASTContext &C, const FunctionProtoType *FPT,2578const CXXRecordDecl *Decl) {2579QualType ClassTy = C.getTypeDeclType(Decl);2580return C.getQualifiedType(ClassTy, FPT->getMethodQuals());2581}25822583QualType CXXMethodDecl::getThisType(const FunctionProtoType *FPT,2584const CXXRecordDecl *Decl) {2585ASTContext &C = Decl->getASTContext();2586QualType ObjectTy = ::getThisObjectType(C, FPT, Decl);25872588// Unlike 'const' and 'volatile', a '__restrict' qualifier must be2589// attached to the pointer type, not the pointee.2590bool Restrict = FPT->getMethodQuals().hasRestrict();2591if (Restrict)2592ObjectTy.removeLocalRestrict();25932594ObjectTy = C.getLangOpts().HLSL ? C.getLValueReferenceType(ObjectTy)2595: C.getPointerType(ObjectTy);25962597if (Restrict)2598ObjectTy.addRestrict();2599return ObjectTy;2600}26012602QualType CXXMethodDecl::getThisType() const {2603// C++ 9.3.2p1: The type of this in a member function of a class X is X*.2604// If the member function is declared const, the type of this is const X*,2605// if the member function is declared volatile, the type of this is2606// volatile X*, and if the member function is declared const volatile,2607// the type of this is const volatile X*.2608assert(isInstance() && "No 'this' for static methods!");2609return CXXMethodDecl::getThisType(getType()->castAs<FunctionProtoType>(),2610getParent());2611}26122613QualType CXXMethodDecl::getFunctionObjectParameterReferenceType() const {2614if (isExplicitObjectMemberFunction())2615return parameters()[0]->getType();26162617ASTContext &C = getParentASTContext();2618const FunctionProtoType *FPT = getType()->castAs<FunctionProtoType>();2619QualType Type = ::getThisObjectType(C, FPT, getParent());2620RefQualifierKind RK = FPT->getRefQualifier();2621if (RK == RefQualifierKind::RQ_RValue)2622return C.getRValueReferenceType(Type);2623return C.getLValueReferenceType(Type);2624}26252626bool CXXMethodDecl::hasInlineBody() const {2627// If this function is a template instantiation, look at the template from2628// which it was instantiated.2629const FunctionDecl *CheckFn = getTemplateInstantiationPattern();2630if (!CheckFn)2631CheckFn = this;26322633const FunctionDecl *fn;2634return CheckFn->isDefined(fn) && !fn->isOutOfLine() &&2635(fn->doesThisDeclarationHaveABody() || fn->willHaveBody());2636}26372638bool CXXMethodDecl::isLambdaStaticInvoker() const {2639const CXXRecordDecl *P = getParent();2640return P->isLambda() && getDeclName().isIdentifier() &&2641getName() == getLambdaStaticInvokerName();2642}26432644CXXCtorInitializer::CXXCtorInitializer(ASTContext &Context,2645TypeSourceInfo *TInfo, bool IsVirtual,2646SourceLocation L, Expr *Init,2647SourceLocation R,2648SourceLocation EllipsisLoc)2649: Initializee(TInfo), Init(Init), MemberOrEllipsisLocation(EllipsisLoc),2650LParenLoc(L), RParenLoc(R), IsDelegating(false), IsVirtual(IsVirtual),2651IsWritten(false), SourceOrder(0) {}26522653CXXCtorInitializer::CXXCtorInitializer(ASTContext &Context, FieldDecl *Member,2654SourceLocation MemberLoc,2655SourceLocation L, Expr *Init,2656SourceLocation R)2657: Initializee(Member), Init(Init), MemberOrEllipsisLocation(MemberLoc),2658LParenLoc(L), RParenLoc(R), IsDelegating(false), IsVirtual(false),2659IsWritten(false), SourceOrder(0) {}26602661CXXCtorInitializer::CXXCtorInitializer(ASTContext &Context,2662IndirectFieldDecl *Member,2663SourceLocation MemberLoc,2664SourceLocation L, Expr *Init,2665SourceLocation R)2666: Initializee(Member), Init(Init), MemberOrEllipsisLocation(MemberLoc),2667LParenLoc(L), RParenLoc(R), IsDelegating(false), IsVirtual(false),2668IsWritten(false), SourceOrder(0) {}26692670CXXCtorInitializer::CXXCtorInitializer(ASTContext &Context,2671TypeSourceInfo *TInfo,2672SourceLocation L, Expr *Init,2673SourceLocation R)2674: Initializee(TInfo), Init(Init), LParenLoc(L), RParenLoc(R),2675IsDelegating(true), IsVirtual(false), IsWritten(false), SourceOrder(0) {}26762677int64_t CXXCtorInitializer::getID(const ASTContext &Context) const {2678return Context.getAllocator()2679.identifyKnownAlignedObject<CXXCtorInitializer>(this);2680}26812682TypeLoc CXXCtorInitializer::getBaseClassLoc() const {2683if (isBaseInitializer())2684return Initializee.get<TypeSourceInfo*>()->getTypeLoc();2685else2686return {};2687}26882689const Type *CXXCtorInitializer::getBaseClass() const {2690if (isBaseInitializer())2691return Initializee.get<TypeSourceInfo*>()->getType().getTypePtr();2692else2693return nullptr;2694}26952696SourceLocation CXXCtorInitializer::getSourceLocation() const {2697if (isInClassMemberInitializer())2698return getAnyMember()->getLocation();26992700if (isAnyMemberInitializer())2701return getMemberLocation();27022703if (const auto *TSInfo = Initializee.get<TypeSourceInfo *>())2704return TSInfo->getTypeLoc().getBeginLoc();27052706return {};2707}27082709SourceRange CXXCtorInitializer::getSourceRange() const {2710if (isInClassMemberInitializer()) {2711FieldDecl *D = getAnyMember();2712if (Expr *I = D->getInClassInitializer())2713return I->getSourceRange();2714return {};2715}27162717return SourceRange(getSourceLocation(), getRParenLoc());2718}27192720CXXConstructorDecl::CXXConstructorDecl(2721ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc,2722const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo,2723ExplicitSpecifier ES, bool UsesFPIntrin, bool isInline,2724bool isImplicitlyDeclared, ConstexprSpecKind ConstexprKind,2725InheritedConstructor Inherited, Expr *TrailingRequiresClause)2726: CXXMethodDecl(CXXConstructor, C, RD, StartLoc, NameInfo, T, TInfo,2727SC_None, UsesFPIntrin, isInline, ConstexprKind,2728SourceLocation(), TrailingRequiresClause) {2729setNumCtorInitializers(0);2730setInheritingConstructor(static_cast<bool>(Inherited));2731setImplicit(isImplicitlyDeclared);2732CXXConstructorDeclBits.HasTrailingExplicitSpecifier = ES.getExpr() ? 1 : 0;2733if (Inherited)2734*getTrailingObjects<InheritedConstructor>() = Inherited;2735setExplicitSpecifier(ES);2736}27372738void CXXConstructorDecl::anchor() {}27392740CXXConstructorDecl *CXXConstructorDecl::CreateDeserialized(ASTContext &C,2741GlobalDeclID ID,2742uint64_t AllocKind) {2743bool hasTrailingExplicit = static_cast<bool>(AllocKind & TAKHasTailExplicit);2744bool isInheritingConstructor =2745static_cast<bool>(AllocKind & TAKInheritsConstructor);2746unsigned Extra =2747additionalSizeToAlloc<InheritedConstructor, ExplicitSpecifier>(2748isInheritingConstructor, hasTrailingExplicit);2749auto *Result = new (C, ID, Extra) CXXConstructorDecl(2750C, nullptr, SourceLocation(), DeclarationNameInfo(), QualType(), nullptr,2751ExplicitSpecifier(), false, false, false, ConstexprSpecKind::Unspecified,2752InheritedConstructor(), nullptr);2753Result->setInheritingConstructor(isInheritingConstructor);2754Result->CXXConstructorDeclBits.HasTrailingExplicitSpecifier =2755hasTrailingExplicit;2756Result->setExplicitSpecifier(ExplicitSpecifier());2757return Result;2758}27592760CXXConstructorDecl *CXXConstructorDecl::Create(2761ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc,2762const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo,2763ExplicitSpecifier ES, bool UsesFPIntrin, bool isInline,2764bool isImplicitlyDeclared, ConstexprSpecKind ConstexprKind,2765InheritedConstructor Inherited, Expr *TrailingRequiresClause) {2766assert(NameInfo.getName().getNameKind()2767== DeclarationName::CXXConstructorName &&2768"Name must refer to a constructor");2769unsigned Extra =2770additionalSizeToAlloc<InheritedConstructor, ExplicitSpecifier>(2771Inherited ? 1 : 0, ES.getExpr() ? 1 : 0);2772return new (C, RD, Extra) CXXConstructorDecl(2773C, RD, StartLoc, NameInfo, T, TInfo, ES, UsesFPIntrin, isInline,2774isImplicitlyDeclared, ConstexprKind, Inherited, TrailingRequiresClause);2775}27762777CXXConstructorDecl::init_const_iterator CXXConstructorDecl::init_begin() const {2778return CtorInitializers.get(getASTContext().getExternalSource());2779}27802781CXXConstructorDecl *CXXConstructorDecl::getTargetConstructor() const {2782assert(isDelegatingConstructor() && "Not a delegating constructor!");2783Expr *E = (*init_begin())->getInit()->IgnoreImplicit();2784if (const auto *Construct = dyn_cast<CXXConstructExpr>(E))2785return Construct->getConstructor();27862787return nullptr;2788}27892790bool CXXConstructorDecl::isDefaultConstructor() const {2791// C++ [class.default.ctor]p1:2792// A default constructor for a class X is a constructor of class X for2793// which each parameter that is not a function parameter pack has a default2794// argument (including the case of a constructor with no parameters)2795return getMinRequiredArguments() == 0;2796}27972798bool2799CXXConstructorDecl::isCopyConstructor(unsigned &TypeQuals) const {2800return isCopyOrMoveConstructor(TypeQuals) &&2801getParamDecl(0)->getType()->isLValueReferenceType();2802}28032804bool CXXConstructorDecl::isMoveConstructor(unsigned &TypeQuals) const {2805return isCopyOrMoveConstructor(TypeQuals) &&2806getParamDecl(0)->getType()->isRValueReferenceType();2807}28082809/// Determine whether this is a copy or move constructor.2810bool CXXConstructorDecl::isCopyOrMoveConstructor(unsigned &TypeQuals) const {2811// C++ [class.copy]p2:2812// A non-template constructor for class X is a copy constructor2813// if its first parameter is of type X&, const X&, volatile X& or2814// const volatile X&, and either there are no other parameters2815// or else all other parameters have default arguments (8.3.6).2816// C++0x [class.copy]p3:2817// A non-template constructor for class X is a move constructor if its2818// first parameter is of type X&&, const X&&, volatile X&&, or2819// const volatile X&&, and either there are no other parameters or else2820// all other parameters have default arguments.2821if (!hasOneParamOrDefaultArgs() || getPrimaryTemplate() != nullptr ||2822getDescribedFunctionTemplate() != nullptr)2823return false;28242825const ParmVarDecl *Param = getParamDecl(0);28262827// Do we have a reference type?2828const auto *ParamRefType = Param->getType()->getAs<ReferenceType>();2829if (!ParamRefType)2830return false;28312832// Is it a reference to our class type?2833ASTContext &Context = getASTContext();28342835CanQualType PointeeType2836= Context.getCanonicalType(ParamRefType->getPointeeType());2837CanQualType ClassTy2838= Context.getCanonicalType(Context.getTagDeclType(getParent()));2839if (PointeeType.getUnqualifiedType() != ClassTy)2840return false;28412842// FIXME: other qualifiers?28432844// We have a copy or move constructor.2845TypeQuals = PointeeType.getCVRQualifiers();2846return true;2847}28482849bool CXXConstructorDecl::isConvertingConstructor(bool AllowExplicit) const {2850// C++ [class.conv.ctor]p1:2851// A constructor declared without the function-specifier explicit2852// that can be called with a single parameter specifies a2853// conversion from the type of its first parameter to the type of2854// its class. Such a constructor is called a converting2855// constructor.2856if (isExplicit() && !AllowExplicit)2857return false;28582859// FIXME: This has nothing to do with the definition of converting2860// constructor, but is convenient for how we use this function in overload2861// resolution.2862return getNumParams() == 02863? getType()->castAs<FunctionProtoType>()->isVariadic()2864: getMinRequiredArguments() <= 1;2865}28662867bool CXXConstructorDecl::isSpecializationCopyingObject() const {2868if (!hasOneParamOrDefaultArgs() || getDescribedFunctionTemplate() != nullptr)2869return false;28702871const ParmVarDecl *Param = getParamDecl(0);28722873ASTContext &Context = getASTContext();2874CanQualType ParamType = Context.getCanonicalType(Param->getType());28752876// Is it the same as our class type?2877CanQualType ClassTy2878= Context.getCanonicalType(Context.getTagDeclType(getParent()));2879if (ParamType.getUnqualifiedType() != ClassTy)2880return false;28812882return true;2883}28842885void CXXDestructorDecl::anchor() {}28862887CXXDestructorDecl *CXXDestructorDecl::CreateDeserialized(ASTContext &C,2888GlobalDeclID ID) {2889return new (C, ID) CXXDestructorDecl(2890C, nullptr, SourceLocation(), DeclarationNameInfo(), QualType(), nullptr,2891false, false, false, ConstexprSpecKind::Unspecified, nullptr);2892}28932894CXXDestructorDecl *CXXDestructorDecl::Create(2895ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc,2896const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo,2897bool UsesFPIntrin, bool isInline, bool isImplicitlyDeclared,2898ConstexprSpecKind ConstexprKind, Expr *TrailingRequiresClause) {2899assert(NameInfo.getName().getNameKind()2900== DeclarationName::CXXDestructorName &&2901"Name must refer to a destructor");2902return new (C, RD) CXXDestructorDecl(2903C, RD, StartLoc, NameInfo, T, TInfo, UsesFPIntrin, isInline,2904isImplicitlyDeclared, ConstexprKind, TrailingRequiresClause);2905}29062907void CXXDestructorDecl::setOperatorDelete(FunctionDecl *OD, Expr *ThisArg) {2908auto *First = cast<CXXDestructorDecl>(getFirstDecl());2909if (OD && !First->OperatorDelete) {2910First->OperatorDelete = OD;2911First->OperatorDeleteThisArg = ThisArg;2912if (auto *L = getASTMutationListener())2913L->ResolvedOperatorDelete(First, OD, ThisArg);2914}2915}29162917void CXXConversionDecl::anchor() {}29182919CXXConversionDecl *CXXConversionDecl::CreateDeserialized(ASTContext &C,2920GlobalDeclID ID) {2921return new (C, ID) CXXConversionDecl(2922C, nullptr, SourceLocation(), DeclarationNameInfo(), QualType(), nullptr,2923false, false, ExplicitSpecifier(), ConstexprSpecKind::Unspecified,2924SourceLocation(), nullptr);2925}29262927CXXConversionDecl *CXXConversionDecl::Create(2928ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc,2929const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo,2930bool UsesFPIntrin, bool isInline, ExplicitSpecifier ES,2931ConstexprSpecKind ConstexprKind, SourceLocation EndLocation,2932Expr *TrailingRequiresClause) {2933assert(NameInfo.getName().getNameKind()2934== DeclarationName::CXXConversionFunctionName &&2935"Name must refer to a conversion function");2936return new (C, RD) CXXConversionDecl(2937C, RD, StartLoc, NameInfo, T, TInfo, UsesFPIntrin, isInline, ES,2938ConstexprKind, EndLocation, TrailingRequiresClause);2939}29402941bool CXXConversionDecl::isLambdaToBlockPointerConversion() const {2942return isImplicit() && getParent()->isLambda() &&2943getConversionType()->isBlockPointerType();2944}29452946LinkageSpecDecl::LinkageSpecDecl(DeclContext *DC, SourceLocation ExternLoc,2947SourceLocation LangLoc,2948LinkageSpecLanguageIDs lang, bool HasBraces)2949: Decl(LinkageSpec, DC, LangLoc), DeclContext(LinkageSpec),2950ExternLoc(ExternLoc), RBraceLoc(SourceLocation()) {2951setLanguage(lang);2952LinkageSpecDeclBits.HasBraces = HasBraces;2953}29542955void LinkageSpecDecl::anchor() {}29562957LinkageSpecDecl *LinkageSpecDecl::Create(ASTContext &C, DeclContext *DC,2958SourceLocation ExternLoc,2959SourceLocation LangLoc,2960LinkageSpecLanguageIDs Lang,2961bool HasBraces) {2962return new (C, DC) LinkageSpecDecl(DC, ExternLoc, LangLoc, Lang, HasBraces);2963}29642965LinkageSpecDecl *LinkageSpecDecl::CreateDeserialized(ASTContext &C,2966GlobalDeclID ID) {2967return new (C, ID)2968LinkageSpecDecl(nullptr, SourceLocation(), SourceLocation(),2969LinkageSpecLanguageIDs::C, false);2970}29712972void UsingDirectiveDecl::anchor() {}29732974UsingDirectiveDecl *UsingDirectiveDecl::Create(ASTContext &C, DeclContext *DC,2975SourceLocation L,2976SourceLocation NamespaceLoc,2977NestedNameSpecifierLoc QualifierLoc,2978SourceLocation IdentLoc,2979NamedDecl *Used,2980DeclContext *CommonAncestor) {2981if (auto *NS = dyn_cast_or_null<NamespaceDecl>(Used))2982Used = NS->getFirstDecl();2983return new (C, DC) UsingDirectiveDecl(DC, L, NamespaceLoc, QualifierLoc,2984IdentLoc, Used, CommonAncestor);2985}29862987UsingDirectiveDecl *UsingDirectiveDecl::CreateDeserialized(ASTContext &C,2988GlobalDeclID ID) {2989return new (C, ID) UsingDirectiveDecl(nullptr, SourceLocation(),2990SourceLocation(),2991NestedNameSpecifierLoc(),2992SourceLocation(), nullptr, nullptr);2993}29942995NamespaceDecl *UsingDirectiveDecl::getNominatedNamespace() {2996if (auto *NA = dyn_cast_or_null<NamespaceAliasDecl>(NominatedNamespace))2997return NA->getNamespace();2998return cast_or_null<NamespaceDecl>(NominatedNamespace);2999}30003001NamespaceDecl::NamespaceDecl(ASTContext &C, DeclContext *DC, bool Inline,3002SourceLocation StartLoc, SourceLocation IdLoc,3003IdentifierInfo *Id, NamespaceDecl *PrevDecl,3004bool Nested)3005: NamedDecl(Namespace, DC, IdLoc, Id), DeclContext(Namespace),3006redeclarable_base(C), LocStart(StartLoc) {3007setInline(Inline);3008setNested(Nested);3009setPreviousDecl(PrevDecl);3010}30113012NamespaceDecl *NamespaceDecl::Create(ASTContext &C, DeclContext *DC,3013bool Inline, SourceLocation StartLoc,3014SourceLocation IdLoc, IdentifierInfo *Id,3015NamespaceDecl *PrevDecl, bool Nested) {3016return new (C, DC)3017NamespaceDecl(C, DC, Inline, StartLoc, IdLoc, Id, PrevDecl, Nested);3018}30193020NamespaceDecl *NamespaceDecl::CreateDeserialized(ASTContext &C,3021GlobalDeclID ID) {3022return new (C, ID) NamespaceDecl(C, nullptr, false, SourceLocation(),3023SourceLocation(), nullptr, nullptr, false);3024}30253026NamespaceDecl *NamespaceDecl::getNextRedeclarationImpl() {3027return getNextRedeclaration();3028}30293030NamespaceDecl *NamespaceDecl::getPreviousDeclImpl() {3031return getPreviousDecl();3032}30333034NamespaceDecl *NamespaceDecl::getMostRecentDeclImpl() {3035return getMostRecentDecl();3036}30373038void NamespaceAliasDecl::anchor() {}30393040NamespaceAliasDecl *NamespaceAliasDecl::getNextRedeclarationImpl() {3041return getNextRedeclaration();3042}30433044NamespaceAliasDecl *NamespaceAliasDecl::getPreviousDeclImpl() {3045return getPreviousDecl();3046}30473048NamespaceAliasDecl *NamespaceAliasDecl::getMostRecentDeclImpl() {3049return getMostRecentDecl();3050}30513052NamespaceAliasDecl *NamespaceAliasDecl::Create(ASTContext &C, DeclContext *DC,3053SourceLocation UsingLoc,3054SourceLocation AliasLoc,3055IdentifierInfo *Alias,3056NestedNameSpecifierLoc QualifierLoc,3057SourceLocation IdentLoc,3058NamedDecl *Namespace) {3059// FIXME: Preserve the aliased namespace as written.3060if (auto *NS = dyn_cast_or_null<NamespaceDecl>(Namespace))3061Namespace = NS->getFirstDecl();3062return new (C, DC) NamespaceAliasDecl(C, DC, UsingLoc, AliasLoc, Alias,3063QualifierLoc, IdentLoc, Namespace);3064}30653066NamespaceAliasDecl *NamespaceAliasDecl::CreateDeserialized(ASTContext &C,3067GlobalDeclID ID) {3068return new (C, ID) NamespaceAliasDecl(C, nullptr, SourceLocation(),3069SourceLocation(), nullptr,3070NestedNameSpecifierLoc(),3071SourceLocation(), nullptr);3072}30733074void LifetimeExtendedTemporaryDecl::anchor() {}30753076/// Retrieve the storage duration for the materialized temporary.3077StorageDuration LifetimeExtendedTemporaryDecl::getStorageDuration() const {3078const ValueDecl *ExtendingDecl = getExtendingDecl();3079if (!ExtendingDecl)3080return SD_FullExpression;3081// FIXME: This is not necessarily correct for a temporary materialized3082// within a default initializer.3083if (isa<FieldDecl>(ExtendingDecl))3084return SD_Automatic;3085// FIXME: This only works because storage class specifiers are not allowed3086// on decomposition declarations.3087if (isa<BindingDecl>(ExtendingDecl))3088return ExtendingDecl->getDeclContext()->isFunctionOrMethod() ? SD_Automatic3089: SD_Static;3090return cast<VarDecl>(ExtendingDecl)->getStorageDuration();3091}30923093APValue *LifetimeExtendedTemporaryDecl::getOrCreateValue(bool MayCreate) const {3094assert(getStorageDuration() == SD_Static &&3095"don't need to cache the computed value for this temporary");3096if (MayCreate && !Value) {3097Value = (new (getASTContext()) APValue);3098getASTContext().addDestruction(Value);3099}3100assert(Value && "may not be null");3101return Value;3102}31033104void UsingShadowDecl::anchor() {}31053106UsingShadowDecl::UsingShadowDecl(Kind K, ASTContext &C, DeclContext *DC,3107SourceLocation Loc, DeclarationName Name,3108BaseUsingDecl *Introducer, NamedDecl *Target)3109: NamedDecl(K, DC, Loc, Name), redeclarable_base(C),3110UsingOrNextShadow(Introducer) {3111if (Target) {3112assert(!isa<UsingShadowDecl>(Target));3113setTargetDecl(Target);3114}3115setImplicit();3116}31173118UsingShadowDecl::UsingShadowDecl(Kind K, ASTContext &C, EmptyShell Empty)3119: NamedDecl(K, nullptr, SourceLocation(), DeclarationName()),3120redeclarable_base(C) {}31213122UsingShadowDecl *UsingShadowDecl::CreateDeserialized(ASTContext &C,3123GlobalDeclID ID) {3124return new (C, ID) UsingShadowDecl(UsingShadow, C, EmptyShell());3125}31263127BaseUsingDecl *UsingShadowDecl::getIntroducer() const {3128const UsingShadowDecl *Shadow = this;3129while (const auto *NextShadow =3130dyn_cast<UsingShadowDecl>(Shadow->UsingOrNextShadow))3131Shadow = NextShadow;3132return cast<BaseUsingDecl>(Shadow->UsingOrNextShadow);3133}31343135void ConstructorUsingShadowDecl::anchor() {}31363137ConstructorUsingShadowDecl *3138ConstructorUsingShadowDecl::Create(ASTContext &C, DeclContext *DC,3139SourceLocation Loc, UsingDecl *Using,3140NamedDecl *Target, bool IsVirtual) {3141return new (C, DC) ConstructorUsingShadowDecl(C, DC, Loc, Using, Target,3142IsVirtual);3143}31443145ConstructorUsingShadowDecl *3146ConstructorUsingShadowDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID) {3147return new (C, ID) ConstructorUsingShadowDecl(C, EmptyShell());3148}31493150CXXRecordDecl *ConstructorUsingShadowDecl::getNominatedBaseClass() const {3151return getIntroducer()->getQualifier()->getAsRecordDecl();3152}31533154void BaseUsingDecl::anchor() {}31553156void BaseUsingDecl::addShadowDecl(UsingShadowDecl *S) {3157assert(!llvm::is_contained(shadows(), S) && "declaration already in set");3158assert(S->getIntroducer() == this);31593160if (FirstUsingShadow.getPointer())3161S->UsingOrNextShadow = FirstUsingShadow.getPointer();3162FirstUsingShadow.setPointer(S);3163}31643165void BaseUsingDecl::removeShadowDecl(UsingShadowDecl *S) {3166assert(llvm::is_contained(shadows(), S) && "declaration not in set");3167assert(S->getIntroducer() == this);31683169// Remove S from the shadow decl chain. This is O(n) but hopefully rare.31703171if (FirstUsingShadow.getPointer() == S) {3172FirstUsingShadow.setPointer(3173dyn_cast<UsingShadowDecl>(S->UsingOrNextShadow));3174S->UsingOrNextShadow = this;3175return;3176}31773178UsingShadowDecl *Prev = FirstUsingShadow.getPointer();3179while (Prev->UsingOrNextShadow != S)3180Prev = cast<UsingShadowDecl>(Prev->UsingOrNextShadow);3181Prev->UsingOrNextShadow = S->UsingOrNextShadow;3182S->UsingOrNextShadow = this;3183}31843185void UsingDecl::anchor() {}31863187UsingDecl *UsingDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation UL,3188NestedNameSpecifierLoc QualifierLoc,3189const DeclarationNameInfo &NameInfo,3190bool HasTypename) {3191return new (C, DC) UsingDecl(DC, UL, QualifierLoc, NameInfo, HasTypename);3192}31933194UsingDecl *UsingDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID) {3195return new (C, ID) UsingDecl(nullptr, SourceLocation(),3196NestedNameSpecifierLoc(), DeclarationNameInfo(),3197false);3198}31993200SourceRange UsingDecl::getSourceRange() const {3201SourceLocation Begin = isAccessDeclaration()3202? getQualifierLoc().getBeginLoc() : UsingLocation;3203return SourceRange(Begin, getNameInfo().getEndLoc());3204}32053206void UsingEnumDecl::anchor() {}32073208UsingEnumDecl *UsingEnumDecl::Create(ASTContext &C, DeclContext *DC,3209SourceLocation UL,3210SourceLocation EL,3211SourceLocation NL,3212TypeSourceInfo *EnumType) {3213assert(isa<EnumDecl>(EnumType->getType()->getAsTagDecl()));3214return new (C, DC)3215UsingEnumDecl(DC, EnumType->getType()->getAsTagDecl()->getDeclName(), UL, EL, NL, EnumType);3216}32173218UsingEnumDecl *UsingEnumDecl::CreateDeserialized(ASTContext &C,3219GlobalDeclID ID) {3220return new (C, ID)3221UsingEnumDecl(nullptr, DeclarationName(), SourceLocation(),3222SourceLocation(), SourceLocation(), nullptr);3223}32243225SourceRange UsingEnumDecl::getSourceRange() const {3226return SourceRange(UsingLocation, EnumType->getTypeLoc().getEndLoc());3227}32283229void UsingPackDecl::anchor() {}32303231UsingPackDecl *UsingPackDecl::Create(ASTContext &C, DeclContext *DC,3232NamedDecl *InstantiatedFrom,3233ArrayRef<NamedDecl *> UsingDecls) {3234size_t Extra = additionalSizeToAlloc<NamedDecl *>(UsingDecls.size());3235return new (C, DC, Extra) UsingPackDecl(DC, InstantiatedFrom, UsingDecls);3236}32373238UsingPackDecl *UsingPackDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID,3239unsigned NumExpansions) {3240size_t Extra = additionalSizeToAlloc<NamedDecl *>(NumExpansions);3241auto *Result =3242new (C, ID, Extra) UsingPackDecl(nullptr, nullptr, std::nullopt);3243Result->NumExpansions = NumExpansions;3244auto *Trail = Result->getTrailingObjects<NamedDecl *>();3245for (unsigned I = 0; I != NumExpansions; ++I)3246new (Trail + I) NamedDecl*(nullptr);3247return Result;3248}32493250void UnresolvedUsingValueDecl::anchor() {}32513252UnresolvedUsingValueDecl *3253UnresolvedUsingValueDecl::Create(ASTContext &C, DeclContext *DC,3254SourceLocation UsingLoc,3255NestedNameSpecifierLoc QualifierLoc,3256const DeclarationNameInfo &NameInfo,3257SourceLocation EllipsisLoc) {3258return new (C, DC) UnresolvedUsingValueDecl(DC, C.DependentTy, UsingLoc,3259QualifierLoc, NameInfo,3260EllipsisLoc);3261}32623263UnresolvedUsingValueDecl *3264UnresolvedUsingValueDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID) {3265return new (C, ID) UnresolvedUsingValueDecl(nullptr, QualType(),3266SourceLocation(),3267NestedNameSpecifierLoc(),3268DeclarationNameInfo(),3269SourceLocation());3270}32713272SourceRange UnresolvedUsingValueDecl::getSourceRange() const {3273SourceLocation Begin = isAccessDeclaration()3274? getQualifierLoc().getBeginLoc() : UsingLocation;3275return SourceRange(Begin, getNameInfo().getEndLoc());3276}32773278void UnresolvedUsingTypenameDecl::anchor() {}32793280UnresolvedUsingTypenameDecl *3281UnresolvedUsingTypenameDecl::Create(ASTContext &C, DeclContext *DC,3282SourceLocation UsingLoc,3283SourceLocation TypenameLoc,3284NestedNameSpecifierLoc QualifierLoc,3285SourceLocation TargetNameLoc,3286DeclarationName TargetName,3287SourceLocation EllipsisLoc) {3288return new (C, DC) UnresolvedUsingTypenameDecl(3289DC, UsingLoc, TypenameLoc, QualifierLoc, TargetNameLoc,3290TargetName.getAsIdentifierInfo(), EllipsisLoc);3291}32923293UnresolvedUsingTypenameDecl *3294UnresolvedUsingTypenameDecl::CreateDeserialized(ASTContext &C,3295GlobalDeclID ID) {3296return new (C, ID) UnresolvedUsingTypenameDecl(3297nullptr, SourceLocation(), SourceLocation(), NestedNameSpecifierLoc(),3298SourceLocation(), nullptr, SourceLocation());3299}33003301UnresolvedUsingIfExistsDecl *3302UnresolvedUsingIfExistsDecl::Create(ASTContext &Ctx, DeclContext *DC,3303SourceLocation Loc, DeclarationName Name) {3304return new (Ctx, DC) UnresolvedUsingIfExistsDecl(DC, Loc, Name);3305}33063307UnresolvedUsingIfExistsDecl *3308UnresolvedUsingIfExistsDecl::CreateDeserialized(ASTContext &Ctx,3309GlobalDeclID ID) {3310return new (Ctx, ID)3311UnresolvedUsingIfExistsDecl(nullptr, SourceLocation(), DeclarationName());3312}33133314UnresolvedUsingIfExistsDecl::UnresolvedUsingIfExistsDecl(DeclContext *DC,3315SourceLocation Loc,3316DeclarationName Name)3317: NamedDecl(Decl::UnresolvedUsingIfExists, DC, Loc, Name) {}33183319void UnresolvedUsingIfExistsDecl::anchor() {}33203321void StaticAssertDecl::anchor() {}33223323StaticAssertDecl *StaticAssertDecl::Create(ASTContext &C, DeclContext *DC,3324SourceLocation StaticAssertLoc,3325Expr *AssertExpr, Expr *Message,3326SourceLocation RParenLoc,3327bool Failed) {3328return new (C, DC) StaticAssertDecl(DC, StaticAssertLoc, AssertExpr, Message,3329RParenLoc, Failed);3330}33313332StaticAssertDecl *StaticAssertDecl::CreateDeserialized(ASTContext &C,3333GlobalDeclID ID) {3334return new (C, ID) StaticAssertDecl(nullptr, SourceLocation(), nullptr,3335nullptr, SourceLocation(), false);3336}33373338VarDecl *ValueDecl::getPotentiallyDecomposedVarDecl() {3339assert((isa<VarDecl, BindingDecl>(this)) &&3340"expected a VarDecl or a BindingDecl");3341if (auto *Var = llvm::dyn_cast<VarDecl>(this))3342return Var;3343if (auto *BD = llvm::dyn_cast<BindingDecl>(this))3344return llvm::dyn_cast<VarDecl>(BD->getDecomposedDecl());3345return nullptr;3346}33473348void BindingDecl::anchor() {}33493350BindingDecl *BindingDecl::Create(ASTContext &C, DeclContext *DC,3351SourceLocation IdLoc, IdentifierInfo *Id) {3352return new (C, DC) BindingDecl(DC, IdLoc, Id);3353}33543355BindingDecl *BindingDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID) {3356return new (C, ID) BindingDecl(nullptr, SourceLocation(), nullptr);3357}33583359VarDecl *BindingDecl::getHoldingVar() const {3360Expr *B = getBinding();3361if (!B)3362return nullptr;3363auto *DRE = dyn_cast<DeclRefExpr>(B->IgnoreImplicit());3364if (!DRE)3365return nullptr;33663367auto *VD = cast<VarDecl>(DRE->getDecl());3368assert(VD->isImplicit() && "holding var for binding decl not implicit");3369return VD;3370}33713372void DecompositionDecl::anchor() {}33733374DecompositionDecl *DecompositionDecl::Create(ASTContext &C, DeclContext *DC,3375SourceLocation StartLoc,3376SourceLocation LSquareLoc,3377QualType T, TypeSourceInfo *TInfo,3378StorageClass SC,3379ArrayRef<BindingDecl *> Bindings) {3380size_t Extra = additionalSizeToAlloc<BindingDecl *>(Bindings.size());3381return new (C, DC, Extra)3382DecompositionDecl(C, DC, StartLoc, LSquareLoc, T, TInfo, SC, Bindings);3383}33843385DecompositionDecl *DecompositionDecl::CreateDeserialized(ASTContext &C,3386GlobalDeclID ID,3387unsigned NumBindings) {3388size_t Extra = additionalSizeToAlloc<BindingDecl *>(NumBindings);3389auto *Result = new (C, ID, Extra)3390DecompositionDecl(C, nullptr, SourceLocation(), SourceLocation(),3391QualType(), nullptr, StorageClass(), std::nullopt);3392// Set up and clean out the bindings array.3393Result->NumBindings = NumBindings;3394auto *Trail = Result->getTrailingObjects<BindingDecl *>();3395for (unsigned I = 0; I != NumBindings; ++I)3396new (Trail + I) BindingDecl*(nullptr);3397return Result;3398}33993400void DecompositionDecl::printName(llvm::raw_ostream &OS,3401const PrintingPolicy &Policy) const {3402OS << '[';3403bool Comma = false;3404for (const auto *B : bindings()) {3405if (Comma)3406OS << ", ";3407B->printName(OS, Policy);3408Comma = true;3409}3410OS << ']';3411}34123413void MSPropertyDecl::anchor() {}34143415MSPropertyDecl *MSPropertyDecl::Create(ASTContext &C, DeclContext *DC,3416SourceLocation L, DeclarationName N,3417QualType T, TypeSourceInfo *TInfo,3418SourceLocation StartL,3419IdentifierInfo *Getter,3420IdentifierInfo *Setter) {3421return new (C, DC) MSPropertyDecl(DC, L, N, T, TInfo, StartL, Getter, Setter);3422}34233424MSPropertyDecl *MSPropertyDecl::CreateDeserialized(ASTContext &C,3425GlobalDeclID ID) {3426return new (C, ID) MSPropertyDecl(nullptr, SourceLocation(),3427DeclarationName(), QualType(), nullptr,3428SourceLocation(), nullptr, nullptr);3429}34303431void MSGuidDecl::anchor() {}34323433MSGuidDecl::MSGuidDecl(DeclContext *DC, QualType T, Parts P)3434: ValueDecl(Decl::MSGuid, DC, SourceLocation(), DeclarationName(), T),3435PartVal(P) {}34363437MSGuidDecl *MSGuidDecl::Create(const ASTContext &C, QualType T, Parts P) {3438DeclContext *DC = C.getTranslationUnitDecl();3439return new (C, DC) MSGuidDecl(DC, T, P);3440}34413442MSGuidDecl *MSGuidDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID) {3443return new (C, ID) MSGuidDecl(nullptr, QualType(), Parts());3444}34453446void MSGuidDecl::printName(llvm::raw_ostream &OS,3447const PrintingPolicy &) const {3448OS << llvm::format("GUID{%08" PRIx32 "-%04" PRIx16 "-%04" PRIx16 "-",3449PartVal.Part1, PartVal.Part2, PartVal.Part3);3450unsigned I = 0;3451for (uint8_t Byte : PartVal.Part4And5) {3452OS << llvm::format("%02" PRIx8, Byte);3453if (++I == 2)3454OS << '-';3455}3456OS << '}';3457}34583459/// Determine if T is a valid 'struct _GUID' of the shape that we expect.3460static bool isValidStructGUID(ASTContext &Ctx, QualType T) {3461// FIXME: We only need to check this once, not once each time we compute a3462// GUID APValue.3463using MatcherRef = llvm::function_ref<bool(QualType)>;34643465auto IsInt = [&Ctx](unsigned N) {3466return [&Ctx, N](QualType T) {3467return T->isUnsignedIntegerOrEnumerationType() &&3468Ctx.getIntWidth(T) == N;3469};3470};34713472auto IsArray = [&Ctx](MatcherRef Elem, unsigned N) {3473return [&Ctx, Elem, N](QualType T) {3474const ConstantArrayType *CAT = Ctx.getAsConstantArrayType(T);3475return CAT && CAT->getSize() == N && Elem(CAT->getElementType());3476};3477};34783479auto IsStruct = [](std::initializer_list<MatcherRef> Fields) {3480return [Fields](QualType T) {3481const RecordDecl *RD = T->getAsRecordDecl();3482if (!RD || RD->isUnion())3483return false;3484RD = RD->getDefinition();3485if (!RD)3486return false;3487if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))3488if (CXXRD->getNumBases())3489return false;3490auto MatcherIt = Fields.begin();3491for (const FieldDecl *FD : RD->fields()) {3492if (FD->isUnnamedBitField())3493continue;3494if (FD->isBitField() || MatcherIt == Fields.end() ||3495!(*MatcherIt)(FD->getType()))3496return false;3497++MatcherIt;3498}3499return MatcherIt == Fields.end();3500};3501};35023503// We expect an {i32, i16, i16, [8 x i8]}.3504return IsStruct({IsInt(32), IsInt(16), IsInt(16), IsArray(IsInt(8), 8)})(T);3505}35063507APValue &MSGuidDecl::getAsAPValue() const {3508if (APVal.isAbsent() && isValidStructGUID(getASTContext(), getType())) {3509using llvm::APInt;3510using llvm::APSInt;3511APVal = APValue(APValue::UninitStruct(), 0, 4);3512APVal.getStructField(0) = APValue(APSInt(APInt(32, PartVal.Part1), true));3513APVal.getStructField(1) = APValue(APSInt(APInt(16, PartVal.Part2), true));3514APVal.getStructField(2) = APValue(APSInt(APInt(16, PartVal.Part3), true));3515APValue &Arr = APVal.getStructField(3) =3516APValue(APValue::UninitArray(), 8, 8);3517for (unsigned I = 0; I != 8; ++I) {3518Arr.getArrayInitializedElt(I) =3519APValue(APSInt(APInt(8, PartVal.Part4And5[I]), true));3520}3521// Register this APValue to be destroyed if necessary. (Note that the3522// MSGuidDecl destructor is never run.)3523getASTContext().addDestruction(&APVal);3524}35253526return APVal;3527}35283529void UnnamedGlobalConstantDecl::anchor() {}35303531UnnamedGlobalConstantDecl::UnnamedGlobalConstantDecl(const ASTContext &C,3532DeclContext *DC,3533QualType Ty,3534const APValue &Val)3535: ValueDecl(Decl::UnnamedGlobalConstant, DC, SourceLocation(),3536DeclarationName(), Ty),3537Value(Val) {3538// Cleanup the embedded APValue if required (note that our destructor is never3539// run)3540if (Value.needsCleanup())3541C.addDestruction(&Value);3542}35433544UnnamedGlobalConstantDecl *3545UnnamedGlobalConstantDecl::Create(const ASTContext &C, QualType T,3546const APValue &Value) {3547DeclContext *DC = C.getTranslationUnitDecl();3548return new (C, DC) UnnamedGlobalConstantDecl(C, DC, T, Value);3549}35503551UnnamedGlobalConstantDecl *3552UnnamedGlobalConstantDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID) {3553return new (C, ID)3554UnnamedGlobalConstantDecl(C, nullptr, QualType(), APValue());3555}35563557void UnnamedGlobalConstantDecl::printName(llvm::raw_ostream &OS,3558const PrintingPolicy &) const {3559OS << "unnamed-global-constant";3560}35613562static const char *getAccessName(AccessSpecifier AS) {3563switch (AS) {3564case AS_none:3565llvm_unreachable("Invalid access specifier!");3566case AS_public:3567return "public";3568case AS_private:3569return "private";3570case AS_protected:3571return "protected";3572}3573llvm_unreachable("Invalid access specifier!");3574}35753576const StreamingDiagnostic &clang::operator<<(const StreamingDiagnostic &DB,3577AccessSpecifier AS) {3578return DB << getAccessName(AS);3579}358035813582