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