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