3834 lines · cpp
1//===- DeclCXX.cpp - C++ Declaration AST Node Implementation --------------===//2//3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.4// See https://llvm.org/LICENSE.txt for license information.5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception6//7//===----------------------------------------------------------------------===//8//9// This file implements the C++ related Decl classes.10//11//===----------------------------------------------------------------------===//12 13#include "clang/AST/DeclCXX.h"14#include "clang/AST/ASTContext.h"15#include "clang/AST/ASTLambda.h"16#include "clang/AST/ASTMutationListener.h"17#include "clang/AST/ASTUnresolvedSet.h"18#include "clang/AST/Attr.h"19#include "clang/AST/CXXInheritance.h"20#include "clang/AST/DeclBase.h"21#include "clang/AST/DeclTemplate.h"22#include "clang/AST/DeclarationName.h"23#include "clang/AST/Expr.h"24#include "clang/AST/ExprCXX.h"25#include "clang/AST/LambdaCapture.h"26#include "clang/AST/NestedNameSpecifier.h"27#include "clang/AST/ODRHash.h"28#include "clang/AST/Type.h"29#include "clang/AST/TypeLoc.h"30#include "clang/AST/UnresolvedSet.h"31#include "clang/Basic/Diagnostic.h"32#include "clang/Basic/DiagnosticAST.h"33#include "clang/Basic/IdentifierTable.h"34#include "clang/Basic/LLVM.h"35#include "clang/Basic/LangOptions.h"36#include "clang/Basic/OperatorKinds.h"37#include "clang/Basic/SourceLocation.h"38#include "clang/Basic/Specifiers.h"39#include "clang/Basic/TargetInfo.h"40#include "llvm/ADT/SmallPtrSet.h"41#include "llvm/ADT/SmallVector.h"42#include "llvm/ADT/iterator_range.h"43#include "llvm/Support/Casting.h"44#include "llvm/Support/ErrorHandling.h"45#include "llvm/Support/Format.h"46#include "llvm/Support/raw_ostream.h"47#include <algorithm>48#include <cassert>49#include <cstddef>50#include <cstdint>51 52using namespace clang;53 54//===----------------------------------------------------------------------===//55// Decl Allocation/Deallocation Method Implementations56//===----------------------------------------------------------------------===//57 58void AccessSpecDecl::anchor() {}59 60AccessSpecDecl *AccessSpecDecl::CreateDeserialized(ASTContext &C,61 GlobalDeclID ID) {62 return new (C, ID) AccessSpecDecl(EmptyShell());63}64 65void LazyASTUnresolvedSet::getFromExternalSource(ASTContext &C) const {66 ExternalASTSource *Source = C.getExternalSource();67 assert(Impl.Decls.isLazy() && "getFromExternalSource for non-lazy set");68 assert(Source && "getFromExternalSource with no external source");69 70 for (ASTUnresolvedSet::iterator I = Impl.begin(); I != Impl.end(); ++I)71 I.setDecl(72 cast<NamedDecl>(Source->GetExternalDecl(GlobalDeclID(I.getDeclID()))));73 Impl.Decls.setLazy(false);74}75 76CXXRecordDecl::DefinitionData::DefinitionData(CXXRecordDecl *D)77 : UserDeclaredConstructor(false), UserDeclaredSpecialMembers(0),78 Aggregate(true), PlainOldData(true), Empty(true), Polymorphic(false),79 Abstract(false), IsStandardLayout(true), IsCXX11StandardLayout(true),80 HasBasesWithFields(false), HasBasesWithNonStaticDataMembers(false),81 HasPrivateFields(false), HasProtectedFields(false),82 HasPublicFields(false), HasMutableFields(false), HasVariantMembers(false),83 HasOnlyCMembers(true), HasInitMethod(false), HasInClassInitializer(false),84 HasUninitializedReferenceMember(false), HasUninitializedFields(false),85 HasInheritedConstructor(false), HasInheritedDefaultConstructor(false),86 HasInheritedAssignment(false),87 NeedOverloadResolutionForCopyConstructor(false),88 NeedOverloadResolutionForMoveConstructor(false),89 NeedOverloadResolutionForCopyAssignment(false),90 NeedOverloadResolutionForMoveAssignment(false),91 NeedOverloadResolutionForDestructor(false),92 DefaultedCopyConstructorIsDeleted(false),93 DefaultedMoveConstructorIsDeleted(false),94 DefaultedCopyAssignmentIsDeleted(false),95 DefaultedMoveAssignmentIsDeleted(false),96 DefaultedDestructorIsDeleted(false), HasTrivialSpecialMembers(SMF_All),97 HasTrivialSpecialMembersForCall(SMF_All),98 DeclaredNonTrivialSpecialMembers(0),99 DeclaredNonTrivialSpecialMembersForCall(0), HasIrrelevantDestructor(true),100 HasConstexprNonCopyMoveConstructor(false),101 HasDefaultedDefaultConstructor(false),102 DefaultedDefaultConstructorIsConstexpr(true),103 HasConstexprDefaultConstructor(false),104 DefaultedDestructorIsConstexpr(true),105 HasNonLiteralTypeFieldsOrBases(false), StructuralIfLiteral(true),106 UserProvidedDefaultConstructor(false), DeclaredSpecialMembers(0),107 ImplicitCopyConstructorCanHaveConstParamForVBase(true),108 ImplicitCopyConstructorCanHaveConstParamForNonVBase(true),109 ImplicitCopyAssignmentHasConstParam(true),110 HasDeclaredCopyConstructorWithConstParam(false),111 HasDeclaredCopyAssignmentWithConstParam(false),112 IsAnyDestructorNoReturn(false), IsHLSLIntangible(false), IsLambda(false),113 IsParsingBaseSpecifiers(false), ComputedVisibleConversions(false),114 HasODRHash(false), Definition(D) {}115 116CXXBaseSpecifier *CXXRecordDecl::DefinitionData::getBasesSlowCase() const {117 return Bases.get(Definition->getASTContext().getExternalSource());118}119 120CXXBaseSpecifier *CXXRecordDecl::DefinitionData::getVBasesSlowCase() const {121 return VBases.get(Definition->getASTContext().getExternalSource());122}123 124CXXRecordDecl::CXXRecordDecl(Kind K, TagKind TK, const ASTContext &C,125 DeclContext *DC, SourceLocation StartLoc,126 SourceLocation IdLoc, IdentifierInfo *Id,127 CXXRecordDecl *PrevDecl)128 : RecordDecl(K, TK, C, DC, StartLoc, IdLoc, Id, PrevDecl),129 DefinitionData(PrevDecl ? PrevDecl->DefinitionData130 : nullptr) {}131 132CXXRecordDecl *CXXRecordDecl::Create(const ASTContext &C, TagKind TK,133 DeclContext *DC, SourceLocation StartLoc,134 SourceLocation IdLoc, IdentifierInfo *Id,135 CXXRecordDecl *PrevDecl) {136 return new (C, DC)137 CXXRecordDecl(CXXRecord, TK, C, DC, StartLoc, IdLoc, Id, PrevDecl);138}139 140CXXRecordDecl *141CXXRecordDecl::CreateLambda(const ASTContext &C, DeclContext *DC,142 TypeSourceInfo *Info, SourceLocation Loc,143 unsigned DependencyKind, bool IsGeneric,144 LambdaCaptureDefault CaptureDefault) {145 auto *R = new (C, DC) CXXRecordDecl(CXXRecord, TagTypeKind::Class, C, DC, Loc,146 Loc, nullptr, nullptr);147 R->setBeingDefined(true);148 R->DefinitionData = new (C) struct LambdaDefinitionData(149 R, Info, DependencyKind, IsGeneric, CaptureDefault);150 R->setImplicit(true);151 return R;152}153 154CXXRecordDecl *CXXRecordDecl::CreateDeserialized(const ASTContext &C,155 GlobalDeclID ID) {156 auto *R = new (C, ID)157 CXXRecordDecl(CXXRecord, TagTypeKind::Struct, C, nullptr,158 SourceLocation(), SourceLocation(), nullptr, nullptr);159 return R;160}161 162/// Determine whether a class has a repeated base class. This is intended for163/// use when determining if a class is standard-layout, so makes no attempt to164/// handle virtual bases.165static bool hasRepeatedBaseClass(const CXXRecordDecl *StartRD) {166 llvm::SmallPtrSet<const CXXRecordDecl*, 8> SeenBaseTypes;167 SmallVector<const CXXRecordDecl*, 8> WorkList = {StartRD};168 while (!WorkList.empty()) {169 const CXXRecordDecl *RD = WorkList.pop_back_val();170 if (RD->isDependentType())171 continue;172 for (const CXXBaseSpecifier &BaseSpec : RD->bases()) {173 if (const CXXRecordDecl *B = BaseSpec.getType()->getAsCXXRecordDecl()) {174 if (!SeenBaseTypes.insert(B).second)175 return true;176 WorkList.push_back(B);177 }178 }179 }180 return false;181}182 183void184CXXRecordDecl::setBases(CXXBaseSpecifier const * const *Bases,185 unsigned NumBases) {186 ASTContext &C = getASTContext();187 188 if (!data().Bases.isOffset() && data().NumBases > 0)189 C.Deallocate(data().getBases());190 191 if (NumBases) {192 if (!C.getLangOpts().CPlusPlus17) {193 // C++ [dcl.init.aggr]p1:194 // An aggregate is [...] a class with [...] no base classes [...].195 data().Aggregate = false;196 }197 198 // C++ [class]p4:199 // A POD-struct is an aggregate class...200 data().PlainOldData = false;201 }202 203 // The set of seen virtual base types.204 llvm::SmallPtrSet<CanQualType, 8> SeenVBaseTypes;205 206 // The virtual bases of this class.207 SmallVector<const CXXBaseSpecifier *, 8> VBases;208 209 data().Bases = new(C) CXXBaseSpecifier [NumBases];210 data().NumBases = NumBases;211 for (unsigned i = 0; i < NumBases; ++i) {212 data().getBases()[i] = *Bases[i];213 // Keep track of inherited vbases for this base class.214 const CXXBaseSpecifier *Base = Bases[i];215 QualType BaseType = Base->getType();216 // Skip dependent types; we can't do any checking on them now.217 if (BaseType->isDependentType())218 continue;219 auto *BaseClassDecl = BaseType->castAsCXXRecordDecl();220 221 // C++2a [class]p7:222 // A standard-layout class is a class that:223 // [...]224 // -- has all non-static data members and bit-fields in the class and225 // its base classes first declared in the same class226 if (BaseClassDecl->data().HasBasesWithFields ||227 !BaseClassDecl->field_empty()) {228 if (data().HasBasesWithFields)229 // Two bases have members or bit-fields: not standard-layout.230 data().IsStandardLayout = false;231 data().HasBasesWithFields = true;232 }233 234 // C++11 [class]p7:235 // A standard-layout class is a class that:236 // -- [...] has [...] at most one base class with non-static data237 // members238 if (BaseClassDecl->data().HasBasesWithNonStaticDataMembers ||239 BaseClassDecl->hasDirectFields()) {240 if (data().HasBasesWithNonStaticDataMembers)241 data().IsCXX11StandardLayout = false;242 data().HasBasesWithNonStaticDataMembers = true;243 }244 245 if (!BaseClassDecl->isEmpty()) {246 // C++14 [meta.unary.prop]p4:247 // T is a class type [...] with [...] no base class B for which248 // is_empty<B>::value is false.249 data().Empty = false;250 }251 252 // C++1z [dcl.init.agg]p1:253 // An aggregate is a class with [...] no private or protected base classes254 if (Base->getAccessSpecifier() != AS_public) {255 data().Aggregate = false;256 257 // C++20 [temp.param]p7:258 // A structural type is [...] a literal class type with [...] all base259 // classes [...] public260 data().StructuralIfLiteral = false;261 }262 263 // C++ [class.virtual]p1:264 // A class that declares or inherits a virtual function is called a265 // polymorphic class.266 if (BaseClassDecl->isPolymorphic()) {267 data().Polymorphic = true;268 269 // An aggregate is a class with [...] no virtual functions.270 data().Aggregate = false;271 }272 273 // C++0x [class]p7:274 // A standard-layout class is a class that: [...]275 // -- has no non-standard-layout base classes276 if (!BaseClassDecl->isStandardLayout())277 data().IsStandardLayout = false;278 if (!BaseClassDecl->isCXX11StandardLayout())279 data().IsCXX11StandardLayout = false;280 281 // Record if this base is the first non-literal field or base.282 if (!hasNonLiteralTypeFieldsOrBases() && !BaseType->isLiteralType(C))283 data().HasNonLiteralTypeFieldsOrBases = true;284 285 // Now go through all virtual bases of this base and add them.286 for (const auto &VBase : BaseClassDecl->vbases()) {287 // Add this base if it's not already in the list.288 if (SeenVBaseTypes.insert(C.getCanonicalType(VBase.getType())).second) {289 VBases.push_back(&VBase);290 291 // C++11 [class.copy]p8:292 // The implicitly-declared copy constructor for a class X will have293 // the form 'X::X(const X&)' if each [...] virtual base class B of X294 // has a copy constructor whose first parameter is of type295 // 'const B&' or 'const volatile B&' [...]296 if (CXXRecordDecl *VBaseDecl = VBase.getType()->getAsCXXRecordDecl())297 if (!VBaseDecl->hasCopyConstructorWithConstParam())298 data().ImplicitCopyConstructorCanHaveConstParamForVBase = false;299 300 // C++1z [dcl.init.agg]p1:301 // An aggregate is a class with [...] no virtual base classes302 data().Aggregate = false;303 }304 }305 306 if (Base->isVirtual()) {307 // Add this base if it's not already in the list.308 if (SeenVBaseTypes.insert(C.getCanonicalType(BaseType)).second)309 VBases.push_back(Base);310 311 // C++14 [meta.unary.prop] is_empty:312 // T is a class type, but not a union type, with ... no virtual base313 // classes314 data().Empty = false;315 316 // C++1z [dcl.init.agg]p1:317 // An aggregate is a class with [...] no virtual base classes318 data().Aggregate = false;319 320 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:321 // A [default constructor, copy/move constructor, or copy/move assignment322 // operator for a class X] is trivial [...] if:323 // -- class X has [...] no virtual base classes324 data().HasTrivialSpecialMembers &= SMF_Destructor;325 data().HasTrivialSpecialMembersForCall &= SMF_Destructor;326 327 // C++0x [class]p7:328 // A standard-layout class is a class that: [...]329 // -- has [...] no virtual base classes330 data().IsStandardLayout = false;331 data().IsCXX11StandardLayout = false;332 333 // C++20 [dcl.constexpr]p3:334 // In the definition of a constexpr function [...]335 // -- if the function is a constructor or destructor,336 // its class shall not have any virtual base classes337 data().DefaultedDefaultConstructorIsConstexpr = false;338 data().DefaultedDestructorIsConstexpr = false;339 340 // C++1z [class.copy]p8:341 // The implicitly-declared copy constructor for a class X will have342 // the form 'X::X(const X&)' if each potentially constructed subobject343 // has a copy constructor whose first parameter is of type344 // 'const B&' or 'const volatile B&' [...]345 if (!BaseClassDecl->hasCopyConstructorWithConstParam())346 data().ImplicitCopyConstructorCanHaveConstParamForVBase = false;347 } else {348 // C++ [class.ctor]p5:349 // A default constructor is trivial [...] if:350 // -- all the direct base classes of its class have trivial default351 // constructors.352 if (!BaseClassDecl->hasTrivialDefaultConstructor())353 data().HasTrivialSpecialMembers &= ~SMF_DefaultConstructor;354 355 // C++0x [class.copy]p13:356 // A copy/move constructor for class X is trivial if [...]357 // [...]358 // -- the constructor selected to copy/move each direct base class359 // subobject is trivial, and360 if (!BaseClassDecl->hasTrivialCopyConstructor())361 data().HasTrivialSpecialMembers &= ~SMF_CopyConstructor;362 363 if (!BaseClassDecl->hasTrivialCopyConstructorForCall())364 data().HasTrivialSpecialMembersForCall &= ~SMF_CopyConstructor;365 366 // If the base class doesn't have a simple move constructor, we'll eagerly367 // declare it and perform overload resolution to determine which function368 // it actually calls. If it does have a simple move constructor, this369 // check is correct.370 if (!BaseClassDecl->hasTrivialMoveConstructor())371 data().HasTrivialSpecialMembers &= ~SMF_MoveConstructor;372 373 if (!BaseClassDecl->hasTrivialMoveConstructorForCall())374 data().HasTrivialSpecialMembersForCall &= ~SMF_MoveConstructor;375 376 // C++0x [class.copy]p27:377 // A copy/move assignment operator for class X is trivial if [...]378 // [...]379 // -- the assignment operator selected to copy/move each direct base380 // class subobject is trivial, and381 if (!BaseClassDecl->hasTrivialCopyAssignment())382 data().HasTrivialSpecialMembers &= ~SMF_CopyAssignment;383 // If the base class doesn't have a simple move assignment, we'll eagerly384 // declare it and perform overload resolution to determine which function385 // it actually calls. If it does have a simple move assignment, this386 // check is correct.387 if (!BaseClassDecl->hasTrivialMoveAssignment())388 data().HasTrivialSpecialMembers &= ~SMF_MoveAssignment;389 390 // C++11 [class.ctor]p6:391 // If that user-written default constructor would satisfy the392 // requirements of a constexpr constructor/function(C++23), the393 // implicitly-defined default constructor is constexpr.394 if (!BaseClassDecl->hasConstexprDefaultConstructor())395 data().DefaultedDefaultConstructorIsConstexpr =396 C.getLangOpts().CPlusPlus23;397 398 // C++1z [class.copy]p8:399 // The implicitly-declared copy constructor for a class X will have400 // the form 'X::X(const X&)' if each potentially constructed subobject401 // has a copy constructor whose first parameter is of type402 // 'const B&' or 'const volatile B&' [...]403 if (!BaseClassDecl->hasCopyConstructorWithConstParam())404 data().ImplicitCopyConstructorCanHaveConstParamForNonVBase = false;405 }406 407 // C++ [class.ctor]p3:408 // A destructor is trivial if all the direct base classes of its class409 // have trivial destructors.410 if (!BaseClassDecl->hasTrivialDestructor())411 data().HasTrivialSpecialMembers &= ~SMF_Destructor;412 413 if (!BaseClassDecl->hasTrivialDestructorForCall())414 data().HasTrivialSpecialMembersForCall &= ~SMF_Destructor;415 416 if (!BaseClassDecl->hasIrrelevantDestructor())417 data().HasIrrelevantDestructor = false;418 419 if (BaseClassDecl->isAnyDestructorNoReturn())420 data().IsAnyDestructorNoReturn = true;421 422 if (BaseClassDecl->isHLSLIntangible())423 data().IsHLSLIntangible = true;424 425 // C++11 [class.copy]p18:426 // The implicitly-declared copy assignment operator for a class X will427 // have the form 'X& X::operator=(const X&)' if each direct base class B428 // of X has a copy assignment operator whose parameter is of type 'const429 // B&', 'const volatile B&', or 'B' [...]430 if (!BaseClassDecl->hasCopyAssignmentWithConstParam())431 data().ImplicitCopyAssignmentHasConstParam = false;432 433 // A class has an Objective-C object member if... or any of its bases434 // has an Objective-C object member.435 if (BaseClassDecl->hasObjectMember())436 setHasObjectMember(true);437 438 if (BaseClassDecl->hasVolatileMember())439 setHasVolatileMember(true);440 441 if (BaseClassDecl->getArgPassingRestrictions() ==442 RecordArgPassingKind::CanNeverPassInRegs)443 setArgPassingRestrictions(RecordArgPassingKind::CanNeverPassInRegs);444 445 // Keep track of the presence of mutable fields.446 if (BaseClassDecl->hasMutableFields())447 data().HasMutableFields = true;448 449 if (BaseClassDecl->hasUninitializedExplicitInitFields() &&450 BaseClassDecl->isAggregate())451 setHasUninitializedExplicitInitFields(true);452 453 if (BaseClassDecl->hasUninitializedReferenceMember())454 data().HasUninitializedReferenceMember = true;455 456 if (!BaseClassDecl->allowConstDefaultInit())457 data().HasUninitializedFields = true;458 459 addedClassSubobject(BaseClassDecl);460 }461 462 // C++2a [class]p7:463 // A class S is a standard-layout class if it:464 // -- has at most one base class subobject of any given type465 //466 // Note that we only need to check this for classes with more than one base467 // class. If there's only one base class, and it's standard layout, then468 // we know there are no repeated base classes.469 if (data().IsStandardLayout && NumBases > 1 && hasRepeatedBaseClass(this))470 data().IsStandardLayout = false;471 472 if (VBases.empty()) {473 data().IsParsingBaseSpecifiers = false;474 return;475 }476 477 // Create base specifier for any direct or indirect virtual bases.478 data().VBases = new (C) CXXBaseSpecifier[VBases.size()];479 data().NumVBases = VBases.size();480 for (int I = 0, E = VBases.size(); I != E; ++I) {481 QualType Type = VBases[I]->getType();482 if (!Type->isDependentType())483 addedClassSubobject(Type->getAsCXXRecordDecl());484 data().getVBases()[I] = *VBases[I];485 }486 487 data().IsParsingBaseSpecifiers = false;488}489 490unsigned CXXRecordDecl::getODRHash() const {491 assert(hasDefinition() && "ODRHash only for records with definitions");492 493 // Previously calculated hash is stored in DefinitionData.494 if (DefinitionData->HasODRHash)495 return DefinitionData->ODRHash;496 497 // Only calculate hash on first call of getODRHash per record.498 ODRHash Hash;499 Hash.AddCXXRecordDecl(getDefinition());500 DefinitionData->HasODRHash = true;501 DefinitionData->ODRHash = Hash.CalculateHash();502 503 return DefinitionData->ODRHash;504}505 506void CXXRecordDecl::addedClassSubobject(CXXRecordDecl *Subobj) {507 // C++11 [class.copy]p11:508 // A defaulted copy/move constructor for a class X is defined as509 // deleted if X has:510 // -- a direct or virtual base class B that cannot be copied/moved [...]511 // -- a non-static data member of class type M (or array thereof)512 // that cannot be copied or moved [...]513 if (!Subobj->hasSimpleCopyConstructor())514 data().NeedOverloadResolutionForCopyConstructor = true;515 if (!Subobj->hasSimpleMoveConstructor())516 data().NeedOverloadResolutionForMoveConstructor = true;517 518 // C++11 [class.copy]p23:519 // A defaulted copy/move assignment operator for a class X is defined as520 // deleted if X has:521 // -- a direct or virtual base class B that cannot be copied/moved [...]522 // -- a non-static data member of class type M (or array thereof)523 // that cannot be copied or moved [...]524 if (!Subobj->hasSimpleCopyAssignment())525 data().NeedOverloadResolutionForCopyAssignment = true;526 if (!Subobj->hasSimpleMoveAssignment())527 data().NeedOverloadResolutionForMoveAssignment = true;528 529 // C++11 [class.ctor]p5, C++11 [class.copy]p11, C++11 [class.dtor]p5:530 // A defaulted [ctor or dtor] for a class X is defined as531 // deleted if X has:532 // -- any direct or virtual base class [...] has a type with a destructor533 // that is deleted or inaccessible from the defaulted [ctor or dtor].534 // -- any non-static data member has a type with a destructor535 // that is deleted or inaccessible from the defaulted [ctor or dtor].536 if (!Subobj->hasSimpleDestructor()) {537 data().NeedOverloadResolutionForCopyConstructor = true;538 data().NeedOverloadResolutionForMoveConstructor = true;539 data().NeedOverloadResolutionForDestructor = true;540 }541 542 // C++20 [dcl.constexpr]p5:543 // The definition of a constexpr destructor whose function-body is not544 // = delete shall additionally satisfy the following requirement:545 // -- for every subobject of class type or (possibly multi-dimensional)546 // array thereof, that class type shall have a constexpr destructor547 if (!Subobj->hasConstexprDestructor())548 data().DefaultedDestructorIsConstexpr =549 getASTContext().getLangOpts().CPlusPlus23;550 551 // C++20 [temp.param]p7:552 // A structural type is [...] a literal class type [for which] the types553 // of all base classes and non-static data members are structural types or554 // (possibly multi-dimensional) array thereof555 if (!Subobj->data().StructuralIfLiteral)556 data().StructuralIfLiteral = false;557}558 559const CXXRecordDecl *CXXRecordDecl::getStandardLayoutBaseWithFields() const {560 assert(561 isStandardLayout() &&562 "getStandardLayoutBaseWithFields called on a non-standard-layout type");563#ifdef EXPENSIVE_CHECKS564 {565 unsigned NumberOfBasesWithFields = 0;566 if (!field_empty())567 ++NumberOfBasesWithFields;568 llvm::SmallPtrSet<const CXXRecordDecl *, 8> UniqueBases;569 forallBases([&](const CXXRecordDecl *Base) -> bool {570 if (!Base->field_empty())571 ++NumberOfBasesWithFields;572 assert(573 UniqueBases.insert(Base->getCanonicalDecl()).second &&574 "Standard layout struct has multiple base classes of the same type");575 return true;576 });577 assert(NumberOfBasesWithFields <= 1 &&578 "Standard layout struct has fields declared in more than one class");579 }580#endif581 if (!field_empty())582 return this;583 const CXXRecordDecl *Result = this;584 forallBases([&](const CXXRecordDecl *Base) -> bool {585 if (!Base->field_empty()) {586 // This is the base where the fields are declared; return early587 Result = Base;588 return false;589 }590 return true;591 });592 return Result;593}594 595bool CXXRecordDecl::hasConstexprDestructor() const {596 auto *Dtor = getDestructor();597 return Dtor ? Dtor->isConstexpr() : defaultedDestructorIsConstexpr();598}599 600bool CXXRecordDecl::hasAnyDependentBases() const {601 if (!isDependentContext())602 return false;603 604 return !forallBases([](const CXXRecordDecl *) { return true; });605}606 607bool CXXRecordDecl::isTriviallyCopyable() const {608 // C++0x [class]p5:609 // A trivially copyable class is a class that:610 // -- has no non-trivial copy constructors,611 if (hasNonTrivialCopyConstructor()) return false;612 // -- has no non-trivial move constructors,613 if (hasNonTrivialMoveConstructor()) return false;614 // -- has no non-trivial copy assignment operators,615 if (hasNonTrivialCopyAssignment()) return false;616 // -- has no non-trivial move assignment operators, and617 if (hasNonTrivialMoveAssignment()) return false;618 // -- has a trivial destructor.619 if (!hasTrivialDestructor()) return false;620 621 return true;622}623 624bool CXXRecordDecl::isTriviallyCopyConstructible() const {625 626 // A trivially copy constructible class is a class that:627 // -- has no non-trivial copy constructors,628 if (hasNonTrivialCopyConstructor())629 return false;630 // -- has a trivial destructor.631 if (!hasTrivialDestructor())632 return false;633 634 return true;635}636 637void CXXRecordDecl::markedVirtualFunctionPure() {638 // C++ [class.abstract]p2:639 // A class is abstract if it has at least one pure virtual function.640 data().Abstract = true;641}642 643bool CXXRecordDecl::hasSubobjectAtOffsetZeroOfEmptyBaseType(644 ASTContext &Ctx, const CXXRecordDecl *XFirst) {645 if (!getNumBases())646 return false;647 648 llvm::SmallPtrSet<const CXXRecordDecl*, 8> Bases;649 llvm::SmallPtrSet<const CXXRecordDecl*, 8> M;650 SmallVector<const CXXRecordDecl*, 8> WorkList;651 652 // Visit a type that we have determined is an element of M(S).653 auto Visit = [&](const CXXRecordDecl *RD) -> bool {654 RD = RD->getCanonicalDecl();655 656 // C++2a [class]p8:657 // A class S is a standard-layout class if it [...] has no element of the658 // set M(S) of types as a base class.659 //660 // If we find a subobject of an empty type, it might also be a base class,661 // so we'll need to walk the base classes to check.662 if (!RD->data().HasBasesWithFields) {663 // Walk the bases the first time, stopping if we find the type. Build a664 // set of them so we don't need to walk them again.665 if (Bases.empty()) {666 bool RDIsBase = !forallBases([&](const CXXRecordDecl *Base) -> bool {667 Base = Base->getCanonicalDecl();668 if (RD == Base)669 return false;670 Bases.insert(Base);671 return true;672 });673 if (RDIsBase)674 return true;675 } else {676 if (Bases.count(RD))677 return true;678 }679 }680 681 if (M.insert(RD).second)682 WorkList.push_back(RD);683 return false;684 };685 686 if (Visit(XFirst))687 return true;688 689 while (!WorkList.empty()) {690 const CXXRecordDecl *X = WorkList.pop_back_val();691 692 // FIXME: We don't check the bases of X. That matches the standard, but693 // that sure looks like a wording bug.694 695 // -- If X is a non-union class type with a non-static data member696 // [recurse to each field] that is either of zero size or is the697 // first non-static data member of X698 // -- If X is a union type, [recurse to union members]699 bool IsFirstField = true;700 for (auto *FD : X->fields()) {701 // FIXME: Should we really care about the type of the first non-static702 // data member of a non-union if there are preceding unnamed bit-fields?703 if (FD->isUnnamedBitField())704 continue;705 706 if (!IsFirstField && !FD->isZeroSize(Ctx))707 continue;708 709 if (FD->isInvalidDecl())710 continue;711 712 // -- If X is n array type, [visit the element type]713 QualType T = Ctx.getBaseElementType(FD->getType());714 if (auto *RD = T->getAsCXXRecordDecl())715 if (Visit(RD))716 return true;717 718 if (!X->isUnion())719 IsFirstField = false;720 }721 }722 723 return false;724}725 726bool CXXRecordDecl::lambdaIsDefaultConstructibleAndAssignable() const {727 assert(isLambda() && "not a lambda");728 729 // C++2a [expr.prim.lambda.capture]p11:730 // The closure type associated with a lambda-expression has no default731 // constructor if the lambda-expression has a lambda-capture and a732 // defaulted default constructor otherwise. It has a deleted copy733 // assignment operator if the lambda-expression has a lambda-capture and734 // defaulted copy and move assignment operators otherwise.735 //736 // C++17 [expr.prim.lambda]p21:737 // The closure type associated with a lambda-expression has no default738 // constructor and a deleted copy assignment operator.739 if (!isCapturelessLambda())740 return false;741 return getASTContext().getLangOpts().CPlusPlus20;742}743 744void CXXRecordDecl::addedMember(Decl *D) {745 if (!D->isImplicit() && !isa<FieldDecl>(D) && !isa<IndirectFieldDecl>(D) &&746 (!isa<TagDecl>(D) ||747 cast<TagDecl>(D)->getTagKind() == TagTypeKind::Class ||748 cast<TagDecl>(D)->getTagKind() == TagTypeKind::Interface))749 data().HasOnlyCMembers = false;750 751 // Ignore friends and invalid declarations.752 if (D->getFriendObjectKind() || D->isInvalidDecl())753 return;754 755 auto *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);756 if (FunTmpl)757 D = FunTmpl->getTemplatedDecl();758 759 // FIXME: Pass NamedDecl* to addedMember?760 Decl *DUnderlying = D;761 if (auto *ND = dyn_cast<NamedDecl>(DUnderlying)) {762 DUnderlying = ND->getUnderlyingDecl();763 if (auto *UnderlyingFunTmpl = dyn_cast<FunctionTemplateDecl>(DUnderlying))764 DUnderlying = UnderlyingFunTmpl->getTemplatedDecl();765 }766 767 if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) {768 if (Method->isVirtual()) {769 // C++ [dcl.init.aggr]p1:770 // An aggregate is an array or a class with [...] no virtual functions.771 data().Aggregate = false;772 773 // C++ [class]p4:774 // A POD-struct is an aggregate class...775 data().PlainOldData = false;776 777 // C++14 [meta.unary.prop]p4:778 // T is a class type [...] with [...] no virtual member functions...779 data().Empty = false;780 781 // C++ [class.virtual]p1:782 // A class that declares or inherits a virtual function is called a783 // polymorphic class.784 data().Polymorphic = true;785 786 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:787 // A [default constructor, copy/move constructor, or copy/move788 // assignment operator for a class X] is trivial [...] if:789 // -- class X has no virtual functions [...]790 data().HasTrivialSpecialMembers &= SMF_Destructor;791 data().HasTrivialSpecialMembersForCall &= SMF_Destructor;792 793 // C++0x [class]p7:794 // A standard-layout class is a class that: [...]795 // -- has no virtual functions796 data().IsStandardLayout = false;797 data().IsCXX11StandardLayout = false;798 }799 }800 801 // Notify the listener if an implicit member was added after the definition802 // was completed.803 if (!isBeingDefined() && D->isImplicit())804 if (ASTMutationListener *L = getASTMutationListener())805 L->AddedCXXImplicitMember(data().Definition, D);806 807 // The kind of special member this declaration is, if any.808 unsigned SMKind = 0;809 810 // Handle constructors.811 if (const auto *Constructor = dyn_cast<CXXConstructorDecl>(D)) {812 if (Constructor->isInheritingConstructor()) {813 // Ignore constructor shadow declarations. They are lazily created and814 // so shouldn't affect any properties of the class.815 } else {816 if (!Constructor->isImplicit()) {817 // Note that we have a user-declared constructor.818 data().UserDeclaredConstructor = true;819 820 const TargetInfo &TI = getASTContext().getTargetInfo();821 if ((!Constructor->isDeleted() && !Constructor->isDefaulted()) ||822 !TI.areDefaultedSMFStillPOD(getLangOpts())) {823 // C++ [class]p4:824 // A POD-struct is an aggregate class [...]825 // Since the POD bit is meant to be C++03 POD-ness, clear it even if826 // the type is technically an aggregate in C++0x since it wouldn't be827 // in 03.828 data().PlainOldData = false;829 }830 }831 832 if (Constructor->isDefaultConstructor()) {833 SMKind |= SMF_DefaultConstructor;834 835 if (Constructor->isUserProvided())836 data().UserProvidedDefaultConstructor = true;837 if (Constructor->isConstexpr())838 data().HasConstexprDefaultConstructor = true;839 if (Constructor->isDefaulted())840 data().HasDefaultedDefaultConstructor = true;841 }842 843 if (!FunTmpl) {844 unsigned Quals;845 if (Constructor->isCopyConstructor(Quals)) {846 SMKind |= SMF_CopyConstructor;847 848 if (Quals & Qualifiers::Const)849 data().HasDeclaredCopyConstructorWithConstParam = true;850 } else if (Constructor->isMoveConstructor())851 SMKind |= SMF_MoveConstructor;852 }853 854 // C++11 [dcl.init.aggr]p1: DR1518855 // An aggregate is an array or a class with no user-provided [or]856 // explicit [...] constructors857 // C++20 [dcl.init.aggr]p1:858 // An aggregate is an array or a class with no user-declared [...]859 // constructors860 if (getASTContext().getLangOpts().CPlusPlus20861 ? !Constructor->isImplicit()862 : (Constructor->isUserProvided() || Constructor->isExplicit()))863 data().Aggregate = false;864 }865 }866 867 // Handle constructors, including those inherited from base classes.868 if (const auto *Constructor = dyn_cast<CXXConstructorDecl>(DUnderlying)) {869 // Record if we see any constexpr constructors which are neither copy870 // nor move constructors.871 // C++1z [basic.types]p10:872 // [...] has at least one constexpr constructor or constructor template873 // (possibly inherited from a base class) that is not a copy or move874 // constructor [...]875 if (Constructor->isConstexpr() && !Constructor->isCopyOrMoveConstructor())876 data().HasConstexprNonCopyMoveConstructor = true;877 if (!isa<CXXConstructorDecl>(D) && Constructor->isDefaultConstructor())878 data().HasInheritedDefaultConstructor = true;879 }880 881 // Handle member functions.882 if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) {883 if (isa<CXXDestructorDecl>(D))884 SMKind |= SMF_Destructor;885 886 if (Method->isCopyAssignmentOperator()) {887 SMKind |= SMF_CopyAssignment;888 889 const auto *ParamTy =890 Method->getNonObjectParameter(0)->getType()->getAs<ReferenceType>();891 if (!ParamTy || ParamTy->getPointeeType().isConstQualified())892 data().HasDeclaredCopyAssignmentWithConstParam = true;893 }894 895 if (Method->isMoveAssignmentOperator())896 SMKind |= SMF_MoveAssignment;897 898 // Keep the list of conversion functions up-to-date.899 if (auto *Conversion = dyn_cast<CXXConversionDecl>(D)) {900 // FIXME: We use the 'unsafe' accessor for the access specifier here,901 // because Sema may not have set it yet. That's really just a misdesign902 // in Sema. However, LLDB *will* have set the access specifier correctly,903 // and adds declarations after the class is technically completed,904 // so completeDefinition()'s overriding of the access specifiers doesn't905 // work.906 AccessSpecifier AS = Conversion->getAccessUnsafe();907 908 if (Conversion->getPrimaryTemplate()) {909 // We don't record specializations.910 } else {911 ASTContext &Ctx = getASTContext();912 ASTUnresolvedSet &Conversions = data().Conversions.get(Ctx);913 NamedDecl *Primary =914 FunTmpl ? cast<NamedDecl>(FunTmpl) : cast<NamedDecl>(Conversion);915 if (Primary->getPreviousDecl())916 Conversions.replace(cast<NamedDecl>(Primary->getPreviousDecl()),917 Primary, AS);918 else919 Conversions.addDecl(Ctx, Primary, AS);920 }921 }922 923 if (SMKind) {924 // If this is the first declaration of a special member, we no longer have925 // an implicit trivial special member.926 data().HasTrivialSpecialMembers &=927 data().DeclaredSpecialMembers | ~SMKind;928 data().HasTrivialSpecialMembersForCall &=929 data().DeclaredSpecialMembers | ~SMKind;930 931 // Note when we have declared a declared special member, and suppress the932 // implicit declaration of this special member.933 data().DeclaredSpecialMembers |= SMKind;934 if (!Method->isImplicit()) {935 data().UserDeclaredSpecialMembers |= SMKind;936 937 const TargetInfo &TI = getASTContext().getTargetInfo();938 if ((!Method->isDeleted() && !Method->isDefaulted() &&939 SMKind != SMF_MoveAssignment) ||940 !TI.areDefaultedSMFStillPOD(getLangOpts())) {941 // C++03 [class]p4:942 // A POD-struct is an aggregate class that has [...] no user-defined943 // copy assignment operator and no user-defined destructor.944 //945 // Since the POD bit is meant to be C++03 POD-ness, and in C++03,946 // aggregates could not have any constructors, clear it even for an947 // explicitly defaulted or deleted constructor.948 // type is technically an aggregate in C++0x since it wouldn't be in949 // 03.950 //951 // Also, a user-declared move assignment operator makes a class952 // non-POD. This is an extension in C++03.953 data().PlainOldData = false;954 }955 }956 // When instantiating a class, we delay updating the destructor and957 // triviality properties of the class until selecting a destructor and958 // computing the eligibility of its special member functions. This is959 // because there might be function constraints that we need to evaluate960 // and compare later in the instantiation.961 if (!Method->isIneligibleOrNotSelected()) {962 addedEligibleSpecialMemberFunction(Method, SMKind);963 }964 }965 966 return;967 }968 969 // Handle non-static data members.970 if (const auto *Field = dyn_cast<FieldDecl>(D)) {971 ASTContext &Context = getASTContext();972 973 // C++2a [class]p7:974 // A standard-layout class is a class that:975 // [...]976 // -- has all non-static data members and bit-fields in the class and977 // its base classes first declared in the same class978 if (data().HasBasesWithFields)979 data().IsStandardLayout = false;980 981 // C++ [class.bit]p2:982 // A declaration for a bit-field that omits the identifier declares an983 // unnamed bit-field. Unnamed bit-fields are not members and cannot be984 // initialized.985 if (Field->isUnnamedBitField()) {986 // C++ [meta.unary.prop]p4: [LWG2358]987 // T is a class type [...] with [...] no unnamed bit-fields of non-zero988 // length989 if (data().Empty && !Field->isZeroLengthBitField() &&990 Context.getLangOpts().getClangABICompat() >991 LangOptions::ClangABI::Ver6)992 data().Empty = false;993 return;994 }995 996 // C++11 [class]p7:997 // A standard-layout class is a class that:998 // -- either has no non-static data members in the most derived class999 // [...] or has no base classes with non-static data members1000 if (data().HasBasesWithNonStaticDataMembers)1001 data().IsCXX11StandardLayout = false;1002 1003 // C++ [dcl.init.aggr]p1:1004 // An aggregate is an array or a class (clause 9) with [...] no1005 // private or protected non-static data members (clause 11).1006 //1007 // A POD must be an aggregate.1008 if (D->getAccess() == AS_private || D->getAccess() == AS_protected) {1009 data().Aggregate = false;1010 data().PlainOldData = false;1011 1012 // C++20 [temp.param]p7:1013 // A structural type is [...] a literal class type [for which] all1014 // non-static data members are public1015 data().StructuralIfLiteral = false;1016 }1017 1018 // Track whether this is the first field. We use this when checking1019 // whether the class is standard-layout below.1020 bool IsFirstField = !data().HasPrivateFields &&1021 !data().HasProtectedFields && !data().HasPublicFields;1022 1023 // C++0x [class]p7:1024 // A standard-layout class is a class that:1025 // [...]1026 // -- has the same access control for all non-static data members,1027 switch (D->getAccess()) {1028 case AS_private: data().HasPrivateFields = true; break;1029 case AS_protected: data().HasProtectedFields = true; break;1030 case AS_public: data().HasPublicFields = true; break;1031 case AS_none: llvm_unreachable("Invalid access specifier");1032 };1033 if ((data().HasPrivateFields + data().HasProtectedFields +1034 data().HasPublicFields) > 1) {1035 data().IsStandardLayout = false;1036 data().IsCXX11StandardLayout = false;1037 }1038 1039 // Keep track of the presence of mutable fields.1040 if (Field->isMutable()) {1041 data().HasMutableFields = true;1042 1043 // C++20 [temp.param]p7:1044 // A structural type is [...] a literal class type [for which] all1045 // non-static data members are public1046 data().StructuralIfLiteral = false;1047 }1048 1049 // C++11 [class.union]p8, DR1460:1050 // If X is a union, a non-static data member of X that is not an anonymous1051 // union is a variant member of X.1052 if (isUnion() && !Field->isAnonymousStructOrUnion())1053 data().HasVariantMembers = true;1054 1055 if (isUnion() && IsFirstField)1056 data().HasUninitializedFields = true;1057 1058 // C++0x [class]p9:1059 // A POD struct is a class that is both a trivial class and a1060 // standard-layout class, and has no non-static data members of type1061 // non-POD struct, non-POD union (or array of such types).1062 //1063 // Automatic Reference Counting: the presence of a member of Objective-C pointer type1064 // that does not explicitly have no lifetime makes the class a non-POD.1065 QualType T = Context.getBaseElementType(Field->getType());1066 if (T->isObjCRetainableType() || T.isObjCGCStrong()) {1067 if (T.hasNonTrivialObjCLifetime()) {1068 // Objective-C Automatic Reference Counting:1069 // If a class has a non-static data member of Objective-C pointer1070 // type (or array thereof), it is a non-POD type and its1071 // default constructor (if any), copy constructor, move constructor,1072 // copy assignment operator, move assignment operator, and destructor are1073 // non-trivial.1074 setHasObjectMember(true);1075 struct DefinitionData &Data = data();1076 Data.PlainOldData = false;1077 Data.HasTrivialSpecialMembers = 0;1078 1079 // __strong or __weak fields do not make special functions non-trivial1080 // for the purpose of calls.1081 Qualifiers::ObjCLifetime LT = T.getQualifiers().getObjCLifetime();1082 if (LT != Qualifiers::OCL_Strong && LT != Qualifiers::OCL_Weak)1083 data().HasTrivialSpecialMembersForCall = 0;1084 1085 // Structs with __weak fields should never be passed directly.1086 if (LT == Qualifiers::OCL_Weak)1087 setArgPassingRestrictions(RecordArgPassingKind::CanNeverPassInRegs);1088 1089 Data.HasIrrelevantDestructor = false;1090 1091 if (isUnion()) {1092 data().DefaultedCopyConstructorIsDeleted = true;1093 data().DefaultedMoveConstructorIsDeleted = true;1094 data().DefaultedCopyAssignmentIsDeleted = true;1095 data().DefaultedMoveAssignmentIsDeleted = true;1096 data().DefaultedDestructorIsDeleted = true;1097 data().NeedOverloadResolutionForCopyConstructor = true;1098 data().NeedOverloadResolutionForMoveConstructor = true;1099 data().NeedOverloadResolutionForCopyAssignment = true;1100 data().NeedOverloadResolutionForMoveAssignment = true;1101 data().NeedOverloadResolutionForDestructor = true;1102 }1103 } else if (!Context.getLangOpts().ObjCAutoRefCount) {1104 setHasObjectMember(true);1105 }1106 } else if (!T.isCXX98PODType(Context))1107 data().PlainOldData = false;1108 1109 // If a class has an address-discriminated signed pointer member, it is a1110 // non-POD type and its copy constructor, move constructor, copy assignment1111 // operator, move assignment operator are non-trivial.1112 if (PointerAuthQualifier Q = T.getPointerAuth()) {1113 if (Q.isAddressDiscriminated()) {1114 struct DefinitionData &Data = data();1115 Data.PlainOldData = false;1116 Data.HasTrivialSpecialMembers &=1117 ~(SMF_CopyConstructor | SMF_MoveConstructor | SMF_CopyAssignment |1118 SMF_MoveAssignment);1119 setArgPassingRestrictions(RecordArgPassingKind::CanNeverPassInRegs);1120 1121 // Copy/move constructors/assignment operators of a union are deleted by1122 // default if it has an address-discriminated ptrauth field.1123 if (isUnion()) {1124 data().DefaultedCopyConstructorIsDeleted = true;1125 data().DefaultedMoveConstructorIsDeleted = true;1126 data().DefaultedCopyAssignmentIsDeleted = true;1127 data().DefaultedMoveAssignmentIsDeleted = true;1128 data().NeedOverloadResolutionForCopyConstructor = true;1129 data().NeedOverloadResolutionForMoveConstructor = true;1130 data().NeedOverloadResolutionForCopyAssignment = true;1131 data().NeedOverloadResolutionForMoveAssignment = true;1132 }1133 }1134 }1135 1136 if (Field->hasAttr<ExplicitInitAttr>())1137 setHasUninitializedExplicitInitFields(true);1138 1139 if (T->isReferenceType()) {1140 if (!Field->hasInClassInitializer())1141 data().HasUninitializedReferenceMember = true;1142 1143 // C++0x [class]p7:1144 // A standard-layout class is a class that:1145 // -- has no non-static data members of type [...] reference,1146 data().IsStandardLayout = false;1147 data().IsCXX11StandardLayout = false;1148 1149 // C++1z [class.copy.ctor]p10:1150 // A defaulted copy constructor for a class X is defined as deleted if X has:1151 // -- a non-static data member of rvalue reference type1152 if (T->isRValueReferenceType())1153 data().DefaultedCopyConstructorIsDeleted = true;1154 }1155 1156 if (isUnion() && !Field->isMutable()) {1157 if (Field->hasInClassInitializer())1158 data().HasUninitializedFields = false;1159 } else if (!Field->hasInClassInitializer() && !Field->isMutable()) {1160 if (CXXRecordDecl *FieldType = T->getAsCXXRecordDecl()) {1161 if (FieldType->hasDefinition() && !FieldType->allowConstDefaultInit())1162 data().HasUninitializedFields = true;1163 } else {1164 data().HasUninitializedFields = true;1165 }1166 }1167 1168 // Record if this field is the first non-literal or volatile field or base.1169 if (!T->isLiteralType(Context) || T.isVolatileQualified())1170 data().HasNonLiteralTypeFieldsOrBases = true;1171 1172 if (Field->hasInClassInitializer() ||1173 (Field->isAnonymousStructOrUnion() &&1174 Field->getType()->getAsCXXRecordDecl()->hasInClassInitializer())) {1175 data().HasInClassInitializer = true;1176 1177 // C++11 [class]p5:1178 // A default constructor is trivial if [...] no non-static data member1179 // of its class has a brace-or-equal-initializer.1180 data().HasTrivialSpecialMembers &= ~SMF_DefaultConstructor;1181 1182 // C++11 [dcl.init.aggr]p1:1183 // An aggregate is a [...] class with [...] no1184 // brace-or-equal-initializers for non-static data members.1185 //1186 // This rule was removed in C++14.1187 if (!getASTContext().getLangOpts().CPlusPlus14)1188 data().Aggregate = false;1189 1190 // C++11 [class]p10:1191 // A POD struct is [...] a trivial class.1192 data().PlainOldData = false;1193 }1194 1195 // C++11 [class.copy]p23:1196 // A defaulted copy/move assignment operator for a class X is defined1197 // as deleted if X has:1198 // -- a non-static data member of reference type1199 if (T->isReferenceType()) {1200 data().DefaultedCopyAssignmentIsDeleted = true;1201 data().DefaultedMoveAssignmentIsDeleted = true;1202 }1203 1204 // Bitfields of length 0 are also zero-sized, but we already bailed out for1205 // those because they are always unnamed.1206 bool IsZeroSize = Field->isZeroSize(Context);1207 1208 if (auto *FieldRec = T->getAsCXXRecordDecl()) {1209 if (FieldRec->isBeingDefined() || FieldRec->isCompleteDefinition()) {1210 addedClassSubobject(FieldRec);1211 1212 // We may need to perform overload resolution to determine whether a1213 // field can be moved if it's const or volatile qualified.1214 if (T.getCVRQualifiers() & (Qualifiers::Const | Qualifiers::Volatile)) {1215 // We need to care about 'const' for the copy constructor because an1216 // implicit copy constructor might be declared with a non-const1217 // parameter.1218 data().NeedOverloadResolutionForCopyConstructor = true;1219 data().NeedOverloadResolutionForMoveConstructor = true;1220 data().NeedOverloadResolutionForCopyAssignment = true;1221 data().NeedOverloadResolutionForMoveAssignment = true;1222 }1223 1224 // C++11 [class.ctor]p5, C++11 [class.copy]p11:1225 // A defaulted [special member] for a class X is defined as1226 // deleted if:1227 // -- X is a union-like class that has a variant member with a1228 // non-trivial [corresponding special member]1229 if (isUnion()) {1230 if (FieldRec->hasNonTrivialCopyConstructor())1231 data().DefaultedCopyConstructorIsDeleted = true;1232 if (FieldRec->hasNonTrivialMoveConstructor())1233 data().DefaultedMoveConstructorIsDeleted = true;1234 if (FieldRec->hasNonTrivialCopyAssignment())1235 data().DefaultedCopyAssignmentIsDeleted = true;1236 if (FieldRec->hasNonTrivialMoveAssignment())1237 data().DefaultedMoveAssignmentIsDeleted = true;1238 if (FieldRec->hasNonTrivialDestructor()) {1239 data().DefaultedDestructorIsDeleted = true;1240 // C++20 [dcl.constexpr]p5:1241 // The definition of a constexpr destructor whose function-body is1242 // not = delete shall additionally satisfy...1243 data().DefaultedDestructorIsConstexpr = true;1244 }1245 }1246 1247 // For an anonymous union member, our overload resolution will perform1248 // overload resolution for its members.1249 if (Field->isAnonymousStructOrUnion()) {1250 data().NeedOverloadResolutionForCopyConstructor |=1251 FieldRec->data().NeedOverloadResolutionForCopyConstructor;1252 data().NeedOverloadResolutionForMoveConstructor |=1253 FieldRec->data().NeedOverloadResolutionForMoveConstructor;1254 data().NeedOverloadResolutionForCopyAssignment |=1255 FieldRec->data().NeedOverloadResolutionForCopyAssignment;1256 data().NeedOverloadResolutionForMoveAssignment |=1257 FieldRec->data().NeedOverloadResolutionForMoveAssignment;1258 data().NeedOverloadResolutionForDestructor |=1259 FieldRec->data().NeedOverloadResolutionForDestructor;1260 }1261 1262 // C++0x [class.ctor]p5:1263 // A default constructor is trivial [...] if:1264 // -- for all the non-static data members of its class that are of1265 // class type (or array thereof), each such class has a trivial1266 // default constructor.1267 if (!FieldRec->hasTrivialDefaultConstructor())1268 data().HasTrivialSpecialMembers &= ~SMF_DefaultConstructor;1269 1270 // C++0x [class.copy]p13:1271 // A copy/move constructor for class X is trivial if [...]1272 // [...]1273 // -- for each non-static data member of X that is of class type (or1274 // an array thereof), the constructor selected to copy/move that1275 // member is trivial;1276 if (!FieldRec->hasTrivialCopyConstructor())1277 data().HasTrivialSpecialMembers &= ~SMF_CopyConstructor;1278 1279 if (!FieldRec->hasTrivialCopyConstructorForCall())1280 data().HasTrivialSpecialMembersForCall &= ~SMF_CopyConstructor;1281 1282 // If the field doesn't have a simple move constructor, we'll eagerly1283 // declare the move constructor for this class and we'll decide whether1284 // it's trivial then.1285 if (!FieldRec->hasTrivialMoveConstructor())1286 data().HasTrivialSpecialMembers &= ~SMF_MoveConstructor;1287 1288 if (!FieldRec->hasTrivialMoveConstructorForCall())1289 data().HasTrivialSpecialMembersForCall &= ~SMF_MoveConstructor;1290 1291 // C++0x [class.copy]p27:1292 // A copy/move assignment operator for class X is trivial if [...]1293 // [...]1294 // -- for each non-static data member of X that is of class type (or1295 // an array thereof), the assignment operator selected to1296 // copy/move that member is trivial;1297 if (!FieldRec->hasTrivialCopyAssignment())1298 data().HasTrivialSpecialMembers &= ~SMF_CopyAssignment;1299 // If the field doesn't have a simple move assignment, we'll eagerly1300 // declare the move assignment for this class and we'll decide whether1301 // it's trivial then.1302 if (!FieldRec->hasTrivialMoveAssignment())1303 data().HasTrivialSpecialMembers &= ~SMF_MoveAssignment;1304 1305 if (!FieldRec->hasTrivialDestructor())1306 data().HasTrivialSpecialMembers &= ~SMF_Destructor;1307 if (!FieldRec->hasTrivialDestructorForCall())1308 data().HasTrivialSpecialMembersForCall &= ~SMF_Destructor;1309 if (!FieldRec->hasIrrelevantDestructor())1310 data().HasIrrelevantDestructor = false;1311 if (FieldRec->isAnyDestructorNoReturn())1312 data().IsAnyDestructorNoReturn = true;1313 if (FieldRec->hasObjectMember())1314 setHasObjectMember(true);1315 if (FieldRec->hasVolatileMember())1316 setHasVolatileMember(true);1317 if (FieldRec->getArgPassingRestrictions() ==1318 RecordArgPassingKind::CanNeverPassInRegs)1319 setArgPassingRestrictions(RecordArgPassingKind::CanNeverPassInRegs);1320 1321 // C++0x [class]p7:1322 // A standard-layout class is a class that:1323 // -- has no non-static data members of type non-standard-layout1324 // class (or array of such types) [...]1325 if (!FieldRec->isStandardLayout())1326 data().IsStandardLayout = false;1327 if (!FieldRec->isCXX11StandardLayout())1328 data().IsCXX11StandardLayout = false;1329 1330 // C++2a [class]p7:1331 // A standard-layout class is a class that:1332 // [...]1333 // -- has no element of the set M(S) of types as a base class.1334 if (data().IsStandardLayout &&1335 (isUnion() || IsFirstField || IsZeroSize) &&1336 hasSubobjectAtOffsetZeroOfEmptyBaseType(Context, FieldRec))1337 data().IsStandardLayout = false;1338 1339 // C++11 [class]p7:1340 // A standard-layout class is a class that:1341 // -- has no base classes of the same type as the first non-static1342 // data member1343 if (data().IsCXX11StandardLayout && IsFirstField) {1344 // FIXME: We should check all base classes here, not just direct1345 // base classes.1346 for (const auto &BI : bases()) {1347 if (Context.hasSameUnqualifiedType(BI.getType(), T)) {1348 data().IsCXX11StandardLayout = false;1349 break;1350 }1351 }1352 }1353 1354 // Keep track of the presence of mutable fields.1355 if (FieldRec->hasMutableFields())1356 data().HasMutableFields = true;1357 1358 if (Field->isMutable()) {1359 // Our copy constructor/assignment might call something other than1360 // the subobject's copy constructor/assignment if it's mutable and of1361 // class type.1362 data().NeedOverloadResolutionForCopyConstructor = true;1363 data().NeedOverloadResolutionForCopyAssignment = true;1364 }1365 1366 // C++11 [class.copy]p13:1367 // If the implicitly-defined constructor would satisfy the1368 // requirements of a constexpr constructor, the implicitly-defined1369 // constructor is constexpr.1370 // C++11 [dcl.constexpr]p4:1371 // -- every constructor involved in initializing non-static data1372 // members [...] shall be a constexpr constructor1373 if (!Field->hasInClassInitializer() &&1374 !FieldRec->hasConstexprDefaultConstructor() && !isUnion())1375 // The standard requires any in-class initializer to be a constant1376 // expression. We consider this to be a defect.1377 data().DefaultedDefaultConstructorIsConstexpr =1378 Context.getLangOpts().CPlusPlus23;1379 1380 // C++11 [class.copy]p8:1381 // The implicitly-declared copy constructor for a class X will have1382 // the form 'X::X(const X&)' if each potentially constructed subobject1383 // of a class type M (or array thereof) has a copy constructor whose1384 // first parameter is of type 'const M&' or 'const volatile M&'.1385 if (!FieldRec->hasCopyConstructorWithConstParam())1386 data().ImplicitCopyConstructorCanHaveConstParamForNonVBase = false;1387 1388 // C++11 [class.copy]p18:1389 // The implicitly-declared copy assignment oeprator for a class X will1390 // have the form 'X& X::operator=(const X&)' if [...] for all the1391 // non-static data members of X that are of a class type M (or array1392 // thereof), each such class type has a copy assignment operator whose1393 // parameter is of type 'const M&', 'const volatile M&' or 'M'.1394 if (!FieldRec->hasCopyAssignmentWithConstParam())1395 data().ImplicitCopyAssignmentHasConstParam = false;1396 1397 if (FieldRec->hasUninitializedExplicitInitFields() &&1398 FieldRec->isAggregate())1399 setHasUninitializedExplicitInitFields(true);1400 1401 if (FieldRec->hasUninitializedReferenceMember() &&1402 !Field->hasInClassInitializer())1403 data().HasUninitializedReferenceMember = true;1404 1405 // C++11 [class.union]p8, DR1460:1406 // a non-static data member of an anonymous union that is a member of1407 // X is also a variant member of X.1408 if (FieldRec->hasVariantMembers() &&1409 Field->isAnonymousStructOrUnion())1410 data().HasVariantMembers = true;1411 }1412 } else {1413 // Base element type of field is a non-class type.1414 if (!T->isLiteralType(Context) ||1415 (!Field->hasInClassInitializer() && !isUnion() &&1416 !Context.getLangOpts().CPlusPlus20))1417 data().DefaultedDefaultConstructorIsConstexpr = false;1418 1419 // C++11 [class.copy]p23:1420 // A defaulted copy/move assignment operator for a class X is defined1421 // as deleted if X has:1422 // -- a non-static data member of const non-class type (or array1423 // thereof)1424 if (T.isConstQualified()) {1425 data().DefaultedCopyAssignmentIsDeleted = true;1426 data().DefaultedMoveAssignmentIsDeleted = true;1427 }1428 1429 // C++20 [temp.param]p7:1430 // A structural type is [...] a literal class type [for which] the1431 // types of all non-static data members are structural types or1432 // (possibly multidimensional) array thereof1433 // We deal with class types elsewhere.1434 if (!T->isStructuralType())1435 data().StructuralIfLiteral = false;1436 }1437 1438 // If this type contains any address discriminated values we should1439 // have already indicated that the only special member functions that1440 // can possibly be trivial are the default constructor and destructor.1441 if (T.hasAddressDiscriminatedPointerAuth())1442 data().HasTrivialSpecialMembers &=1443 SMF_DefaultConstructor | SMF_Destructor;1444 1445 // C++14 [meta.unary.prop]p4:1446 // T is a class type [...] with [...] no non-static data members other1447 // than subobjects of zero size1448 if (data().Empty && !IsZeroSize)1449 data().Empty = false;1450 1451 if (getLangOpts().HLSL) {1452 const Type *Ty = Field->getType()->getUnqualifiedDesugaredType();1453 while (isa<ConstantArrayType>(Ty))1454 Ty = Ty->getArrayElementTypeNoTypeQual();1455 1456 Ty = Ty->getUnqualifiedDesugaredType();1457 if (const RecordType *RT = dyn_cast<RecordType>(Ty))1458 data().IsHLSLIntangible |= RT->getAsCXXRecordDecl()->isHLSLIntangible();1459 else1460 data().IsHLSLIntangible |= (Ty->isHLSLAttributedResourceType() ||1461 Ty->isHLSLBuiltinIntangibleType());1462 }1463 }1464 1465 // Handle using declarations of conversion functions.1466 if (auto *Shadow = dyn_cast<UsingShadowDecl>(D)) {1467 if (Shadow->getDeclName().getNameKind()1468 == DeclarationName::CXXConversionFunctionName) {1469 ASTContext &Ctx = getASTContext();1470 data().Conversions.get(Ctx).addDecl(Ctx, Shadow, Shadow->getAccess());1471 }1472 }1473 1474 if (const auto *Using = dyn_cast<UsingDecl>(D)) {1475 if (Using->getDeclName().getNameKind() ==1476 DeclarationName::CXXConstructorName) {1477 data().HasInheritedConstructor = true;1478 // C++1z [dcl.init.aggr]p1:1479 // An aggregate is [...] a class [...] with no inherited constructors1480 data().Aggregate = false;1481 }1482 1483 if (Using->getDeclName().getCXXOverloadedOperator() == OO_Equal)1484 data().HasInheritedAssignment = true;1485 }1486 1487 // HLSL: All user-defined data types are aggregates and use aggregate1488 // initialization, meanwhile most, but not all built-in types behave like1489 // aggregates. Resource types, and some other HLSL types that wrap handles1490 // don't behave like aggregates. We can identify these as different because we1491 // implicitly define "special" member functions, which aren't spellable in1492 // HLSL. This all _needs_ to change in the future. There are two1493 // relevant HLSL feature proposals that will depend on this changing:1494 // * 0005-strict-initializer-lists.md1495 // * https://github.com/microsoft/hlsl-specs/pull/3251496 if (getLangOpts().HLSL)1497 data().Aggregate = data().UserDeclaredSpecialMembers == 0;1498}1499 1500bool CXXRecordDecl::isLiteral() const {1501 const LangOptions &LangOpts = getLangOpts();1502 if (!(LangOpts.CPlusPlus20 ? hasConstexprDestructor()1503 : hasTrivialDestructor()))1504 return false;1505 1506 if (hasNonLiteralTypeFieldsOrBases()) {1507 // CWG25981508 // is an aggregate union type that has either no variant1509 // members or at least one variant member of non-volatile literal type,1510 if (!isUnion())1511 return false;1512 bool HasAtLeastOneLiteralMember =1513 fields().empty() || any_of(fields(), [this](const FieldDecl *D) {1514 return !D->getType().isVolatileQualified() &&1515 D->getType()->isLiteralType(getASTContext());1516 });1517 if (!HasAtLeastOneLiteralMember)1518 return false;1519 }1520 1521 return isAggregate() || (isLambda() && LangOpts.CPlusPlus17) ||1522 hasConstexprNonCopyMoveConstructor() || hasTrivialDefaultConstructor();1523}1524 1525void CXXRecordDecl::addedSelectedDestructor(CXXDestructorDecl *DD) {1526 DD->setIneligibleOrNotSelected(false);1527 addedEligibleSpecialMemberFunction(DD, SMF_Destructor);1528}1529 1530void CXXRecordDecl::addedEligibleSpecialMemberFunction(const CXXMethodDecl *MD,1531 unsigned SMKind) {1532 // FIXME: We shouldn't change DeclaredNonTrivialSpecialMembers if `MD` is1533 // a function template, but this needs CWG attention before we break ABI.1534 // See https://github.com/llvm/llvm-project/issues/592061535 1536 if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD)) {1537 if (DD->isUserProvided())1538 data().HasIrrelevantDestructor = false;1539 // If the destructor is explicitly defaulted and not trivial or not public1540 // or if the destructor is deleted, we clear HasIrrelevantDestructor in1541 // finishedDefaultedOrDeletedMember.1542 1543 // C++11 [class.dtor]p5:1544 // A destructor is trivial if [...] the destructor is not virtual.1545 if (DD->isVirtual()) {1546 data().HasTrivialSpecialMembers &= ~SMF_Destructor;1547 data().HasTrivialSpecialMembersForCall &= ~SMF_Destructor;1548 }1549 1550 if (DD->isNoReturn())1551 data().IsAnyDestructorNoReturn = true;1552 }1553 if (!MD->isImplicit() && !MD->isUserProvided()) {1554 // This method is user-declared but not user-provided. We can't work1555 // out whether it's trivial yet (not until we get to the end of the1556 // class). We'll handle this method in1557 // finishedDefaultedOrDeletedMember.1558 } else if (MD->isTrivial()) {1559 data().HasTrivialSpecialMembers |= SMKind;1560 data().HasTrivialSpecialMembersForCall |= SMKind;1561 } else if (MD->isTrivialForCall()) {1562 data().HasTrivialSpecialMembersForCall |= SMKind;1563 data().DeclaredNonTrivialSpecialMembers |= SMKind;1564 } else {1565 data().DeclaredNonTrivialSpecialMembers |= SMKind;1566 // If this is a user-provided function, do not set1567 // DeclaredNonTrivialSpecialMembersForCall here since we don't know1568 // yet whether the method would be considered non-trivial for the1569 // purpose of calls (attribute "trivial_abi" can be dropped from the1570 // class later, which can change the special method's triviality).1571 if (!MD->isUserProvided())1572 data().DeclaredNonTrivialSpecialMembersForCall |= SMKind;1573 }1574}1575 1576void CXXRecordDecl::finishedDefaultedOrDeletedMember(CXXMethodDecl *D) {1577 assert(!D->isImplicit() && !D->isUserProvided());1578 1579 // The kind of special member this declaration is, if any.1580 unsigned SMKind = 0;1581 1582 if (const auto *Constructor = dyn_cast<CXXConstructorDecl>(D)) {1583 if (Constructor->isDefaultConstructor()) {1584 SMKind |= SMF_DefaultConstructor;1585 if (Constructor->isConstexpr())1586 data().HasConstexprDefaultConstructor = true;1587 }1588 if (Constructor->isCopyConstructor())1589 SMKind |= SMF_CopyConstructor;1590 else if (Constructor->isMoveConstructor())1591 SMKind |= SMF_MoveConstructor;1592 else if (Constructor->isConstexpr())1593 // We may now know that the constructor is constexpr.1594 data().HasConstexprNonCopyMoveConstructor = true;1595 } else if (isa<CXXDestructorDecl>(D)) {1596 SMKind |= SMF_Destructor;1597 if (!D->isTrivial() || D->getAccess() != AS_public || D->isDeleted())1598 data().HasIrrelevantDestructor = false;1599 } else if (D->isCopyAssignmentOperator())1600 SMKind |= SMF_CopyAssignment;1601 else if (D->isMoveAssignmentOperator())1602 SMKind |= SMF_MoveAssignment;1603 1604 // Update which trivial / non-trivial special members we have.1605 // addedMember will have skipped this step for this member.1606 if (!D->isIneligibleOrNotSelected()) {1607 if (D->isTrivial())1608 data().HasTrivialSpecialMembers |= SMKind;1609 else1610 data().DeclaredNonTrivialSpecialMembers |= SMKind;1611 }1612}1613 1614void CXXRecordDecl::LambdaDefinitionData::AddCaptureList(ASTContext &Ctx,1615 Capture *CaptureList) {1616 Captures.push_back(CaptureList);1617 if (Captures.size() == 2) {1618 // The TinyPtrVector member now needs destruction.1619 Ctx.addDestruction(&Captures);1620 }1621}1622 1623void CXXRecordDecl::setCaptures(ASTContext &Context,1624 ArrayRef<LambdaCapture> Captures) {1625 CXXRecordDecl::LambdaDefinitionData &Data = getLambdaData();1626 1627 // Copy captures.1628 Data.NumCaptures = Captures.size();1629 Data.NumExplicitCaptures = 0;1630 auto *ToCapture = (LambdaCapture *)Context.Allocate(sizeof(LambdaCapture) *1631 Captures.size());1632 Data.AddCaptureList(Context, ToCapture);1633 for (const LambdaCapture &C : Captures) {1634 if (C.isExplicit())1635 ++Data.NumExplicitCaptures;1636 1637 new (ToCapture) LambdaCapture(C);1638 ToCapture++;1639 }1640 1641 if (!lambdaIsDefaultConstructibleAndAssignable())1642 Data.DefaultedCopyAssignmentIsDeleted = true;1643}1644 1645void CXXRecordDecl::setTrivialForCallFlags(CXXMethodDecl *D) {1646 unsigned SMKind = 0;1647 1648 if (const auto *Constructor = dyn_cast<CXXConstructorDecl>(D)) {1649 if (Constructor->isCopyConstructor())1650 SMKind = SMF_CopyConstructor;1651 else if (Constructor->isMoveConstructor())1652 SMKind = SMF_MoveConstructor;1653 } else if (isa<CXXDestructorDecl>(D))1654 SMKind = SMF_Destructor;1655 1656 if (D->isTrivialForCall())1657 data().HasTrivialSpecialMembersForCall |= SMKind;1658 else1659 data().DeclaredNonTrivialSpecialMembersForCall |= SMKind;1660}1661 1662bool CXXRecordDecl::isCLike() const {1663 if (getTagKind() == TagTypeKind::Class ||1664 getTagKind() == TagTypeKind::Interface ||1665 !TemplateOrInstantiation.isNull())1666 return false;1667 if (!hasDefinition())1668 return true;1669 1670 return isPOD() && data().HasOnlyCMembers;1671}1672 1673bool CXXRecordDecl::isGenericLambda() const {1674 if (!isLambda()) return false;1675 return getLambdaData().IsGenericLambda;1676}1677 1678#ifndef NDEBUG1679static bool allLookupResultsAreTheSame(const DeclContext::lookup_result &R) {1680 return llvm::all_of(R, [&](NamedDecl *D) {1681 return D->isInvalidDecl() || declaresSameEntity(D, R.front());1682 });1683}1684#endif1685 1686static NamedDecl* getLambdaCallOperatorHelper(const CXXRecordDecl &RD) {1687 if (!RD.isLambda()) return nullptr;1688 DeclarationName Name =1689 RD.getASTContext().DeclarationNames.getCXXOperatorName(OO_Call);1690 1691 DeclContext::lookup_result Calls = RD.lookup(Name);1692 1693 // This can happen while building the lambda.1694 if (Calls.empty())1695 return nullptr;1696 1697 assert(allLookupResultsAreTheSame(Calls) &&1698 "More than one lambda call operator!");1699 1700 // FIXME: If we have multiple call operators, we might be in a situation1701 // where we merged this lambda with one from another module; in that1702 // case, return our method (instead of that of the other lambda).1703 //1704 // This avoids situations where, given two modules A and B, if we1705 // try to instantiate A's call operator in a function in B, anything1706 // in the call operator that relies on local decls in the surrounding1707 // function will crash because it tries to find A's decls, but we only1708 // instantiated B's:1709 //1710 // template <typename>1711 // void f() {1712 // using T = int; // We only instantiate B's version of this.1713 // auto L = [](T) { }; // But A's call operator would want A's here.1714 // }1715 //1716 // Walk the call operator’s redecl chain to find the one that belongs1717 // to this module.1718 //1719 // TODO: We need to fix this properly (see1720 // https://github.com/llvm/llvm-project/issues/90154).1721 Module *M = RD.getOwningModule();1722 for (Decl *D : Calls.front()->redecls()) {1723 auto *MD = cast<NamedDecl>(D);1724 if (MD->getOwningModule() == M)1725 return MD;1726 }1727 1728 llvm_unreachable("Couldn't find our call operator!");1729}1730 1731FunctionTemplateDecl* CXXRecordDecl::getDependentLambdaCallOperator() const {1732 NamedDecl *CallOp = getLambdaCallOperatorHelper(*this);1733 return dyn_cast_or_null<FunctionTemplateDecl>(CallOp);1734}1735 1736CXXMethodDecl *CXXRecordDecl::getLambdaCallOperator() const {1737 NamedDecl *CallOp = getLambdaCallOperatorHelper(*this);1738 1739 if (CallOp == nullptr)1740 return nullptr;1741 1742 if (const auto *CallOpTmpl = dyn_cast<FunctionTemplateDecl>(CallOp))1743 return cast<CXXMethodDecl>(CallOpTmpl->getTemplatedDecl());1744 1745 return cast<CXXMethodDecl>(CallOp);1746}1747 1748CXXMethodDecl* CXXRecordDecl::getLambdaStaticInvoker() const {1749 CXXMethodDecl *CallOp = getLambdaCallOperator();1750 assert(CallOp && "null call operator");1751 CallingConv CC = CallOp->getType()->castAs<FunctionType>()->getCallConv();1752 return getLambdaStaticInvoker(CC);1753}1754 1755static DeclContext::lookup_result1756getLambdaStaticInvokers(const CXXRecordDecl &RD) {1757 assert(RD.isLambda() && "Must be a lambda");1758 DeclarationName Name =1759 &RD.getASTContext().Idents.get(getLambdaStaticInvokerName());1760 return RD.lookup(Name);1761}1762 1763static CXXMethodDecl *getInvokerAsMethod(NamedDecl *ND) {1764 if (const auto *InvokerTemplate = dyn_cast<FunctionTemplateDecl>(ND))1765 return cast<CXXMethodDecl>(InvokerTemplate->getTemplatedDecl());1766 return cast<CXXMethodDecl>(ND);1767}1768 1769CXXMethodDecl *CXXRecordDecl::getLambdaStaticInvoker(CallingConv CC) const {1770 if (!isLambda())1771 return nullptr;1772 DeclContext::lookup_result Invoker = getLambdaStaticInvokers(*this);1773 1774 for (NamedDecl *ND : Invoker) {1775 const auto *FTy =1776 cast<ValueDecl>(ND->getAsFunction())->getType()->castAs<FunctionType>();1777 if (FTy->getCallConv() == CC)1778 return getInvokerAsMethod(ND);1779 }1780 1781 return nullptr;1782}1783 1784void CXXRecordDecl::getCaptureFields(1785 llvm::DenseMap<const ValueDecl *, FieldDecl *> &Captures,1786 FieldDecl *&ThisCapture) const {1787 Captures.clear();1788 ThisCapture = nullptr;1789 1790 LambdaDefinitionData &Lambda = getLambdaData();1791 for (const LambdaCapture *List : Lambda.Captures) {1792 RecordDecl::field_iterator Field = field_begin();1793 for (const LambdaCapture *C = List, *CEnd = C + Lambda.NumCaptures;1794 C != CEnd; ++C, ++Field) {1795 if (C->capturesThis())1796 ThisCapture = *Field;1797 else if (C->capturesVariable())1798 Captures[C->getCapturedVar()] = *Field;1799 }1800 assert(Field == field_end());1801 }1802}1803 1804TemplateParameterList *1805CXXRecordDecl::getGenericLambdaTemplateParameterList() const {1806 if (!isGenericLambda()) return nullptr;1807 CXXMethodDecl *CallOp = getLambdaCallOperator();1808 if (FunctionTemplateDecl *Tmpl = CallOp->getDescribedFunctionTemplate())1809 return Tmpl->getTemplateParameters();1810 return nullptr;1811}1812 1813ArrayRef<NamedDecl *>1814CXXRecordDecl::getLambdaExplicitTemplateParameters() const {1815 TemplateParameterList *List = getGenericLambdaTemplateParameterList();1816 if (!List)1817 return {};1818 1819 assert(std::is_partitioned(List->begin(), List->end(),1820 [](const NamedDecl *D) { return !D->isImplicit(); })1821 && "Explicit template params should be ordered before implicit ones");1822 1823 const auto ExplicitEnd = llvm::partition_point(1824 *List, [](const NamedDecl *D) { return !D->isImplicit(); });1825 return ArrayRef(List->begin(), ExplicitEnd);1826}1827 1828Decl *CXXRecordDecl::getLambdaContextDecl() const {1829 assert(isLambda() && "Not a lambda closure type!");1830 ExternalASTSource *Source = getParentASTContext().getExternalSource();1831 return getLambdaData().ContextDecl.get(Source);1832}1833 1834void CXXRecordDecl::setLambdaNumbering(LambdaNumbering Numbering) {1835 assert(isLambda() && "Not a lambda closure type!");1836 getLambdaData().ManglingNumber = Numbering.ManglingNumber;1837 if (Numbering.DeviceManglingNumber)1838 getASTContext().DeviceLambdaManglingNumbers[this] =1839 Numbering.DeviceManglingNumber;1840 getLambdaData().IndexInContext = Numbering.IndexInContext;1841 getLambdaData().ContextDecl = Numbering.ContextDecl;1842 getLambdaData().HasKnownInternalLinkage = Numbering.HasKnownInternalLinkage;1843}1844 1845unsigned CXXRecordDecl::getDeviceLambdaManglingNumber() const {1846 assert(isLambda() && "Not a lambda closure type!");1847 return getASTContext().DeviceLambdaManglingNumbers.lookup(this);1848}1849 1850static CanQualType GetConversionType(ASTContext &Context, NamedDecl *Conv) {1851 QualType T =1852 cast<CXXConversionDecl>(Conv->getUnderlyingDecl()->getAsFunction())1853 ->getConversionType();1854 return Context.getCanonicalType(T);1855}1856 1857/// Collect the visible conversions of a base class.1858///1859/// \param Record a base class of the class we're considering1860/// \param InVirtual whether this base class is a virtual base (or a base1861/// of a virtual base)1862/// \param Access the access along the inheritance path to this base1863/// \param ParentHiddenTypes the conversions provided by the inheritors1864/// of this base1865/// \param Output the set to which to add conversions from non-virtual bases1866/// \param VOutput the set to which to add conversions from virtual bases1867/// \param HiddenVBaseCs the set of conversions which were hidden in a1868/// virtual base along some inheritance path1869static void CollectVisibleConversions(1870 ASTContext &Context, const CXXRecordDecl *Record, bool InVirtual,1871 AccessSpecifier Access,1872 const llvm::SmallPtrSet<CanQualType, 8> &ParentHiddenTypes,1873 ASTUnresolvedSet &Output, UnresolvedSetImpl &VOutput,1874 llvm::SmallPtrSet<NamedDecl *, 8> &HiddenVBaseCs) {1875 // The set of types which have conversions in this class or its1876 // subclasses. As an optimization, we don't copy the derived set1877 // unless it might change.1878 const llvm::SmallPtrSet<CanQualType, 8> *HiddenTypes = &ParentHiddenTypes;1879 llvm::SmallPtrSet<CanQualType, 8> HiddenTypesBuffer;1880 1881 // Collect the direct conversions and figure out which conversions1882 // will be hidden in the subclasses.1883 CXXRecordDecl::conversion_iterator ConvI = Record->conversion_begin();1884 CXXRecordDecl::conversion_iterator ConvE = Record->conversion_end();1885 if (ConvI != ConvE) {1886 HiddenTypesBuffer = ParentHiddenTypes;1887 HiddenTypes = &HiddenTypesBuffer;1888 1889 for (CXXRecordDecl::conversion_iterator I = ConvI; I != ConvE; ++I) {1890 CanQualType ConvType(GetConversionType(Context, I.getDecl()));1891 bool Hidden = ParentHiddenTypes.count(ConvType);1892 if (!Hidden)1893 HiddenTypesBuffer.insert(ConvType);1894 1895 // If this conversion is hidden and we're in a virtual base,1896 // remember that it's hidden along some inheritance path.1897 if (Hidden && InVirtual)1898 HiddenVBaseCs.insert(cast<NamedDecl>(I.getDecl()->getCanonicalDecl()));1899 1900 // If this conversion isn't hidden, add it to the appropriate output.1901 else if (!Hidden) {1902 AccessSpecifier IAccess1903 = CXXRecordDecl::MergeAccess(Access, I.getAccess());1904 1905 if (InVirtual)1906 VOutput.addDecl(I.getDecl(), IAccess);1907 else1908 Output.addDecl(Context, I.getDecl(), IAccess);1909 }1910 }1911 }1912 1913 // Collect information recursively from any base classes.1914 for (const auto &I : Record->bases()) {1915 const auto *Base = I.getType()->getAsCXXRecordDecl();1916 if (!Base)1917 continue;1918 1919 AccessSpecifier BaseAccess1920 = CXXRecordDecl::MergeAccess(Access, I.getAccessSpecifier());1921 bool BaseInVirtual = InVirtual || I.isVirtual();1922 1923 CollectVisibleConversions(Context, Base, BaseInVirtual, BaseAccess,1924 *HiddenTypes, Output, VOutput, HiddenVBaseCs);1925 }1926}1927 1928/// Collect the visible conversions of a class.1929///1930/// This would be extremely straightforward if it weren't for virtual1931/// bases. It might be worth special-casing that, really.1932static void CollectVisibleConversions(ASTContext &Context,1933 const CXXRecordDecl *Record,1934 ASTUnresolvedSet &Output) {1935 // The collection of all conversions in virtual bases that we've1936 // found. These will be added to the output as long as they don't1937 // appear in the hidden-conversions set.1938 UnresolvedSet<8> VBaseCs;1939 1940 // The set of conversions in virtual bases that we've determined to1941 // be hidden.1942 llvm::SmallPtrSet<NamedDecl*, 8> HiddenVBaseCs;1943 1944 // The set of types hidden by classes derived from this one.1945 llvm::SmallPtrSet<CanQualType, 8> HiddenTypes;1946 1947 // Go ahead and collect the direct conversions and add them to the1948 // hidden-types set.1949 CXXRecordDecl::conversion_iterator ConvI = Record->conversion_begin();1950 CXXRecordDecl::conversion_iterator ConvE = Record->conversion_end();1951 Output.append(Context, ConvI, ConvE);1952 for (; ConvI != ConvE; ++ConvI)1953 HiddenTypes.insert(GetConversionType(Context, ConvI.getDecl()));1954 1955 // Recursively collect conversions from base classes.1956 for (const auto &I : Record->bases()) {1957 const auto *Base = I.getType()->getAsCXXRecordDecl();1958 if (!Base)1959 continue;1960 1961 CollectVisibleConversions(Context, Base, I.isVirtual(),1962 I.getAccessSpecifier(), HiddenTypes, Output,1963 VBaseCs, HiddenVBaseCs);1964 }1965 1966 // Add any unhidden conversions provided by virtual bases.1967 for (UnresolvedSetIterator I = VBaseCs.begin(), E = VBaseCs.end();1968 I != E; ++I) {1969 if (!HiddenVBaseCs.count(cast<NamedDecl>(I.getDecl()->getCanonicalDecl())))1970 Output.addDecl(Context, I.getDecl(), I.getAccess());1971 }1972}1973 1974/// getVisibleConversionFunctions - get all conversion functions visible1975/// in current class; including conversion function templates.1976llvm::iterator_range<CXXRecordDecl::conversion_iterator>1977CXXRecordDecl::getVisibleConversionFunctions() const {1978 ASTContext &Ctx = getASTContext();1979 1980 ASTUnresolvedSet *Set;1981 if (bases().empty()) {1982 // If root class, all conversions are visible.1983 Set = &data().Conversions.get(Ctx);1984 } else {1985 Set = &data().VisibleConversions.get(Ctx);1986 // If visible conversion list is not evaluated, evaluate it.1987 if (!data().ComputedVisibleConversions) {1988 CollectVisibleConversions(Ctx, this, *Set);1989 data().ComputedVisibleConversions = true;1990 }1991 }1992 return llvm::make_range(Set->begin(), Set->end());1993}1994 1995void CXXRecordDecl::removeConversion(const NamedDecl *ConvDecl) {1996 // This operation is O(N) but extremely rare. Sema only uses it to1997 // remove UsingShadowDecls in a class that were followed by a direct1998 // declaration, e.g.:1999 // class A : B {2000 // using B::operator int;2001 // operator int();2002 // };2003 // This is uncommon by itself and even more uncommon in conjunction2004 // with sufficiently large numbers of directly-declared conversions2005 // that asymptotic behavior matters.2006 2007 ASTUnresolvedSet &Convs = data().Conversions.get(getASTContext());2008 for (unsigned I = 0, E = Convs.size(); I != E; ++I) {2009 if (Convs[I].getDecl() == ConvDecl) {2010 Convs.erase(I);2011 assert(!llvm::is_contained(Convs, ConvDecl) &&2012 "conversion was found multiple times in unresolved set");2013 return;2014 }2015 }2016 2017 llvm_unreachable("conversion not found in set!");2018}2019 2020CXXRecordDecl *CXXRecordDecl::getInstantiatedFromMemberClass() const {2021 if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo())2022 return cast<CXXRecordDecl>(MSInfo->getInstantiatedFrom());2023 2024 return nullptr;2025}2026 2027MemberSpecializationInfo *CXXRecordDecl::getMemberSpecializationInfo() const {2028 return dyn_cast_if_present<MemberSpecializationInfo *>(2029 TemplateOrInstantiation);2030}2031 2032void2033CXXRecordDecl::setInstantiationOfMemberClass(CXXRecordDecl *RD,2034 TemplateSpecializationKind TSK) {2035 assert(TemplateOrInstantiation.isNull() &&2036 "Previous template or instantiation?");2037 assert(!isa<ClassTemplatePartialSpecializationDecl>(this));2038 TemplateOrInstantiation2039 = new (getASTContext()) MemberSpecializationInfo(RD, TSK);2040}2041 2042ClassTemplateDecl *CXXRecordDecl::getDescribedClassTemplate() const {2043 return dyn_cast_if_present<ClassTemplateDecl *>(TemplateOrInstantiation);2044}2045 2046void CXXRecordDecl::setDescribedClassTemplate(ClassTemplateDecl *Template) {2047 TemplateOrInstantiation = Template;2048}2049 2050TemplateSpecializationKind CXXRecordDecl::getTemplateSpecializationKind() const{2051 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(this))2052 return Spec->getSpecializationKind();2053 2054 if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo())2055 return MSInfo->getTemplateSpecializationKind();2056 2057 return TSK_Undeclared;2058}2059 2060void2061CXXRecordDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK) {2062 if (auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(this)) {2063 Spec->setSpecializationKind(TSK);2064 return;2065 }2066 2067 if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo()) {2068 MSInfo->setTemplateSpecializationKind(TSK);2069 return;2070 }2071 2072 llvm_unreachable("Not a class template or member class specialization");2073}2074 2075const CXXRecordDecl *CXXRecordDecl::getTemplateInstantiationPattern() const {2076 auto GetDefinitionOrSelf =2077 [](const CXXRecordDecl *D) -> const CXXRecordDecl * {2078 if (auto *Def = D->getDefinition())2079 return Def;2080 return D;2081 };2082 2083 // If it's a class template specialization, find the template or partial2084 // specialization from which it was instantiated.2085 if (auto *TD = dyn_cast<ClassTemplateSpecializationDecl>(this)) {2086 auto From = TD->getInstantiatedFrom();2087 if (auto *CTD = dyn_cast_if_present<ClassTemplateDecl *>(From)) {2088 while (auto *NewCTD = CTD->getInstantiatedFromMemberTemplate()) {2089 if (NewCTD->isMemberSpecialization())2090 break;2091 CTD = NewCTD;2092 }2093 return GetDefinitionOrSelf(CTD->getTemplatedDecl());2094 }2095 if (auto *CTPSD =2096 dyn_cast_if_present<ClassTemplatePartialSpecializationDecl *>(2097 From)) {2098 while (auto *NewCTPSD = CTPSD->getInstantiatedFromMember()) {2099 if (NewCTPSD->isMemberSpecialization())2100 break;2101 CTPSD = NewCTPSD;2102 }2103 return GetDefinitionOrSelf(CTPSD);2104 }2105 }2106 2107 if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo()) {2108 if (isTemplateInstantiation(MSInfo->getTemplateSpecializationKind())) {2109 const CXXRecordDecl *RD = this;2110 while (auto *NewRD = RD->getInstantiatedFromMemberClass())2111 RD = NewRD;2112 return GetDefinitionOrSelf(RD);2113 }2114 }2115 2116 assert(!isTemplateInstantiation(this->getTemplateSpecializationKind()) &&2117 "couldn't find pattern for class template instantiation");2118 return nullptr;2119}2120 2121CXXDestructorDecl *CXXRecordDecl::getDestructor() const {2122 ASTContext &Context = getASTContext();2123 CanQualType ClassType = Context.getCanonicalTagType(this);2124 2125 DeclarationName Name =2126 Context.DeclarationNames.getCXXDestructorName(ClassType);2127 2128 DeclContext::lookup_result R = lookup(Name);2129 2130 // If a destructor was marked as not selected, we skip it. We don't always2131 // have a selected destructor: dependent types, unnamed structs.2132 for (auto *Decl : R) {2133 auto* DD = dyn_cast<CXXDestructorDecl>(Decl);2134 if (DD && !DD->isIneligibleOrNotSelected())2135 return DD;2136 }2137 return nullptr;2138}2139 2140bool CXXRecordDecl::hasDeletedDestructor() const {2141 if (const CXXDestructorDecl *D = getDestructor())2142 return D->isDeleted();2143 return false;2144}2145 2146bool CXXRecordDecl::isInjectedClassName() const {2147 if (!isImplicit() || !getDeclName())2148 return false;2149 2150 if (const auto *RD = dyn_cast<CXXRecordDecl>(getDeclContext()))2151 return RD->getDeclName() == getDeclName();2152 2153 return false;2154}2155 2156bool CXXRecordDecl::hasInjectedClassType() const {2157 switch (getDeclKind()) {2158 case Decl::ClassTemplatePartialSpecialization:2159 return true;2160 case Decl::ClassTemplateSpecialization:2161 return false;2162 case Decl::CXXRecord:2163 return getDescribedClassTemplate() != nullptr;2164 default:2165 llvm_unreachable("unexpected decl kind");2166 }2167}2168 2169CanQualType CXXRecordDecl::getCanonicalTemplateSpecializationType(2170 const ASTContext &Ctx) const {2171 if (auto *RD = dyn_cast<ClassTemplatePartialSpecializationDecl>(this))2172 return RD->getCanonicalInjectedSpecializationType(Ctx);2173 if (const ClassTemplateDecl *TD = getDescribedClassTemplate();2174 TD && !isa<ClassTemplateSpecializationDecl>(this))2175 return TD->getCanonicalInjectedSpecializationType(Ctx);2176 return CanQualType();2177}2178 2179static bool isDeclContextInNamespace(const DeclContext *DC) {2180 while (!DC->isTranslationUnit()) {2181 if (DC->isNamespace())2182 return true;2183 DC = DC->getParent();2184 }2185 return false;2186}2187 2188bool CXXRecordDecl::isInterfaceLike() const {2189 assert(hasDefinition() && "checking for interface-like without a definition");2190 // All __interfaces are inheritently interface-like.2191 if (isInterface())2192 return true;2193 2194 // Interface-like types cannot have a user declared constructor, destructor,2195 // friends, VBases, conversion functions, or fields. Additionally, lambdas2196 // cannot be interface types.2197 if (isLambda() || hasUserDeclaredConstructor() ||2198 hasUserDeclaredDestructor() || !field_empty() || hasFriends() ||2199 getNumVBases() > 0 || conversion_end() - conversion_begin() > 0)2200 return false;2201 2202 // No interface-like type can have a method with a definition.2203 for (const auto *const Method : methods())2204 if (Method->isDefined() && !Method->isImplicit())2205 return false;2206 2207 // Check "Special" types.2208 const auto *Uuid = getAttr<UuidAttr>();2209 // MS SDK declares IUnknown/IDispatch both in the root of a TU, or in an2210 // extern C++ block directly in the TU. These are only valid if in one2211 // of these two situations.2212 if (Uuid && isStruct() && !getDeclContext()->isExternCContext() &&2213 !isDeclContextInNamespace(getDeclContext()) &&2214 ((getName() == "IUnknown" &&2215 Uuid->getGuid() == "00000000-0000-0000-C000-000000000046") ||2216 (getName() == "IDispatch" &&2217 Uuid->getGuid() == "00020400-0000-0000-C000-000000000046"))) {2218 if (getNumBases() > 0)2219 return false;2220 return true;2221 }2222 2223 // FIXME: Any access specifiers is supposed to make this no longer interface2224 // like.2225 2226 // If this isn't a 'special' type, it must have a single interface-like base.2227 if (getNumBases() != 1)2228 return false;2229 2230 const auto BaseSpec = *bases_begin();2231 if (BaseSpec.isVirtual() || BaseSpec.getAccessSpecifier() != AS_public)2232 return false;2233 const auto *Base = BaseSpec.getType()->getAsCXXRecordDecl();2234 if (Base->isInterface() || !Base->isInterfaceLike())2235 return false;2236 return true;2237}2238 2239void CXXRecordDecl::completeDefinition() {2240 completeDefinition(nullptr);2241}2242 2243static bool hasPureVirtualFinalOverrider(2244 const CXXRecordDecl &RD, const CXXFinalOverriderMap *FinalOverriders) {2245 if (!FinalOverriders) {2246 CXXFinalOverriderMap MyFinalOverriders;2247 RD.getFinalOverriders(MyFinalOverriders);2248 return hasPureVirtualFinalOverrider(RD, &MyFinalOverriders);2249 }2250 2251 for (const CXXFinalOverriderMap::value_type &2252 OverridingMethodsEntry : *FinalOverriders) {2253 for (const auto &[_, SubobjOverrides] : OverridingMethodsEntry.second) {2254 assert(SubobjOverrides.size() > 0 &&2255 "All virtual functions have overriding virtual functions");2256 2257 if (SubobjOverrides.front().Method->isPureVirtual())2258 return true;2259 }2260 }2261 return false;2262}2263 2264void CXXRecordDecl::completeDefinition(CXXFinalOverriderMap *FinalOverriders) {2265 RecordDecl::completeDefinition();2266 2267 // If the class may be abstract (but hasn't been marked as such), check for2268 // any pure final overriders.2269 //2270 // C++ [class.abstract]p4:2271 // A class is abstract if it contains or inherits at least one2272 // pure virtual function for which the final overrider is pure2273 // virtual.2274 if (mayBeAbstract() && hasPureVirtualFinalOverrider(*this, FinalOverriders))2275 markAbstract();2276 2277 // Set access bits correctly on the directly-declared conversions.2278 for (conversion_iterator I = conversion_begin(), E = conversion_end();2279 I != E; ++I)2280 I.setAccess((*I)->getAccess());2281 2282 ASTContext &Context = getASTContext();2283 2284 if (isAggregate() && hasUserDeclaredConstructor() &&2285 !Context.getLangOpts().CPlusPlus20) {2286 // Diagnose any aggregate behavior changes in C++202287 for (const FieldDecl *FD : fields()) {2288 if (const auto *AT = FD->getAttr<ExplicitInitAttr>())2289 Context.getDiagnostics().Report(2290 AT->getLocation(),2291 diag::warn_cxx20_compat_requires_explicit_init_non_aggregate)2292 << AT << FD << Context.getCanonicalTagType(this);2293 }2294 }2295 2296 if (!isAggregate() && hasUninitializedExplicitInitFields()) {2297 // Diagnose any fields that required explicit initialization in a2298 // non-aggregate type. (Note that the fields may not be directly in this2299 // type, but in a subobject. In such cases we don't emit diagnoses here.)2300 for (const FieldDecl *FD : fields()) {2301 if (const auto *AT = FD->getAttr<ExplicitInitAttr>())2302 Context.getDiagnostics().Report(AT->getLocation(),2303 diag::warn_attribute_needs_aggregate)2304 << AT << Context.getCanonicalTagType(this);2305 }2306 setHasUninitializedExplicitInitFields(false);2307 }2308}2309 2310bool CXXRecordDecl::mayBeAbstract() const {2311 if (data().Abstract || isInvalidDecl() || !data().Polymorphic ||2312 isDependentContext())2313 return false;2314 2315 for (const auto &B : bases()) {2316 const auto *BaseDecl = cast<CXXRecordDecl>(2317 B.getType()->castAsCanonical<RecordType>()->getDecl());2318 if (BaseDecl->isAbstract())2319 return true;2320 }2321 2322 return false;2323}2324 2325bool CXXRecordDecl::isEffectivelyFinal() const {2326 auto *Def = getDefinition();2327 if (!Def)2328 return false;2329 if (Def->hasAttr<FinalAttr>())2330 return true;2331 if (const auto *Dtor = Def->getDestructor())2332 if (Dtor->hasAttr<FinalAttr>())2333 return true;2334 return false;2335}2336 2337void CXXDeductionGuideDecl::anchor() {}2338 2339bool ExplicitSpecifier::isEquivalent(const ExplicitSpecifier Other) const {2340 if ((getKind() != Other.getKind() ||2341 getKind() == ExplicitSpecKind::Unresolved)) {2342 if (getKind() == ExplicitSpecKind::Unresolved &&2343 Other.getKind() == ExplicitSpecKind::Unresolved) {2344 ODRHash SelfHash, OtherHash;2345 SelfHash.AddStmt(getExpr());2346 OtherHash.AddStmt(Other.getExpr());2347 return SelfHash.CalculateHash() == OtherHash.CalculateHash();2348 } else2349 return false;2350 }2351 return true;2352}2353 2354ExplicitSpecifier ExplicitSpecifier::getFromDecl(FunctionDecl *Function) {2355 switch (Function->getDeclKind()) {2356 case Decl::Kind::CXXConstructor:2357 return cast<CXXConstructorDecl>(Function)->getExplicitSpecifier();2358 case Decl::Kind::CXXConversion:2359 return cast<CXXConversionDecl>(Function)->getExplicitSpecifier();2360 case Decl::Kind::CXXDeductionGuide:2361 return cast<CXXDeductionGuideDecl>(Function)->getExplicitSpecifier();2362 default:2363 return {};2364 }2365}2366 2367CXXDeductionGuideDecl *CXXDeductionGuideDecl::Create(2368 ASTContext &C, DeclContext *DC, SourceLocation StartLoc,2369 ExplicitSpecifier ES, const DeclarationNameInfo &NameInfo, QualType T,2370 TypeSourceInfo *TInfo, SourceLocation EndLocation, CXXConstructorDecl *Ctor,2371 DeductionCandidate Kind, const AssociatedConstraint &TrailingRequiresClause,2372 const CXXDeductionGuideDecl *GeneratedFrom,2373 SourceDeductionGuideKind SourceKind) {2374 return new (C, DC) CXXDeductionGuideDecl(2375 C, DC, StartLoc, ES, NameInfo, T, TInfo, EndLocation, Ctor, Kind,2376 TrailingRequiresClause, GeneratedFrom, SourceKind);2377}2378 2379CXXDeductionGuideDecl *2380CXXDeductionGuideDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID) {2381 return new (C, ID) CXXDeductionGuideDecl(2382 C, /*DC=*/nullptr, SourceLocation(), ExplicitSpecifier(),2383 DeclarationNameInfo(), QualType(), /*TInfo=*/nullptr, SourceLocation(),2384 /*Ctor=*/nullptr, DeductionCandidate::Normal,2385 /*TrailingRequiresClause=*/{},2386 /*GeneratedFrom=*/nullptr, SourceDeductionGuideKind::None);2387}2388 2389RequiresExprBodyDecl *RequiresExprBodyDecl::Create(2390 ASTContext &C, DeclContext *DC, SourceLocation StartLoc) {2391 return new (C, DC) RequiresExprBodyDecl(C, DC, StartLoc);2392}2393 2394RequiresExprBodyDecl *2395RequiresExprBodyDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID) {2396 return new (C, ID) RequiresExprBodyDecl(C, nullptr, SourceLocation());2397}2398 2399void CXXMethodDecl::anchor() {}2400 2401bool CXXMethodDecl::isStatic() const {2402 const CXXMethodDecl *MD = getCanonicalDecl();2403 2404 if (MD->getStorageClass() == SC_Static)2405 return true;2406 2407 OverloadedOperatorKind OOK = getDeclName().getCXXOverloadedOperator();2408 return isStaticOverloadedOperator(OOK);2409}2410 2411static bool recursivelyOverrides(const CXXMethodDecl *DerivedMD,2412 const CXXMethodDecl *BaseMD) {2413 for (const CXXMethodDecl *MD : DerivedMD->overridden_methods()) {2414 if (MD->getCanonicalDecl() == BaseMD->getCanonicalDecl())2415 return true;2416 if (recursivelyOverrides(MD, BaseMD))2417 return true;2418 }2419 return false;2420}2421 2422CXXMethodDecl *2423CXXMethodDecl::getCorrespondingMethodDeclaredInClass(const CXXRecordDecl *RD,2424 bool MayBeBase) {2425 if (this->getParent()->getCanonicalDecl() == RD->getCanonicalDecl())2426 return this;2427 2428 // Lookup doesn't work for destructors, so handle them separately.2429 if (isa<CXXDestructorDecl>(this)) {2430 CXXMethodDecl *MD = RD->getDestructor();2431 if (MD) {2432 if (recursivelyOverrides(MD, this))2433 return MD;2434 if (MayBeBase && recursivelyOverrides(this, MD))2435 return MD;2436 }2437 return nullptr;2438 }2439 2440 for (auto *ND : RD->lookup(getDeclName())) {2441 auto *MD = dyn_cast<CXXMethodDecl>(ND);2442 if (!MD)2443 continue;2444 if (recursivelyOverrides(MD, this))2445 return MD;2446 if (MayBeBase && recursivelyOverrides(this, MD))2447 return MD;2448 }2449 2450 return nullptr;2451}2452 2453CXXMethodDecl *2454CXXMethodDecl::getCorrespondingMethodInClass(const CXXRecordDecl *RD,2455 bool MayBeBase) {2456 if (auto *MD = getCorrespondingMethodDeclaredInClass(RD, MayBeBase))2457 return MD;2458 2459 llvm::SmallVector<CXXMethodDecl*, 4> FinalOverriders;2460 auto AddFinalOverrider = [&](CXXMethodDecl *D) {2461 // If this function is overridden by a candidate final overrider, it is not2462 // a final overrider.2463 for (CXXMethodDecl *OtherD : FinalOverriders) {2464 if (declaresSameEntity(D, OtherD) || recursivelyOverrides(OtherD, D))2465 return;2466 }2467 2468 // Other candidate final overriders might be overridden by this function.2469 llvm::erase_if(FinalOverriders, [&](CXXMethodDecl *OtherD) {2470 return recursivelyOverrides(D, OtherD);2471 });2472 2473 FinalOverriders.push_back(D);2474 };2475 2476 for (const auto &I : RD->bases()) {2477 const auto *Base = I.getType()->getAsCXXRecordDecl();2478 if (!Base)2479 continue;2480 if (CXXMethodDecl *D = this->getCorrespondingMethodInClass(Base))2481 AddFinalOverrider(D);2482 }2483 2484 return FinalOverriders.size() == 1 ? FinalOverriders.front() : nullptr;2485}2486 2487CXXMethodDecl *2488CXXMethodDecl::Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc,2489 const DeclarationNameInfo &NameInfo, QualType T,2490 TypeSourceInfo *TInfo, StorageClass SC, bool UsesFPIntrin,2491 bool isInline, ConstexprSpecKind ConstexprKind,2492 SourceLocation EndLocation,2493 const AssociatedConstraint &TrailingRequiresClause) {2494 return new (C, RD) CXXMethodDecl(2495 CXXMethod, C, RD, StartLoc, NameInfo, T, TInfo, SC, UsesFPIntrin,2496 isInline, ConstexprKind, EndLocation, TrailingRequiresClause);2497}2498 2499CXXMethodDecl *CXXMethodDecl::CreateDeserialized(ASTContext &C,2500 GlobalDeclID ID) {2501 return new (C, ID)2502 CXXMethodDecl(CXXMethod, C, nullptr, SourceLocation(),2503 DeclarationNameInfo(), QualType(), nullptr, SC_None, false,2504 false, ConstexprSpecKind::Unspecified, SourceLocation(),2505 /*TrailingRequiresClause=*/{});2506}2507 2508CXXMethodDecl *CXXMethodDecl::getDevirtualizedMethod(const Expr *Base,2509 bool IsAppleKext) {2510 assert(isVirtual() && "this method is expected to be virtual");2511 2512 // When building with -fapple-kext, all calls must go through the vtable since2513 // the kernel linker can do runtime patching of vtables.2514 if (IsAppleKext)2515 return nullptr;2516 2517 // If the member function is marked 'final', we know that it can't be2518 // overridden and can therefore devirtualize it unless it's pure virtual.2519 if (hasAttr<FinalAttr>())2520 return isPureVirtual() ? nullptr : this;2521 2522 // If Base is unknown, we cannot devirtualize.2523 if (!Base)2524 return nullptr;2525 2526 // If the base expression (after skipping derived-to-base conversions) is a2527 // class prvalue, then we can devirtualize.2528 Base = Base->getBestDynamicClassTypeExpr();2529 if (Base->isPRValue() && Base->getType()->isRecordType())2530 return this;2531 2532 // If we don't even know what we would call, we can't devirtualize.2533 const CXXRecordDecl *BestDynamicDecl = Base->getBestDynamicClassType();2534 if (!BestDynamicDecl)2535 return nullptr;2536 2537 // There may be a method corresponding to MD in a derived class.2538 CXXMethodDecl *DevirtualizedMethod =2539 getCorrespondingMethodInClass(BestDynamicDecl);2540 2541 // If there final overrider in the dynamic type is ambiguous, we can't2542 // devirtualize this call.2543 if (!DevirtualizedMethod)2544 return nullptr;2545 2546 // If that method is pure virtual, we can't devirtualize. If this code is2547 // reached, the result would be UB, not a direct call to the derived class2548 // function, and we can't assume the derived class function is defined.2549 if (DevirtualizedMethod->isPureVirtual())2550 return nullptr;2551 2552 // If that method is marked final, we can devirtualize it.2553 if (DevirtualizedMethod->hasAttr<FinalAttr>())2554 return DevirtualizedMethod;2555 2556 // Similarly, if the class itself or its destructor is marked 'final',2557 // the class can't be derived from and we can therefore devirtualize the2558 // member function call.2559 if (BestDynamicDecl->isEffectivelyFinal())2560 return DevirtualizedMethod;2561 2562 if (const auto *DRE = dyn_cast<DeclRefExpr>(Base)) {2563 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))2564 if (VD->getType()->isRecordType())2565 // This is a record decl. We know the type and can devirtualize it.2566 return DevirtualizedMethod;2567 2568 return nullptr;2569 }2570 2571 // We can devirtualize calls on an object accessed by a class member access2572 // expression, since by C++11 [basic.life]p6 we know that it can't refer to2573 // a derived class object constructed in the same location.2574 if (const auto *ME = dyn_cast<MemberExpr>(Base)) {2575 const ValueDecl *VD = ME->getMemberDecl();2576 return VD->getType()->isRecordType() ? DevirtualizedMethod : nullptr;2577 }2578 2579 // Likewise for calls on an object accessed by a (non-reference) pointer to2580 // member access.2581 if (auto *BO = dyn_cast<BinaryOperator>(Base)) {2582 if (BO->isPtrMemOp()) {2583 auto *MPT = BO->getRHS()->getType()->castAs<MemberPointerType>();2584 if (MPT->getPointeeType()->isRecordType())2585 return DevirtualizedMethod;2586 }2587 }2588 2589 // We can't devirtualize the call.2590 return nullptr;2591}2592 2593bool CXXMethodDecl::isUsualDeallocationFunction(2594 SmallVectorImpl<const FunctionDecl *> &PreventedBy) const {2595 assert(PreventedBy.empty() && "PreventedBy is expected to be empty");2596 if (!getDeclName().isAnyOperatorDelete())2597 return false;2598 2599 if (isTypeAwareOperatorNewOrDelete()) {2600 // A variadic type aware allocation function is not a usual deallocation2601 // function2602 if (isVariadic())2603 return false;2604 2605 // Type aware deallocation functions are only usual if they only accept the2606 // mandatory arguments2607 if (getNumParams() != FunctionDecl::RequiredTypeAwareDeleteParameterCount)2608 return false;2609 2610 FunctionTemplateDecl *PrimaryTemplate = getPrimaryTemplate();2611 if (!PrimaryTemplate)2612 return true;2613 2614 // A template instance is is only a usual deallocation function if it has a2615 // type-identity parameter, the type-identity parameter is a dependent type2616 // (i.e. the type-identity parameter is of type std::type_identity<U> where2617 // U shall be a dependent type), and the type-identity parameter is the only2618 // dependent parameter, and there are no template packs in the parameter2619 // list.2620 FunctionDecl *SpecializedDecl = PrimaryTemplate->getTemplatedDecl();2621 if (!SpecializedDecl->getParamDecl(0)->getType()->isDependentType())2622 return false;2623 for (unsigned Idx = 1; Idx < getNumParams(); ++Idx) {2624 if (SpecializedDecl->getParamDecl(Idx)->getType()->isDependentType())2625 return false;2626 }2627 return true;2628 }2629 2630 // C++ [basic.stc.dynamic.deallocation]p2:2631 // A template instance is never a usual deallocation function,2632 // regardless of its signature.2633 // Post-P2719 adoption:2634 // A template instance is is only a usual deallocation function if it has a2635 // type-identity parameter2636 if (getPrimaryTemplate())2637 return false;2638 2639 // C++ [basic.stc.dynamic.deallocation]p2:2640 // If a class T has a member deallocation function named operator delete2641 // with exactly one parameter, then that function is a usual (non-placement)2642 // deallocation function. [...]2643 if (getNumParams() == 1)2644 return true;2645 unsigned UsualParams = 1;2646 2647 // C++ P0722:2648 // A destroying operator delete is a usual deallocation function if2649 // removing the std::destroying_delete_t parameter and changing the2650 // first parameter type from T* to void* results in the signature of2651 // a usual deallocation function.2652 if (isDestroyingOperatorDelete())2653 ++UsualParams;2654 2655 // C++ <=14 [basic.stc.dynamic.deallocation]p2:2656 // [...] If class T does not declare such an operator delete but does2657 // declare a member deallocation function named operator delete with2658 // exactly two parameters, the second of which has type std::size_t (18.1),2659 // then this function is a usual deallocation function.2660 //2661 // C++17 says a usual deallocation function is one with the signature2662 // (void* [, size_t] [, std::align_val_t] [, ...])2663 // and all such functions are usual deallocation functions. It's not clear2664 // that allowing varargs functions was intentional.2665 ASTContext &Context = getASTContext();2666 if (UsualParams < getNumParams() &&2667 Context.hasSameUnqualifiedType(getParamDecl(UsualParams)->getType(),2668 Context.getSizeType()))2669 ++UsualParams;2670 2671 if (UsualParams < getNumParams() &&2672 getParamDecl(UsualParams)->getType()->isAlignValT())2673 ++UsualParams;2674 2675 if (UsualParams != getNumParams())2676 return false;2677 2678 // In C++17 onwards, all potential usual deallocation functions are actual2679 // usual deallocation functions. Honor this behavior when post-C++142680 // deallocation functions are offered as extensions too.2681 // FIXME(EricWF): Destroying Delete should be a language option. How do we2682 // handle when destroying delete is used prior to C++17?2683 if (Context.getLangOpts().CPlusPlus17 ||2684 Context.getLangOpts().AlignedAllocation ||2685 isDestroyingOperatorDelete())2686 return true;2687 2688 // This function is a usual deallocation function if there are no2689 // single-parameter deallocation functions of the same kind.2690 DeclContext::lookup_result R = getDeclContext()->lookup(getDeclName());2691 bool Result = true;2692 for (const auto *D : R) {2693 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {2694 if (FD->getNumParams() == 1) {2695 PreventedBy.push_back(FD);2696 Result = false;2697 }2698 }2699 }2700 return Result;2701}2702 2703bool CXXMethodDecl::isExplicitObjectMemberFunction() const {2704 // C++2b [dcl.fct]p6:2705 // An explicit object member function is a non-static member2706 // function with an explicit object parameter2707 return !isStatic() && hasCXXExplicitFunctionObjectParameter();2708}2709 2710bool CXXMethodDecl::isImplicitObjectMemberFunction() const {2711 return !isStatic() && !hasCXXExplicitFunctionObjectParameter();2712}2713 2714bool CXXMethodDecl::isCopyAssignmentOperator() const {2715 // C++0x [class.copy]p17:2716 // A user-declared copy assignment operator X::operator= is a non-static2717 // non-template member function of class X with exactly one parameter of2718 // type X, X&, const X&, volatile X& or const volatile X&.2719 if (/*operator=*/getOverloadedOperator() != OO_Equal ||2720 /*non-static*/ isStatic() ||2721 2722 /*non-template*/ getPrimaryTemplate() || getDescribedFunctionTemplate() ||2723 getNumExplicitParams() != 1)2724 return false;2725 2726 QualType ParamType = getNonObjectParameter(0)->getType();2727 if (const auto *Ref = ParamType->getAs<LValueReferenceType>())2728 ParamType = Ref->getPointeeType();2729 2730 ASTContext &Context = getASTContext();2731 CanQualType ClassType = Context.getCanonicalTagType(getParent());2732 return Context.hasSameUnqualifiedType(ClassType, ParamType);2733}2734 2735bool CXXMethodDecl::isMoveAssignmentOperator() const {2736 // C++0x [class.copy]p19:2737 // A user-declared move assignment operator X::operator= is a non-static2738 // non-template member function of class X with exactly one parameter of type2739 // X&&, const X&&, volatile X&&, or const volatile X&&.2740 if (getOverloadedOperator() != OO_Equal || isStatic() ||2741 getPrimaryTemplate() || getDescribedFunctionTemplate() ||2742 getNumExplicitParams() != 1)2743 return false;2744 2745 QualType ParamType = getNonObjectParameter(0)->getType();2746 if (!ParamType->isRValueReferenceType())2747 return false;2748 ParamType = ParamType->getPointeeType();2749 2750 ASTContext &Context = getASTContext();2751 CanQualType ClassType = Context.getCanonicalTagType(getParent());2752 return Context.hasSameUnqualifiedType(ClassType, ParamType);2753}2754 2755void CXXMethodDecl::addOverriddenMethod(const CXXMethodDecl *MD) {2756 assert(MD->isCanonicalDecl() && "Method is not canonical!");2757 assert(MD->isVirtual() && "Method is not virtual!");2758 2759 getASTContext().addOverriddenMethod(this, MD);2760}2761 2762CXXMethodDecl::method_iterator CXXMethodDecl::begin_overridden_methods() const {2763 if (isa<CXXConstructorDecl>(this)) return nullptr;2764 return getASTContext().overridden_methods_begin(this);2765}2766 2767CXXMethodDecl::method_iterator CXXMethodDecl::end_overridden_methods() const {2768 if (isa<CXXConstructorDecl>(this)) return nullptr;2769 return getASTContext().overridden_methods_end(this);2770}2771 2772unsigned CXXMethodDecl::size_overridden_methods() const {2773 if (isa<CXXConstructorDecl>(this)) return 0;2774 return getASTContext().overridden_methods_size(this);2775}2776 2777CXXMethodDecl::overridden_method_range2778CXXMethodDecl::overridden_methods() const {2779 if (isa<CXXConstructorDecl>(this))2780 return overridden_method_range(nullptr, nullptr);2781 return getASTContext().overridden_methods(this);2782}2783 2784static QualType getThisObjectType(ASTContext &C, const FunctionProtoType *FPT,2785 const CXXRecordDecl *Decl) {2786 CanQualType ClassTy = C.getCanonicalTagType(Decl);2787 return C.getQualifiedType(ClassTy, FPT->getMethodQuals());2788}2789 2790QualType CXXMethodDecl::getThisType(const FunctionProtoType *FPT,2791 const CXXRecordDecl *Decl) {2792 ASTContext &C = Decl->getASTContext();2793 QualType ObjectTy = ::getThisObjectType(C, FPT, Decl);2794 2795 // Unlike 'const' and 'volatile', a '__restrict' qualifier must be2796 // attached to the pointer type, not the pointee.2797 bool Restrict = FPT->getMethodQuals().hasRestrict();2798 if (Restrict)2799 ObjectTy.removeLocalRestrict();2800 2801 ObjectTy = C.getLangOpts().HLSL ? C.getLValueReferenceType(ObjectTy)2802 : C.getPointerType(ObjectTy);2803 2804 if (Restrict)2805 ObjectTy.addRestrict();2806 return ObjectTy;2807}2808 2809QualType CXXMethodDecl::getThisType() const {2810 // C++ 9.3.2p1: The type of this in a member function of a class X is X*.2811 // If the member function is declared const, the type of this is const X*,2812 // if the member function is declared volatile, the type of this is2813 // volatile X*, and if the member function is declared const volatile,2814 // the type of this is const volatile X*.2815 assert(isInstance() && "No 'this' for static methods!");2816 return CXXMethodDecl::getThisType(getType()->castAs<FunctionProtoType>(),2817 getParent());2818}2819 2820QualType CXXMethodDecl::getFunctionObjectParameterReferenceType() const {2821 if (isExplicitObjectMemberFunction())2822 return parameters()[0]->getType();2823 2824 ASTContext &C = getParentASTContext();2825 const FunctionProtoType *FPT = getType()->castAs<FunctionProtoType>();2826 QualType Type = ::getThisObjectType(C, FPT, getParent());2827 RefQualifierKind RK = FPT->getRefQualifier();2828 if (RK == RefQualifierKind::RQ_RValue)2829 return C.getRValueReferenceType(Type);2830 return C.getLValueReferenceType(Type);2831}2832 2833bool CXXMethodDecl::hasInlineBody() const {2834 // If this function is a template instantiation, look at the template from2835 // which it was instantiated.2836 const FunctionDecl *CheckFn = getTemplateInstantiationPattern();2837 if (!CheckFn)2838 CheckFn = this;2839 2840 const FunctionDecl *fn;2841 return CheckFn->isDefined(fn) && !fn->isOutOfLine() &&2842 (fn->doesThisDeclarationHaveABody() || fn->willHaveBody());2843}2844 2845bool CXXMethodDecl::isLambdaStaticInvoker() const {2846 const CXXRecordDecl *P = getParent();2847 return P->isLambda() && getDeclName().isIdentifier() &&2848 getName() == getLambdaStaticInvokerName();2849}2850 2851CXXCtorInitializer::CXXCtorInitializer(ASTContext &Context,2852 TypeSourceInfo *TInfo, bool IsVirtual,2853 SourceLocation L, Expr *Init,2854 SourceLocation R,2855 SourceLocation EllipsisLoc)2856 : Initializee(TInfo), Init(Init), MemberOrEllipsisLocation(EllipsisLoc),2857 LParenLoc(L), RParenLoc(R), IsDelegating(false), IsVirtual(IsVirtual),2858 IsWritten(false), SourceOrder(0) {}2859 2860CXXCtorInitializer::CXXCtorInitializer(ASTContext &Context, FieldDecl *Member,2861 SourceLocation MemberLoc,2862 SourceLocation L, Expr *Init,2863 SourceLocation R)2864 : Initializee(Member), Init(Init), MemberOrEllipsisLocation(MemberLoc),2865 LParenLoc(L), RParenLoc(R), IsDelegating(false), IsVirtual(false),2866 IsWritten(false), SourceOrder(0) {}2867 2868CXXCtorInitializer::CXXCtorInitializer(ASTContext &Context,2869 IndirectFieldDecl *Member,2870 SourceLocation MemberLoc,2871 SourceLocation L, Expr *Init,2872 SourceLocation R)2873 : Initializee(Member), Init(Init), MemberOrEllipsisLocation(MemberLoc),2874 LParenLoc(L), RParenLoc(R), IsDelegating(false), IsVirtual(false),2875 IsWritten(false), SourceOrder(0) {}2876 2877CXXCtorInitializer::CXXCtorInitializer(ASTContext &Context,2878 TypeSourceInfo *TInfo,2879 SourceLocation L, Expr *Init,2880 SourceLocation R)2881 : Initializee(TInfo), Init(Init), LParenLoc(L), RParenLoc(R),2882 IsDelegating(true), IsVirtual(false), IsWritten(false), SourceOrder(0) {}2883 2884int64_t CXXCtorInitializer::getID(const ASTContext &Context) const {2885 return Context.getAllocator()2886 .identifyKnownAlignedObject<CXXCtorInitializer>(this);2887}2888 2889TypeLoc CXXCtorInitializer::getBaseClassLoc() const {2890 if (isBaseInitializer())2891 return cast<TypeSourceInfo *>(Initializee)->getTypeLoc();2892 else2893 return {};2894}2895 2896const Type *CXXCtorInitializer::getBaseClass() const {2897 if (isBaseInitializer())2898 return cast<TypeSourceInfo *>(Initializee)->getType().getTypePtr();2899 else2900 return nullptr;2901}2902 2903SourceLocation CXXCtorInitializer::getSourceLocation() const {2904 if (isInClassMemberInitializer())2905 return getAnyMember()->getLocation();2906 2907 if (isAnyMemberInitializer())2908 return getMemberLocation();2909 2910 if (const auto *TSInfo = cast<TypeSourceInfo *>(Initializee))2911 return TSInfo->getTypeLoc().getBeginLoc();2912 2913 return {};2914}2915 2916SourceRange CXXCtorInitializer::getSourceRange() const {2917 if (isInClassMemberInitializer()) {2918 FieldDecl *D = getAnyMember();2919 if (Expr *I = D->getInClassInitializer())2920 return I->getSourceRange();2921 return {};2922 }2923 2924 return SourceRange(getSourceLocation(), getRParenLoc());2925}2926 2927CXXConstructorDecl::CXXConstructorDecl(2928 ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc,2929 const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo,2930 ExplicitSpecifier ES, bool UsesFPIntrin, bool isInline,2931 bool isImplicitlyDeclared, ConstexprSpecKind ConstexprKind,2932 InheritedConstructor Inherited,2933 const AssociatedConstraint &TrailingRequiresClause)2934 : CXXMethodDecl(CXXConstructor, C, RD, StartLoc, NameInfo, T, TInfo,2935 SC_None, UsesFPIntrin, isInline, ConstexprKind,2936 SourceLocation(), TrailingRequiresClause) {2937 setNumCtorInitializers(0);2938 setInheritingConstructor(static_cast<bool>(Inherited));2939 setImplicit(isImplicitlyDeclared);2940 CXXConstructorDeclBits.HasTrailingExplicitSpecifier = ES.getExpr() ? 1 : 0;2941 if (Inherited)2942 *getTrailingObjects<InheritedConstructor>() = Inherited;2943 setExplicitSpecifier(ES);2944}2945 2946void CXXConstructorDecl::anchor() {}2947 2948CXXConstructorDecl *CXXConstructorDecl::CreateDeserialized(ASTContext &C,2949 GlobalDeclID ID,2950 uint64_t AllocKind) {2951 bool hasTrailingExplicit = static_cast<bool>(AllocKind & TAKHasTailExplicit);2952 bool isInheritingConstructor =2953 static_cast<bool>(AllocKind & TAKInheritsConstructor);2954 unsigned Extra =2955 additionalSizeToAlloc<InheritedConstructor, ExplicitSpecifier>(2956 isInheritingConstructor, hasTrailingExplicit);2957 auto *Result = new (C, ID, Extra) CXXConstructorDecl(2958 C, nullptr, SourceLocation(), DeclarationNameInfo(), QualType(), nullptr,2959 ExplicitSpecifier(), false, false, false, ConstexprSpecKind::Unspecified,2960 InheritedConstructor(), /*TrailingRequiresClause=*/{});2961 Result->setInheritingConstructor(isInheritingConstructor);2962 Result->CXXConstructorDeclBits.HasTrailingExplicitSpecifier =2963 hasTrailingExplicit;2964 Result->setExplicitSpecifier(ExplicitSpecifier());2965 return Result;2966}2967 2968CXXConstructorDecl *CXXConstructorDecl::Create(2969 ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc,2970 const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo,2971 ExplicitSpecifier ES, bool UsesFPIntrin, bool isInline,2972 bool isImplicitlyDeclared, ConstexprSpecKind ConstexprKind,2973 InheritedConstructor Inherited,2974 const AssociatedConstraint &TrailingRequiresClause) {2975 assert(NameInfo.getName().getNameKind()2976 == DeclarationName::CXXConstructorName &&2977 "Name must refer to a constructor");2978 unsigned Extra =2979 additionalSizeToAlloc<InheritedConstructor, ExplicitSpecifier>(2980 Inherited ? 1 : 0, ES.getExpr() ? 1 : 0);2981 return new (C, RD, Extra) CXXConstructorDecl(2982 C, RD, StartLoc, NameInfo, T, TInfo, ES, UsesFPIntrin, isInline,2983 isImplicitlyDeclared, ConstexprKind, Inherited, TrailingRequiresClause);2984}2985 2986CXXConstructorDecl::init_const_iterator CXXConstructorDecl::init_begin() const {2987 return CtorInitializers.get(getASTContext().getExternalSource());2988}2989 2990CXXConstructorDecl *CXXConstructorDecl::getTargetConstructor() const {2991 assert(isDelegatingConstructor() && "Not a delegating constructor!");2992 Expr *E = (*init_begin())->getInit()->IgnoreImplicit();2993 if (const auto *Construct = dyn_cast<CXXConstructExpr>(E))2994 return Construct->getConstructor();2995 2996 return nullptr;2997}2998 2999bool CXXConstructorDecl::isDefaultConstructor() const {3000 // C++ [class.default.ctor]p1:3001 // A default constructor for a class X is a constructor of class X for3002 // which each parameter that is not a function parameter pack has a default3003 // argument (including the case of a constructor with no parameters)3004 return getMinRequiredArguments() == 0;3005}3006 3007bool3008CXXConstructorDecl::isCopyConstructor(unsigned &TypeQuals) const {3009 return isCopyOrMoveConstructor(TypeQuals) &&3010 getParamDecl(0)->getType()->isLValueReferenceType();3011}3012 3013bool CXXConstructorDecl::isMoveConstructor(unsigned &TypeQuals) const {3014 return isCopyOrMoveConstructor(TypeQuals) &&3015 getParamDecl(0)->getType()->isRValueReferenceType();3016}3017 3018/// Determine whether this is a copy or move constructor.3019bool CXXConstructorDecl::isCopyOrMoveConstructor(unsigned &TypeQuals) const {3020 // C++ [class.copy]p2:3021 // A non-template constructor for class X is a copy constructor3022 // if its first parameter is of type X&, const X&, volatile X& or3023 // const volatile X&, and either there are no other parameters3024 // or else all other parameters have default arguments (8.3.6).3025 // C++0x [class.copy]p3:3026 // A non-template constructor for class X is a move constructor if its3027 // first parameter is of type X&&, const X&&, volatile X&&, or3028 // const volatile X&&, and either there are no other parameters or else3029 // all other parameters have default arguments.3030 if (!hasOneParamOrDefaultArgs() || getPrimaryTemplate() != nullptr ||3031 getDescribedFunctionTemplate() != nullptr)3032 return false;3033 3034 const ParmVarDecl *Param = getParamDecl(0);3035 3036 // Do we have a reference type?3037 const auto *ParamRefType = Param->getType()->getAs<ReferenceType>();3038 if (!ParamRefType)3039 return false;3040 3041 // Is it a reference to our class type?3042 ASTContext &Context = getASTContext();3043 3044 QualType PointeeType = ParamRefType->getPointeeType();3045 CanQualType ClassTy = Context.getCanonicalTagType(getParent());3046 if (!Context.hasSameUnqualifiedType(PointeeType, ClassTy))3047 return false;3048 3049 // FIXME: other qualifiers?3050 3051 // We have a copy or move constructor.3052 TypeQuals = PointeeType.getCVRQualifiers();3053 return true;3054}3055 3056bool CXXConstructorDecl::isConvertingConstructor(bool AllowExplicit) const {3057 // C++ [class.conv.ctor]p1:3058 // A constructor declared without the function-specifier explicit3059 // that can be called with a single parameter specifies a3060 // conversion from the type of its first parameter to the type of3061 // its class. Such a constructor is called a converting3062 // constructor.3063 if (isExplicit() && !AllowExplicit)3064 return false;3065 3066 // FIXME: This has nothing to do with the definition of converting3067 // constructor, but is convenient for how we use this function in overload3068 // resolution.3069 return getNumParams() == 03070 ? getType()->castAs<FunctionProtoType>()->isVariadic()3071 : getMinRequiredArguments() <= 1;3072}3073 3074bool CXXConstructorDecl::isSpecializationCopyingObject() const {3075 if (!hasOneParamOrDefaultArgs() || getDescribedFunctionTemplate() != nullptr)3076 return false;3077 3078 const ParmVarDecl *Param = getParamDecl(0);3079 3080 ASTContext &Context = getASTContext();3081 CanQualType ParamType = Param->getType()->getCanonicalTypeUnqualified();3082 3083 // Is it the same as our class type?3084 CanQualType ClassTy = Context.getCanonicalTagType(getParent());3085 return ParamType == ClassTy;3086}3087 3088void CXXDestructorDecl::anchor() {}3089 3090CXXDestructorDecl *CXXDestructorDecl::CreateDeserialized(ASTContext &C,3091 GlobalDeclID ID) {3092 return new (C, ID) CXXDestructorDecl(3093 C, nullptr, SourceLocation(), DeclarationNameInfo(), QualType(), nullptr,3094 false, false, false, ConstexprSpecKind::Unspecified,3095 /*TrailingRequiresClause=*/{});3096}3097 3098CXXDestructorDecl *CXXDestructorDecl::Create(3099 ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc,3100 const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo,3101 bool UsesFPIntrin, bool isInline, bool isImplicitlyDeclared,3102 ConstexprSpecKind ConstexprKind,3103 const AssociatedConstraint &TrailingRequiresClause) {3104 assert(NameInfo.getName().getNameKind()3105 == DeclarationName::CXXDestructorName &&3106 "Name must refer to a destructor");3107 return new (C, RD) CXXDestructorDecl(3108 C, RD, StartLoc, NameInfo, T, TInfo, UsesFPIntrin, isInline,3109 isImplicitlyDeclared, ConstexprKind, TrailingRequiresClause);3110}3111 3112void CXXDestructorDecl::setOperatorDelete(FunctionDecl *OD, Expr *ThisArg) {3113 auto *First = cast<CXXDestructorDecl>(getFirstDecl());3114 if (OD && !First->OperatorDelete) {3115 First->OperatorDelete = OD;3116 First->OperatorDeleteThisArg = ThisArg;3117 if (auto *L = getASTMutationListener())3118 L->ResolvedOperatorDelete(First, OD, ThisArg);3119 }3120}3121 3122void CXXDestructorDecl::setOperatorGlobalDelete(FunctionDecl *OD) {3123 // FIXME: C++23 [expr.delete] specifies that the delete operator will be3124 // a usual deallocation function declared at global scope. A convenient3125 // function to assert that is lacking; Sema::isUsualDeallocationFunction()3126 // only works for CXXMethodDecl.3127 assert(!OD ||3128 (OD->getDeclName().getCXXOverloadedOperator() == OO_Delete &&3129 OD->getDeclContext()->getRedeclContext()->isTranslationUnit()));3130 auto *Canonical = cast<CXXDestructorDecl>(getCanonicalDecl());3131 if (!Canonical->OperatorGlobalDelete) {3132 Canonical->OperatorGlobalDelete = OD;3133 if (auto *L = getASTMutationListener())3134 L->ResolvedOperatorGlobDelete(Canonical, OD);3135 }3136}3137 3138bool CXXDestructorDecl::isCalledByDelete(const FunctionDecl *OpDel) const {3139 // C++20 [expr.delete]p6: If the value of the operand of the delete-3140 // expression is not a null pointer value and the selected deallocation3141 // function (see below) is not a destroying operator delete, the delete-3142 // expression will invoke the destructor (if any) for the object or the3143 // elements of the array being deleted.3144 //3145 // This means we should not look at the destructor for a destroying3146 // delete operator, as that destructor is never called, unless the3147 // destructor is virtual (see [expr.delete]p8.1) because then the3148 // selected operator depends on the dynamic type of the pointer.3149 const FunctionDecl *SelectedOperatorDelete = OpDel ? OpDel : OperatorDelete;3150 if (!SelectedOperatorDelete)3151 return true;3152 3153 if (!SelectedOperatorDelete->isDestroyingOperatorDelete())3154 return true;3155 3156 // We have a destroying operator delete, so it depends on the dtor.3157 return isVirtual();3158}3159 3160void CXXConversionDecl::anchor() {}3161 3162CXXConversionDecl *CXXConversionDecl::CreateDeserialized(ASTContext &C,3163 GlobalDeclID ID) {3164 return new (C, ID) CXXConversionDecl(3165 C, nullptr, SourceLocation(), DeclarationNameInfo(), QualType(), nullptr,3166 false, false, ExplicitSpecifier(), ConstexprSpecKind::Unspecified,3167 SourceLocation(), /*TrailingRequiresClause=*/{});3168}3169 3170CXXConversionDecl *CXXConversionDecl::Create(3171 ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc,3172 const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo,3173 bool UsesFPIntrin, bool isInline, ExplicitSpecifier ES,3174 ConstexprSpecKind ConstexprKind, SourceLocation EndLocation,3175 const AssociatedConstraint &TrailingRequiresClause) {3176 assert(NameInfo.getName().getNameKind()3177 == DeclarationName::CXXConversionFunctionName &&3178 "Name must refer to a conversion function");3179 return new (C, RD) CXXConversionDecl(3180 C, RD, StartLoc, NameInfo, T, TInfo, UsesFPIntrin, isInline, ES,3181 ConstexprKind, EndLocation, TrailingRequiresClause);3182}3183 3184bool CXXConversionDecl::isLambdaToBlockPointerConversion() const {3185 return isImplicit() && getParent()->isLambda() &&3186 getConversionType()->isBlockPointerType();3187}3188 3189LinkageSpecDecl::LinkageSpecDecl(DeclContext *DC, SourceLocation ExternLoc,3190 SourceLocation LangLoc,3191 LinkageSpecLanguageIDs lang, bool HasBraces)3192 : Decl(LinkageSpec, DC, LangLoc), DeclContext(LinkageSpec),3193 ExternLoc(ExternLoc), RBraceLoc(SourceLocation()) {3194 setLanguage(lang);3195 LinkageSpecDeclBits.HasBraces = HasBraces;3196}3197 3198void LinkageSpecDecl::anchor() {}3199 3200LinkageSpecDecl *LinkageSpecDecl::Create(ASTContext &C, DeclContext *DC,3201 SourceLocation ExternLoc,3202 SourceLocation LangLoc,3203 LinkageSpecLanguageIDs Lang,3204 bool HasBraces) {3205 return new (C, DC) LinkageSpecDecl(DC, ExternLoc, LangLoc, Lang, HasBraces);3206}3207 3208LinkageSpecDecl *LinkageSpecDecl::CreateDeserialized(ASTContext &C,3209 GlobalDeclID ID) {3210 return new (C, ID)3211 LinkageSpecDecl(nullptr, SourceLocation(), SourceLocation(),3212 LinkageSpecLanguageIDs::C, false);3213}3214 3215void UsingDirectiveDecl::anchor() {}3216 3217UsingDirectiveDecl *UsingDirectiveDecl::Create(ASTContext &C, DeclContext *DC,3218 SourceLocation L,3219 SourceLocation NamespaceLoc,3220 NestedNameSpecifierLoc QualifierLoc,3221 SourceLocation IdentLoc,3222 NamedDecl *Used,3223 DeclContext *CommonAncestor) {3224 if (auto *NS = dyn_cast_or_null<NamespaceDecl>(Used))3225 Used = NS->getFirstDecl();3226 return new (C, DC) UsingDirectiveDecl(DC, L, NamespaceLoc, QualifierLoc,3227 IdentLoc, Used, CommonAncestor);3228}3229 3230UsingDirectiveDecl *UsingDirectiveDecl::CreateDeserialized(ASTContext &C,3231 GlobalDeclID ID) {3232 return new (C, ID) UsingDirectiveDecl(nullptr, SourceLocation(),3233 SourceLocation(),3234 NestedNameSpecifierLoc(),3235 SourceLocation(), nullptr, nullptr);3236}3237 3238NamespaceDecl *NamespaceBaseDecl::getNamespace() {3239 if (auto *Alias = dyn_cast<NamespaceAliasDecl>(this))3240 return Alias->getNamespace();3241 return cast<NamespaceDecl>(this);3242}3243 3244NamespaceDecl *UsingDirectiveDecl::getNominatedNamespace() {3245 if (auto *NA = dyn_cast_or_null<NamespaceAliasDecl>(NominatedNamespace))3246 return NA->getNamespace();3247 return cast_or_null<NamespaceDecl>(NominatedNamespace);3248}3249 3250NamespaceDecl::NamespaceDecl(ASTContext &C, DeclContext *DC, bool Inline,3251 SourceLocation StartLoc, SourceLocation IdLoc,3252 IdentifierInfo *Id, NamespaceDecl *PrevDecl,3253 bool Nested)3254 : NamespaceBaseDecl(Namespace, DC, IdLoc, Id), DeclContext(Namespace),3255 redeclarable_base(C), LocStart(StartLoc) {3256 setInline(Inline);3257 setNested(Nested);3258 setPreviousDecl(PrevDecl);3259}3260 3261NamespaceDecl *NamespaceDecl::Create(ASTContext &C, DeclContext *DC,3262 bool Inline, SourceLocation StartLoc,3263 SourceLocation IdLoc, IdentifierInfo *Id,3264 NamespaceDecl *PrevDecl, bool Nested) {3265 return new (C, DC)3266 NamespaceDecl(C, DC, Inline, StartLoc, IdLoc, Id, PrevDecl, Nested);3267}3268 3269NamespaceDecl *NamespaceDecl::CreateDeserialized(ASTContext &C,3270 GlobalDeclID ID) {3271 return new (C, ID) NamespaceDecl(C, nullptr, false, SourceLocation(),3272 SourceLocation(), nullptr, nullptr, false);3273}3274 3275NamespaceDecl *NamespaceDecl::getNextRedeclarationImpl() {3276 return getNextRedeclaration();3277}3278 3279NamespaceDecl *NamespaceDecl::getPreviousDeclImpl() {3280 return getPreviousDecl();3281}3282 3283NamespaceDecl *NamespaceDecl::getMostRecentDeclImpl() {3284 return getMostRecentDecl();3285}3286 3287void NamespaceAliasDecl::anchor() {}3288 3289NamespaceAliasDecl *NamespaceAliasDecl::getNextRedeclarationImpl() {3290 return getNextRedeclaration();3291}3292 3293NamespaceAliasDecl *NamespaceAliasDecl::getPreviousDeclImpl() {3294 return getPreviousDecl();3295}3296 3297NamespaceAliasDecl *NamespaceAliasDecl::getMostRecentDeclImpl() {3298 return getMostRecentDecl();3299}3300 3301NamespaceAliasDecl *NamespaceAliasDecl::Create(3302 ASTContext &C, DeclContext *DC, SourceLocation UsingLoc,3303 SourceLocation AliasLoc, IdentifierInfo *Alias,3304 NestedNameSpecifierLoc QualifierLoc, SourceLocation IdentLoc,3305 NamespaceBaseDecl *Namespace) {3306 // FIXME: Preserve the aliased namespace as written.3307 if (auto *NS = dyn_cast_or_null<NamespaceDecl>(Namespace))3308 Namespace = NS->getFirstDecl();3309 return new (C, DC) NamespaceAliasDecl(C, DC, UsingLoc, AliasLoc, Alias,3310 QualifierLoc, IdentLoc, Namespace);3311}3312 3313NamespaceAliasDecl *NamespaceAliasDecl::CreateDeserialized(ASTContext &C,3314 GlobalDeclID ID) {3315 return new (C, ID) NamespaceAliasDecl(C, nullptr, SourceLocation(),3316 SourceLocation(), nullptr,3317 NestedNameSpecifierLoc(),3318 SourceLocation(), nullptr);3319}3320 3321void LifetimeExtendedTemporaryDecl::anchor() {}3322 3323/// Retrieve the storage duration for the materialized temporary.3324StorageDuration LifetimeExtendedTemporaryDecl::getStorageDuration() const {3325 const ValueDecl *ExtendingDecl = getExtendingDecl();3326 if (!ExtendingDecl)3327 return SD_FullExpression;3328 // FIXME: This is not necessarily correct for a temporary materialized3329 // within a default initializer.3330 if (isa<FieldDecl>(ExtendingDecl))3331 return SD_Automatic;3332 // FIXME: This only works because storage class specifiers are not allowed3333 // on decomposition declarations.3334 if (isa<BindingDecl>(ExtendingDecl))3335 return ExtendingDecl->getDeclContext()->isFunctionOrMethod() ? SD_Automatic3336 : SD_Static;3337 return cast<VarDecl>(ExtendingDecl)->getStorageDuration();3338}3339 3340APValue *LifetimeExtendedTemporaryDecl::getOrCreateValue(bool MayCreate) const {3341 assert(getStorageDuration() == SD_Static &&3342 "don't need to cache the computed value for this temporary");3343 if (MayCreate && !Value) {3344 Value = (new (getASTContext()) APValue);3345 getASTContext().addDestruction(Value);3346 }3347 assert(Value && "may not be null");3348 return Value;3349}3350 3351void UsingShadowDecl::anchor() {}3352 3353UsingShadowDecl::UsingShadowDecl(Kind K, ASTContext &C, DeclContext *DC,3354 SourceLocation Loc, DeclarationName Name,3355 BaseUsingDecl *Introducer, NamedDecl *Target)3356 : NamedDecl(K, DC, Loc, Name), redeclarable_base(C),3357 UsingOrNextShadow(Introducer) {3358 if (Target) {3359 assert(!isa<UsingShadowDecl>(Target));3360 setTargetDecl(Target);3361 }3362 setImplicit();3363}3364 3365UsingShadowDecl::UsingShadowDecl(Kind K, ASTContext &C, EmptyShell Empty)3366 : NamedDecl(K, nullptr, SourceLocation(), DeclarationName()),3367 redeclarable_base(C) {}3368 3369UsingShadowDecl *UsingShadowDecl::CreateDeserialized(ASTContext &C,3370 GlobalDeclID ID) {3371 return new (C, ID) UsingShadowDecl(UsingShadow, C, EmptyShell());3372}3373 3374BaseUsingDecl *UsingShadowDecl::getIntroducer() const {3375 const UsingShadowDecl *Shadow = this;3376 while (const auto *NextShadow =3377 dyn_cast<UsingShadowDecl>(Shadow->UsingOrNextShadow))3378 Shadow = NextShadow;3379 return cast<BaseUsingDecl>(Shadow->UsingOrNextShadow);3380}3381 3382void ConstructorUsingShadowDecl::anchor() {}3383 3384ConstructorUsingShadowDecl *3385ConstructorUsingShadowDecl::Create(ASTContext &C, DeclContext *DC,3386 SourceLocation Loc, UsingDecl *Using,3387 NamedDecl *Target, bool IsVirtual) {3388 return new (C, DC) ConstructorUsingShadowDecl(C, DC, Loc, Using, Target,3389 IsVirtual);3390}3391 3392ConstructorUsingShadowDecl *3393ConstructorUsingShadowDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID) {3394 return new (C, ID) ConstructorUsingShadowDecl(C, EmptyShell());3395}3396 3397CXXRecordDecl *ConstructorUsingShadowDecl::getNominatedBaseClass() const {3398 return getIntroducer()->getQualifier().getAsRecordDecl();3399}3400 3401void BaseUsingDecl::anchor() {}3402 3403void BaseUsingDecl::addShadowDecl(UsingShadowDecl *S) {3404 assert(!llvm::is_contained(shadows(), S) && "declaration already in set");3405 assert(S->getIntroducer() == this);3406 3407 if (FirstUsingShadow.getPointer())3408 S->UsingOrNextShadow = FirstUsingShadow.getPointer();3409 FirstUsingShadow.setPointer(S);3410}3411 3412void BaseUsingDecl::removeShadowDecl(UsingShadowDecl *S) {3413 assert(llvm::is_contained(shadows(), S) && "declaration not in set");3414 assert(S->getIntroducer() == this);3415 3416 // Remove S from the shadow decl chain. This is O(n) but hopefully rare.3417 3418 if (FirstUsingShadow.getPointer() == S) {3419 FirstUsingShadow.setPointer(3420 dyn_cast<UsingShadowDecl>(S->UsingOrNextShadow));3421 S->UsingOrNextShadow = this;3422 return;3423 }3424 3425 UsingShadowDecl *Prev = FirstUsingShadow.getPointer();3426 while (Prev->UsingOrNextShadow != S)3427 Prev = cast<UsingShadowDecl>(Prev->UsingOrNextShadow);3428 Prev->UsingOrNextShadow = S->UsingOrNextShadow;3429 S->UsingOrNextShadow = this;3430}3431 3432void UsingDecl::anchor() {}3433 3434UsingDecl *UsingDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation UL,3435 NestedNameSpecifierLoc QualifierLoc,3436 const DeclarationNameInfo &NameInfo,3437 bool HasTypename) {3438 return new (C, DC) UsingDecl(DC, UL, QualifierLoc, NameInfo, HasTypename);3439}3440 3441UsingDecl *UsingDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID) {3442 return new (C, ID) UsingDecl(nullptr, SourceLocation(),3443 NestedNameSpecifierLoc(), DeclarationNameInfo(),3444 false);3445}3446 3447SourceRange UsingDecl::getSourceRange() const {3448 SourceLocation Begin = isAccessDeclaration()3449 ? getQualifierLoc().getBeginLoc() : UsingLocation;3450 return SourceRange(Begin, getNameInfo().getEndLoc());3451}3452 3453void UsingEnumDecl::anchor() {}3454 3455UsingEnumDecl *UsingEnumDecl::Create(ASTContext &C, DeclContext *DC,3456 SourceLocation UL, SourceLocation EL,3457 SourceLocation NL,3458 TypeSourceInfo *EnumType) {3459 return new (C, DC)3460 UsingEnumDecl(DC, EnumType->getType()->castAsEnumDecl()->getDeclName(),3461 UL, EL, NL, EnumType);3462}3463 3464UsingEnumDecl *UsingEnumDecl::CreateDeserialized(ASTContext &C,3465 GlobalDeclID ID) {3466 return new (C, ID)3467 UsingEnumDecl(nullptr, DeclarationName(), SourceLocation(),3468 SourceLocation(), SourceLocation(), nullptr);3469}3470 3471SourceRange UsingEnumDecl::getSourceRange() const {3472 return SourceRange(UsingLocation, EnumType->getTypeLoc().getEndLoc());3473}3474 3475void UsingPackDecl::anchor() {}3476 3477UsingPackDecl *UsingPackDecl::Create(ASTContext &C, DeclContext *DC,3478 NamedDecl *InstantiatedFrom,3479 ArrayRef<NamedDecl *> UsingDecls) {3480 size_t Extra = additionalSizeToAlloc<NamedDecl *>(UsingDecls.size());3481 return new (C, DC, Extra) UsingPackDecl(DC, InstantiatedFrom, UsingDecls);3482}3483 3484UsingPackDecl *UsingPackDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID,3485 unsigned NumExpansions) {3486 size_t Extra = additionalSizeToAlloc<NamedDecl *>(NumExpansions);3487 auto *Result = new (C, ID, Extra) UsingPackDecl(nullptr, nullptr, {});3488 Result->NumExpansions = NumExpansions;3489 auto *Trail = Result->getTrailingObjects();3490 std::uninitialized_fill_n(Trail, NumExpansions, nullptr);3491 return Result;3492}3493 3494void UnresolvedUsingValueDecl::anchor() {}3495 3496UnresolvedUsingValueDecl *3497UnresolvedUsingValueDecl::Create(ASTContext &C, DeclContext *DC,3498 SourceLocation UsingLoc,3499 NestedNameSpecifierLoc QualifierLoc,3500 const DeclarationNameInfo &NameInfo,3501 SourceLocation EllipsisLoc) {3502 return new (C, DC) UnresolvedUsingValueDecl(DC, C.DependentTy, UsingLoc,3503 QualifierLoc, NameInfo,3504 EllipsisLoc);3505}3506 3507UnresolvedUsingValueDecl *3508UnresolvedUsingValueDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID) {3509 return new (C, ID) UnresolvedUsingValueDecl(nullptr, QualType(),3510 SourceLocation(),3511 NestedNameSpecifierLoc(),3512 DeclarationNameInfo(),3513 SourceLocation());3514}3515 3516SourceRange UnresolvedUsingValueDecl::getSourceRange() const {3517 SourceLocation Begin = isAccessDeclaration()3518 ? getQualifierLoc().getBeginLoc() : UsingLocation;3519 return SourceRange(Begin, getNameInfo().getEndLoc());3520}3521 3522void UnresolvedUsingTypenameDecl::anchor() {}3523 3524UnresolvedUsingTypenameDecl *3525UnresolvedUsingTypenameDecl::Create(ASTContext &C, DeclContext *DC,3526 SourceLocation UsingLoc,3527 SourceLocation TypenameLoc,3528 NestedNameSpecifierLoc QualifierLoc,3529 SourceLocation TargetNameLoc,3530 DeclarationName TargetName,3531 SourceLocation EllipsisLoc) {3532 return new (C, DC) UnresolvedUsingTypenameDecl(3533 DC, UsingLoc, TypenameLoc, QualifierLoc, TargetNameLoc,3534 TargetName.getAsIdentifierInfo(), EllipsisLoc);3535}3536 3537UnresolvedUsingTypenameDecl *3538UnresolvedUsingTypenameDecl::CreateDeserialized(ASTContext &C,3539 GlobalDeclID ID) {3540 return new (C, ID) UnresolvedUsingTypenameDecl(3541 nullptr, SourceLocation(), SourceLocation(), NestedNameSpecifierLoc(),3542 SourceLocation(), nullptr, SourceLocation());3543}3544 3545UnresolvedUsingIfExistsDecl *3546UnresolvedUsingIfExistsDecl::Create(ASTContext &Ctx, DeclContext *DC,3547 SourceLocation Loc, DeclarationName Name) {3548 return new (Ctx, DC) UnresolvedUsingIfExistsDecl(DC, Loc, Name);3549}3550 3551UnresolvedUsingIfExistsDecl *3552UnresolvedUsingIfExistsDecl::CreateDeserialized(ASTContext &Ctx,3553 GlobalDeclID ID) {3554 return new (Ctx, ID)3555 UnresolvedUsingIfExistsDecl(nullptr, SourceLocation(), DeclarationName());3556}3557 3558UnresolvedUsingIfExistsDecl::UnresolvedUsingIfExistsDecl(DeclContext *DC,3559 SourceLocation Loc,3560 DeclarationName Name)3561 : NamedDecl(Decl::UnresolvedUsingIfExists, DC, Loc, Name) {}3562 3563void UnresolvedUsingIfExistsDecl::anchor() {}3564 3565void StaticAssertDecl::anchor() {}3566 3567StaticAssertDecl *StaticAssertDecl::Create(ASTContext &C, DeclContext *DC,3568 SourceLocation StaticAssertLoc,3569 Expr *AssertExpr, Expr *Message,3570 SourceLocation RParenLoc,3571 bool Failed) {3572 return new (C, DC) StaticAssertDecl(DC, StaticAssertLoc, AssertExpr, Message,3573 RParenLoc, Failed);3574}3575 3576StaticAssertDecl *StaticAssertDecl::CreateDeserialized(ASTContext &C,3577 GlobalDeclID ID) {3578 return new (C, ID) StaticAssertDecl(nullptr, SourceLocation(), nullptr,3579 nullptr, SourceLocation(), false);3580}3581 3582VarDecl *ValueDecl::getPotentiallyDecomposedVarDecl() {3583 assert((isa<VarDecl, BindingDecl>(this)) &&3584 "expected a VarDecl or a BindingDecl");3585 if (auto *Var = llvm::dyn_cast<VarDecl>(this))3586 return Var;3587 if (auto *BD = llvm::dyn_cast<BindingDecl>(this))3588 return llvm::dyn_cast_if_present<VarDecl>(BD->getDecomposedDecl());3589 return nullptr;3590}3591 3592void BindingDecl::anchor() {}3593 3594BindingDecl *BindingDecl::Create(ASTContext &C, DeclContext *DC,3595 SourceLocation IdLoc, IdentifierInfo *Id,3596 QualType T) {3597 return new (C, DC) BindingDecl(DC, IdLoc, Id, T);3598}3599 3600BindingDecl *BindingDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID) {3601 return new (C, ID)3602 BindingDecl(nullptr, SourceLocation(), nullptr, QualType());3603}3604 3605VarDecl *BindingDecl::getHoldingVar() const {3606 Expr *B = getBinding();3607 if (!B)3608 return nullptr;3609 auto *DRE = dyn_cast<DeclRefExpr>(B->IgnoreImplicit());3610 if (!DRE)3611 return nullptr;3612 3613 auto *VD = cast<VarDecl>(DRE->getDecl());3614 assert(VD->isImplicit() && "holding var for binding decl not implicit");3615 return VD;3616}3617 3618ArrayRef<BindingDecl *> BindingDecl::getBindingPackDecls() const {3619 assert(Binding && "expecting a pack expr");3620 auto *FP = cast<FunctionParmPackExpr>(Binding);3621 ValueDecl *const *First = FP->getNumExpansions() > 0 ? FP->begin() : nullptr;3622 assert((!First || isa<BindingDecl>(*First)) && "expecting a BindingDecl");3623 return ArrayRef<BindingDecl *>(reinterpret_cast<BindingDecl *const *>(First),3624 FP->getNumExpansions());3625}3626 3627void DecompositionDecl::anchor() {}3628 3629DecompositionDecl *DecompositionDecl::Create(ASTContext &C, DeclContext *DC,3630 SourceLocation StartLoc,3631 SourceLocation LSquareLoc,3632 QualType T, TypeSourceInfo *TInfo,3633 StorageClass SC,3634 ArrayRef<BindingDecl *> Bindings) {3635 size_t Extra = additionalSizeToAlloc<BindingDecl *>(Bindings.size());3636 return new (C, DC, Extra)3637 DecompositionDecl(C, DC, StartLoc, LSquareLoc, T, TInfo, SC, Bindings);3638}3639 3640DecompositionDecl *DecompositionDecl::CreateDeserialized(ASTContext &C,3641 GlobalDeclID ID,3642 unsigned NumBindings) {3643 size_t Extra = additionalSizeToAlloc<BindingDecl *>(NumBindings);3644 auto *Result = new (C, ID, Extra)3645 DecompositionDecl(C, nullptr, SourceLocation(), SourceLocation(),3646 QualType(), nullptr, StorageClass(), {});3647 // Set up and clean out the bindings array.3648 Result->NumBindings = NumBindings;3649 auto *Trail = Result->getTrailingObjects();3650 std::uninitialized_fill_n(Trail, NumBindings, nullptr);3651 return Result;3652}3653 3654void DecompositionDecl::printName(llvm::raw_ostream &OS,3655 const PrintingPolicy &Policy) const {3656 OS << '[';3657 bool Comma = false;3658 for (const auto *B : bindings()) {3659 if (Comma)3660 OS << ", ";3661 B->printName(OS, Policy);3662 Comma = true;3663 }3664 OS << ']';3665}3666 3667void MSPropertyDecl::anchor() {}3668 3669MSPropertyDecl *MSPropertyDecl::Create(ASTContext &C, DeclContext *DC,3670 SourceLocation L, DeclarationName N,3671 QualType T, TypeSourceInfo *TInfo,3672 SourceLocation StartL,3673 IdentifierInfo *Getter,3674 IdentifierInfo *Setter) {3675 return new (C, DC) MSPropertyDecl(DC, L, N, T, TInfo, StartL, Getter, Setter);3676}3677 3678MSPropertyDecl *MSPropertyDecl::CreateDeserialized(ASTContext &C,3679 GlobalDeclID ID) {3680 return new (C, ID) MSPropertyDecl(nullptr, SourceLocation(),3681 DeclarationName(), QualType(), nullptr,3682 SourceLocation(), nullptr, nullptr);3683}3684 3685void MSGuidDecl::anchor() {}3686 3687MSGuidDecl::MSGuidDecl(DeclContext *DC, QualType T, Parts P)3688 : ValueDecl(Decl::MSGuid, DC, SourceLocation(), DeclarationName(), T),3689 PartVal(P) {}3690 3691MSGuidDecl *MSGuidDecl::Create(const ASTContext &C, QualType T, Parts P) {3692 DeclContext *DC = C.getTranslationUnitDecl();3693 return new (C, DC) MSGuidDecl(DC, T, P);3694}3695 3696MSGuidDecl *MSGuidDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID) {3697 return new (C, ID) MSGuidDecl(nullptr, QualType(), Parts());3698}3699 3700void MSGuidDecl::printName(llvm::raw_ostream &OS,3701 const PrintingPolicy &) const {3702 OS << llvm::format("GUID{%08" PRIx32 "-%04" PRIx16 "-%04" PRIx16 "-",3703 PartVal.Part1, PartVal.Part2, PartVal.Part3);3704 unsigned I = 0;3705 for (uint8_t Byte : PartVal.Part4And5) {3706 OS << llvm::format("%02" PRIx8, Byte);3707 if (++I == 2)3708 OS << '-';3709 }3710 OS << '}';3711}3712 3713/// Determine if T is a valid 'struct _GUID' of the shape that we expect.3714static bool isValidStructGUID(ASTContext &Ctx, QualType T) {3715 // FIXME: We only need to check this once, not once each time we compute a3716 // GUID APValue.3717 using MatcherRef = llvm::function_ref<bool(QualType)>;3718 3719 auto IsInt = [&Ctx](unsigned N) {3720 return [&Ctx, N](QualType T) {3721 return T->isUnsignedIntegerOrEnumerationType() &&3722 Ctx.getIntWidth(T) == N;3723 };3724 };3725 3726 auto IsArray = [&Ctx](MatcherRef Elem, unsigned N) {3727 return [&Ctx, Elem, N](QualType T) {3728 const ConstantArrayType *CAT = Ctx.getAsConstantArrayType(T);3729 return CAT && CAT->getSize() == N && Elem(CAT->getElementType());3730 };3731 };3732 3733 auto IsStruct = [](std::initializer_list<MatcherRef> Fields) {3734 return [Fields](QualType T) {3735 const RecordDecl *RD = T->getAsRecordDecl();3736 if (!RD || RD->isUnion())3737 return false;3738 RD = RD->getDefinition();3739 if (!RD)3740 return false;3741 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))3742 if (CXXRD->getNumBases())3743 return false;3744 auto MatcherIt = Fields.begin();3745 for (const FieldDecl *FD : RD->fields()) {3746 if (FD->isUnnamedBitField())3747 continue;3748 if (FD->isBitField() || MatcherIt == Fields.end() ||3749 !(*MatcherIt)(FD->getType()))3750 return false;3751 ++MatcherIt;3752 }3753 return MatcherIt == Fields.end();3754 };3755 };3756 3757 // We expect an {i32, i16, i16, [8 x i8]}.3758 return IsStruct({IsInt(32), IsInt(16), IsInt(16), IsArray(IsInt(8), 8)})(T);3759}3760 3761APValue &MSGuidDecl::getAsAPValue() const {3762 if (APVal.isAbsent() && isValidStructGUID(getASTContext(), getType())) {3763 using llvm::APInt;3764 using llvm::APSInt;3765 APVal = APValue(APValue::UninitStruct(), 0, 4);3766 APVal.getStructField(0) = APValue(APSInt(APInt(32, PartVal.Part1), true));3767 APVal.getStructField(1) = APValue(APSInt(APInt(16, PartVal.Part2), true));3768 APVal.getStructField(2) = APValue(APSInt(APInt(16, PartVal.Part3), true));3769 APValue &Arr = APVal.getStructField(3) =3770 APValue(APValue::UninitArray(), 8, 8);3771 for (unsigned I = 0; I != 8; ++I) {3772 Arr.getArrayInitializedElt(I) =3773 APValue(APSInt(APInt(8, PartVal.Part4And5[I]), true));3774 }3775 // Register this APValue to be destroyed if necessary. (Note that the3776 // MSGuidDecl destructor is never run.)3777 getASTContext().addDestruction(&APVal);3778 }3779 3780 return APVal;3781}3782 3783void UnnamedGlobalConstantDecl::anchor() {}3784 3785UnnamedGlobalConstantDecl::UnnamedGlobalConstantDecl(const ASTContext &C,3786 DeclContext *DC,3787 QualType Ty,3788 const APValue &Val)3789 : ValueDecl(Decl::UnnamedGlobalConstant, DC, SourceLocation(),3790 DeclarationName(), Ty),3791 Value(Val) {3792 // Cleanup the embedded APValue if required (note that our destructor is never3793 // run)3794 if (Value.needsCleanup())3795 C.addDestruction(&Value);3796}3797 3798UnnamedGlobalConstantDecl *3799UnnamedGlobalConstantDecl::Create(const ASTContext &C, QualType T,3800 const APValue &Value) {3801 DeclContext *DC = C.getTranslationUnitDecl();3802 return new (C, DC) UnnamedGlobalConstantDecl(C, DC, T, Value);3803}3804 3805UnnamedGlobalConstantDecl *3806UnnamedGlobalConstantDecl::CreateDeserialized(ASTContext &C, GlobalDeclID ID) {3807 return new (C, ID)3808 UnnamedGlobalConstantDecl(C, nullptr, QualType(), APValue());3809}3810 3811void UnnamedGlobalConstantDecl::printName(llvm::raw_ostream &OS,3812 const PrintingPolicy &) const {3813 OS << "unnamed-global-constant";3814}3815 3816static const char *getAccessName(AccessSpecifier AS) {3817 switch (AS) {3818 case AS_none:3819 llvm_unreachable("Invalid access specifier!");3820 case AS_public:3821 return "public";3822 case AS_private:3823 return "private";3824 case AS_protected:3825 return "protected";3826 }3827 llvm_unreachable("Invalid access specifier!");3828}3829 3830const StreamingDiagnostic &clang::operator<<(const StreamingDiagnostic &DB,3831 AccessSpecifier AS) {3832 return DB << getAccessName(AS);3833}3834