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-exception 6 // 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/IdentifierTable.h" 33 #include "clang/Basic/LLVM.h" 34 #include "clang/Basic/LangOptions.h" 35 #include "clang/Basic/OperatorKinds.h" 36 #include "clang/Basic/PartialDiagnostic.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 52 using namespace clang; 53 54 //===----------------------------------------------------------------------===// 55 // Decl Allocation/Deallocation Method Implementations 56 //===----------------------------------------------------------------------===// 57 58 void AccessSpecDecl::anchor() {} 59 60 AccessSpecDecl *AccessSpecDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 61 return new (C, ID) AccessSpecDecl(EmptyShell()); 62 } 63 64 void LazyASTUnresolvedSet::getFromExternalSource(ASTContext &C) const { 65 ExternalASTSource *Source = C.getExternalSource(); 66 assert(Impl.Decls.isLazy() && "getFromExternalSource for non-lazy set"); 67 assert(Source && "getFromExternalSource with no external source"); 68 69 for (ASTUnresolvedSet::iterator I = Impl.begin(); I != Impl.end(); ++I) 70 I.setDecl(cast<NamedDecl>(Source->GetExternalDecl( 71 reinterpret_cast<uintptr_t>(I.getDecl()) >> 2))); 72 Impl.Decls.setLazy(false); 73 } 74 75 CXXRecordDecl::DefinitionData::DefinitionData(CXXRecordDecl *D) 76 : UserDeclaredConstructor(false), UserDeclaredSpecialMembers(0), 77 Aggregate(true), PlainOldData(true), Empty(true), Polymorphic(false), 78 Abstract(false), IsStandardLayout(true), IsCXX11StandardLayout(true), 79 HasBasesWithFields(false), HasBasesWithNonStaticDataMembers(false), 80 HasPrivateFields(false), HasProtectedFields(false), 81 HasPublicFields(false), HasMutableFields(false), HasVariantMembers(false), 82 HasOnlyCMembers(true), HasInitMethod(false), HasInClassInitializer(false), 83 HasUninitializedReferenceMember(false), HasUninitializedFields(false), 84 HasInheritedConstructor(false), HasInheritedDefaultConstructor(false), 85 HasInheritedAssignment(false), 86 NeedOverloadResolutionForCopyConstructor(false), 87 NeedOverloadResolutionForMoveConstructor(false), 88 NeedOverloadResolutionForCopyAssignment(false), 89 NeedOverloadResolutionForMoveAssignment(false), 90 NeedOverloadResolutionForDestructor(false), 91 DefaultedCopyConstructorIsDeleted(false), 92 DefaultedMoveConstructorIsDeleted(false), 93 DefaultedCopyAssignmentIsDeleted(false), 94 DefaultedMoveAssignmentIsDeleted(false), 95 DefaultedDestructorIsDeleted(false), HasTrivialSpecialMembers(SMF_All), 96 HasTrivialSpecialMembersForCall(SMF_All), 97 DeclaredNonTrivialSpecialMembers(0), 98 DeclaredNonTrivialSpecialMembersForCall(0), HasIrrelevantDestructor(true), 99 HasConstexprNonCopyMoveConstructor(false), 100 HasDefaultedDefaultConstructor(false), 101 DefaultedDefaultConstructorIsConstexpr(true), 102 HasConstexprDefaultConstructor(false), 103 DefaultedDestructorIsConstexpr(true), 104 HasNonLiteralTypeFieldsOrBases(false), StructuralIfLiteral(true), 105 UserProvidedDefaultConstructor(false), DeclaredSpecialMembers(0), 106 ImplicitCopyConstructorCanHaveConstParamForVBase(true), 107 ImplicitCopyConstructorCanHaveConstParamForNonVBase(true), 108 ImplicitCopyAssignmentHasConstParam(true), 109 HasDeclaredCopyConstructorWithConstParam(false), 110 HasDeclaredCopyAssignmentWithConstParam(false), 111 IsAnyDestructorNoReturn(false), IsLambda(false), 112 IsParsingBaseSpecifiers(false), ComputedVisibleConversions(false), 113 HasODRHash(false), Definition(D) {} 114 115 CXXBaseSpecifier *CXXRecordDecl::DefinitionData::getBasesSlowCase() const { 116 return Bases.get(Definition->getASTContext().getExternalSource()); 117 } 118 119 CXXBaseSpecifier *CXXRecordDecl::DefinitionData::getVBasesSlowCase() const { 120 return VBases.get(Definition->getASTContext().getExternalSource()); 121 } 122 123 CXXRecordDecl::CXXRecordDecl(Kind K, TagKind TK, const ASTContext &C, 124 DeclContext *DC, SourceLocation StartLoc, 125 SourceLocation IdLoc, IdentifierInfo *Id, 126 CXXRecordDecl *PrevDecl) 127 : RecordDecl(K, TK, C, DC, StartLoc, IdLoc, Id, PrevDecl), 128 DefinitionData(PrevDecl ? PrevDecl->DefinitionData 129 : nullptr) {} 130 131 CXXRecordDecl *CXXRecordDecl::Create(const ASTContext &C, TagKind TK, 132 DeclContext *DC, SourceLocation StartLoc, 133 SourceLocation IdLoc, IdentifierInfo *Id, 134 CXXRecordDecl *PrevDecl, 135 bool DelayTypeCreation) { 136 auto *R = new (C, DC) CXXRecordDecl(CXXRecord, TK, C, DC, StartLoc, IdLoc, Id, 137 PrevDecl); 138 R->setMayHaveOutOfDateDef(C.getLangOpts().Modules); 139 140 // FIXME: DelayTypeCreation seems like such a hack 141 if (!DelayTypeCreation) 142 C.getTypeDeclType(R, PrevDecl); 143 return R; 144 } 145 146 CXXRecordDecl * 147 CXXRecordDecl::CreateLambda(const ASTContext &C, DeclContext *DC, 148 TypeSourceInfo *Info, SourceLocation Loc, 149 unsigned DependencyKind, bool IsGeneric, 150 LambdaCaptureDefault CaptureDefault) { 151 auto *R = new (C, DC) CXXRecordDecl(CXXRecord, TagTypeKind::Class, C, DC, Loc, 152 Loc, nullptr, nullptr); 153 R->setBeingDefined(true); 154 R->DefinitionData = new (C) struct LambdaDefinitionData( 155 R, Info, DependencyKind, IsGeneric, CaptureDefault); 156 R->setMayHaveOutOfDateDef(false); 157 R->setImplicit(true); 158 159 C.getTypeDeclType(R, /*PrevDecl=*/nullptr); 160 return R; 161 } 162 163 CXXRecordDecl * 164 CXXRecordDecl::CreateDeserialized(const ASTContext &C, unsigned ID) { 165 auto *R = new (C, ID) 166 CXXRecordDecl(CXXRecord, TagTypeKind::Struct, C, nullptr, 167 SourceLocation(), SourceLocation(), nullptr, nullptr); 168 R->setMayHaveOutOfDateDef(false); 169 return R; 170 } 171 172 /// Determine whether a class has a repeated base class. This is intended for 173 /// use when determining if a class is standard-layout, so makes no attempt to 174 /// handle virtual bases. 175 static bool hasRepeatedBaseClass(const CXXRecordDecl *StartRD) { 176 llvm::SmallPtrSet<const CXXRecordDecl*, 8> SeenBaseTypes; 177 SmallVector<const CXXRecordDecl*, 8> WorkList = {StartRD}; 178 while (!WorkList.empty()) { 179 const CXXRecordDecl *RD = WorkList.pop_back_val(); 180 if (RD->getTypeForDecl()->isDependentType()) 181 continue; 182 for (const CXXBaseSpecifier &BaseSpec : RD->bases()) { 183 if (const CXXRecordDecl *B = BaseSpec.getType()->getAsCXXRecordDecl()) { 184 if (!SeenBaseTypes.insert(B).second) 185 return true; 186 WorkList.push_back(B); 187 } 188 } 189 } 190 return false; 191 } 192 193 void 194 CXXRecordDecl::setBases(CXXBaseSpecifier const * const *Bases, 195 unsigned NumBases) { 196 ASTContext &C = getASTContext(); 197 198 if (!data().Bases.isOffset() && data().NumBases > 0) 199 C.Deallocate(data().getBases()); 200 201 if (NumBases) { 202 if (!C.getLangOpts().CPlusPlus17) { 203 // C++ [dcl.init.aggr]p1: 204 // An aggregate is [...] a class with [...] no base classes [...]. 205 data().Aggregate = false; 206 } 207 208 // C++ [class]p4: 209 // A POD-struct is an aggregate class... 210 data().PlainOldData = false; 211 } 212 213 // The set of seen virtual base types. 214 llvm::SmallPtrSet<CanQualType, 8> SeenVBaseTypes; 215 216 // The virtual bases of this class. 217 SmallVector<const CXXBaseSpecifier *, 8> VBases; 218 219 data().Bases = new(C) CXXBaseSpecifier [NumBases]; 220 data().NumBases = NumBases; 221 for (unsigned i = 0; i < NumBases; ++i) { 222 data().getBases()[i] = *Bases[i]; 223 // Keep track of inherited vbases for this base class. 224 const CXXBaseSpecifier *Base = Bases[i]; 225 QualType BaseType = Base->getType(); 226 // Skip dependent types; we can't do any checking on them now. 227 if (BaseType->isDependentType()) 228 continue; 229 auto *BaseClassDecl = 230 cast<CXXRecordDecl>(BaseType->castAs<RecordType>()->getDecl()); 231 232 // C++2a [class]p7: 233 // A standard-layout class is a class that: 234 // [...] 235 // -- has all non-static data members and bit-fields in the class and 236 // its base classes first declared in the same class 237 if (BaseClassDecl->data().HasBasesWithFields || 238 !BaseClassDecl->field_empty()) { 239 if (data().HasBasesWithFields) 240 // Two bases have members or bit-fields: not standard-layout. 241 data().IsStandardLayout = false; 242 data().HasBasesWithFields = true; 243 } 244 245 // C++11 [class]p7: 246 // A standard-layout class is a class that: 247 // -- [...] has [...] at most one base class with non-static data 248 // members 249 if (BaseClassDecl->data().HasBasesWithNonStaticDataMembers || 250 BaseClassDecl->hasDirectFields()) { 251 if (data().HasBasesWithNonStaticDataMembers) 252 data().IsCXX11StandardLayout = false; 253 data().HasBasesWithNonStaticDataMembers = true; 254 } 255 256 if (!BaseClassDecl->isEmpty()) { 257 // C++14 [meta.unary.prop]p4: 258 // T is a class type [...] with [...] no base class B for which 259 // is_empty<B>::value is false. 260 data().Empty = false; 261 } 262 263 // C++1z [dcl.init.agg]p1: 264 // An aggregate is a class with [...] no private or protected base classes 265 if (Base->getAccessSpecifier() != AS_public) { 266 data().Aggregate = false; 267 268 // C++20 [temp.param]p7: 269 // A structural type is [...] a literal class type with [...] all base 270 // classes [...] public 271 data().StructuralIfLiteral = false; 272 } 273 274 // C++ [class.virtual]p1: 275 // A class that declares or inherits a virtual function is called a 276 // polymorphic class. 277 if (BaseClassDecl->isPolymorphic()) { 278 data().Polymorphic = true; 279 280 // An aggregate is a class with [...] no virtual functions. 281 data().Aggregate = false; 282 } 283 284 // C++0x [class]p7: 285 // A standard-layout class is a class that: [...] 286 // -- has no non-standard-layout base classes 287 if (!BaseClassDecl->isStandardLayout()) 288 data().IsStandardLayout = false; 289 if (!BaseClassDecl->isCXX11StandardLayout()) 290 data().IsCXX11StandardLayout = false; 291 292 // Record if this base is the first non-literal field or base. 293 if (!hasNonLiteralTypeFieldsOrBases() && !BaseType->isLiteralType(C)) 294 data().HasNonLiteralTypeFieldsOrBases = true; 295 296 // Now go through all virtual bases of this base and add them. 297 for (const auto &VBase : BaseClassDecl->vbases()) { 298 // Add this base if it's not already in the list. 299 if (SeenVBaseTypes.insert(C.getCanonicalType(VBase.getType())).second) { 300 VBases.push_back(&VBase); 301 302 // C++11 [class.copy]p8: 303 // The implicitly-declared copy constructor for a class X will have 304 // the form 'X::X(const X&)' if each [...] virtual base class B of X 305 // has a copy constructor whose first parameter is of type 306 // 'const B&' or 'const volatile B&' [...] 307 if (CXXRecordDecl *VBaseDecl = VBase.getType()->getAsCXXRecordDecl()) 308 if (!VBaseDecl->hasCopyConstructorWithConstParam()) 309 data().ImplicitCopyConstructorCanHaveConstParamForVBase = false; 310 311 // C++1z [dcl.init.agg]p1: 312 // An aggregate is a class with [...] no virtual base classes 313 data().Aggregate = false; 314 } 315 } 316 317 if (Base->isVirtual()) { 318 // Add this base if it's not already in the list. 319 if (SeenVBaseTypes.insert(C.getCanonicalType(BaseType)).second) 320 VBases.push_back(Base); 321 322 // C++14 [meta.unary.prop] is_empty: 323 // T is a class type, but not a union type, with ... no virtual base 324 // classes 325 data().Empty = false; 326 327 // C++1z [dcl.init.agg]p1: 328 // An aggregate is a class with [...] no virtual base classes 329 data().Aggregate = false; 330 331 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25: 332 // A [default constructor, copy/move constructor, or copy/move assignment 333 // operator for a class X] is trivial [...] if: 334 // -- class X has [...] no virtual base classes 335 data().HasTrivialSpecialMembers &= SMF_Destructor; 336 data().HasTrivialSpecialMembersForCall &= SMF_Destructor; 337 338 // C++0x [class]p7: 339 // A standard-layout class is a class that: [...] 340 // -- has [...] no virtual base classes 341 data().IsStandardLayout = false; 342 data().IsCXX11StandardLayout = false; 343 344 // C++20 [dcl.constexpr]p3: 345 // In the definition of a constexpr function [...] 346 // -- if the function is a constructor or destructor, 347 // its class shall not have any virtual base classes 348 data().DefaultedDefaultConstructorIsConstexpr = false; 349 data().DefaultedDestructorIsConstexpr = false; 350 351 // C++1z [class.copy]p8: 352 // The implicitly-declared copy constructor for a class X will have 353 // the form 'X::X(const X&)' if each potentially constructed subobject 354 // has a copy constructor whose first parameter is of type 355 // 'const B&' or 'const volatile B&' [...] 356 if (!BaseClassDecl->hasCopyConstructorWithConstParam()) 357 data().ImplicitCopyConstructorCanHaveConstParamForVBase = false; 358 } else { 359 // C++ [class.ctor]p5: 360 // A default constructor is trivial [...] if: 361 // -- all the direct base classes of its class have trivial default 362 // constructors. 363 if (!BaseClassDecl->hasTrivialDefaultConstructor()) 364 data().HasTrivialSpecialMembers &= ~SMF_DefaultConstructor; 365 366 // C++0x [class.copy]p13: 367 // A copy/move constructor for class X is trivial if [...] 368 // [...] 369 // -- the constructor selected to copy/move each direct base class 370 // subobject is trivial, and 371 if (!BaseClassDecl->hasTrivialCopyConstructor()) 372 data().HasTrivialSpecialMembers &= ~SMF_CopyConstructor; 373 374 if (!BaseClassDecl->hasTrivialCopyConstructorForCall()) 375 data().HasTrivialSpecialMembersForCall &= ~SMF_CopyConstructor; 376 377 // If the base class doesn't have a simple move constructor, we'll eagerly 378 // declare it and perform overload resolution to determine which function 379 // it actually calls. If it does have a simple move constructor, this 380 // check is correct. 381 if (!BaseClassDecl->hasTrivialMoveConstructor()) 382 data().HasTrivialSpecialMembers &= ~SMF_MoveConstructor; 383 384 if (!BaseClassDecl->hasTrivialMoveConstructorForCall()) 385 data().HasTrivialSpecialMembersForCall &= ~SMF_MoveConstructor; 386 387 // C++0x [class.copy]p27: 388 // A copy/move assignment operator for class X is trivial if [...] 389 // [...] 390 // -- the assignment operator selected to copy/move each direct base 391 // class subobject is trivial, and 392 if (!BaseClassDecl->hasTrivialCopyAssignment()) 393 data().HasTrivialSpecialMembers &= ~SMF_CopyAssignment; 394 // If the base class doesn't have a simple move assignment, we'll eagerly 395 // declare it and perform overload resolution to determine which function 396 // it actually calls. If it does have a simple move assignment, this 397 // check is correct. 398 if (!BaseClassDecl->hasTrivialMoveAssignment()) 399 data().HasTrivialSpecialMembers &= ~SMF_MoveAssignment; 400 401 // C++11 [class.ctor]p6: 402 // If that user-written default constructor would satisfy the 403 // requirements of a constexpr constructor, the implicitly-defined 404 // default constructor is constexpr. 405 if (!BaseClassDecl->hasConstexprDefaultConstructor()) 406 data().DefaultedDefaultConstructorIsConstexpr = false; 407 408 // C++1z [class.copy]p8: 409 // The implicitly-declared copy constructor for a class X will have 410 // the form 'X::X(const X&)' if each potentially constructed subobject 411 // has a copy constructor whose first parameter is of type 412 // 'const B&' or 'const volatile B&' [...] 413 if (!BaseClassDecl->hasCopyConstructorWithConstParam()) 414 data().ImplicitCopyConstructorCanHaveConstParamForNonVBase = false; 415 } 416 417 // C++ [class.ctor]p3: 418 // A destructor is trivial if all the direct base classes of its class 419 // have trivial destructors. 420 if (!BaseClassDecl->hasTrivialDestructor()) 421 data().HasTrivialSpecialMembers &= ~SMF_Destructor; 422 423 if (!BaseClassDecl->hasTrivialDestructorForCall()) 424 data().HasTrivialSpecialMembersForCall &= ~SMF_Destructor; 425 426 if (!BaseClassDecl->hasIrrelevantDestructor()) 427 data().HasIrrelevantDestructor = false; 428 429 if (BaseClassDecl->isAnyDestructorNoReturn()) 430 data().IsAnyDestructorNoReturn = true; 431 432 // C++11 [class.copy]p18: 433 // The implicitly-declared copy assignment operator for a class X will 434 // have the form 'X& X::operator=(const X&)' if each direct base class B 435 // of X has a copy assignment operator whose parameter is of type 'const 436 // B&', 'const volatile B&', or 'B' [...] 437 if (!BaseClassDecl->hasCopyAssignmentWithConstParam()) 438 data().ImplicitCopyAssignmentHasConstParam = false; 439 440 // A class has an Objective-C object member if... or any of its bases 441 // has an Objective-C object member. 442 if (BaseClassDecl->hasObjectMember()) 443 setHasObjectMember(true); 444 445 if (BaseClassDecl->hasVolatileMember()) 446 setHasVolatileMember(true); 447 448 if (BaseClassDecl->getArgPassingRestrictions() == 449 RecordArgPassingKind::CanNeverPassInRegs) 450 setArgPassingRestrictions(RecordArgPassingKind::CanNeverPassInRegs); 451 452 // Keep track of the presence of mutable fields. 453 if (BaseClassDecl->hasMutableFields()) 454 data().HasMutableFields = true; 455 456 if (BaseClassDecl->hasUninitializedReferenceMember()) 457 data().HasUninitializedReferenceMember = true; 458 459 if (!BaseClassDecl->allowConstDefaultInit()) 460 data().HasUninitializedFields = true; 461 462 addedClassSubobject(BaseClassDecl); 463 } 464 465 // C++2a [class]p7: 466 // A class S is a standard-layout class if it: 467 // -- has at most one base class subobject of any given type 468 // 469 // Note that we only need to check this for classes with more than one base 470 // class. If there's only one base class, and it's standard layout, then 471 // we know there are no repeated base classes. 472 if (data().IsStandardLayout && NumBases > 1 && hasRepeatedBaseClass(this)) 473 data().IsStandardLayout = false; 474 475 if (VBases.empty()) { 476 data().IsParsingBaseSpecifiers = false; 477 return; 478 } 479 480 // Create base specifier for any direct or indirect virtual bases. 481 data().VBases = new (C) CXXBaseSpecifier[VBases.size()]; 482 data().NumVBases = VBases.size(); 483 for (int I = 0, E = VBases.size(); I != E; ++I) { 484 QualType Type = VBases[I]->getType(); 485 if (!Type->isDependentType()) 486 addedClassSubobject(Type->getAsCXXRecordDecl()); 487 data().getVBases()[I] = *VBases[I]; 488 } 489 490 data().IsParsingBaseSpecifiers = false; 491 } 492 493 unsigned CXXRecordDecl::getODRHash() const { 494 assert(hasDefinition() && "ODRHash only for records with definitions"); 495 496 // Previously calculated hash is stored in DefinitionData. 497 if (DefinitionData->HasODRHash) 498 return DefinitionData->ODRHash; 499 500 // Only calculate hash on first call of getODRHash per record. 501 ODRHash Hash; 502 Hash.AddCXXRecordDecl(getDefinition()); 503 DefinitionData->HasODRHash = true; 504 DefinitionData->ODRHash = Hash.CalculateHash(); 505 506 return DefinitionData->ODRHash; 507 } 508 509 void CXXRecordDecl::addedClassSubobject(CXXRecordDecl *Subobj) { 510 // C++11 [class.copy]p11: 511 // A defaulted copy/move constructor for a class X is defined as 512 // deleted if X has: 513 // -- a direct or virtual base class B that cannot be copied/moved [...] 514 // -- a non-static data member of class type M (or array thereof) 515 // that cannot be copied or moved [...] 516 if (!Subobj->hasSimpleCopyConstructor()) 517 data().NeedOverloadResolutionForCopyConstructor = true; 518 if (!Subobj->hasSimpleMoveConstructor()) 519 data().NeedOverloadResolutionForMoveConstructor = true; 520 521 // C++11 [class.copy]p23: 522 // A defaulted copy/move assignment operator for a class X is defined as 523 // deleted if X has: 524 // -- a direct or virtual base class B that cannot be copied/moved [...] 525 // -- a non-static data member of class type M (or array thereof) 526 // that cannot be copied or moved [...] 527 if (!Subobj->hasSimpleCopyAssignment()) 528 data().NeedOverloadResolutionForCopyAssignment = true; 529 if (!Subobj->hasSimpleMoveAssignment()) 530 data().NeedOverloadResolutionForMoveAssignment = true; 531 532 // C++11 [class.ctor]p5, C++11 [class.copy]p11, C++11 [class.dtor]p5: 533 // A defaulted [ctor or dtor] for a class X is defined as 534 // deleted if X has: 535 // -- any direct or virtual base class [...] has a type with a destructor 536 // that is deleted or inaccessible from the defaulted [ctor or dtor]. 537 // -- any non-static data member has a type with a destructor 538 // that is deleted or inaccessible from the defaulted [ctor or dtor]. 539 if (!Subobj->hasSimpleDestructor()) { 540 data().NeedOverloadResolutionForCopyConstructor = true; 541 data().NeedOverloadResolutionForMoveConstructor = true; 542 data().NeedOverloadResolutionForDestructor = true; 543 } 544 545 // C++2a [dcl.constexpr]p4: 546 // The definition of a constexpr destructor [shall] satisfy the 547 // following requirement: 548 // -- for every subobject of class type or (possibly multi-dimensional) 549 // array thereof, that class type shall have a constexpr destructor 550 if (!Subobj->hasConstexprDestructor()) 551 data().DefaultedDestructorIsConstexpr = false; 552 553 // C++20 [temp.param]p7: 554 // A structural type is [...] a literal class type [for which] the types 555 // of all base classes and non-static data members are structural types or 556 // (possibly multi-dimensional) array thereof 557 if (!Subobj->data().StructuralIfLiteral) 558 data().StructuralIfLiteral = false; 559 } 560 561 bool CXXRecordDecl::hasConstexprDestructor() const { 562 auto *Dtor = getDestructor(); 563 return Dtor ? Dtor->isConstexpr() : defaultedDestructorIsConstexpr(); 564 } 565 566 bool CXXRecordDecl::hasAnyDependentBases() const { 567 if (!isDependentContext()) 568 return false; 569 570 return !forallBases([](const CXXRecordDecl *) { return true; }); 571 } 572 573 bool CXXRecordDecl::isTriviallyCopyable() const { 574 // C++0x [class]p5: 575 // A trivially copyable class is a class that: 576 // -- has no non-trivial copy constructors, 577 if (hasNonTrivialCopyConstructor()) return false; 578 // -- has no non-trivial move constructors, 579 if (hasNonTrivialMoveConstructor()) return false; 580 // -- has no non-trivial copy assignment operators, 581 if (hasNonTrivialCopyAssignment()) return false; 582 // -- has no non-trivial move assignment operators, and 583 if (hasNonTrivialMoveAssignment()) return false; 584 // -- has a trivial destructor. 585 if (!hasTrivialDestructor()) return false; 586 587 return true; 588 } 589 590 void CXXRecordDecl::markedVirtualFunctionPure() { 591 // C++ [class.abstract]p2: 592 // A class is abstract if it has at least one pure virtual function. 593 data().Abstract = true; 594 } 595 596 bool CXXRecordDecl::hasSubobjectAtOffsetZeroOfEmptyBaseType( 597 ASTContext &Ctx, const CXXRecordDecl *XFirst) { 598 if (!getNumBases()) 599 return false; 600 601 llvm::SmallPtrSet<const CXXRecordDecl*, 8> Bases; 602 llvm::SmallPtrSet<const CXXRecordDecl*, 8> M; 603 SmallVector<const CXXRecordDecl*, 8> WorkList; 604 605 // Visit a type that we have determined is an element of M(S). 606 auto Visit = [&](const CXXRecordDecl *RD) -> bool { 607 RD = RD->getCanonicalDecl(); 608 609 // C++2a [class]p8: 610 // A class S is a standard-layout class if it [...] has no element of the 611 // set M(S) of types as a base class. 612 // 613 // If we find a subobject of an empty type, it might also be a base class, 614 // so we'll need to walk the base classes to check. 615 if (!RD->data().HasBasesWithFields) { 616 // Walk the bases the first time, stopping if we find the type. Build a 617 // set of them so we don't need to walk them again. 618 if (Bases.empty()) { 619 bool RDIsBase = !forallBases([&](const CXXRecordDecl *Base) -> bool { 620 Base = Base->getCanonicalDecl(); 621 if (RD == Base) 622 return false; 623 Bases.insert(Base); 624 return true; 625 }); 626 if (RDIsBase) 627 return true; 628 } else { 629 if (Bases.count(RD)) 630 return true; 631 } 632 } 633 634 if (M.insert(RD).second) 635 WorkList.push_back(RD); 636 return false; 637 }; 638 639 if (Visit(XFirst)) 640 return true; 641 642 while (!WorkList.empty()) { 643 const CXXRecordDecl *X = WorkList.pop_back_val(); 644 645 // FIXME: We don't check the bases of X. That matches the standard, but 646 // that sure looks like a wording bug. 647 648 // -- If X is a non-union class type with a non-static data member 649 // [recurse to each field] that is either of zero size or is the 650 // first non-static data member of X 651 // -- If X is a union type, [recurse to union members] 652 bool IsFirstField = true; 653 for (auto *FD : X->fields()) { 654 // FIXME: Should we really care about the type of the first non-static 655 // data member of a non-union if there are preceding unnamed bit-fields? 656 if (FD->isUnnamedBitfield()) 657 continue; 658 659 if (!IsFirstField && !FD->isZeroSize(Ctx)) 660 continue; 661 662 // -- If X is n array type, [visit the element type] 663 QualType T = Ctx.getBaseElementType(FD->getType()); 664 if (auto *RD = T->getAsCXXRecordDecl()) 665 if (Visit(RD)) 666 return true; 667 668 if (!X->isUnion()) 669 IsFirstField = false; 670 } 671 } 672 673 return false; 674 } 675 676 bool CXXRecordDecl::lambdaIsDefaultConstructibleAndAssignable() const { 677 assert(isLambda() && "not a lambda"); 678 679 // C++2a [expr.prim.lambda.capture]p11: 680 // The closure type associated with a lambda-expression has no default 681 // constructor if the lambda-expression has a lambda-capture and a 682 // defaulted default constructor otherwise. It has a deleted copy 683 // assignment operator if the lambda-expression has a lambda-capture and 684 // defaulted copy and move assignment operators otherwise. 685 // 686 // C++17 [expr.prim.lambda]p21: 687 // The closure type associated with a lambda-expression has no default 688 // constructor and a deleted copy assignment operator. 689 if (!isCapturelessLambda()) 690 return false; 691 return getASTContext().getLangOpts().CPlusPlus20; 692 } 693 694 void CXXRecordDecl::addedMember(Decl *D) { 695 if (!D->isImplicit() && !isa<FieldDecl>(D) && !isa<IndirectFieldDecl>(D) && 696 (!isa<TagDecl>(D) || 697 cast<TagDecl>(D)->getTagKind() == TagTypeKind::Class || 698 cast<TagDecl>(D)->getTagKind() == TagTypeKind::Interface)) 699 data().HasOnlyCMembers = false; 700 701 // Ignore friends and invalid declarations. 702 if (D->getFriendObjectKind() || D->isInvalidDecl()) 703 return; 704 705 auto *FunTmpl = dyn_cast<FunctionTemplateDecl>(D); 706 if (FunTmpl) 707 D = FunTmpl->getTemplatedDecl(); 708 709 // FIXME: Pass NamedDecl* to addedMember? 710 Decl *DUnderlying = D; 711 if (auto *ND = dyn_cast<NamedDecl>(DUnderlying)) { 712 DUnderlying = ND->getUnderlyingDecl(); 713 if (auto *UnderlyingFunTmpl = dyn_cast<FunctionTemplateDecl>(DUnderlying)) 714 DUnderlying = UnderlyingFunTmpl->getTemplatedDecl(); 715 } 716 717 if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) { 718 if (Method->isVirtual()) { 719 // C++ [dcl.init.aggr]p1: 720 // An aggregate is an array or a class with [...] no virtual functions. 721 data().Aggregate = false; 722 723 // C++ [class]p4: 724 // A POD-struct is an aggregate class... 725 data().PlainOldData = false; 726 727 // C++14 [meta.unary.prop]p4: 728 // T is a class type [...] with [...] no virtual member functions... 729 data().Empty = false; 730 731 // C++ [class.virtual]p1: 732 // A class that declares or inherits a virtual function is called a 733 // polymorphic class. 734 data().Polymorphic = true; 735 736 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25: 737 // A [default constructor, copy/move constructor, or copy/move 738 // assignment operator for a class X] is trivial [...] if: 739 // -- class X has no virtual functions [...] 740 data().HasTrivialSpecialMembers &= SMF_Destructor; 741 data().HasTrivialSpecialMembersForCall &= SMF_Destructor; 742 743 // C++0x [class]p7: 744 // A standard-layout class is a class that: [...] 745 // -- has no virtual functions 746 data().IsStandardLayout = false; 747 data().IsCXX11StandardLayout = false; 748 } 749 } 750 751 // Notify the listener if an implicit member was added after the definition 752 // was completed. 753 if (!isBeingDefined() && D->isImplicit()) 754 if (ASTMutationListener *L = getASTMutationListener()) 755 L->AddedCXXImplicitMember(data().Definition, D); 756 757 // The kind of special member this declaration is, if any. 758 unsigned SMKind = 0; 759 760 // Handle constructors. 761 if (const auto *Constructor = dyn_cast<CXXConstructorDecl>(D)) { 762 if (Constructor->isInheritingConstructor()) { 763 // Ignore constructor shadow declarations. They are lazily created and 764 // so shouldn't affect any properties of the class. 765 } else { 766 if (!Constructor->isImplicit()) { 767 // Note that we have a user-declared constructor. 768 data().UserDeclaredConstructor = true; 769 770 const TargetInfo &TI = getASTContext().getTargetInfo(); 771 if ((!Constructor->isDeleted() && !Constructor->isDefaulted()) || 772 !TI.areDefaultedSMFStillPOD(getLangOpts())) { 773 // C++ [class]p4: 774 // A POD-struct is an aggregate class [...] 775 // Since the POD bit is meant to be C++03 POD-ness, clear it even if 776 // the type is technically an aggregate in C++0x since it wouldn't be 777 // in 03. 778 data().PlainOldData = false; 779 } 780 } 781 782 if (Constructor->isDefaultConstructor()) { 783 SMKind |= SMF_DefaultConstructor; 784 785 if (Constructor->isUserProvided()) 786 data().UserProvidedDefaultConstructor = true; 787 if (Constructor->isConstexpr()) 788 data().HasConstexprDefaultConstructor = true; 789 if (Constructor->isDefaulted()) 790 data().HasDefaultedDefaultConstructor = true; 791 } 792 793 if (!FunTmpl) { 794 unsigned Quals; 795 if (Constructor->isCopyConstructor(Quals)) { 796 SMKind |= SMF_CopyConstructor; 797 798 if (Quals & Qualifiers::Const) 799 data().HasDeclaredCopyConstructorWithConstParam = true; 800 } else if (Constructor->isMoveConstructor()) 801 SMKind |= SMF_MoveConstructor; 802 } 803 804 // C++11 [dcl.init.aggr]p1: DR1518 805 // An aggregate is an array or a class with no user-provided [or] 806 // explicit [...] constructors 807 // C++20 [dcl.init.aggr]p1: 808 // An aggregate is an array or a class with no user-declared [...] 809 // constructors 810 if (getASTContext().getLangOpts().CPlusPlus20 811 ? !Constructor->isImplicit() 812 : (Constructor->isUserProvided() || Constructor->isExplicit())) 813 data().Aggregate = false; 814 } 815 } 816 817 // Handle constructors, including those inherited from base classes. 818 if (const auto *Constructor = dyn_cast<CXXConstructorDecl>(DUnderlying)) { 819 // Record if we see any constexpr constructors which are neither copy 820 // nor move constructors. 821 // C++1z [basic.types]p10: 822 // [...] has at least one constexpr constructor or constructor template 823 // (possibly inherited from a base class) that is not a copy or move 824 // constructor [...] 825 if (Constructor->isConstexpr() && !Constructor->isCopyOrMoveConstructor()) 826 data().HasConstexprNonCopyMoveConstructor = true; 827 if (!isa<CXXConstructorDecl>(D) && Constructor->isDefaultConstructor()) 828 data().HasInheritedDefaultConstructor = true; 829 } 830 831 // Handle member functions. 832 if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) { 833 if (isa<CXXDestructorDecl>(D)) 834 SMKind |= SMF_Destructor; 835 836 if (Method->isCopyAssignmentOperator()) { 837 SMKind |= SMF_CopyAssignment; 838 839 const auto *ParamTy = 840 Method->getNonObjectParameter(0)->getType()->getAs<ReferenceType>(); 841 if (!ParamTy || ParamTy->getPointeeType().isConstQualified()) 842 data().HasDeclaredCopyAssignmentWithConstParam = true; 843 } 844 845 if (Method->isMoveAssignmentOperator()) 846 SMKind |= SMF_MoveAssignment; 847 848 // Keep the list of conversion functions up-to-date. 849 if (auto *Conversion = dyn_cast<CXXConversionDecl>(D)) { 850 // FIXME: We use the 'unsafe' accessor for the access specifier here, 851 // because Sema may not have set it yet. That's really just a misdesign 852 // in Sema. However, LLDB *will* have set the access specifier correctly, 853 // and adds declarations after the class is technically completed, 854 // so completeDefinition()'s overriding of the access specifiers doesn't 855 // work. 856 AccessSpecifier AS = Conversion->getAccessUnsafe(); 857 858 if (Conversion->getPrimaryTemplate()) { 859 // We don't record specializations. 860 } else { 861 ASTContext &Ctx = getASTContext(); 862 ASTUnresolvedSet &Conversions = data().Conversions.get(Ctx); 863 NamedDecl *Primary = 864 FunTmpl ? cast<NamedDecl>(FunTmpl) : cast<NamedDecl>(Conversion); 865 if (Primary->getPreviousDecl()) 866 Conversions.replace(cast<NamedDecl>(Primary->getPreviousDecl()), 867 Primary, AS); 868 else 869 Conversions.addDecl(Ctx, Primary, AS); 870 } 871 } 872 873 if (SMKind) { 874 // If this is the first declaration of a special member, we no longer have 875 // an implicit trivial special member. 876 data().HasTrivialSpecialMembers &= 877 data().DeclaredSpecialMembers | ~SMKind; 878 data().HasTrivialSpecialMembersForCall &= 879 data().DeclaredSpecialMembers | ~SMKind; 880 881 // Note when we have declared a declared special member, and suppress the 882 // implicit declaration of this special member. 883 data().DeclaredSpecialMembers |= SMKind; 884 if (!Method->isImplicit()) { 885 data().UserDeclaredSpecialMembers |= SMKind; 886 887 const TargetInfo &TI = getASTContext().getTargetInfo(); 888 if ((!Method->isDeleted() && !Method->isDefaulted() && 889 SMKind != SMF_MoveAssignment) || 890 !TI.areDefaultedSMFStillPOD(getLangOpts())) { 891 // C++03 [class]p4: 892 // A POD-struct is an aggregate class that has [...] no user-defined 893 // copy assignment operator and no user-defined destructor. 894 // 895 // Since the POD bit is meant to be C++03 POD-ness, and in C++03, 896 // aggregates could not have any constructors, clear it even for an 897 // explicitly defaulted or deleted constructor. 898 // type is technically an aggregate in C++0x since it wouldn't be in 899 // 03. 900 // 901 // Also, a user-declared move assignment operator makes a class 902 // non-POD. This is an extension in C++03. 903 data().PlainOldData = false; 904 } 905 } 906 // When instantiating a class, we delay updating the destructor and 907 // triviality properties of the class until selecting a destructor and 908 // computing the eligibility of its special member functions. This is 909 // because there might be function constraints that we need to evaluate 910 // and compare later in the instantiation. 911 if (!Method->isIneligibleOrNotSelected()) { 912 addedEligibleSpecialMemberFunction(Method, SMKind); 913 } 914 } 915 916 return; 917 } 918 919 // Handle non-static data members. 920 if (const auto *Field = dyn_cast<FieldDecl>(D)) { 921 ASTContext &Context = getASTContext(); 922 923 // C++2a [class]p7: 924 // A standard-layout class is a class that: 925 // [...] 926 // -- has all non-static data members and bit-fields in the class and 927 // its base classes first declared in the same class 928 if (data().HasBasesWithFields) 929 data().IsStandardLayout = false; 930 931 // C++ [class.bit]p2: 932 // A declaration for a bit-field that omits the identifier declares an 933 // unnamed bit-field. Unnamed bit-fields are not members and cannot be 934 // initialized. 935 if (Field->isUnnamedBitfield()) { 936 // C++ [meta.unary.prop]p4: [LWG2358] 937 // T is a class type [...] with [...] no unnamed bit-fields of non-zero 938 // length 939 if (data().Empty && !Field->isZeroLengthBitField(Context) && 940 Context.getLangOpts().getClangABICompat() > 941 LangOptions::ClangABI::Ver6) 942 data().Empty = false; 943 return; 944 } 945 946 // C++11 [class]p7: 947 // A standard-layout class is a class that: 948 // -- either has no non-static data members in the most derived class 949 // [...] or has no base classes with non-static data members 950 if (data().HasBasesWithNonStaticDataMembers) 951 data().IsCXX11StandardLayout = false; 952 953 // C++ [dcl.init.aggr]p1: 954 // An aggregate is an array or a class (clause 9) with [...] no 955 // private or protected non-static data members (clause 11). 956 // 957 // A POD must be an aggregate. 958 if (D->getAccess() == AS_private || D->getAccess() == AS_protected) { 959 data().Aggregate = false; 960 data().PlainOldData = false; 961 962 // C++20 [temp.param]p7: 963 // A structural type is [...] a literal class type [for which] all 964 // non-static data members are public 965 data().StructuralIfLiteral = false; 966 } 967 968 // Track whether this is the first field. We use this when checking 969 // whether the class is standard-layout below. 970 bool IsFirstField = !data().HasPrivateFields && 971 !data().HasProtectedFields && !data().HasPublicFields; 972 973 // C++0x [class]p7: 974 // A standard-layout class is a class that: 975 // [...] 976 // -- has the same access control for all non-static data members, 977 switch (D->getAccess()) { 978 case AS_private: data().HasPrivateFields = true; break; 979 case AS_protected: data().HasProtectedFields = true; break; 980 case AS_public: data().HasPublicFields = true; break; 981 case AS_none: llvm_unreachable("Invalid access specifier"); 982 }; 983 if ((data().HasPrivateFields + data().HasProtectedFields + 984 data().HasPublicFields) > 1) { 985 data().IsStandardLayout = false; 986 data().IsCXX11StandardLayout = false; 987 } 988 989 // Keep track of the presence of mutable fields. 990 if (Field->isMutable()) { 991 data().HasMutableFields = true; 992 993 // C++20 [temp.param]p7: 994 // A structural type is [...] a literal class type [for which] all 995 // non-static data members are public 996 data().StructuralIfLiteral = false; 997 } 998 999 // C++11 [class.union]p8, DR1460: 1000 // If X is a union, a non-static data member of X that is not an anonymous 1001 // union is a variant member of X. 1002 if (isUnion() && !Field->isAnonymousStructOrUnion()) 1003 data().HasVariantMembers = true; 1004 1005 // C++0x [class]p9: 1006 // A POD struct is a class that is both a trivial class and a 1007 // standard-layout class, and has no non-static data members of type 1008 // non-POD struct, non-POD union (or array of such types). 1009 // 1010 // Automatic Reference Counting: the presence of a member of Objective-C pointer type 1011 // that does not explicitly have no lifetime makes the class a non-POD. 1012 QualType T = Context.getBaseElementType(Field->getType()); 1013 if (T->isObjCRetainableType() || T.isObjCGCStrong()) { 1014 if (T.hasNonTrivialObjCLifetime()) { 1015 // Objective-C Automatic Reference Counting: 1016 // If a class has a non-static data member of Objective-C pointer 1017 // type (or array thereof), it is a non-POD type and its 1018 // default constructor (if any), copy constructor, move constructor, 1019 // copy assignment operator, move assignment operator, and destructor are 1020 // non-trivial. 1021 setHasObjectMember(true); 1022 struct DefinitionData &Data = data(); 1023 Data.PlainOldData = false; 1024 Data.HasTrivialSpecialMembers = 0; 1025 1026 // __strong or __weak fields do not make special functions non-trivial 1027 // for the purpose of calls. 1028 Qualifiers::ObjCLifetime LT = T.getQualifiers().getObjCLifetime(); 1029 if (LT != Qualifiers::OCL_Strong && LT != Qualifiers::OCL_Weak) 1030 data().HasTrivialSpecialMembersForCall = 0; 1031 1032 // Structs with __weak fields should never be passed directly. 1033 if (LT == Qualifiers::OCL_Weak) 1034 setArgPassingRestrictions(RecordArgPassingKind::CanNeverPassInRegs); 1035 1036 Data.HasIrrelevantDestructor = false; 1037 1038 if (isUnion()) { 1039 data().DefaultedCopyConstructorIsDeleted = true; 1040 data().DefaultedMoveConstructorIsDeleted = true; 1041 data().DefaultedCopyAssignmentIsDeleted = true; 1042 data().DefaultedMoveAssignmentIsDeleted = true; 1043 data().DefaultedDestructorIsDeleted = true; 1044 data().NeedOverloadResolutionForCopyConstructor = true; 1045 data().NeedOverloadResolutionForMoveConstructor = true; 1046 data().NeedOverloadResolutionForCopyAssignment = true; 1047 data().NeedOverloadResolutionForMoveAssignment = true; 1048 data().NeedOverloadResolutionForDestructor = true; 1049 } 1050 } else if (!Context.getLangOpts().ObjCAutoRefCount) { 1051 setHasObjectMember(true); 1052 } 1053 } else if (!T.isCXX98PODType(Context)) 1054 data().PlainOldData = false; 1055 1056 if (T->isReferenceType()) { 1057 if (!Field->hasInClassInitializer()) 1058 data().HasUninitializedReferenceMember = true; 1059 1060 // C++0x [class]p7: 1061 // A standard-layout class is a class that: 1062 // -- has no non-static data members of type [...] reference, 1063 data().IsStandardLayout = false; 1064 data().IsCXX11StandardLayout = false; 1065 1066 // C++1z [class.copy.ctor]p10: 1067 // A defaulted copy constructor for a class X is defined as deleted if X has: 1068 // -- a non-static data member of rvalue reference type 1069 if (T->isRValueReferenceType()) 1070 data().DefaultedCopyConstructorIsDeleted = true; 1071 } 1072 1073 if (!Field->hasInClassInitializer() && !Field->isMutable()) { 1074 if (CXXRecordDecl *FieldType = T->getAsCXXRecordDecl()) { 1075 if (FieldType->hasDefinition() && !FieldType->allowConstDefaultInit()) 1076 data().HasUninitializedFields = true; 1077 } else { 1078 data().HasUninitializedFields = true; 1079 } 1080 } 1081 1082 // Record if this field is the first non-literal or volatile field or base. 1083 if (!T->isLiteralType(Context) || T.isVolatileQualified()) 1084 data().HasNonLiteralTypeFieldsOrBases = true; 1085 1086 if (Field->hasInClassInitializer() || 1087 (Field->isAnonymousStructOrUnion() && 1088 Field->getType()->getAsCXXRecordDecl()->hasInClassInitializer())) { 1089 data().HasInClassInitializer = true; 1090 1091 // C++11 [class]p5: 1092 // A default constructor is trivial if [...] no non-static data member 1093 // of its class has a brace-or-equal-initializer. 1094 data().HasTrivialSpecialMembers &= ~SMF_DefaultConstructor; 1095 1096 // C++11 [dcl.init.aggr]p1: 1097 // An aggregate is a [...] class with [...] no 1098 // brace-or-equal-initializers for non-static data members. 1099 // 1100 // This rule was removed in C++14. 1101 if (!getASTContext().getLangOpts().CPlusPlus14) 1102 data().Aggregate = false; 1103 1104 // C++11 [class]p10: 1105 // A POD struct is [...] a trivial class. 1106 data().PlainOldData = false; 1107 } 1108 1109 // C++11 [class.copy]p23: 1110 // A defaulted copy/move assignment operator for a class X is defined 1111 // as deleted if X has: 1112 // -- a non-static data member of reference type 1113 if (T->isReferenceType()) { 1114 data().DefaultedCopyAssignmentIsDeleted = true; 1115 data().DefaultedMoveAssignmentIsDeleted = true; 1116 } 1117 1118 // Bitfields of length 0 are also zero-sized, but we already bailed out for 1119 // those because they are always unnamed. 1120 bool IsZeroSize = Field->isZeroSize(Context); 1121 1122 if (const auto *RecordTy = T->getAs<RecordType>()) { 1123 auto *FieldRec = cast<CXXRecordDecl>(RecordTy->getDecl()); 1124 if (FieldRec->getDefinition()) { 1125 addedClassSubobject(FieldRec); 1126 1127 // We may need to perform overload resolution to determine whether a 1128 // field can be moved if it's const or volatile qualified. 1129 if (T.getCVRQualifiers() & (Qualifiers::Const | Qualifiers::Volatile)) { 1130 // We need to care about 'const' for the copy constructor because an 1131 // implicit copy constructor might be declared with a non-const 1132 // parameter. 1133 data().NeedOverloadResolutionForCopyConstructor = true; 1134 data().NeedOverloadResolutionForMoveConstructor = true; 1135 data().NeedOverloadResolutionForCopyAssignment = true; 1136 data().NeedOverloadResolutionForMoveAssignment = true; 1137 } 1138 1139 // C++11 [class.ctor]p5, C++11 [class.copy]p11: 1140 // A defaulted [special member] for a class X is defined as 1141 // deleted if: 1142 // -- X is a union-like class that has a variant member with a 1143 // non-trivial [corresponding special member] 1144 if (isUnion()) { 1145 if (FieldRec->hasNonTrivialCopyConstructor()) 1146 data().DefaultedCopyConstructorIsDeleted = true; 1147 if (FieldRec->hasNonTrivialMoveConstructor()) 1148 data().DefaultedMoveConstructorIsDeleted = true; 1149 if (FieldRec->hasNonTrivialCopyAssignment()) 1150 data().DefaultedCopyAssignmentIsDeleted = true; 1151 if (FieldRec->hasNonTrivialMoveAssignment()) 1152 data().DefaultedMoveAssignmentIsDeleted = true; 1153 if (FieldRec->hasNonTrivialDestructor()) 1154 data().DefaultedDestructorIsDeleted = true; 1155 } 1156 1157 // For an anonymous union member, our overload resolution will perform 1158 // overload resolution for its members. 1159 if (Field->isAnonymousStructOrUnion()) { 1160 data().NeedOverloadResolutionForCopyConstructor |= 1161 FieldRec->data().NeedOverloadResolutionForCopyConstructor; 1162 data().NeedOverloadResolutionForMoveConstructor |= 1163 FieldRec->data().NeedOverloadResolutionForMoveConstructor; 1164 data().NeedOverloadResolutionForCopyAssignment |= 1165 FieldRec->data().NeedOverloadResolutionForCopyAssignment; 1166 data().NeedOverloadResolutionForMoveAssignment |= 1167 FieldRec->data().NeedOverloadResolutionForMoveAssignment; 1168 data().NeedOverloadResolutionForDestructor |= 1169 FieldRec->data().NeedOverloadResolutionForDestructor; 1170 } 1171 1172 // C++0x [class.ctor]p5: 1173 // A default constructor is trivial [...] if: 1174 // -- for all the non-static data members of its class that are of 1175 // class type (or array thereof), each such class has a trivial 1176 // default constructor. 1177 if (!FieldRec->hasTrivialDefaultConstructor()) 1178 data().HasTrivialSpecialMembers &= ~SMF_DefaultConstructor; 1179 1180 // C++0x [class.copy]p13: 1181 // A copy/move constructor for class X is trivial if [...] 1182 // [...] 1183 // -- for each non-static data member of X that is of class type (or 1184 // an array thereof), the constructor selected to copy/move that 1185 // member is trivial; 1186 if (!FieldRec->hasTrivialCopyConstructor()) 1187 data().HasTrivialSpecialMembers &= ~SMF_CopyConstructor; 1188 1189 if (!FieldRec->hasTrivialCopyConstructorForCall()) 1190 data().HasTrivialSpecialMembersForCall &= ~SMF_CopyConstructor; 1191 1192 // If the field doesn't have a simple move constructor, we'll eagerly 1193 // declare the move constructor for this class and we'll decide whether 1194 // it's trivial then. 1195 if (!FieldRec->hasTrivialMoveConstructor()) 1196 data().HasTrivialSpecialMembers &= ~SMF_MoveConstructor; 1197 1198 if (!FieldRec->hasTrivialMoveConstructorForCall()) 1199 data().HasTrivialSpecialMembersForCall &= ~SMF_MoveConstructor; 1200 1201 // C++0x [class.copy]p27: 1202 // A copy/move assignment operator for class X is trivial if [...] 1203 // [...] 1204 // -- for each non-static data member of X that is of class type (or 1205 // an array thereof), the assignment operator selected to 1206 // copy/move that member is trivial; 1207 if (!FieldRec->hasTrivialCopyAssignment()) 1208 data().HasTrivialSpecialMembers &= ~SMF_CopyAssignment; 1209 // If the field doesn't have a simple move assignment, we'll eagerly 1210 // declare the move assignment for this class and we'll decide whether 1211 // it's trivial then. 1212 if (!FieldRec->hasTrivialMoveAssignment()) 1213 data().HasTrivialSpecialMembers &= ~SMF_MoveAssignment; 1214 1215 if (!FieldRec->hasTrivialDestructor()) 1216 data().HasTrivialSpecialMembers &= ~SMF_Destructor; 1217 if (!FieldRec->hasTrivialDestructorForCall()) 1218 data().HasTrivialSpecialMembersForCall &= ~SMF_Destructor; 1219 if (!FieldRec->hasIrrelevantDestructor()) 1220 data().HasIrrelevantDestructor = false; 1221 if (FieldRec->isAnyDestructorNoReturn()) 1222 data().IsAnyDestructorNoReturn = true; 1223 if (FieldRec->hasObjectMember()) 1224 setHasObjectMember(true); 1225 if (FieldRec->hasVolatileMember()) 1226 setHasVolatileMember(true); 1227 if (FieldRec->getArgPassingRestrictions() == 1228 RecordArgPassingKind::CanNeverPassInRegs) 1229 setArgPassingRestrictions(RecordArgPassingKind::CanNeverPassInRegs); 1230 1231 // C++0x [class]p7: 1232 // A standard-layout class is a class that: 1233 // -- has no non-static data members of type non-standard-layout 1234 // class (or array of such types) [...] 1235 if (!FieldRec->isStandardLayout()) 1236 data().IsStandardLayout = false; 1237 if (!FieldRec->isCXX11StandardLayout()) 1238 data().IsCXX11StandardLayout = false; 1239 1240 // C++2a [class]p7: 1241 // A standard-layout class is a class that: 1242 // [...] 1243 // -- has no element of the set M(S) of types as a base class. 1244 if (data().IsStandardLayout && 1245 (isUnion() || IsFirstField || IsZeroSize) && 1246 hasSubobjectAtOffsetZeroOfEmptyBaseType(Context, FieldRec)) 1247 data().IsStandardLayout = false; 1248 1249 // C++11 [class]p7: 1250 // A standard-layout class is a class that: 1251 // -- has no base classes of the same type as the first non-static 1252 // data member 1253 if (data().IsCXX11StandardLayout && IsFirstField) { 1254 // FIXME: We should check all base classes here, not just direct 1255 // base classes. 1256 for (const auto &BI : bases()) { 1257 if (Context.hasSameUnqualifiedType(BI.getType(), T)) { 1258 data().IsCXX11StandardLayout = false; 1259 break; 1260 } 1261 } 1262 } 1263 1264 // Keep track of the presence of mutable fields. 1265 if (FieldRec->hasMutableFields()) 1266 data().HasMutableFields = true; 1267 1268 if (Field->isMutable()) { 1269 // Our copy constructor/assignment might call something other than 1270 // the subobject's copy constructor/assignment if it's mutable and of 1271 // class type. 1272 data().NeedOverloadResolutionForCopyConstructor = true; 1273 data().NeedOverloadResolutionForCopyAssignment = true; 1274 } 1275 1276 // C++11 [class.copy]p13: 1277 // If the implicitly-defined constructor would satisfy the 1278 // requirements of a constexpr constructor, the implicitly-defined 1279 // constructor is constexpr. 1280 // C++11 [dcl.constexpr]p4: 1281 // -- every constructor involved in initializing non-static data 1282 // members [...] shall be a constexpr constructor 1283 if (!Field->hasInClassInitializer() && 1284 !FieldRec->hasConstexprDefaultConstructor() && !isUnion()) 1285 // The standard requires any in-class initializer to be a constant 1286 // expression. We consider this to be a defect. 1287 data().DefaultedDefaultConstructorIsConstexpr = false; 1288 1289 // C++11 [class.copy]p8: 1290 // The implicitly-declared copy constructor for a class X will have 1291 // the form 'X::X(const X&)' if each potentially constructed subobject 1292 // of a class type M (or array thereof) has a copy constructor whose 1293 // first parameter is of type 'const M&' or 'const volatile M&'. 1294 if (!FieldRec->hasCopyConstructorWithConstParam()) 1295 data().ImplicitCopyConstructorCanHaveConstParamForNonVBase = false; 1296 1297 // C++11 [class.copy]p18: 1298 // The implicitly-declared copy assignment oeprator for a class X will 1299 // have the form 'X& X::operator=(const X&)' if [...] for all the 1300 // non-static data members of X that are of a class type M (or array 1301 // thereof), each such class type has a copy assignment operator whose 1302 // parameter is of type 'const M&', 'const volatile M&' or 'M'. 1303 if (!FieldRec->hasCopyAssignmentWithConstParam()) 1304 data().ImplicitCopyAssignmentHasConstParam = false; 1305 1306 if (FieldRec->hasUninitializedReferenceMember() && 1307 !Field->hasInClassInitializer()) 1308 data().HasUninitializedReferenceMember = true; 1309 1310 // C++11 [class.union]p8, DR1460: 1311 // a non-static data member of an anonymous union that is a member of 1312 // X is also a variant member of X. 1313 if (FieldRec->hasVariantMembers() && 1314 Field->isAnonymousStructOrUnion()) 1315 data().HasVariantMembers = true; 1316 } 1317 } else { 1318 // Base element type of field is a non-class type. 1319 if (!T->isLiteralType(Context) || 1320 (!Field->hasInClassInitializer() && !isUnion() && 1321 !Context.getLangOpts().CPlusPlus20)) 1322 data().DefaultedDefaultConstructorIsConstexpr = false; 1323 1324 // C++11 [class.copy]p23: 1325 // A defaulted copy/move assignment operator for a class X is defined 1326 // as deleted if X has: 1327 // -- a non-static data member of const non-class type (or array 1328 // thereof) 1329 if (T.isConstQualified()) { 1330 data().DefaultedCopyAssignmentIsDeleted = true; 1331 data().DefaultedMoveAssignmentIsDeleted = true; 1332 } 1333 1334 // C++20 [temp.param]p7: 1335 // A structural type is [...] a literal class type [for which] the 1336 // types of all non-static data members are structural types or 1337 // (possibly multidimensional) array thereof 1338 // We deal with class types elsewhere. 1339 if (!T->isStructuralType()) 1340 data().StructuralIfLiteral = false; 1341 } 1342 1343 // C++14 [meta.unary.prop]p4: 1344 // T is a class type [...] with [...] no non-static data members other 1345 // than subobjects of zero size 1346 if (data().Empty && !IsZeroSize) 1347 data().Empty = false; 1348 } 1349 1350 // Handle using declarations of conversion functions. 1351 if (auto *Shadow = dyn_cast<UsingShadowDecl>(D)) { 1352 if (Shadow->getDeclName().getNameKind() 1353 == DeclarationName::CXXConversionFunctionName) { 1354 ASTContext &Ctx = getASTContext(); 1355 data().Conversions.get(Ctx).addDecl(Ctx, Shadow, Shadow->getAccess()); 1356 } 1357 } 1358 1359 if (const auto *Using = dyn_cast<UsingDecl>(D)) { 1360 if (Using->getDeclName().getNameKind() == 1361 DeclarationName::CXXConstructorName) { 1362 data().HasInheritedConstructor = true; 1363 // C++1z [dcl.init.aggr]p1: 1364 // An aggregate is [...] a class [...] with no inherited constructors 1365 data().Aggregate = false; 1366 } 1367 1368 if (Using->getDeclName().getCXXOverloadedOperator() == OO_Equal) 1369 data().HasInheritedAssignment = true; 1370 } 1371 } 1372 1373 void CXXRecordDecl::addedSelectedDestructor(CXXDestructorDecl *DD) { 1374 DD->setIneligibleOrNotSelected(false); 1375 addedEligibleSpecialMemberFunction(DD, SMF_Destructor); 1376 } 1377 1378 void CXXRecordDecl::addedEligibleSpecialMemberFunction(const CXXMethodDecl *MD, 1379 unsigned SMKind) { 1380 // FIXME: We shouldn't change DeclaredNonTrivialSpecialMembers if `MD` is 1381 // a function template, but this needs CWG attention before we break ABI. 1382 // See https://github.com/llvm/llvm-project/issues/59206 1383 1384 if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD)) { 1385 if (DD->isUserProvided()) 1386 data().HasIrrelevantDestructor = false; 1387 // If the destructor is explicitly defaulted and not trivial or not public 1388 // or if the destructor is deleted, we clear HasIrrelevantDestructor in 1389 // finishedDefaultedOrDeletedMember. 1390 1391 // C++11 [class.dtor]p5: 1392 // A destructor is trivial if [...] the destructor is not virtual. 1393 if (DD->isVirtual()) { 1394 data().HasTrivialSpecialMembers &= ~SMF_Destructor; 1395 data().HasTrivialSpecialMembersForCall &= ~SMF_Destructor; 1396 } 1397 1398 if (DD->isNoReturn()) 1399 data().IsAnyDestructorNoReturn = true; 1400 } 1401 1402 if (!MD->isImplicit() && !MD->isUserProvided()) { 1403 // This method is user-declared but not user-provided. We can't work 1404 // out whether it's trivial yet (not until we get to the end of the 1405 // class). We'll handle this method in 1406 // finishedDefaultedOrDeletedMember. 1407 } else if (MD->isTrivial()) { 1408 data().HasTrivialSpecialMembers |= SMKind; 1409 data().HasTrivialSpecialMembersForCall |= SMKind; 1410 } else if (MD->isTrivialForCall()) { 1411 data().HasTrivialSpecialMembersForCall |= SMKind; 1412 data().DeclaredNonTrivialSpecialMembers |= SMKind; 1413 } else { 1414 data().DeclaredNonTrivialSpecialMembers |= SMKind; 1415 // If this is a user-provided function, do not set 1416 // DeclaredNonTrivialSpecialMembersForCall here since we don't know 1417 // yet whether the method would be considered non-trivial for the 1418 // purpose of calls (attribute "trivial_abi" can be dropped from the 1419 // class later, which can change the special method's triviality). 1420 if (!MD->isUserProvided()) 1421 data().DeclaredNonTrivialSpecialMembersForCall |= SMKind; 1422 } 1423 } 1424 1425 void CXXRecordDecl::finishedDefaultedOrDeletedMember(CXXMethodDecl *D) { 1426 assert(!D->isImplicit() && !D->isUserProvided()); 1427 1428 // The kind of special member this declaration is, if any. 1429 unsigned SMKind = 0; 1430 1431 if (const auto *Constructor = dyn_cast<CXXConstructorDecl>(D)) { 1432 if (Constructor->isDefaultConstructor()) { 1433 SMKind |= SMF_DefaultConstructor; 1434 if (Constructor->isConstexpr()) 1435 data().HasConstexprDefaultConstructor = true; 1436 } 1437 if (Constructor->isCopyConstructor()) 1438 SMKind |= SMF_CopyConstructor; 1439 else if (Constructor->isMoveConstructor()) 1440 SMKind |= SMF_MoveConstructor; 1441 else if (Constructor->isConstexpr()) 1442 // We may now know that the constructor is constexpr. 1443 data().HasConstexprNonCopyMoveConstructor = true; 1444 } else if (isa<CXXDestructorDecl>(D)) { 1445 SMKind |= SMF_Destructor; 1446 if (!D->isTrivial() || D->getAccess() != AS_public || D->isDeleted()) 1447 data().HasIrrelevantDestructor = false; 1448 } else if (D->isCopyAssignmentOperator()) 1449 SMKind |= SMF_CopyAssignment; 1450 else if (D->isMoveAssignmentOperator()) 1451 SMKind |= SMF_MoveAssignment; 1452 1453 // Update which trivial / non-trivial special members we have. 1454 // addedMember will have skipped this step for this member. 1455 if (!D->isIneligibleOrNotSelected()) { 1456 if (D->isTrivial()) 1457 data().HasTrivialSpecialMembers |= SMKind; 1458 else 1459 data().DeclaredNonTrivialSpecialMembers |= SMKind; 1460 } 1461 } 1462 1463 void CXXRecordDecl::LambdaDefinitionData::AddCaptureList(ASTContext &Ctx, 1464 Capture *CaptureList) { 1465 Captures.push_back(CaptureList); 1466 if (Captures.size() == 2) { 1467 // The TinyPtrVector member now needs destruction. 1468 Ctx.addDestruction(&Captures); 1469 } 1470 } 1471 1472 void CXXRecordDecl::setCaptures(ASTContext &Context, 1473 ArrayRef<LambdaCapture> Captures) { 1474 CXXRecordDecl::LambdaDefinitionData &Data = getLambdaData(); 1475 1476 // Copy captures. 1477 Data.NumCaptures = Captures.size(); 1478 Data.NumExplicitCaptures = 0; 1479 auto *ToCapture = (LambdaCapture *)Context.Allocate(sizeof(LambdaCapture) * 1480 Captures.size()); 1481 Data.AddCaptureList(Context, ToCapture); 1482 for (unsigned I = 0, N = Captures.size(); I != N; ++I) { 1483 if (Captures[I].isExplicit()) 1484 ++Data.NumExplicitCaptures; 1485 1486 new (ToCapture) LambdaCapture(Captures[I]); 1487 ToCapture++; 1488 } 1489 1490 if (!lambdaIsDefaultConstructibleAndAssignable()) 1491 Data.DefaultedCopyAssignmentIsDeleted = true; 1492 } 1493 1494 void CXXRecordDecl::setTrivialForCallFlags(CXXMethodDecl *D) { 1495 unsigned SMKind = 0; 1496 1497 if (const auto *Constructor = dyn_cast<CXXConstructorDecl>(D)) { 1498 if (Constructor->isCopyConstructor()) 1499 SMKind = SMF_CopyConstructor; 1500 else if (Constructor->isMoveConstructor()) 1501 SMKind = SMF_MoveConstructor; 1502 } else if (isa<CXXDestructorDecl>(D)) 1503 SMKind = SMF_Destructor; 1504 1505 if (D->isTrivialForCall()) 1506 data().HasTrivialSpecialMembersForCall |= SMKind; 1507 else 1508 data().DeclaredNonTrivialSpecialMembersForCall |= SMKind; 1509 } 1510 1511 bool CXXRecordDecl::isCLike() const { 1512 if (getTagKind() == TagTypeKind::Class || 1513 getTagKind() == TagTypeKind::Interface || 1514 !TemplateOrInstantiation.isNull()) 1515 return false; 1516 if (!hasDefinition()) 1517 return true; 1518 1519 return isPOD() && data().HasOnlyCMembers; 1520 } 1521 1522 bool CXXRecordDecl::isGenericLambda() const { 1523 if (!isLambda()) return false; 1524 return getLambdaData().IsGenericLambda; 1525 } 1526 1527 #ifndef NDEBUG 1528 static bool allLookupResultsAreTheSame(const DeclContext::lookup_result &R) { 1529 for (auto *D : R) 1530 if (!declaresSameEntity(D, R.front())) 1531 return false; 1532 return true; 1533 } 1534 #endif 1535 1536 static NamedDecl* getLambdaCallOperatorHelper(const CXXRecordDecl &RD) { 1537 if (!RD.isLambda()) return nullptr; 1538 DeclarationName Name = 1539 RD.getASTContext().DeclarationNames.getCXXOperatorName(OO_Call); 1540 DeclContext::lookup_result Calls = RD.lookup(Name); 1541 1542 assert(!Calls.empty() && "Missing lambda call operator!"); 1543 assert(allLookupResultsAreTheSame(Calls) && 1544 "More than one lambda call operator!"); 1545 return Calls.front(); 1546 } 1547 1548 FunctionTemplateDecl* CXXRecordDecl::getDependentLambdaCallOperator() const { 1549 NamedDecl *CallOp = getLambdaCallOperatorHelper(*this); 1550 return dyn_cast_or_null<FunctionTemplateDecl>(CallOp); 1551 } 1552 1553 CXXMethodDecl *CXXRecordDecl::getLambdaCallOperator() const { 1554 NamedDecl *CallOp = getLambdaCallOperatorHelper(*this); 1555 1556 if (CallOp == nullptr) 1557 return nullptr; 1558 1559 if (const auto *CallOpTmpl = dyn_cast<FunctionTemplateDecl>(CallOp)) 1560 return cast<CXXMethodDecl>(CallOpTmpl->getTemplatedDecl()); 1561 1562 return cast<CXXMethodDecl>(CallOp); 1563 } 1564 1565 CXXMethodDecl* CXXRecordDecl::getLambdaStaticInvoker() const { 1566 CXXMethodDecl *CallOp = getLambdaCallOperator(); 1567 CallingConv CC = CallOp->getType()->castAs<FunctionType>()->getCallConv(); 1568 return getLambdaStaticInvoker(CC); 1569 } 1570 1571 static DeclContext::lookup_result 1572 getLambdaStaticInvokers(const CXXRecordDecl &RD) { 1573 assert(RD.isLambda() && "Must be a lambda"); 1574 DeclarationName Name = 1575 &RD.getASTContext().Idents.get(getLambdaStaticInvokerName()); 1576 return RD.lookup(Name); 1577 } 1578 1579 static CXXMethodDecl *getInvokerAsMethod(NamedDecl *ND) { 1580 if (const auto *InvokerTemplate = dyn_cast<FunctionTemplateDecl>(ND)) 1581 return cast<CXXMethodDecl>(InvokerTemplate->getTemplatedDecl()); 1582 return cast<CXXMethodDecl>(ND); 1583 } 1584 1585 CXXMethodDecl *CXXRecordDecl::getLambdaStaticInvoker(CallingConv CC) const { 1586 if (!isLambda()) 1587 return nullptr; 1588 DeclContext::lookup_result Invoker = getLambdaStaticInvokers(*this); 1589 1590 for (NamedDecl *ND : Invoker) { 1591 const auto *FTy = 1592 cast<ValueDecl>(ND->getAsFunction())->getType()->castAs<FunctionType>(); 1593 if (FTy->getCallConv() == CC) 1594 return getInvokerAsMethod(ND); 1595 } 1596 1597 return nullptr; 1598 } 1599 1600 void CXXRecordDecl::getCaptureFields( 1601 llvm::DenseMap<const ValueDecl *, FieldDecl *> &Captures, 1602 FieldDecl *&ThisCapture) const { 1603 Captures.clear(); 1604 ThisCapture = nullptr; 1605 1606 LambdaDefinitionData &Lambda = getLambdaData(); 1607 for (const LambdaCapture *List : Lambda.Captures) { 1608 RecordDecl::field_iterator Field = field_begin(); 1609 for (const LambdaCapture *C = List, *CEnd = C + Lambda.NumCaptures; 1610 C != CEnd; ++C, ++Field) { 1611 if (C->capturesThis()) 1612 ThisCapture = *Field; 1613 else if (C->capturesVariable()) 1614 Captures[C->getCapturedVar()] = *Field; 1615 } 1616 assert(Field == field_end()); 1617 } 1618 } 1619 1620 TemplateParameterList * 1621 CXXRecordDecl::getGenericLambdaTemplateParameterList() const { 1622 if (!isGenericLambda()) return nullptr; 1623 CXXMethodDecl *CallOp = getLambdaCallOperator(); 1624 if (FunctionTemplateDecl *Tmpl = CallOp->getDescribedFunctionTemplate()) 1625 return Tmpl->getTemplateParameters(); 1626 return nullptr; 1627 } 1628 1629 ArrayRef<NamedDecl *> 1630 CXXRecordDecl::getLambdaExplicitTemplateParameters() const { 1631 TemplateParameterList *List = getGenericLambdaTemplateParameterList(); 1632 if (!List) 1633 return {}; 1634 1635 assert(std::is_partitioned(List->begin(), List->end(), 1636 [](const NamedDecl *D) { return !D->isImplicit(); }) 1637 && "Explicit template params should be ordered before implicit ones"); 1638 1639 const auto ExplicitEnd = llvm::partition_point( 1640 *List, [](const NamedDecl *D) { return !D->isImplicit(); }); 1641 return llvm::ArrayRef(List->begin(), ExplicitEnd); 1642 } 1643 1644 Decl *CXXRecordDecl::getLambdaContextDecl() const { 1645 assert(isLambda() && "Not a lambda closure type!"); 1646 ExternalASTSource *Source = getParentASTContext().getExternalSource(); 1647 return getLambdaData().ContextDecl.get(Source); 1648 } 1649 1650 void CXXRecordDecl::setLambdaNumbering(LambdaNumbering Numbering) { 1651 assert(isLambda() && "Not a lambda closure type!"); 1652 getLambdaData().ManglingNumber = Numbering.ManglingNumber; 1653 if (Numbering.DeviceManglingNumber) 1654 getASTContext().DeviceLambdaManglingNumbers[this] = 1655 Numbering.DeviceManglingNumber; 1656 getLambdaData().IndexInContext = Numbering.IndexInContext; 1657 getLambdaData().ContextDecl = Numbering.ContextDecl; 1658 getLambdaData().HasKnownInternalLinkage = Numbering.HasKnownInternalLinkage; 1659 } 1660 1661 unsigned CXXRecordDecl::getDeviceLambdaManglingNumber() const { 1662 assert(isLambda() && "Not a lambda closure type!"); 1663 return getASTContext().DeviceLambdaManglingNumbers.lookup(this); 1664 } 1665 1666 static CanQualType GetConversionType(ASTContext &Context, NamedDecl *Conv) { 1667 QualType T = 1668 cast<CXXConversionDecl>(Conv->getUnderlyingDecl()->getAsFunction()) 1669 ->getConversionType(); 1670 return Context.getCanonicalType(T); 1671 } 1672 1673 /// Collect the visible conversions of a base class. 1674 /// 1675 /// \param Record a base class of the class we're considering 1676 /// \param InVirtual whether this base class is a virtual base (or a base 1677 /// of a virtual base) 1678 /// \param Access the access along the inheritance path to this base 1679 /// \param ParentHiddenTypes the conversions provided by the inheritors 1680 /// of this base 1681 /// \param Output the set to which to add conversions from non-virtual bases 1682 /// \param VOutput the set to which to add conversions from virtual bases 1683 /// \param HiddenVBaseCs the set of conversions which were hidden in a 1684 /// virtual base along some inheritance path 1685 static void CollectVisibleConversions( 1686 ASTContext &Context, const CXXRecordDecl *Record, bool InVirtual, 1687 AccessSpecifier Access, 1688 const llvm::SmallPtrSet<CanQualType, 8> &ParentHiddenTypes, 1689 ASTUnresolvedSet &Output, UnresolvedSetImpl &VOutput, 1690 llvm::SmallPtrSet<NamedDecl *, 8> &HiddenVBaseCs) { 1691 // The set of types which have conversions in this class or its 1692 // subclasses. As an optimization, we don't copy the derived set 1693 // unless it might change. 1694 const llvm::SmallPtrSet<CanQualType, 8> *HiddenTypes = &ParentHiddenTypes; 1695 llvm::SmallPtrSet<CanQualType, 8> HiddenTypesBuffer; 1696 1697 // Collect the direct conversions and figure out which conversions 1698 // will be hidden in the subclasses. 1699 CXXRecordDecl::conversion_iterator ConvI = Record->conversion_begin(); 1700 CXXRecordDecl::conversion_iterator ConvE = Record->conversion_end(); 1701 if (ConvI != ConvE) { 1702 HiddenTypesBuffer = ParentHiddenTypes; 1703 HiddenTypes = &HiddenTypesBuffer; 1704 1705 for (CXXRecordDecl::conversion_iterator I = ConvI; I != ConvE; ++I) { 1706 CanQualType ConvType(GetConversionType(Context, I.getDecl())); 1707 bool Hidden = ParentHiddenTypes.count(ConvType); 1708 if (!Hidden) 1709 HiddenTypesBuffer.insert(ConvType); 1710 1711 // If this conversion is hidden and we're in a virtual base, 1712 // remember that it's hidden along some inheritance path. 1713 if (Hidden && InVirtual) 1714 HiddenVBaseCs.insert(cast<NamedDecl>(I.getDecl()->getCanonicalDecl())); 1715 1716 // If this conversion isn't hidden, add it to the appropriate output. 1717 else if (!Hidden) { 1718 AccessSpecifier IAccess 1719 = CXXRecordDecl::MergeAccess(Access, I.getAccess()); 1720 1721 if (InVirtual) 1722 VOutput.addDecl(I.getDecl(), IAccess); 1723 else 1724 Output.addDecl(Context, I.getDecl(), IAccess); 1725 } 1726 } 1727 } 1728 1729 // Collect information recursively from any base classes. 1730 for (const auto &I : Record->bases()) { 1731 const auto *RT = I.getType()->getAs<RecordType>(); 1732 if (!RT) continue; 1733 1734 AccessSpecifier BaseAccess 1735 = CXXRecordDecl::MergeAccess(Access, I.getAccessSpecifier()); 1736 bool BaseInVirtual = InVirtual || I.isVirtual(); 1737 1738 auto *Base = cast<CXXRecordDecl>(RT->getDecl()); 1739 CollectVisibleConversions(Context, Base, BaseInVirtual, BaseAccess, 1740 *HiddenTypes, Output, VOutput, HiddenVBaseCs); 1741 } 1742 } 1743 1744 /// Collect the visible conversions of a class. 1745 /// 1746 /// This would be extremely straightforward if it weren't for virtual 1747 /// bases. It might be worth special-casing that, really. 1748 static void CollectVisibleConversions(ASTContext &Context, 1749 const CXXRecordDecl *Record, 1750 ASTUnresolvedSet &Output) { 1751 // The collection of all conversions in virtual bases that we've 1752 // found. These will be added to the output as long as they don't 1753 // appear in the hidden-conversions set. 1754 UnresolvedSet<8> VBaseCs; 1755 1756 // The set of conversions in virtual bases that we've determined to 1757 // be hidden. 1758 llvm::SmallPtrSet<NamedDecl*, 8> HiddenVBaseCs; 1759 1760 // The set of types hidden by classes derived from this one. 1761 llvm::SmallPtrSet<CanQualType, 8> HiddenTypes; 1762 1763 // Go ahead and collect the direct conversions and add them to the 1764 // hidden-types set. 1765 CXXRecordDecl::conversion_iterator ConvI = Record->conversion_begin(); 1766 CXXRecordDecl::conversion_iterator ConvE = Record->conversion_end(); 1767 Output.append(Context, ConvI, ConvE); 1768 for (; ConvI != ConvE; ++ConvI) 1769 HiddenTypes.insert(GetConversionType(Context, ConvI.getDecl())); 1770 1771 // Recursively collect conversions from base classes. 1772 for (const auto &I : Record->bases()) { 1773 const auto *RT = I.getType()->getAs<RecordType>(); 1774 if (!RT) continue; 1775 1776 CollectVisibleConversions(Context, cast<CXXRecordDecl>(RT->getDecl()), 1777 I.isVirtual(), I.getAccessSpecifier(), 1778 HiddenTypes, Output, VBaseCs, HiddenVBaseCs); 1779 } 1780 1781 // Add any unhidden conversions provided by virtual bases. 1782 for (UnresolvedSetIterator I = VBaseCs.begin(), E = VBaseCs.end(); 1783 I != E; ++I) { 1784 if (!HiddenVBaseCs.count(cast<NamedDecl>(I.getDecl()->getCanonicalDecl()))) 1785 Output.addDecl(Context, I.getDecl(), I.getAccess()); 1786 } 1787 } 1788 1789 /// getVisibleConversionFunctions - get all conversion functions visible 1790 /// in current class; including conversion function templates. 1791 llvm::iterator_range<CXXRecordDecl::conversion_iterator> 1792 CXXRecordDecl::getVisibleConversionFunctions() const { 1793 ASTContext &Ctx = getASTContext(); 1794 1795 ASTUnresolvedSet *Set; 1796 if (bases_begin() == bases_end()) { 1797 // If root class, all conversions are visible. 1798 Set = &data().Conversions.get(Ctx); 1799 } else { 1800 Set = &data().VisibleConversions.get(Ctx); 1801 // If visible conversion list is not evaluated, evaluate it. 1802 if (!data().ComputedVisibleConversions) { 1803 CollectVisibleConversions(Ctx, this, *Set); 1804 data().ComputedVisibleConversions = true; 1805 } 1806 } 1807 return llvm::make_range(Set->begin(), Set->end()); 1808 } 1809 1810 void CXXRecordDecl::removeConversion(const NamedDecl *ConvDecl) { 1811 // This operation is O(N) but extremely rare. Sema only uses it to 1812 // remove UsingShadowDecls in a class that were followed by a direct 1813 // declaration, e.g.: 1814 // class A : B { 1815 // using B::operator int; 1816 // operator int(); 1817 // }; 1818 // This is uncommon by itself and even more uncommon in conjunction 1819 // with sufficiently large numbers of directly-declared conversions 1820 // that asymptotic behavior matters. 1821 1822 ASTUnresolvedSet &Convs = data().Conversions.get(getASTContext()); 1823 for (unsigned I = 0, E = Convs.size(); I != E; ++I) { 1824 if (Convs[I].getDecl() == ConvDecl) { 1825 Convs.erase(I); 1826 assert(!llvm::is_contained(Convs, ConvDecl) && 1827 "conversion was found multiple times in unresolved set"); 1828 return; 1829 } 1830 } 1831 1832 llvm_unreachable("conversion not found in set!"); 1833 } 1834 1835 CXXRecordDecl *CXXRecordDecl::getInstantiatedFromMemberClass() const { 1836 if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo()) 1837 return cast<CXXRecordDecl>(MSInfo->getInstantiatedFrom()); 1838 1839 return nullptr; 1840 } 1841 1842 MemberSpecializationInfo *CXXRecordDecl::getMemberSpecializationInfo() const { 1843 return TemplateOrInstantiation.dyn_cast<MemberSpecializationInfo *>(); 1844 } 1845 1846 void 1847 CXXRecordDecl::setInstantiationOfMemberClass(CXXRecordDecl *RD, 1848 TemplateSpecializationKind TSK) { 1849 assert(TemplateOrInstantiation.isNull() && 1850 "Previous template or instantiation?"); 1851 assert(!isa<ClassTemplatePartialSpecializationDecl>(this)); 1852 TemplateOrInstantiation 1853 = new (getASTContext()) MemberSpecializationInfo(RD, TSK); 1854 } 1855 1856 ClassTemplateDecl *CXXRecordDecl::getDescribedClassTemplate() const { 1857 return TemplateOrInstantiation.dyn_cast<ClassTemplateDecl *>(); 1858 } 1859 1860 void CXXRecordDecl::setDescribedClassTemplate(ClassTemplateDecl *Template) { 1861 TemplateOrInstantiation = Template; 1862 } 1863 1864 TemplateSpecializationKind CXXRecordDecl::getTemplateSpecializationKind() const{ 1865 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(this)) 1866 return Spec->getSpecializationKind(); 1867 1868 if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo()) 1869 return MSInfo->getTemplateSpecializationKind(); 1870 1871 return TSK_Undeclared; 1872 } 1873 1874 void 1875 CXXRecordDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK) { 1876 if (auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(this)) { 1877 Spec->setSpecializationKind(TSK); 1878 return; 1879 } 1880 1881 if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo()) { 1882 MSInfo->setTemplateSpecializationKind(TSK); 1883 return; 1884 } 1885 1886 llvm_unreachable("Not a class template or member class specialization"); 1887 } 1888 1889 const CXXRecordDecl *CXXRecordDecl::getTemplateInstantiationPattern() const { 1890 auto GetDefinitionOrSelf = 1891 [](const CXXRecordDecl *D) -> const CXXRecordDecl * { 1892 if (auto *Def = D->getDefinition()) 1893 return Def; 1894 return D; 1895 }; 1896 1897 // If it's a class template specialization, find the template or partial 1898 // specialization from which it was instantiated. 1899 if (auto *TD = dyn_cast<ClassTemplateSpecializationDecl>(this)) { 1900 auto From = TD->getInstantiatedFrom(); 1901 if (auto *CTD = From.dyn_cast<ClassTemplateDecl *>()) { 1902 while (auto *NewCTD = CTD->getInstantiatedFromMemberTemplate()) { 1903 if (NewCTD->isMemberSpecialization()) 1904 break; 1905 CTD = NewCTD; 1906 } 1907 return GetDefinitionOrSelf(CTD->getTemplatedDecl()); 1908 } 1909 if (auto *CTPSD = 1910 From.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) { 1911 while (auto *NewCTPSD = CTPSD->getInstantiatedFromMember()) { 1912 if (NewCTPSD->isMemberSpecialization()) 1913 break; 1914 CTPSD = NewCTPSD; 1915 } 1916 return GetDefinitionOrSelf(CTPSD); 1917 } 1918 } 1919 1920 if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo()) { 1921 if (isTemplateInstantiation(MSInfo->getTemplateSpecializationKind())) { 1922 const CXXRecordDecl *RD = this; 1923 while (auto *NewRD = RD->getInstantiatedFromMemberClass()) 1924 RD = NewRD; 1925 return GetDefinitionOrSelf(RD); 1926 } 1927 } 1928 1929 assert(!isTemplateInstantiation(this->getTemplateSpecializationKind()) && 1930 "couldn't find pattern for class template instantiation"); 1931 return nullptr; 1932 } 1933 1934 CXXDestructorDecl *CXXRecordDecl::getDestructor() const { 1935 ASTContext &Context = getASTContext(); 1936 QualType ClassType = Context.getTypeDeclType(this); 1937 1938 DeclarationName Name 1939 = Context.DeclarationNames.getCXXDestructorName( 1940 Context.getCanonicalType(ClassType)); 1941 1942 DeclContext::lookup_result R = lookup(Name); 1943 1944 // If a destructor was marked as not selected, we skip it. We don't always 1945 // have a selected destructor: dependent types, unnamed structs. 1946 for (auto *Decl : R) { 1947 auto* DD = dyn_cast<CXXDestructorDecl>(Decl); 1948 if (DD && !DD->isIneligibleOrNotSelected()) 1949 return DD; 1950 } 1951 return nullptr; 1952 } 1953 1954 static bool isDeclContextInNamespace(const DeclContext *DC) { 1955 while (!DC->isTranslationUnit()) { 1956 if (DC->isNamespace()) 1957 return true; 1958 DC = DC->getParent(); 1959 } 1960 return false; 1961 } 1962 1963 bool CXXRecordDecl::isInterfaceLike() const { 1964 assert(hasDefinition() && "checking for interface-like without a definition"); 1965 // All __interfaces are inheritently interface-like. 1966 if (isInterface()) 1967 return true; 1968 1969 // Interface-like types cannot have a user declared constructor, destructor, 1970 // friends, VBases, conversion functions, or fields. Additionally, lambdas 1971 // cannot be interface types. 1972 if (isLambda() || hasUserDeclaredConstructor() || 1973 hasUserDeclaredDestructor() || !field_empty() || hasFriends() || 1974 getNumVBases() > 0 || conversion_end() - conversion_begin() > 0) 1975 return false; 1976 1977 // No interface-like type can have a method with a definition. 1978 for (const auto *const Method : methods()) 1979 if (Method->isDefined() && !Method->isImplicit()) 1980 return false; 1981 1982 // Check "Special" types. 1983 const auto *Uuid = getAttr<UuidAttr>(); 1984 // MS SDK declares IUnknown/IDispatch both in the root of a TU, or in an 1985 // extern C++ block directly in the TU. These are only valid if in one 1986 // of these two situations. 1987 if (Uuid && isStruct() && !getDeclContext()->isExternCContext() && 1988 !isDeclContextInNamespace(getDeclContext()) && 1989 ((getName() == "IUnknown" && 1990 Uuid->getGuid() == "00000000-0000-0000-C000-000000000046") || 1991 (getName() == "IDispatch" && 1992 Uuid->getGuid() == "00020400-0000-0000-C000-000000000046"))) { 1993 if (getNumBases() > 0) 1994 return false; 1995 return true; 1996 } 1997 1998 // FIXME: Any access specifiers is supposed to make this no longer interface 1999 // like. 2000 2001 // If this isn't a 'special' type, it must have a single interface-like base. 2002 if (getNumBases() != 1) 2003 return false; 2004 2005 const auto BaseSpec = *bases_begin(); 2006 if (BaseSpec.isVirtual() || BaseSpec.getAccessSpecifier() != AS_public) 2007 return false; 2008 const auto *Base = BaseSpec.getType()->getAsCXXRecordDecl(); 2009 if (Base->isInterface() || !Base->isInterfaceLike()) 2010 return false; 2011 return true; 2012 } 2013 2014 void CXXRecordDecl::completeDefinition() { 2015 completeDefinition(nullptr); 2016 } 2017 2018 void CXXRecordDecl::completeDefinition(CXXFinalOverriderMap *FinalOverriders) { 2019 RecordDecl::completeDefinition(); 2020 2021 // If the class may be abstract (but hasn't been marked as such), check for 2022 // any pure final overriders. 2023 if (mayBeAbstract()) { 2024 CXXFinalOverriderMap MyFinalOverriders; 2025 if (!FinalOverriders) { 2026 getFinalOverriders(MyFinalOverriders); 2027 FinalOverriders = &MyFinalOverriders; 2028 } 2029 2030 bool Done = false; 2031 for (CXXFinalOverriderMap::iterator M = FinalOverriders->begin(), 2032 MEnd = FinalOverriders->end(); 2033 M != MEnd && !Done; ++M) { 2034 for (OverridingMethods::iterator SO = M->second.begin(), 2035 SOEnd = M->second.end(); 2036 SO != SOEnd && !Done; ++SO) { 2037 assert(SO->second.size() > 0 && 2038 "All virtual functions have overriding virtual functions"); 2039 2040 // C++ [class.abstract]p4: 2041 // A class is abstract if it contains or inherits at least one 2042 // pure virtual function for which the final overrider is pure 2043 // virtual. 2044 if (SO->second.front().Method->isPure()) { 2045 data().Abstract = true; 2046 Done = true; 2047 break; 2048 } 2049 } 2050 } 2051 } 2052 2053 // Set access bits correctly on the directly-declared conversions. 2054 for (conversion_iterator I = conversion_begin(), E = conversion_end(); 2055 I != E; ++I) 2056 I.setAccess((*I)->getAccess()); 2057 } 2058 2059 bool CXXRecordDecl::mayBeAbstract() const { 2060 if (data().Abstract || isInvalidDecl() || !data().Polymorphic || 2061 isDependentContext()) 2062 return false; 2063 2064 for (const auto &B : bases()) { 2065 const auto *BaseDecl = 2066 cast<CXXRecordDecl>(B.getType()->castAs<RecordType>()->getDecl()); 2067 if (BaseDecl->isAbstract()) 2068 return true; 2069 } 2070 2071 return false; 2072 } 2073 2074 bool CXXRecordDecl::isEffectivelyFinal() const { 2075 auto *Def = getDefinition(); 2076 if (!Def) 2077 return false; 2078 if (Def->hasAttr<FinalAttr>()) 2079 return true; 2080 if (const auto *Dtor = Def->getDestructor()) 2081 if (Dtor->hasAttr<FinalAttr>()) 2082 return true; 2083 return false; 2084 } 2085 2086 void CXXDeductionGuideDecl::anchor() {} 2087 2088 bool ExplicitSpecifier::isEquivalent(const ExplicitSpecifier Other) const { 2089 if ((getKind() != Other.getKind() || 2090 getKind() == ExplicitSpecKind::Unresolved)) { 2091 if (getKind() == ExplicitSpecKind::Unresolved && 2092 Other.getKind() == ExplicitSpecKind::Unresolved) { 2093 ODRHash SelfHash, OtherHash; 2094 SelfHash.AddStmt(getExpr()); 2095 OtherHash.AddStmt(Other.getExpr()); 2096 return SelfHash.CalculateHash() == OtherHash.CalculateHash(); 2097 } else 2098 return false; 2099 } 2100 return true; 2101 } 2102 2103 ExplicitSpecifier ExplicitSpecifier::getFromDecl(FunctionDecl *Function) { 2104 switch (Function->getDeclKind()) { 2105 case Decl::Kind::CXXConstructor: 2106 return cast<CXXConstructorDecl>(Function)->getExplicitSpecifier(); 2107 case Decl::Kind::CXXConversion: 2108 return cast<CXXConversionDecl>(Function)->getExplicitSpecifier(); 2109 case Decl::Kind::CXXDeductionGuide: 2110 return cast<CXXDeductionGuideDecl>(Function)->getExplicitSpecifier(); 2111 default: 2112 return {}; 2113 } 2114 } 2115 2116 CXXDeductionGuideDecl *CXXDeductionGuideDecl::Create( 2117 ASTContext &C, DeclContext *DC, SourceLocation StartLoc, 2118 ExplicitSpecifier ES, const DeclarationNameInfo &NameInfo, QualType T, 2119 TypeSourceInfo *TInfo, SourceLocation EndLocation, CXXConstructorDecl *Ctor, 2120 DeductionCandidate Kind) { 2121 return new (C, DC) CXXDeductionGuideDecl(C, DC, StartLoc, ES, NameInfo, T, 2122 TInfo, EndLocation, Ctor, Kind); 2123 } 2124 2125 CXXDeductionGuideDecl *CXXDeductionGuideDecl::CreateDeserialized(ASTContext &C, 2126 unsigned ID) { 2127 return new (C, ID) CXXDeductionGuideDecl( 2128 C, nullptr, SourceLocation(), ExplicitSpecifier(), DeclarationNameInfo(), 2129 QualType(), nullptr, SourceLocation(), nullptr, 2130 DeductionCandidate::Normal); 2131 } 2132 2133 RequiresExprBodyDecl *RequiresExprBodyDecl::Create( 2134 ASTContext &C, DeclContext *DC, SourceLocation StartLoc) { 2135 return new (C, DC) RequiresExprBodyDecl(C, DC, StartLoc); 2136 } 2137 2138 RequiresExprBodyDecl *RequiresExprBodyDecl::CreateDeserialized(ASTContext &C, 2139 unsigned ID) { 2140 return new (C, ID) RequiresExprBodyDecl(C, nullptr, SourceLocation()); 2141 } 2142 2143 void CXXMethodDecl::anchor() {} 2144 2145 bool CXXMethodDecl::isStatic() const { 2146 const CXXMethodDecl *MD = getCanonicalDecl(); 2147 2148 if (MD->getStorageClass() == SC_Static) 2149 return true; 2150 2151 OverloadedOperatorKind OOK = getDeclName().getCXXOverloadedOperator(); 2152 return isStaticOverloadedOperator(OOK); 2153 } 2154 2155 static bool recursivelyOverrides(const CXXMethodDecl *DerivedMD, 2156 const CXXMethodDecl *BaseMD) { 2157 for (const CXXMethodDecl *MD : DerivedMD->overridden_methods()) { 2158 if (MD->getCanonicalDecl() == BaseMD->getCanonicalDecl()) 2159 return true; 2160 if (recursivelyOverrides(MD, BaseMD)) 2161 return true; 2162 } 2163 return false; 2164 } 2165 2166 CXXMethodDecl * 2167 CXXMethodDecl::getCorrespondingMethodDeclaredInClass(const CXXRecordDecl *RD, 2168 bool MayBeBase) { 2169 if (this->getParent()->getCanonicalDecl() == RD->getCanonicalDecl()) 2170 return this; 2171 2172 // Lookup doesn't work for destructors, so handle them separately. 2173 if (isa<CXXDestructorDecl>(this)) { 2174 CXXMethodDecl *MD = RD->getDestructor(); 2175 if (MD) { 2176 if (recursivelyOverrides(MD, this)) 2177 return MD; 2178 if (MayBeBase && recursivelyOverrides(this, MD)) 2179 return MD; 2180 } 2181 return nullptr; 2182 } 2183 2184 for (auto *ND : RD->lookup(getDeclName())) { 2185 auto *MD = dyn_cast<CXXMethodDecl>(ND); 2186 if (!MD) 2187 continue; 2188 if (recursivelyOverrides(MD, this)) 2189 return MD; 2190 if (MayBeBase && recursivelyOverrides(this, MD)) 2191 return MD; 2192 } 2193 2194 return nullptr; 2195 } 2196 2197 CXXMethodDecl * 2198 CXXMethodDecl::getCorrespondingMethodInClass(const CXXRecordDecl *RD, 2199 bool MayBeBase) { 2200 if (auto *MD = getCorrespondingMethodDeclaredInClass(RD, MayBeBase)) 2201 return MD; 2202 2203 llvm::SmallVector<CXXMethodDecl*, 4> FinalOverriders; 2204 auto AddFinalOverrider = [&](CXXMethodDecl *D) { 2205 // If this function is overridden by a candidate final overrider, it is not 2206 // a final overrider. 2207 for (CXXMethodDecl *OtherD : FinalOverriders) { 2208 if (declaresSameEntity(D, OtherD) || recursivelyOverrides(OtherD, D)) 2209 return; 2210 } 2211 2212 // Other candidate final overriders might be overridden by this function. 2213 llvm::erase_if(FinalOverriders, [&](CXXMethodDecl *OtherD) { 2214 return recursivelyOverrides(D, OtherD); 2215 }); 2216 2217 FinalOverriders.push_back(D); 2218 }; 2219 2220 for (const auto &I : RD->bases()) { 2221 const RecordType *RT = I.getType()->getAs<RecordType>(); 2222 if (!RT) 2223 continue; 2224 const auto *Base = cast<CXXRecordDecl>(RT->getDecl()); 2225 if (CXXMethodDecl *D = this->getCorrespondingMethodInClass(Base)) 2226 AddFinalOverrider(D); 2227 } 2228 2229 return FinalOverriders.size() == 1 ? FinalOverriders.front() : nullptr; 2230 } 2231 2232 CXXMethodDecl * 2233 CXXMethodDecl::Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, 2234 const DeclarationNameInfo &NameInfo, QualType T, 2235 TypeSourceInfo *TInfo, StorageClass SC, bool UsesFPIntrin, 2236 bool isInline, ConstexprSpecKind ConstexprKind, 2237 SourceLocation EndLocation, 2238 Expr *TrailingRequiresClause) { 2239 return new (C, RD) CXXMethodDecl( 2240 CXXMethod, C, RD, StartLoc, NameInfo, T, TInfo, SC, UsesFPIntrin, 2241 isInline, ConstexprKind, EndLocation, TrailingRequiresClause); 2242 } 2243 2244 CXXMethodDecl *CXXMethodDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 2245 return new (C, ID) CXXMethodDecl( 2246 CXXMethod, C, nullptr, SourceLocation(), DeclarationNameInfo(), 2247 QualType(), nullptr, SC_None, false, false, 2248 ConstexprSpecKind::Unspecified, SourceLocation(), nullptr); 2249 } 2250 2251 CXXMethodDecl *CXXMethodDecl::getDevirtualizedMethod(const Expr *Base, 2252 bool IsAppleKext) { 2253 assert(isVirtual() && "this method is expected to be virtual"); 2254 2255 // When building with -fapple-kext, all calls must go through the vtable since 2256 // the kernel linker can do runtime patching of vtables. 2257 if (IsAppleKext) 2258 return nullptr; 2259 2260 // If the member function is marked 'final', we know that it can't be 2261 // overridden and can therefore devirtualize it unless it's pure virtual. 2262 if (hasAttr<FinalAttr>()) 2263 return isPure() ? nullptr : this; 2264 2265 // If Base is unknown, we cannot devirtualize. 2266 if (!Base) 2267 return nullptr; 2268 2269 // If the base expression (after skipping derived-to-base conversions) is a 2270 // class prvalue, then we can devirtualize. 2271 Base = Base->getBestDynamicClassTypeExpr(); 2272 if (Base->isPRValue() && Base->getType()->isRecordType()) 2273 return this; 2274 2275 // If we don't even know what we would call, we can't devirtualize. 2276 const CXXRecordDecl *BestDynamicDecl = Base->getBestDynamicClassType(); 2277 if (!BestDynamicDecl) 2278 return nullptr; 2279 2280 // There may be a method corresponding to MD in a derived class. 2281 CXXMethodDecl *DevirtualizedMethod = 2282 getCorrespondingMethodInClass(BestDynamicDecl); 2283 2284 // If there final overrider in the dynamic type is ambiguous, we can't 2285 // devirtualize this call. 2286 if (!DevirtualizedMethod) 2287 return nullptr; 2288 2289 // If that method is pure virtual, we can't devirtualize. If this code is 2290 // reached, the result would be UB, not a direct call to the derived class 2291 // function, and we can't assume the derived class function is defined. 2292 if (DevirtualizedMethod->isPure()) 2293 return nullptr; 2294 2295 // If that method is marked final, we can devirtualize it. 2296 if (DevirtualizedMethod->hasAttr<FinalAttr>()) 2297 return DevirtualizedMethod; 2298 2299 // Similarly, if the class itself or its destructor is marked 'final', 2300 // the class can't be derived from and we can therefore devirtualize the 2301 // member function call. 2302 if (BestDynamicDecl->isEffectivelyFinal()) 2303 return DevirtualizedMethod; 2304 2305 if (const auto *DRE = dyn_cast<DeclRefExpr>(Base)) { 2306 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) 2307 if (VD->getType()->isRecordType()) 2308 // This is a record decl. We know the type and can devirtualize it. 2309 return DevirtualizedMethod; 2310 2311 return nullptr; 2312 } 2313 2314 // We can devirtualize calls on an object accessed by a class member access 2315 // expression, since by C++11 [basic.life]p6 we know that it can't refer to 2316 // a derived class object constructed in the same location. 2317 if (const auto *ME = dyn_cast<MemberExpr>(Base)) { 2318 const ValueDecl *VD = ME->getMemberDecl(); 2319 return VD->getType()->isRecordType() ? DevirtualizedMethod : nullptr; 2320 } 2321 2322 // Likewise for calls on an object accessed by a (non-reference) pointer to 2323 // member access. 2324 if (auto *BO = dyn_cast<BinaryOperator>(Base)) { 2325 if (BO->isPtrMemOp()) { 2326 auto *MPT = BO->getRHS()->getType()->castAs<MemberPointerType>(); 2327 if (MPT->getPointeeType()->isRecordType()) 2328 return DevirtualizedMethod; 2329 } 2330 } 2331 2332 // We can't devirtualize the call. 2333 return nullptr; 2334 } 2335 2336 bool CXXMethodDecl::isUsualDeallocationFunction( 2337 SmallVectorImpl<const FunctionDecl *> &PreventedBy) const { 2338 assert(PreventedBy.empty() && "PreventedBy is expected to be empty"); 2339 if (getOverloadedOperator() != OO_Delete && 2340 getOverloadedOperator() != OO_Array_Delete) 2341 return false; 2342 2343 // C++ [basic.stc.dynamic.deallocation]p2: 2344 // A template instance is never a usual deallocation function, 2345 // regardless of its signature. 2346 if (getPrimaryTemplate()) 2347 return false; 2348 2349 // C++ [basic.stc.dynamic.deallocation]p2: 2350 // If a class T has a member deallocation function named operator delete 2351 // with exactly one parameter, then that function is a usual (non-placement) 2352 // deallocation function. [...] 2353 if (getNumParams() == 1) 2354 return true; 2355 unsigned UsualParams = 1; 2356 2357 // C++ P0722: 2358 // A destroying operator delete is a usual deallocation function if 2359 // removing the std::destroying_delete_t parameter and changing the 2360 // first parameter type from T* to void* results in the signature of 2361 // a usual deallocation function. 2362 if (isDestroyingOperatorDelete()) 2363 ++UsualParams; 2364 2365 // C++ <=14 [basic.stc.dynamic.deallocation]p2: 2366 // [...] If class T does not declare such an operator delete but does 2367 // declare a member deallocation function named operator delete with 2368 // exactly two parameters, the second of which has type std::size_t (18.1), 2369 // then this function is a usual deallocation function. 2370 // 2371 // C++17 says a usual deallocation function is one with the signature 2372 // (void* [, size_t] [, std::align_val_t] [, ...]) 2373 // and all such functions are usual deallocation functions. It's not clear 2374 // that allowing varargs functions was intentional. 2375 ASTContext &Context = getASTContext(); 2376 if (UsualParams < getNumParams() && 2377 Context.hasSameUnqualifiedType(getParamDecl(UsualParams)->getType(), 2378 Context.getSizeType())) 2379 ++UsualParams; 2380 2381 if (UsualParams < getNumParams() && 2382 getParamDecl(UsualParams)->getType()->isAlignValT()) 2383 ++UsualParams; 2384 2385 if (UsualParams != getNumParams()) 2386 return false; 2387 2388 // In C++17 onwards, all potential usual deallocation functions are actual 2389 // usual deallocation functions. Honor this behavior when post-C++14 2390 // deallocation functions are offered as extensions too. 2391 // FIXME(EricWF): Destroying Delete should be a language option. How do we 2392 // handle when destroying delete is used prior to C++17? 2393 if (Context.getLangOpts().CPlusPlus17 || 2394 Context.getLangOpts().AlignedAllocation || 2395 isDestroyingOperatorDelete()) 2396 return true; 2397 2398 // This function is a usual deallocation function if there are no 2399 // single-parameter deallocation functions of the same kind. 2400 DeclContext::lookup_result R = getDeclContext()->lookup(getDeclName()); 2401 bool Result = true; 2402 for (const auto *D : R) { 2403 if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 2404 if (FD->getNumParams() == 1) { 2405 PreventedBy.push_back(FD); 2406 Result = false; 2407 } 2408 } 2409 } 2410 return Result; 2411 } 2412 2413 bool CXXMethodDecl::isExplicitObjectMemberFunction() const { 2414 // C++2b [dcl.fct]p6: 2415 // An explicit object member function is a non-static member 2416 // function with an explicit object parameter 2417 return !isStatic() && hasCXXExplicitFunctionObjectParameter(); 2418 } 2419 2420 bool CXXMethodDecl::isImplicitObjectMemberFunction() const { 2421 return !isStatic() && !hasCXXExplicitFunctionObjectParameter(); 2422 } 2423 2424 bool CXXMethodDecl::isCopyAssignmentOperator() const { 2425 // C++0x [class.copy]p17: 2426 // A user-declared copy assignment operator X::operator= is a non-static 2427 // non-template member function of class X with exactly one parameter of 2428 // type X, X&, const X&, volatile X& or const volatile X&. 2429 if (/*operator=*/getOverloadedOperator() != OO_Equal || 2430 /*non-static*/ isStatic() || 2431 2432 /*non-template*/ getPrimaryTemplate() || getDescribedFunctionTemplate() || 2433 getNumExplicitParams() != 1) 2434 return false; 2435 2436 QualType ParamType = getNonObjectParameter(0)->getType(); 2437 if (const auto *Ref = ParamType->getAs<LValueReferenceType>()) 2438 ParamType = Ref->getPointeeType(); 2439 2440 ASTContext &Context = getASTContext(); 2441 QualType ClassType 2442 = Context.getCanonicalType(Context.getTypeDeclType(getParent())); 2443 return Context.hasSameUnqualifiedType(ClassType, ParamType); 2444 } 2445 2446 bool CXXMethodDecl::isMoveAssignmentOperator() const { 2447 // C++0x [class.copy]p19: 2448 // A user-declared move assignment operator X::operator= is a non-static 2449 // non-template member function of class X with exactly one parameter of type 2450 // X&&, const X&&, volatile X&&, or const volatile X&&. 2451 if (getOverloadedOperator() != OO_Equal || isStatic() || 2452 getPrimaryTemplate() || getDescribedFunctionTemplate() || 2453 getNumExplicitParams() != 1) 2454 return false; 2455 2456 QualType ParamType = getNonObjectParameter(0)->getType(); 2457 if (!ParamType->isRValueReferenceType()) 2458 return false; 2459 ParamType = ParamType->getPointeeType(); 2460 2461 ASTContext &Context = getASTContext(); 2462 QualType ClassType 2463 = Context.getCanonicalType(Context.getTypeDeclType(getParent())); 2464 return Context.hasSameUnqualifiedType(ClassType, ParamType); 2465 } 2466 2467 void CXXMethodDecl::addOverriddenMethod(const CXXMethodDecl *MD) { 2468 assert(MD->isCanonicalDecl() && "Method is not canonical!"); 2469 assert(!MD->getParent()->isDependentContext() && 2470 "Can't add an overridden method to a class template!"); 2471 assert(MD->isVirtual() && "Method is not virtual!"); 2472 2473 getASTContext().addOverriddenMethod(this, MD); 2474 } 2475 2476 CXXMethodDecl::method_iterator CXXMethodDecl::begin_overridden_methods() const { 2477 if (isa<CXXConstructorDecl>(this)) return nullptr; 2478 return getASTContext().overridden_methods_begin(this); 2479 } 2480 2481 CXXMethodDecl::method_iterator CXXMethodDecl::end_overridden_methods() const { 2482 if (isa<CXXConstructorDecl>(this)) return nullptr; 2483 return getASTContext().overridden_methods_end(this); 2484 } 2485 2486 unsigned CXXMethodDecl::size_overridden_methods() const { 2487 if (isa<CXXConstructorDecl>(this)) return 0; 2488 return getASTContext().overridden_methods_size(this); 2489 } 2490 2491 CXXMethodDecl::overridden_method_range 2492 CXXMethodDecl::overridden_methods() const { 2493 if (isa<CXXConstructorDecl>(this)) 2494 return overridden_method_range(nullptr, nullptr); 2495 return getASTContext().overridden_methods(this); 2496 } 2497 2498 static QualType getThisObjectType(ASTContext &C, const FunctionProtoType *FPT, 2499 const CXXRecordDecl *Decl) { 2500 QualType ClassTy = C.getTypeDeclType(Decl); 2501 return C.getQualifiedType(ClassTy, FPT->getMethodQuals()); 2502 } 2503 2504 QualType CXXMethodDecl::getThisType(const FunctionProtoType *FPT, 2505 const CXXRecordDecl *Decl) { 2506 ASTContext &C = Decl->getASTContext(); 2507 QualType ObjectTy = ::getThisObjectType(C, FPT, Decl); 2508 return C.getLangOpts().HLSL ? C.getLValueReferenceType(ObjectTy) 2509 : C.getPointerType(ObjectTy); 2510 } 2511 2512 QualType CXXMethodDecl::getThisType() const { 2513 // C++ 9.3.2p1: The type of this in a member function of a class X is X*. 2514 // If the member function is declared const, the type of this is const X*, 2515 // if the member function is declared volatile, the type of this is 2516 // volatile X*, and if the member function is declared const volatile, 2517 // the type of this is const volatile X*. 2518 assert(isInstance() && "No 'this' for static methods!"); 2519 return CXXMethodDecl::getThisType(getType()->castAs<FunctionProtoType>(), 2520 getParent()); 2521 } 2522 2523 QualType CXXMethodDecl::getFunctionObjectParameterReferenceType() const { 2524 if (isExplicitObjectMemberFunction()) 2525 return parameters()[0]->getType(); 2526 2527 ASTContext &C = getParentASTContext(); 2528 const FunctionProtoType *FPT = getType()->castAs<FunctionProtoType>(); 2529 QualType Type = ::getThisObjectType(C, FPT, getParent()); 2530 RefQualifierKind RK = FPT->getRefQualifier(); 2531 if (RK == RefQualifierKind::RQ_RValue) 2532 return C.getRValueReferenceType(Type); 2533 return C.getLValueReferenceType(Type); 2534 } 2535 2536 bool CXXMethodDecl::hasInlineBody() const { 2537 // If this function is a template instantiation, look at the template from 2538 // which it was instantiated. 2539 const FunctionDecl *CheckFn = getTemplateInstantiationPattern(); 2540 if (!CheckFn) 2541 CheckFn = this; 2542 2543 const FunctionDecl *fn; 2544 return CheckFn->isDefined(fn) && !fn->isOutOfLine() && 2545 (fn->doesThisDeclarationHaveABody() || fn->willHaveBody()); 2546 } 2547 2548 bool CXXMethodDecl::isLambdaStaticInvoker() const { 2549 const CXXRecordDecl *P = getParent(); 2550 return P->isLambda() && getDeclName().isIdentifier() && 2551 getName() == getLambdaStaticInvokerName(); 2552 } 2553 2554 CXXCtorInitializer::CXXCtorInitializer(ASTContext &Context, 2555 TypeSourceInfo *TInfo, bool IsVirtual, 2556 SourceLocation L, Expr *Init, 2557 SourceLocation R, 2558 SourceLocation EllipsisLoc) 2559 : Initializee(TInfo), Init(Init), MemberOrEllipsisLocation(EllipsisLoc), 2560 LParenLoc(L), RParenLoc(R), IsDelegating(false), IsVirtual(IsVirtual), 2561 IsWritten(false), SourceOrder(0) {} 2562 2563 CXXCtorInitializer::CXXCtorInitializer(ASTContext &Context, FieldDecl *Member, 2564 SourceLocation MemberLoc, 2565 SourceLocation L, Expr *Init, 2566 SourceLocation R) 2567 : Initializee(Member), Init(Init), MemberOrEllipsisLocation(MemberLoc), 2568 LParenLoc(L), RParenLoc(R), IsDelegating(false), IsVirtual(false), 2569 IsWritten(false), SourceOrder(0) {} 2570 2571 CXXCtorInitializer::CXXCtorInitializer(ASTContext &Context, 2572 IndirectFieldDecl *Member, 2573 SourceLocation MemberLoc, 2574 SourceLocation L, Expr *Init, 2575 SourceLocation R) 2576 : Initializee(Member), Init(Init), MemberOrEllipsisLocation(MemberLoc), 2577 LParenLoc(L), RParenLoc(R), IsDelegating(false), IsVirtual(false), 2578 IsWritten(false), SourceOrder(0) {} 2579 2580 CXXCtorInitializer::CXXCtorInitializer(ASTContext &Context, 2581 TypeSourceInfo *TInfo, 2582 SourceLocation L, Expr *Init, 2583 SourceLocation R) 2584 : Initializee(TInfo), Init(Init), LParenLoc(L), RParenLoc(R), 2585 IsDelegating(true), IsVirtual(false), IsWritten(false), SourceOrder(0) {} 2586 2587 int64_t CXXCtorInitializer::getID(const ASTContext &Context) const { 2588 return Context.getAllocator() 2589 .identifyKnownAlignedObject<CXXCtorInitializer>(this); 2590 } 2591 2592 TypeLoc CXXCtorInitializer::getBaseClassLoc() const { 2593 if (isBaseInitializer()) 2594 return Initializee.get<TypeSourceInfo*>()->getTypeLoc(); 2595 else 2596 return {}; 2597 } 2598 2599 const Type *CXXCtorInitializer::getBaseClass() const { 2600 if (isBaseInitializer()) 2601 return Initializee.get<TypeSourceInfo*>()->getType().getTypePtr(); 2602 else 2603 return nullptr; 2604 } 2605 2606 SourceLocation CXXCtorInitializer::getSourceLocation() const { 2607 if (isInClassMemberInitializer()) 2608 return getAnyMember()->getLocation(); 2609 2610 if (isAnyMemberInitializer()) 2611 return getMemberLocation(); 2612 2613 if (const auto *TSInfo = Initializee.get<TypeSourceInfo *>()) 2614 return TSInfo->getTypeLoc().getBeginLoc(); 2615 2616 return {}; 2617 } 2618 2619 SourceRange CXXCtorInitializer::getSourceRange() const { 2620 if (isInClassMemberInitializer()) { 2621 FieldDecl *D = getAnyMember(); 2622 if (Expr *I = D->getInClassInitializer()) 2623 return I->getSourceRange(); 2624 return {}; 2625 } 2626 2627 return SourceRange(getSourceLocation(), getRParenLoc()); 2628 } 2629 2630 CXXConstructorDecl::CXXConstructorDecl( 2631 ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, 2632 const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, 2633 ExplicitSpecifier ES, bool UsesFPIntrin, bool isInline, 2634 bool isImplicitlyDeclared, ConstexprSpecKind ConstexprKind, 2635 InheritedConstructor Inherited, Expr *TrailingRequiresClause) 2636 : CXXMethodDecl(CXXConstructor, C, RD, StartLoc, NameInfo, T, TInfo, 2637 SC_None, UsesFPIntrin, isInline, ConstexprKind, 2638 SourceLocation(), TrailingRequiresClause) { 2639 setNumCtorInitializers(0); 2640 setInheritingConstructor(static_cast<bool>(Inherited)); 2641 setImplicit(isImplicitlyDeclared); 2642 CXXConstructorDeclBits.HasTrailingExplicitSpecifier = ES.getExpr() ? 1 : 0; 2643 if (Inherited) 2644 *getTrailingObjects<InheritedConstructor>() = Inherited; 2645 setExplicitSpecifier(ES); 2646 } 2647 2648 void CXXConstructorDecl::anchor() {} 2649 2650 CXXConstructorDecl *CXXConstructorDecl::CreateDeserialized(ASTContext &C, 2651 unsigned ID, 2652 uint64_t AllocKind) { 2653 bool hasTrailingExplicit = static_cast<bool>(AllocKind & TAKHasTailExplicit); 2654 bool isInheritingConstructor = 2655 static_cast<bool>(AllocKind & TAKInheritsConstructor); 2656 unsigned Extra = 2657 additionalSizeToAlloc<InheritedConstructor, ExplicitSpecifier>( 2658 isInheritingConstructor, hasTrailingExplicit); 2659 auto *Result = new (C, ID, Extra) CXXConstructorDecl( 2660 C, nullptr, SourceLocation(), DeclarationNameInfo(), QualType(), nullptr, 2661 ExplicitSpecifier(), false, false, false, ConstexprSpecKind::Unspecified, 2662 InheritedConstructor(), nullptr); 2663 Result->setInheritingConstructor(isInheritingConstructor); 2664 Result->CXXConstructorDeclBits.HasTrailingExplicitSpecifier = 2665 hasTrailingExplicit; 2666 Result->setExplicitSpecifier(ExplicitSpecifier()); 2667 return Result; 2668 } 2669 2670 CXXConstructorDecl *CXXConstructorDecl::Create( 2671 ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, 2672 const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, 2673 ExplicitSpecifier ES, bool UsesFPIntrin, bool isInline, 2674 bool isImplicitlyDeclared, ConstexprSpecKind ConstexprKind, 2675 InheritedConstructor Inherited, Expr *TrailingRequiresClause) { 2676 assert(NameInfo.getName().getNameKind() 2677 == DeclarationName::CXXConstructorName && 2678 "Name must refer to a constructor"); 2679 unsigned Extra = 2680 additionalSizeToAlloc<InheritedConstructor, ExplicitSpecifier>( 2681 Inherited ? 1 : 0, ES.getExpr() ? 1 : 0); 2682 return new (C, RD, Extra) CXXConstructorDecl( 2683 C, RD, StartLoc, NameInfo, T, TInfo, ES, UsesFPIntrin, isInline, 2684 isImplicitlyDeclared, ConstexprKind, Inherited, TrailingRequiresClause); 2685 } 2686 2687 CXXConstructorDecl::init_const_iterator CXXConstructorDecl::init_begin() const { 2688 return CtorInitializers.get(getASTContext().getExternalSource()); 2689 } 2690 2691 CXXConstructorDecl *CXXConstructorDecl::getTargetConstructor() const { 2692 assert(isDelegatingConstructor() && "Not a delegating constructor!"); 2693 Expr *E = (*init_begin())->getInit()->IgnoreImplicit(); 2694 if (const auto *Construct = dyn_cast<CXXConstructExpr>(E)) 2695 return Construct->getConstructor(); 2696 2697 return nullptr; 2698 } 2699 2700 bool CXXConstructorDecl::isDefaultConstructor() const { 2701 // C++ [class.default.ctor]p1: 2702 // A default constructor for a class X is a constructor of class X for 2703 // which each parameter that is not a function parameter pack has a default 2704 // argument (including the case of a constructor with no parameters) 2705 return getMinRequiredArguments() == 0; 2706 } 2707 2708 bool 2709 CXXConstructorDecl::isCopyConstructor(unsigned &TypeQuals) const { 2710 return isCopyOrMoveConstructor(TypeQuals) && 2711 getParamDecl(0)->getType()->isLValueReferenceType(); 2712 } 2713 2714 bool CXXConstructorDecl::isMoveConstructor(unsigned &TypeQuals) const { 2715 return isCopyOrMoveConstructor(TypeQuals) && 2716 getParamDecl(0)->getType()->isRValueReferenceType(); 2717 } 2718 2719 /// Determine whether this is a copy or move constructor. 2720 bool CXXConstructorDecl::isCopyOrMoveConstructor(unsigned &TypeQuals) const { 2721 // C++ [class.copy]p2: 2722 // A non-template constructor for class X is a copy constructor 2723 // if its first parameter is of type X&, const X&, volatile X& or 2724 // const volatile X&, and either there are no other parameters 2725 // or else all other parameters have default arguments (8.3.6). 2726 // C++0x [class.copy]p3: 2727 // A non-template constructor for class X is a move constructor if its 2728 // first parameter is of type X&&, const X&&, volatile X&&, or 2729 // const volatile X&&, and either there are no other parameters or else 2730 // all other parameters have default arguments. 2731 if (!hasOneParamOrDefaultArgs() || getPrimaryTemplate() != nullptr || 2732 getDescribedFunctionTemplate() != nullptr) 2733 return false; 2734 2735 const ParmVarDecl *Param = getParamDecl(0); 2736 2737 // Do we have a reference type? 2738 const auto *ParamRefType = Param->getType()->getAs<ReferenceType>(); 2739 if (!ParamRefType) 2740 return false; 2741 2742 // Is it a reference to our class type? 2743 ASTContext &Context = getASTContext(); 2744 2745 CanQualType PointeeType 2746 = Context.getCanonicalType(ParamRefType->getPointeeType()); 2747 CanQualType ClassTy 2748 = Context.getCanonicalType(Context.getTagDeclType(getParent())); 2749 if (PointeeType.getUnqualifiedType() != ClassTy) 2750 return false; 2751 2752 // FIXME: other qualifiers? 2753 2754 // We have a copy or move constructor. 2755 TypeQuals = PointeeType.getCVRQualifiers(); 2756 return true; 2757 } 2758 2759 bool CXXConstructorDecl::isConvertingConstructor(bool AllowExplicit) const { 2760 // C++ [class.conv.ctor]p1: 2761 // A constructor declared without the function-specifier explicit 2762 // that can be called with a single parameter specifies a 2763 // conversion from the type of its first parameter to the type of 2764 // its class. Such a constructor is called a converting 2765 // constructor. 2766 if (isExplicit() && !AllowExplicit) 2767 return false; 2768 2769 // FIXME: This has nothing to do with the definition of converting 2770 // constructor, but is convenient for how we use this function in overload 2771 // resolution. 2772 return getNumParams() == 0 2773 ? getType()->castAs<FunctionProtoType>()->isVariadic() 2774 : getMinRequiredArguments() <= 1; 2775 } 2776 2777 bool CXXConstructorDecl::isSpecializationCopyingObject() const { 2778 if (!hasOneParamOrDefaultArgs() || getDescribedFunctionTemplate() != nullptr) 2779 return false; 2780 2781 const ParmVarDecl *Param = getParamDecl(0); 2782 2783 ASTContext &Context = getASTContext(); 2784 CanQualType ParamType = Context.getCanonicalType(Param->getType()); 2785 2786 // Is it the same as our class type? 2787 CanQualType ClassTy 2788 = Context.getCanonicalType(Context.getTagDeclType(getParent())); 2789 if (ParamType.getUnqualifiedType() != ClassTy) 2790 return false; 2791 2792 return true; 2793 } 2794 2795 void CXXDestructorDecl::anchor() {} 2796 2797 CXXDestructorDecl * 2798 CXXDestructorDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 2799 return new (C, ID) CXXDestructorDecl( 2800 C, nullptr, SourceLocation(), DeclarationNameInfo(), QualType(), nullptr, 2801 false, false, false, ConstexprSpecKind::Unspecified, nullptr); 2802 } 2803 2804 CXXDestructorDecl *CXXDestructorDecl::Create( 2805 ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, 2806 const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, 2807 bool UsesFPIntrin, bool isInline, bool isImplicitlyDeclared, 2808 ConstexprSpecKind ConstexprKind, Expr *TrailingRequiresClause) { 2809 assert(NameInfo.getName().getNameKind() 2810 == DeclarationName::CXXDestructorName && 2811 "Name must refer to a destructor"); 2812 return new (C, RD) CXXDestructorDecl( 2813 C, RD, StartLoc, NameInfo, T, TInfo, UsesFPIntrin, isInline, 2814 isImplicitlyDeclared, ConstexprKind, TrailingRequiresClause); 2815 } 2816 2817 void CXXDestructorDecl::setOperatorDelete(FunctionDecl *OD, Expr *ThisArg) { 2818 auto *First = cast<CXXDestructorDecl>(getFirstDecl()); 2819 if (OD && !First->OperatorDelete) { 2820 First->OperatorDelete = OD; 2821 First->OperatorDeleteThisArg = ThisArg; 2822 if (auto *L = getASTMutationListener()) 2823 L->ResolvedOperatorDelete(First, OD, ThisArg); 2824 } 2825 } 2826 2827 void CXXConversionDecl::anchor() {} 2828 2829 CXXConversionDecl * 2830 CXXConversionDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 2831 return new (C, ID) CXXConversionDecl( 2832 C, nullptr, SourceLocation(), DeclarationNameInfo(), QualType(), nullptr, 2833 false, false, ExplicitSpecifier(), ConstexprSpecKind::Unspecified, 2834 SourceLocation(), nullptr); 2835 } 2836 2837 CXXConversionDecl *CXXConversionDecl::Create( 2838 ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, 2839 const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, 2840 bool UsesFPIntrin, bool isInline, ExplicitSpecifier ES, 2841 ConstexprSpecKind ConstexprKind, SourceLocation EndLocation, 2842 Expr *TrailingRequiresClause) { 2843 assert(NameInfo.getName().getNameKind() 2844 == DeclarationName::CXXConversionFunctionName && 2845 "Name must refer to a conversion function"); 2846 return new (C, RD) CXXConversionDecl( 2847 C, RD, StartLoc, NameInfo, T, TInfo, UsesFPIntrin, isInline, ES, 2848 ConstexprKind, EndLocation, TrailingRequiresClause); 2849 } 2850 2851 bool CXXConversionDecl::isLambdaToBlockPointerConversion() const { 2852 return isImplicit() && getParent()->isLambda() && 2853 getConversionType()->isBlockPointerType(); 2854 } 2855 2856 LinkageSpecDecl::LinkageSpecDecl(DeclContext *DC, SourceLocation ExternLoc, 2857 SourceLocation LangLoc, 2858 LinkageSpecLanguageIDs lang, bool HasBraces) 2859 : Decl(LinkageSpec, DC, LangLoc), DeclContext(LinkageSpec), 2860 ExternLoc(ExternLoc), RBraceLoc(SourceLocation()) { 2861 setLanguage(lang); 2862 LinkageSpecDeclBits.HasBraces = HasBraces; 2863 } 2864 2865 void LinkageSpecDecl::anchor() {} 2866 2867 LinkageSpecDecl *LinkageSpecDecl::Create(ASTContext &C, DeclContext *DC, 2868 SourceLocation ExternLoc, 2869 SourceLocation LangLoc, 2870 LinkageSpecLanguageIDs Lang, 2871 bool HasBraces) { 2872 return new (C, DC) LinkageSpecDecl(DC, ExternLoc, LangLoc, Lang, HasBraces); 2873 } 2874 2875 LinkageSpecDecl *LinkageSpecDecl::CreateDeserialized(ASTContext &C, 2876 unsigned ID) { 2877 return new (C, ID) 2878 LinkageSpecDecl(nullptr, SourceLocation(), SourceLocation(), 2879 LinkageSpecLanguageIDs::C, false); 2880 } 2881 2882 void UsingDirectiveDecl::anchor() {} 2883 2884 UsingDirectiveDecl *UsingDirectiveDecl::Create(ASTContext &C, DeclContext *DC, 2885 SourceLocation L, 2886 SourceLocation NamespaceLoc, 2887 NestedNameSpecifierLoc QualifierLoc, 2888 SourceLocation IdentLoc, 2889 NamedDecl *Used, 2890 DeclContext *CommonAncestor) { 2891 if (auto *NS = dyn_cast_or_null<NamespaceDecl>(Used)) 2892 Used = NS->getOriginalNamespace(); 2893 return new (C, DC) UsingDirectiveDecl(DC, L, NamespaceLoc, QualifierLoc, 2894 IdentLoc, Used, CommonAncestor); 2895 } 2896 2897 UsingDirectiveDecl *UsingDirectiveDecl::CreateDeserialized(ASTContext &C, 2898 unsigned ID) { 2899 return new (C, ID) UsingDirectiveDecl(nullptr, SourceLocation(), 2900 SourceLocation(), 2901 NestedNameSpecifierLoc(), 2902 SourceLocation(), nullptr, nullptr); 2903 } 2904 2905 NamespaceDecl *UsingDirectiveDecl::getNominatedNamespace() { 2906 if (auto *NA = dyn_cast_or_null<NamespaceAliasDecl>(NominatedNamespace)) 2907 return NA->getNamespace(); 2908 return cast_or_null<NamespaceDecl>(NominatedNamespace); 2909 } 2910 2911 NamespaceDecl::NamespaceDecl(ASTContext &C, DeclContext *DC, bool Inline, 2912 SourceLocation StartLoc, SourceLocation IdLoc, 2913 IdentifierInfo *Id, NamespaceDecl *PrevDecl, 2914 bool Nested) 2915 : NamedDecl(Namespace, DC, IdLoc, Id), DeclContext(Namespace), 2916 redeclarable_base(C), LocStart(StartLoc) { 2917 unsigned Flags = 0; 2918 if (Inline) 2919 Flags |= F_Inline; 2920 if (Nested) 2921 Flags |= F_Nested; 2922 AnonOrFirstNamespaceAndFlags = {nullptr, Flags}; 2923 setPreviousDecl(PrevDecl); 2924 2925 if (PrevDecl) 2926 AnonOrFirstNamespaceAndFlags.setPointer(PrevDecl->getOriginalNamespace()); 2927 } 2928 2929 NamespaceDecl *NamespaceDecl::Create(ASTContext &C, DeclContext *DC, 2930 bool Inline, SourceLocation StartLoc, 2931 SourceLocation IdLoc, IdentifierInfo *Id, 2932 NamespaceDecl *PrevDecl, bool Nested) { 2933 return new (C, DC) 2934 NamespaceDecl(C, DC, Inline, StartLoc, IdLoc, Id, PrevDecl, Nested); 2935 } 2936 2937 NamespaceDecl *NamespaceDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 2938 return new (C, ID) NamespaceDecl(C, nullptr, false, SourceLocation(), 2939 SourceLocation(), nullptr, nullptr, false); 2940 } 2941 2942 NamespaceDecl *NamespaceDecl::getOriginalNamespace() { 2943 if (isFirstDecl()) 2944 return this; 2945 2946 return AnonOrFirstNamespaceAndFlags.getPointer(); 2947 } 2948 2949 const NamespaceDecl *NamespaceDecl::getOriginalNamespace() const { 2950 if (isFirstDecl()) 2951 return this; 2952 2953 return AnonOrFirstNamespaceAndFlags.getPointer(); 2954 } 2955 2956 bool NamespaceDecl::isOriginalNamespace() const { return isFirstDecl(); } 2957 2958 NamespaceDecl *NamespaceDecl::getNextRedeclarationImpl() { 2959 return getNextRedeclaration(); 2960 } 2961 2962 NamespaceDecl *NamespaceDecl::getPreviousDeclImpl() { 2963 return getPreviousDecl(); 2964 } 2965 2966 NamespaceDecl *NamespaceDecl::getMostRecentDeclImpl() { 2967 return getMostRecentDecl(); 2968 } 2969 2970 void NamespaceAliasDecl::anchor() {} 2971 2972 NamespaceAliasDecl *NamespaceAliasDecl::getNextRedeclarationImpl() { 2973 return getNextRedeclaration(); 2974 } 2975 2976 NamespaceAliasDecl *NamespaceAliasDecl::getPreviousDeclImpl() { 2977 return getPreviousDecl(); 2978 } 2979 2980 NamespaceAliasDecl *NamespaceAliasDecl::getMostRecentDeclImpl() { 2981 return getMostRecentDecl(); 2982 } 2983 2984 NamespaceAliasDecl *NamespaceAliasDecl::Create(ASTContext &C, DeclContext *DC, 2985 SourceLocation UsingLoc, 2986 SourceLocation AliasLoc, 2987 IdentifierInfo *Alias, 2988 NestedNameSpecifierLoc QualifierLoc, 2989 SourceLocation IdentLoc, 2990 NamedDecl *Namespace) { 2991 // FIXME: Preserve the aliased namespace as written. 2992 if (auto *NS = dyn_cast_or_null<NamespaceDecl>(Namespace)) 2993 Namespace = NS->getOriginalNamespace(); 2994 return new (C, DC) NamespaceAliasDecl(C, DC, UsingLoc, AliasLoc, Alias, 2995 QualifierLoc, IdentLoc, Namespace); 2996 } 2997 2998 NamespaceAliasDecl * 2999 NamespaceAliasDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 3000 return new (C, ID) NamespaceAliasDecl(C, nullptr, SourceLocation(), 3001 SourceLocation(), nullptr, 3002 NestedNameSpecifierLoc(), 3003 SourceLocation(), nullptr); 3004 } 3005 3006 void LifetimeExtendedTemporaryDecl::anchor() {} 3007 3008 /// Retrieve the storage duration for the materialized temporary. 3009 StorageDuration LifetimeExtendedTemporaryDecl::getStorageDuration() const { 3010 const ValueDecl *ExtendingDecl = getExtendingDecl(); 3011 if (!ExtendingDecl) 3012 return SD_FullExpression; 3013 // FIXME: This is not necessarily correct for a temporary materialized 3014 // within a default initializer. 3015 if (isa<FieldDecl>(ExtendingDecl)) 3016 return SD_Automatic; 3017 // FIXME: This only works because storage class specifiers are not allowed 3018 // on decomposition declarations. 3019 if (isa<BindingDecl>(ExtendingDecl)) 3020 return ExtendingDecl->getDeclContext()->isFunctionOrMethod() ? SD_Automatic 3021 : SD_Static; 3022 return cast<VarDecl>(ExtendingDecl)->getStorageDuration(); 3023 } 3024 3025 APValue *LifetimeExtendedTemporaryDecl::getOrCreateValue(bool MayCreate) const { 3026 assert(getStorageDuration() == SD_Static && 3027 "don't need to cache the computed value for this temporary"); 3028 if (MayCreate && !Value) { 3029 Value = (new (getASTContext()) APValue); 3030 getASTContext().addDestruction(Value); 3031 } 3032 assert(Value && "may not be null"); 3033 return Value; 3034 } 3035 3036 void UsingShadowDecl::anchor() {} 3037 3038 UsingShadowDecl::UsingShadowDecl(Kind K, ASTContext &C, DeclContext *DC, 3039 SourceLocation Loc, DeclarationName Name, 3040 BaseUsingDecl *Introducer, NamedDecl *Target) 3041 : NamedDecl(K, DC, Loc, Name), redeclarable_base(C), 3042 UsingOrNextShadow(Introducer) { 3043 if (Target) { 3044 assert(!isa<UsingShadowDecl>(Target)); 3045 setTargetDecl(Target); 3046 } 3047 setImplicit(); 3048 } 3049 3050 UsingShadowDecl::UsingShadowDecl(Kind K, ASTContext &C, EmptyShell Empty) 3051 : NamedDecl(K, nullptr, SourceLocation(), DeclarationName()), 3052 redeclarable_base(C) {} 3053 3054 UsingShadowDecl * 3055 UsingShadowDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 3056 return new (C, ID) UsingShadowDecl(UsingShadow, C, EmptyShell()); 3057 } 3058 3059 BaseUsingDecl *UsingShadowDecl::getIntroducer() const { 3060 const UsingShadowDecl *Shadow = this; 3061 while (const auto *NextShadow = 3062 dyn_cast<UsingShadowDecl>(Shadow->UsingOrNextShadow)) 3063 Shadow = NextShadow; 3064 return cast<BaseUsingDecl>(Shadow->UsingOrNextShadow); 3065 } 3066 3067 void ConstructorUsingShadowDecl::anchor() {} 3068 3069 ConstructorUsingShadowDecl * 3070 ConstructorUsingShadowDecl::Create(ASTContext &C, DeclContext *DC, 3071 SourceLocation Loc, UsingDecl *Using, 3072 NamedDecl *Target, bool IsVirtual) { 3073 return new (C, DC) ConstructorUsingShadowDecl(C, DC, Loc, Using, Target, 3074 IsVirtual); 3075 } 3076 3077 ConstructorUsingShadowDecl * 3078 ConstructorUsingShadowDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 3079 return new (C, ID) ConstructorUsingShadowDecl(C, EmptyShell()); 3080 } 3081 3082 CXXRecordDecl *ConstructorUsingShadowDecl::getNominatedBaseClass() const { 3083 return getIntroducer()->getQualifier()->getAsRecordDecl(); 3084 } 3085 3086 void BaseUsingDecl::anchor() {} 3087 3088 void BaseUsingDecl::addShadowDecl(UsingShadowDecl *S) { 3089 assert(!llvm::is_contained(shadows(), S) && "declaration already in set"); 3090 assert(S->getIntroducer() == this); 3091 3092 if (FirstUsingShadow.getPointer()) 3093 S->UsingOrNextShadow = FirstUsingShadow.getPointer(); 3094 FirstUsingShadow.setPointer(S); 3095 } 3096 3097 void BaseUsingDecl::removeShadowDecl(UsingShadowDecl *S) { 3098 assert(llvm::is_contained(shadows(), S) && "declaration not in set"); 3099 assert(S->getIntroducer() == this); 3100 3101 // Remove S from the shadow decl chain. This is O(n) but hopefully rare. 3102 3103 if (FirstUsingShadow.getPointer() == S) { 3104 FirstUsingShadow.setPointer( 3105 dyn_cast<UsingShadowDecl>(S->UsingOrNextShadow)); 3106 S->UsingOrNextShadow = this; 3107 return; 3108 } 3109 3110 UsingShadowDecl *Prev = FirstUsingShadow.getPointer(); 3111 while (Prev->UsingOrNextShadow != S) 3112 Prev = cast<UsingShadowDecl>(Prev->UsingOrNextShadow); 3113 Prev->UsingOrNextShadow = S->UsingOrNextShadow; 3114 S->UsingOrNextShadow = this; 3115 } 3116 3117 void UsingDecl::anchor() {} 3118 3119 UsingDecl *UsingDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation UL, 3120 NestedNameSpecifierLoc QualifierLoc, 3121 const DeclarationNameInfo &NameInfo, 3122 bool HasTypename) { 3123 return new (C, DC) UsingDecl(DC, UL, QualifierLoc, NameInfo, HasTypename); 3124 } 3125 3126 UsingDecl *UsingDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 3127 return new (C, ID) UsingDecl(nullptr, SourceLocation(), 3128 NestedNameSpecifierLoc(), DeclarationNameInfo(), 3129 false); 3130 } 3131 3132 SourceRange UsingDecl::getSourceRange() const { 3133 SourceLocation Begin = isAccessDeclaration() 3134 ? getQualifierLoc().getBeginLoc() : UsingLocation; 3135 return SourceRange(Begin, getNameInfo().getEndLoc()); 3136 } 3137 3138 void UsingEnumDecl::anchor() {} 3139 3140 UsingEnumDecl *UsingEnumDecl::Create(ASTContext &C, DeclContext *DC, 3141 SourceLocation UL, 3142 SourceLocation EL, 3143 SourceLocation NL, 3144 TypeSourceInfo *EnumType) { 3145 assert(isa<EnumDecl>(EnumType->getType()->getAsTagDecl())); 3146 return new (C, DC) 3147 UsingEnumDecl(DC, EnumType->getType()->getAsTagDecl()->getDeclName(), UL, EL, NL, EnumType); 3148 } 3149 3150 UsingEnumDecl *UsingEnumDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 3151 return new (C, ID) 3152 UsingEnumDecl(nullptr, DeclarationName(), SourceLocation(), 3153 SourceLocation(), SourceLocation(), nullptr); 3154 } 3155 3156 SourceRange UsingEnumDecl::getSourceRange() const { 3157 return SourceRange(UsingLocation, EnumType->getTypeLoc().getEndLoc()); 3158 } 3159 3160 void UsingPackDecl::anchor() {} 3161 3162 UsingPackDecl *UsingPackDecl::Create(ASTContext &C, DeclContext *DC, 3163 NamedDecl *InstantiatedFrom, 3164 ArrayRef<NamedDecl *> UsingDecls) { 3165 size_t Extra = additionalSizeToAlloc<NamedDecl *>(UsingDecls.size()); 3166 return new (C, DC, Extra) UsingPackDecl(DC, InstantiatedFrom, UsingDecls); 3167 } 3168 3169 UsingPackDecl *UsingPackDecl::CreateDeserialized(ASTContext &C, unsigned ID, 3170 unsigned NumExpansions) { 3171 size_t Extra = additionalSizeToAlloc<NamedDecl *>(NumExpansions); 3172 auto *Result = 3173 new (C, ID, Extra) UsingPackDecl(nullptr, nullptr, std::nullopt); 3174 Result->NumExpansions = NumExpansions; 3175 auto *Trail = Result->getTrailingObjects<NamedDecl *>(); 3176 for (unsigned I = 0; I != NumExpansions; ++I) 3177 new (Trail + I) NamedDecl*(nullptr); 3178 return Result; 3179 } 3180 3181 void UnresolvedUsingValueDecl::anchor() {} 3182 3183 UnresolvedUsingValueDecl * 3184 UnresolvedUsingValueDecl::Create(ASTContext &C, DeclContext *DC, 3185 SourceLocation UsingLoc, 3186 NestedNameSpecifierLoc QualifierLoc, 3187 const DeclarationNameInfo &NameInfo, 3188 SourceLocation EllipsisLoc) { 3189 return new (C, DC) UnresolvedUsingValueDecl(DC, C.DependentTy, UsingLoc, 3190 QualifierLoc, NameInfo, 3191 EllipsisLoc); 3192 } 3193 3194 UnresolvedUsingValueDecl * 3195 UnresolvedUsingValueDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 3196 return new (C, ID) UnresolvedUsingValueDecl(nullptr, QualType(), 3197 SourceLocation(), 3198 NestedNameSpecifierLoc(), 3199 DeclarationNameInfo(), 3200 SourceLocation()); 3201 } 3202 3203 SourceRange UnresolvedUsingValueDecl::getSourceRange() const { 3204 SourceLocation Begin = isAccessDeclaration() 3205 ? getQualifierLoc().getBeginLoc() : UsingLocation; 3206 return SourceRange(Begin, getNameInfo().getEndLoc()); 3207 } 3208 3209 void UnresolvedUsingTypenameDecl::anchor() {} 3210 3211 UnresolvedUsingTypenameDecl * 3212 UnresolvedUsingTypenameDecl::Create(ASTContext &C, DeclContext *DC, 3213 SourceLocation UsingLoc, 3214 SourceLocation TypenameLoc, 3215 NestedNameSpecifierLoc QualifierLoc, 3216 SourceLocation TargetNameLoc, 3217 DeclarationName TargetName, 3218 SourceLocation EllipsisLoc) { 3219 return new (C, DC) UnresolvedUsingTypenameDecl( 3220 DC, UsingLoc, TypenameLoc, QualifierLoc, TargetNameLoc, 3221 TargetName.getAsIdentifierInfo(), EllipsisLoc); 3222 } 3223 3224 UnresolvedUsingTypenameDecl * 3225 UnresolvedUsingTypenameDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 3226 return new (C, ID) UnresolvedUsingTypenameDecl( 3227 nullptr, SourceLocation(), SourceLocation(), NestedNameSpecifierLoc(), 3228 SourceLocation(), nullptr, SourceLocation()); 3229 } 3230 3231 UnresolvedUsingIfExistsDecl * 3232 UnresolvedUsingIfExistsDecl::Create(ASTContext &Ctx, DeclContext *DC, 3233 SourceLocation Loc, DeclarationName Name) { 3234 return new (Ctx, DC) UnresolvedUsingIfExistsDecl(DC, Loc, Name); 3235 } 3236 3237 UnresolvedUsingIfExistsDecl * 3238 UnresolvedUsingIfExistsDecl::CreateDeserialized(ASTContext &Ctx, unsigned ID) { 3239 return new (Ctx, ID) 3240 UnresolvedUsingIfExistsDecl(nullptr, SourceLocation(), DeclarationName()); 3241 } 3242 3243 UnresolvedUsingIfExistsDecl::UnresolvedUsingIfExistsDecl(DeclContext *DC, 3244 SourceLocation Loc, 3245 DeclarationName Name) 3246 : NamedDecl(Decl::UnresolvedUsingIfExists, DC, Loc, Name) {} 3247 3248 void UnresolvedUsingIfExistsDecl::anchor() {} 3249 3250 void StaticAssertDecl::anchor() {} 3251 3252 StaticAssertDecl *StaticAssertDecl::Create(ASTContext &C, DeclContext *DC, 3253 SourceLocation StaticAssertLoc, 3254 Expr *AssertExpr, Expr *Message, 3255 SourceLocation RParenLoc, 3256 bool Failed) { 3257 return new (C, DC) StaticAssertDecl(DC, StaticAssertLoc, AssertExpr, Message, 3258 RParenLoc, Failed); 3259 } 3260 3261 StaticAssertDecl *StaticAssertDecl::CreateDeserialized(ASTContext &C, 3262 unsigned ID) { 3263 return new (C, ID) StaticAssertDecl(nullptr, SourceLocation(), nullptr, 3264 nullptr, SourceLocation(), false); 3265 } 3266 3267 VarDecl *ValueDecl::getPotentiallyDecomposedVarDecl() { 3268 assert((isa<VarDecl, BindingDecl>(this)) && 3269 "expected a VarDecl or a BindingDecl"); 3270 if (auto *Var = llvm::dyn_cast<VarDecl>(this)) 3271 return Var; 3272 if (auto *BD = llvm::dyn_cast<BindingDecl>(this)) 3273 return llvm::dyn_cast<VarDecl>(BD->getDecomposedDecl()); 3274 return nullptr; 3275 } 3276 3277 void BindingDecl::anchor() {} 3278 3279 BindingDecl *BindingDecl::Create(ASTContext &C, DeclContext *DC, 3280 SourceLocation IdLoc, IdentifierInfo *Id) { 3281 return new (C, DC) BindingDecl(DC, IdLoc, Id); 3282 } 3283 3284 BindingDecl *BindingDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 3285 return new (C, ID) BindingDecl(nullptr, SourceLocation(), nullptr); 3286 } 3287 3288 VarDecl *BindingDecl::getHoldingVar() const { 3289 Expr *B = getBinding(); 3290 if (!B) 3291 return nullptr; 3292 auto *DRE = dyn_cast<DeclRefExpr>(B->IgnoreImplicit()); 3293 if (!DRE) 3294 return nullptr; 3295 3296 auto *VD = cast<VarDecl>(DRE->getDecl()); 3297 assert(VD->isImplicit() && "holding var for binding decl not implicit"); 3298 return VD; 3299 } 3300 3301 void DecompositionDecl::anchor() {} 3302 3303 DecompositionDecl *DecompositionDecl::Create(ASTContext &C, DeclContext *DC, 3304 SourceLocation StartLoc, 3305 SourceLocation LSquareLoc, 3306 QualType T, TypeSourceInfo *TInfo, 3307 StorageClass SC, 3308 ArrayRef<BindingDecl *> Bindings) { 3309 size_t Extra = additionalSizeToAlloc<BindingDecl *>(Bindings.size()); 3310 return new (C, DC, Extra) 3311 DecompositionDecl(C, DC, StartLoc, LSquareLoc, T, TInfo, SC, Bindings); 3312 } 3313 3314 DecompositionDecl *DecompositionDecl::CreateDeserialized(ASTContext &C, 3315 unsigned ID, 3316 unsigned NumBindings) { 3317 size_t Extra = additionalSizeToAlloc<BindingDecl *>(NumBindings); 3318 auto *Result = new (C, ID, Extra) 3319 DecompositionDecl(C, nullptr, SourceLocation(), SourceLocation(), 3320 QualType(), nullptr, StorageClass(), std::nullopt); 3321 // Set up and clean out the bindings array. 3322 Result->NumBindings = NumBindings; 3323 auto *Trail = Result->getTrailingObjects<BindingDecl *>(); 3324 for (unsigned I = 0; I != NumBindings; ++I) 3325 new (Trail + I) BindingDecl*(nullptr); 3326 return Result; 3327 } 3328 3329 void DecompositionDecl::printName(llvm::raw_ostream &OS, 3330 const PrintingPolicy &Policy) const { 3331 OS << '['; 3332 bool Comma = false; 3333 for (const auto *B : bindings()) { 3334 if (Comma) 3335 OS << ", "; 3336 B->printName(OS, Policy); 3337 Comma = true; 3338 } 3339 OS << ']'; 3340 } 3341 3342 void MSPropertyDecl::anchor() {} 3343 3344 MSPropertyDecl *MSPropertyDecl::Create(ASTContext &C, DeclContext *DC, 3345 SourceLocation L, DeclarationName N, 3346 QualType T, TypeSourceInfo *TInfo, 3347 SourceLocation StartL, 3348 IdentifierInfo *Getter, 3349 IdentifierInfo *Setter) { 3350 return new (C, DC) MSPropertyDecl(DC, L, N, T, TInfo, StartL, Getter, Setter); 3351 } 3352 3353 MSPropertyDecl *MSPropertyDecl::CreateDeserialized(ASTContext &C, 3354 unsigned ID) { 3355 return new (C, ID) MSPropertyDecl(nullptr, SourceLocation(), 3356 DeclarationName(), QualType(), nullptr, 3357 SourceLocation(), nullptr, nullptr); 3358 } 3359 3360 void MSGuidDecl::anchor() {} 3361 3362 MSGuidDecl::MSGuidDecl(DeclContext *DC, QualType T, Parts P) 3363 : ValueDecl(Decl::MSGuid, DC, SourceLocation(), DeclarationName(), T), 3364 PartVal(P) {} 3365 3366 MSGuidDecl *MSGuidDecl::Create(const ASTContext &C, QualType T, Parts P) { 3367 DeclContext *DC = C.getTranslationUnitDecl(); 3368 return new (C, DC) MSGuidDecl(DC, T, P); 3369 } 3370 3371 MSGuidDecl *MSGuidDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 3372 return new (C, ID) MSGuidDecl(nullptr, QualType(), Parts()); 3373 } 3374 3375 void MSGuidDecl::printName(llvm::raw_ostream &OS, 3376 const PrintingPolicy &) const { 3377 OS << llvm::format("GUID{%08" PRIx32 "-%04" PRIx16 "-%04" PRIx16 "-", 3378 PartVal.Part1, PartVal.Part2, PartVal.Part3); 3379 unsigned I = 0; 3380 for (uint8_t Byte : PartVal.Part4And5) { 3381 OS << llvm::format("%02" PRIx8, Byte); 3382 if (++I == 2) 3383 OS << '-'; 3384 } 3385 OS << '}'; 3386 } 3387 3388 /// Determine if T is a valid 'struct _GUID' of the shape that we expect. 3389 static bool isValidStructGUID(ASTContext &Ctx, QualType T) { 3390 // FIXME: We only need to check this once, not once each time we compute a 3391 // GUID APValue. 3392 using MatcherRef = llvm::function_ref<bool(QualType)>; 3393 3394 auto IsInt = [&Ctx](unsigned N) { 3395 return [&Ctx, N](QualType T) { 3396 return T->isUnsignedIntegerOrEnumerationType() && 3397 Ctx.getIntWidth(T) == N; 3398 }; 3399 }; 3400 3401 auto IsArray = [&Ctx](MatcherRef Elem, unsigned N) { 3402 return [&Ctx, Elem, N](QualType T) { 3403 const ConstantArrayType *CAT = Ctx.getAsConstantArrayType(T); 3404 return CAT && CAT->getSize() == N && Elem(CAT->getElementType()); 3405 }; 3406 }; 3407 3408 auto IsStruct = [](std::initializer_list<MatcherRef> Fields) { 3409 return [Fields](QualType T) { 3410 const RecordDecl *RD = T->getAsRecordDecl(); 3411 if (!RD || RD->isUnion()) 3412 return false; 3413 RD = RD->getDefinition(); 3414 if (!RD) 3415 return false; 3416 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 3417 if (CXXRD->getNumBases()) 3418 return false; 3419 auto MatcherIt = Fields.begin(); 3420 for (const FieldDecl *FD : RD->fields()) { 3421 if (FD->isUnnamedBitfield()) continue; 3422 if (FD->isBitField() || MatcherIt == Fields.end() || 3423 !(*MatcherIt)(FD->getType())) 3424 return false; 3425 ++MatcherIt; 3426 } 3427 return MatcherIt == Fields.end(); 3428 }; 3429 }; 3430 3431 // We expect an {i32, i16, i16, [8 x i8]}. 3432 return IsStruct({IsInt(32), IsInt(16), IsInt(16), IsArray(IsInt(8), 8)})(T); 3433 } 3434 3435 APValue &MSGuidDecl::getAsAPValue() const { 3436 if (APVal.isAbsent() && isValidStructGUID(getASTContext(), getType())) { 3437 using llvm::APInt; 3438 using llvm::APSInt; 3439 APVal = APValue(APValue::UninitStruct(), 0, 4); 3440 APVal.getStructField(0) = APValue(APSInt(APInt(32, PartVal.Part1), true)); 3441 APVal.getStructField(1) = APValue(APSInt(APInt(16, PartVal.Part2), true)); 3442 APVal.getStructField(2) = APValue(APSInt(APInt(16, PartVal.Part3), true)); 3443 APValue &Arr = APVal.getStructField(3) = 3444 APValue(APValue::UninitArray(), 8, 8); 3445 for (unsigned I = 0; I != 8; ++I) { 3446 Arr.getArrayInitializedElt(I) = 3447 APValue(APSInt(APInt(8, PartVal.Part4And5[I]), true)); 3448 } 3449 // Register this APValue to be destroyed if necessary. (Note that the 3450 // MSGuidDecl destructor is never run.) 3451 getASTContext().addDestruction(&APVal); 3452 } 3453 3454 return APVal; 3455 } 3456 3457 void UnnamedGlobalConstantDecl::anchor() {} 3458 3459 UnnamedGlobalConstantDecl::UnnamedGlobalConstantDecl(const ASTContext &C, 3460 DeclContext *DC, 3461 QualType Ty, 3462 const APValue &Val) 3463 : ValueDecl(Decl::UnnamedGlobalConstant, DC, SourceLocation(), 3464 DeclarationName(), Ty), 3465 Value(Val) { 3466 // Cleanup the embedded APValue if required (note that our destructor is never 3467 // run) 3468 if (Value.needsCleanup()) 3469 C.addDestruction(&Value); 3470 } 3471 3472 UnnamedGlobalConstantDecl * 3473 UnnamedGlobalConstantDecl::Create(const ASTContext &C, QualType T, 3474 const APValue &Value) { 3475 DeclContext *DC = C.getTranslationUnitDecl(); 3476 return new (C, DC) UnnamedGlobalConstantDecl(C, DC, T, Value); 3477 } 3478 3479 UnnamedGlobalConstantDecl * 3480 UnnamedGlobalConstantDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 3481 return new (C, ID) 3482 UnnamedGlobalConstantDecl(C, nullptr, QualType(), APValue()); 3483 } 3484 3485 void UnnamedGlobalConstantDecl::printName(llvm::raw_ostream &OS, 3486 const PrintingPolicy &) const { 3487 OS << "unnamed-global-constant"; 3488 } 3489 3490 static const char *getAccessName(AccessSpecifier AS) { 3491 switch (AS) { 3492 case AS_none: 3493 llvm_unreachable("Invalid access specifier!"); 3494 case AS_public: 3495 return "public"; 3496 case AS_private: 3497 return "private"; 3498 case AS_protected: 3499 return "protected"; 3500 } 3501 llvm_unreachable("Invalid access specifier!"); 3502 } 3503 3504 const StreamingDiagnostic &clang::operator<<(const StreamingDiagnostic &DB, 3505 AccessSpecifier AS) { 3506 return DB << getAccessName(AS); 3507 } 3508