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