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