1 //===- DeclCXX.h - Classes for representing C++ declarations --*- C++ -*-=====//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
10 /// Defines the C++ Decl subclasses, other than those for templates
11 /// (found in DeclTemplate.h) and friends (in DeclFriend.h).
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_CLANG_AST_DECLCXX_H
16 #define LLVM_CLANG_AST_DECLCXX_H
18 #include "clang/AST/ASTContext.h"
19 #include "clang/AST/ASTUnresolvedSet.h"
20 #include "clang/AST/Attr.h"
21 #include "clang/AST/Decl.h"
22 #include "clang/AST/DeclBase.h"
23 #include "clang/AST/DeclarationName.h"
24 #include "clang/AST/Expr.h"
25 #include "clang/AST/ExternalASTSource.h"
26 #include "clang/AST/LambdaCapture.h"
27 #include "clang/AST/NestedNameSpecifier.h"
28 #include "clang/AST/Redeclarable.h"
29 #include "clang/AST/Stmt.h"
30 #include "clang/AST/Type.h"
31 #include "clang/AST/TypeLoc.h"
32 #include "clang/AST/UnresolvedSet.h"
33 #include "clang/Basic/LLVM.h"
34 #include "clang/Basic/Lambda.h"
35 #include "clang/Basic/LangOptions.h"
36 #include "clang/Basic/OperatorKinds.h"
37 #include "clang/Basic/SourceLocation.h"
38 #include "clang/Basic/Specifiers.h"
39 #include "llvm/ADT/ArrayRef.h"
40 #include "llvm/ADT/DenseMap.h"
41 #include "llvm/ADT/PointerIntPair.h"
42 #include "llvm/ADT/PointerUnion.h"
43 #include "llvm/ADT/STLExtras.h"
44 #include "llvm/ADT/iterator_range.h"
45 #include "llvm/BinaryFormat/Dwarf.h"
46 #include "llvm/Support/Casting.h"
47 #include "llvm/Support/Compiler.h"
48 #include "llvm/Support/PointerLikeTypeTraits.h"
49 #include "llvm/Support/TrailingObjects.h"
58 class ClassTemplateDecl;
59 class ConstructorUsingShadowDecl;
62 class CXXConstructorDecl;
63 class CXXDestructorDecl;
64 class CXXFinalOverriderMap;
65 class CXXIndirectPrimaryBaseSet;
67 class DecompositionDecl;
68 class DiagnosticBuilder;
70 class FunctionTemplateDecl;
72 class MemberSpecializationInfo;
74 class TemplateParameterList;
77 /// Represents an access specifier followed by colon ':'.
79 /// An objects of this class represents sugar for the syntactic occurrence
80 /// of an access specifier followed by a colon in the list of member
81 /// specifiers of a C++ class definition.
83 /// Note that they do not represent other uses of access specifiers,
84 /// such as those occurring in a list of base specifiers.
85 /// Also note that this class has nothing to do with so-called
86 /// "access declarations" (C++98 11.3 [class.access.dcl]).
87 class AccessSpecDecl : public Decl {
88 /// The location of the ':'.
89 SourceLocation ColonLoc;
91 AccessSpecDecl(AccessSpecifier AS, DeclContext *DC,
92 SourceLocation ASLoc, SourceLocation ColonLoc)
93 : Decl(AccessSpec, DC, ASLoc), ColonLoc(ColonLoc) {
97 AccessSpecDecl(EmptyShell Empty) : Decl(AccessSpec, Empty) {}
99 virtual void anchor();
102 /// The location of the access specifier.
103 SourceLocation getAccessSpecifierLoc() const { return getLocation(); }
105 /// Sets the location of the access specifier.
106 void setAccessSpecifierLoc(SourceLocation ASLoc) { setLocation(ASLoc); }
108 /// The location of the colon following the access specifier.
109 SourceLocation getColonLoc() const { return ColonLoc; }
111 /// Sets the location of the colon.
112 void setColonLoc(SourceLocation CLoc) { ColonLoc = CLoc; }
114 SourceRange getSourceRange() const override LLVM_READONLY {
115 return SourceRange(getAccessSpecifierLoc(), getColonLoc());
118 static AccessSpecDecl *Create(ASTContext &C, AccessSpecifier AS,
119 DeclContext *DC, SourceLocation ASLoc,
120 SourceLocation ColonLoc) {
121 return new (C, DC) AccessSpecDecl(AS, DC, ASLoc, ColonLoc);
124 static AccessSpecDecl *CreateDeserialized(ASTContext &C, unsigned ID);
126 // Implement isa/cast/dyncast/etc.
127 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
128 static bool classofKind(Kind K) { return K == AccessSpec; }
131 /// Represents a base class of a C++ class.
133 /// Each CXXBaseSpecifier represents a single, direct base class (or
134 /// struct) of a C++ class (or struct). It specifies the type of that
135 /// base class, whether it is a virtual or non-virtual base, and what
136 /// level of access (public, protected, private) is used for the
137 /// derivation. For example:
142 /// class C : public virtual A, protected B { };
145 /// In this code, C will have two CXXBaseSpecifiers, one for "public
146 /// virtual A" and the other for "protected B".
147 class CXXBaseSpecifier {
148 /// The source code range that covers the full base
149 /// specifier, including the "virtual" (if present) and access
150 /// specifier (if present).
153 /// The source location of the ellipsis, if this is a pack
155 SourceLocation EllipsisLoc;
157 /// Whether this is a virtual base class or not.
158 unsigned Virtual : 1;
160 /// Whether this is the base of a class (true) or of a struct (false).
162 /// This determines the mapping from the access specifier as written in the
163 /// source code to the access specifier used for semantic analysis.
164 unsigned BaseOfClass : 1;
166 /// Access specifier as written in the source code (may be AS_none).
168 /// The actual type of data stored here is an AccessSpecifier, but we use
169 /// "unsigned" here to work around a VC++ bug.
172 /// Whether the class contains a using declaration
173 /// to inherit the named class's constructors.
174 unsigned InheritConstructors : 1;
176 /// The type of the base class.
178 /// This will be a class or struct (or a typedef of such). The source code
179 /// range does not include the \c virtual or the access specifier.
180 TypeSourceInfo *BaseTypeInfo;
183 CXXBaseSpecifier() = default;
184 CXXBaseSpecifier(SourceRange R, bool V, bool BC, AccessSpecifier A,
185 TypeSourceInfo *TInfo, SourceLocation EllipsisLoc)
186 : Range(R), EllipsisLoc(EllipsisLoc), Virtual(V), BaseOfClass(BC),
187 Access(A), InheritConstructors(false), BaseTypeInfo(TInfo) {}
189 /// Retrieves the source range that contains the entire base specifier.
190 SourceRange getSourceRange() const LLVM_READONLY { return Range; }
191 SourceLocation getBeginLoc() const LLVM_READONLY { return Range.getBegin(); }
192 SourceLocation getEndLoc() const LLVM_READONLY { return Range.getEnd(); }
194 /// Get the location at which the base class type was written.
195 SourceLocation getBaseTypeLoc() const LLVM_READONLY {
196 return BaseTypeInfo->getTypeLoc().getBeginLoc();
199 /// Determines whether the base class is a virtual base class (or not).
200 bool isVirtual() const { return Virtual; }
202 /// Determine whether this base class is a base of a class declared
203 /// with the 'class' keyword (vs. one declared with the 'struct' keyword).
204 bool isBaseOfClass() const { return BaseOfClass; }
206 /// Determine whether this base specifier is a pack expansion.
207 bool isPackExpansion() const { return EllipsisLoc.isValid(); }
209 /// Determine whether this base class's constructors get inherited.
210 bool getInheritConstructors() const { return InheritConstructors; }
212 /// Set that this base class's constructors should be inherited.
213 void setInheritConstructors(bool Inherit = true) {
214 InheritConstructors = Inherit;
217 /// For a pack expansion, determine the location of the ellipsis.
218 SourceLocation getEllipsisLoc() const {
222 /// Returns the access specifier for this base specifier.
224 /// This is the actual base specifier as used for semantic analysis, so
225 /// the result can never be AS_none. To retrieve the access specifier as
226 /// written in the source code, use getAccessSpecifierAsWritten().
227 AccessSpecifier getAccessSpecifier() const {
228 if ((AccessSpecifier)Access == AS_none)
229 return BaseOfClass? AS_private : AS_public;
231 return (AccessSpecifier)Access;
234 /// Retrieves the access specifier as written in the source code
235 /// (which may mean that no access specifier was explicitly written).
237 /// Use getAccessSpecifier() to retrieve the access specifier for use in
238 /// semantic analysis.
239 AccessSpecifier getAccessSpecifierAsWritten() const {
240 return (AccessSpecifier)Access;
243 /// Retrieves the type of the base class.
245 /// This type will always be an unqualified class type.
246 QualType getType() const {
247 return BaseTypeInfo->getType().getUnqualifiedType();
250 /// Retrieves the type and source location of the base class.
251 TypeSourceInfo *getTypeSourceInfo() const { return BaseTypeInfo; }
254 /// Represents a C++ struct/union/class.
255 class CXXRecordDecl : public RecordDecl {
256 friend class ASTDeclReader;
257 friend class ASTDeclWriter;
258 friend class ASTNodeImporter;
259 friend class ASTReader;
260 friend class ASTRecordWriter;
261 friend class ASTWriter;
262 friend class DeclContext;
263 friend class LambdaExpr;
265 friend void FunctionDecl::setPure(bool);
266 friend void TagDecl::startDefinition();
268 /// Values used in DefinitionData fields to represent special members.
269 enum SpecialMemberFlags {
270 SMF_DefaultConstructor = 0x1,
271 SMF_CopyConstructor = 0x2,
272 SMF_MoveConstructor = 0x4,
273 SMF_CopyAssignment = 0x8,
274 SMF_MoveAssignment = 0x10,
275 SMF_Destructor = 0x20,
279 struct DefinitionData {
280 #define FIELD(Name, Width, Merge) \
281 unsigned Name : Width;
282 #include "CXXRecordDeclDefinitionBits.def"
284 /// Whether this class describes a C++ lambda.
285 unsigned IsLambda : 1;
287 /// Whether we are currently parsing base specifiers.
288 unsigned IsParsingBaseSpecifiers : 1;
290 /// True when visible conversion functions are already computed
291 /// and are available.
292 unsigned ComputedVisibleConversions : 1;
294 unsigned HasODRHash : 1;
296 /// A hash of parts of the class to help in ODR checking.
297 unsigned ODRHash = 0;
299 /// The number of base class specifiers in Bases.
300 unsigned NumBases = 0;
302 /// The number of virtual base class specifiers in VBases.
303 unsigned NumVBases = 0;
305 /// Base classes of this class.
307 /// FIXME: This is wasted space for a union.
308 LazyCXXBaseSpecifiersPtr Bases;
310 /// direct and indirect virtual base classes of this class.
311 LazyCXXBaseSpecifiersPtr VBases;
313 /// The conversion functions of this C++ class (but not its
314 /// inherited conversion functions).
316 /// Each of the entries in this overload set is a CXXConversionDecl.
317 LazyASTUnresolvedSet Conversions;
319 /// The conversion functions of this C++ class and all those
320 /// inherited conversion functions that are visible in this class.
322 /// Each of the entries in this overload set is a CXXConversionDecl or a
323 /// FunctionTemplateDecl.
324 LazyASTUnresolvedSet VisibleConversions;
326 /// The declaration which defines this record.
327 CXXRecordDecl *Definition;
329 /// The first friend declaration in this class, or null if there
332 /// This is actually currently stored in reverse order.
333 LazyDeclPtr FirstFriend;
335 DefinitionData(CXXRecordDecl *D);
337 /// Retrieve the set of direct base classes.
338 CXXBaseSpecifier *getBases() const {
339 if (!Bases.isOffset())
340 return Bases.get(nullptr);
341 return getBasesSlowCase();
344 /// Retrieve the set of virtual base classes.
345 CXXBaseSpecifier *getVBases() const {
346 if (!VBases.isOffset())
347 return VBases.get(nullptr);
348 return getVBasesSlowCase();
351 ArrayRef<CXXBaseSpecifier> bases() const {
352 return llvm::makeArrayRef(getBases(), NumBases);
355 ArrayRef<CXXBaseSpecifier> vbases() const {
356 return llvm::makeArrayRef(getVBases(), NumVBases);
360 CXXBaseSpecifier *getBasesSlowCase() const;
361 CXXBaseSpecifier *getVBasesSlowCase() const;
364 struct DefinitionData *DefinitionData;
366 /// Describes a C++ closure type (generated by a lambda expression).
367 struct LambdaDefinitionData : public DefinitionData {
368 using Capture = LambdaCapture;
370 /// Whether this lambda is known to be dependent, even if its
371 /// context isn't dependent.
373 /// A lambda with a non-dependent context can be dependent if it occurs
374 /// within the default argument of a function template, because the
375 /// lambda will have been created with the enclosing context as its
376 /// declaration context, rather than function. This is an unfortunate
377 /// artifact of having to parse the default arguments before.
378 unsigned Dependent : 1;
380 /// Whether this lambda is a generic lambda.
381 unsigned IsGenericLambda : 1;
383 /// The Default Capture.
384 unsigned CaptureDefault : 2;
386 /// The number of captures in this lambda is limited 2^NumCaptures.
387 unsigned NumCaptures : 15;
389 /// The number of explicit captures in this lambda.
390 unsigned NumExplicitCaptures : 13;
392 /// Has known `internal` linkage.
393 unsigned HasKnownInternalLinkage : 1;
395 /// The number used to indicate this lambda expression for name
396 /// mangling in the Itanium C++ ABI.
397 unsigned ManglingNumber : 31;
399 /// The declaration that provides context for this lambda, if the
400 /// actual DeclContext does not suffice. This is used for lambdas that
401 /// occur within default arguments of function parameters within the class
402 /// or within a data member initializer.
403 LazyDeclPtr ContextDecl;
405 /// The list of captures, both explicit and implicit, for this
407 Capture *Captures = nullptr;
409 /// The type of the call method.
410 TypeSourceInfo *MethodTyInfo;
412 LambdaDefinitionData(CXXRecordDecl *D, TypeSourceInfo *Info, bool Dependent,
413 bool IsGeneric, LambdaCaptureDefault CaptureDefault)
414 : DefinitionData(D), Dependent(Dependent), IsGenericLambda(IsGeneric),
415 CaptureDefault(CaptureDefault), NumCaptures(0),
416 NumExplicitCaptures(0), HasKnownInternalLinkage(0), ManglingNumber(0),
420 // C++1z [expr.prim.lambda]p4:
421 // This class type is not an aggregate type.
423 PlainOldData = false;
427 struct DefinitionData *dataPtr() const {
428 // Complete the redecl chain (if necessary).
430 return DefinitionData;
433 struct DefinitionData &data() const {
434 auto *DD = dataPtr();
435 assert(DD && "queried property of class with no definition");
439 struct LambdaDefinitionData &getLambdaData() const {
440 // No update required: a merged definition cannot change any lambda
442 auto *DD = DefinitionData;
443 assert(DD && DD->IsLambda && "queried lambda property of non-lambda class");
444 return static_cast<LambdaDefinitionData&>(*DD);
447 /// The template or declaration that this declaration
448 /// describes or was instantiated from, respectively.
450 /// For non-templates, this value will be null. For record
451 /// declarations that describe a class template, this will be a
452 /// pointer to a ClassTemplateDecl. For member
453 /// classes of class template specializations, this will be the
454 /// MemberSpecializationInfo referring to the member class that was
455 /// instantiated or specialized.
456 llvm::PointerUnion<ClassTemplateDecl *, MemberSpecializationInfo *>
457 TemplateOrInstantiation;
459 /// Called from setBases and addedMember to notify the class that a
460 /// direct or virtual base class or a member of class type has been added.
461 void addedClassSubobject(CXXRecordDecl *Base);
463 /// Notify the class that member has been added.
465 /// This routine helps maintain information about the class based on which
466 /// members have been added. It will be invoked by DeclContext::addDecl()
467 /// whenever a member is added to this record.
468 void addedMember(Decl *D);
470 void markedVirtualFunctionPure();
472 /// Get the head of our list of friend declarations, possibly
473 /// deserializing the friends from an external AST source.
474 FriendDecl *getFirstFriend() const;
476 /// Determine whether this class has an empty base class subobject of type X
477 /// or of one of the types that might be at offset 0 within X (per the C++
478 /// "standard layout" rules).
479 bool hasSubobjectAtOffsetZeroOfEmptyBaseType(ASTContext &Ctx,
480 const CXXRecordDecl *X);
483 CXXRecordDecl(Kind K, TagKind TK, const ASTContext &C, DeclContext *DC,
484 SourceLocation StartLoc, SourceLocation IdLoc,
485 IdentifierInfo *Id, CXXRecordDecl *PrevDecl);
488 /// Iterator that traverses the base classes of a class.
489 using base_class_iterator = CXXBaseSpecifier *;
491 /// Iterator that traverses the base classes of a class.
492 using base_class_const_iterator = const CXXBaseSpecifier *;
494 CXXRecordDecl *getCanonicalDecl() override {
495 return cast<CXXRecordDecl>(RecordDecl::getCanonicalDecl());
498 const CXXRecordDecl *getCanonicalDecl() const {
499 return const_cast<CXXRecordDecl*>(this)->getCanonicalDecl();
502 CXXRecordDecl *getPreviousDecl() {
503 return cast_or_null<CXXRecordDecl>(
504 static_cast<RecordDecl *>(this)->getPreviousDecl());
507 const CXXRecordDecl *getPreviousDecl() const {
508 return const_cast<CXXRecordDecl*>(this)->getPreviousDecl();
511 CXXRecordDecl *getMostRecentDecl() {
512 return cast<CXXRecordDecl>(
513 static_cast<RecordDecl *>(this)->getMostRecentDecl());
516 const CXXRecordDecl *getMostRecentDecl() const {
517 return const_cast<CXXRecordDecl*>(this)->getMostRecentDecl();
520 CXXRecordDecl *getMostRecentNonInjectedDecl() {
521 CXXRecordDecl *Recent =
522 static_cast<CXXRecordDecl *>(this)->getMostRecentDecl();
523 while (Recent->isInjectedClassName()) {
524 // FIXME: Does injected class name need to be in the redeclarations chain?
525 assert(Recent->getPreviousDecl());
526 Recent = Recent->getPreviousDecl();
531 const CXXRecordDecl *getMostRecentNonInjectedDecl() const {
532 return const_cast<CXXRecordDecl*>(this)->getMostRecentNonInjectedDecl();
535 CXXRecordDecl *getDefinition() const {
536 // We only need an update if we don't already know which
537 // declaration is the definition.
538 auto *DD = DefinitionData ? DefinitionData : dataPtr();
539 return DD ? DD->Definition : nullptr;
542 bool hasDefinition() const { return DefinitionData || dataPtr(); }
544 static CXXRecordDecl *Create(const ASTContext &C, TagKind TK, DeclContext *DC,
545 SourceLocation StartLoc, SourceLocation IdLoc,
547 CXXRecordDecl *PrevDecl = nullptr,
548 bool DelayTypeCreation = false);
549 static CXXRecordDecl *CreateLambda(const ASTContext &C, DeclContext *DC,
550 TypeSourceInfo *Info, SourceLocation Loc,
551 bool DependentLambda, bool IsGeneric,
552 LambdaCaptureDefault CaptureDefault);
553 static CXXRecordDecl *CreateDeserialized(const ASTContext &C, unsigned ID);
555 bool isDynamicClass() const {
556 return data().Polymorphic || data().NumVBases != 0;
559 /// @returns true if class is dynamic or might be dynamic because the
560 /// definition is incomplete of dependent.
561 bool mayBeDynamicClass() const {
562 return !hasDefinition() || isDynamicClass() || hasAnyDependentBases();
565 /// @returns true if class is non dynamic or might be non dynamic because the
566 /// definition is incomplete of dependent.
567 bool mayBeNonDynamicClass() const {
568 return !hasDefinition() || !isDynamicClass() || hasAnyDependentBases();
571 void setIsParsingBaseSpecifiers() { data().IsParsingBaseSpecifiers = true; }
573 bool isParsingBaseSpecifiers() const {
574 return data().IsParsingBaseSpecifiers;
577 unsigned getODRHash() const;
579 /// Sets the base classes of this struct or class.
580 void setBases(CXXBaseSpecifier const * const *Bases, unsigned NumBases);
582 /// Retrieves the number of base classes of this class.
583 unsigned getNumBases() const { return data().NumBases; }
585 using base_class_range = llvm::iterator_range<base_class_iterator>;
586 using base_class_const_range =
587 llvm::iterator_range<base_class_const_iterator>;
589 base_class_range bases() {
590 return base_class_range(bases_begin(), bases_end());
592 base_class_const_range bases() const {
593 return base_class_const_range(bases_begin(), bases_end());
596 base_class_iterator bases_begin() { return data().getBases(); }
597 base_class_const_iterator bases_begin() const { return data().getBases(); }
598 base_class_iterator bases_end() { return bases_begin() + data().NumBases; }
599 base_class_const_iterator bases_end() const {
600 return bases_begin() + data().NumBases;
603 /// Retrieves the number of virtual base classes of this class.
604 unsigned getNumVBases() const { return data().NumVBases; }
606 base_class_range vbases() {
607 return base_class_range(vbases_begin(), vbases_end());
609 base_class_const_range vbases() const {
610 return base_class_const_range(vbases_begin(), vbases_end());
613 base_class_iterator vbases_begin() { return data().getVBases(); }
614 base_class_const_iterator vbases_begin() const { return data().getVBases(); }
615 base_class_iterator vbases_end() { return vbases_begin() + data().NumVBases; }
616 base_class_const_iterator vbases_end() const {
617 return vbases_begin() + data().NumVBases;
620 /// Determine whether this class has any dependent base classes which
621 /// are not the current instantiation.
622 bool hasAnyDependentBases() const;
624 /// Iterator access to method members. The method iterator visits
625 /// all method members of the class, including non-instance methods,
626 /// special methods, etc.
627 using method_iterator = specific_decl_iterator<CXXMethodDecl>;
629 llvm::iterator_range<specific_decl_iterator<CXXMethodDecl>>;
631 method_range methods() const {
632 return method_range(method_begin(), method_end());
635 /// Method begin iterator. Iterates in the order the methods
637 method_iterator method_begin() const {
638 return method_iterator(decls_begin());
641 /// Method past-the-end iterator.
642 method_iterator method_end() const {
643 return method_iterator(decls_end());
646 /// Iterator access to constructor members.
647 using ctor_iterator = specific_decl_iterator<CXXConstructorDecl>;
649 llvm::iterator_range<specific_decl_iterator<CXXConstructorDecl>>;
651 ctor_range ctors() const { return ctor_range(ctor_begin(), ctor_end()); }
653 ctor_iterator ctor_begin() const {
654 return ctor_iterator(decls_begin());
657 ctor_iterator ctor_end() const {
658 return ctor_iterator(decls_end());
661 /// An iterator over friend declarations. All of these are defined
663 class friend_iterator;
664 using friend_range = llvm::iterator_range<friend_iterator>;
666 friend_range friends() const;
667 friend_iterator friend_begin() const;
668 friend_iterator friend_end() const;
669 void pushFriendDecl(FriendDecl *FD);
671 /// Determines whether this record has any friends.
672 bool hasFriends() const {
673 return data().FirstFriend.isValid();
676 /// \c true if a defaulted copy constructor for this class would be
678 bool defaultedCopyConstructorIsDeleted() const {
679 assert((!needsOverloadResolutionForCopyConstructor() ||
680 (data().DeclaredSpecialMembers & SMF_CopyConstructor)) &&
681 "this property has not yet been computed by Sema");
682 return data().DefaultedCopyConstructorIsDeleted;
685 /// \c true if a defaulted move constructor for this class would be
687 bool defaultedMoveConstructorIsDeleted() const {
688 assert((!needsOverloadResolutionForMoveConstructor() ||
689 (data().DeclaredSpecialMembers & SMF_MoveConstructor)) &&
690 "this property has not yet been computed by Sema");
691 return data().DefaultedMoveConstructorIsDeleted;
694 /// \c true if a defaulted destructor for this class would be deleted.
695 bool defaultedDestructorIsDeleted() const {
696 assert((!needsOverloadResolutionForDestructor() ||
697 (data().DeclaredSpecialMembers & SMF_Destructor)) &&
698 "this property has not yet been computed by Sema");
699 return data().DefaultedDestructorIsDeleted;
702 /// \c true if we know for sure that this class has a single,
703 /// accessible, unambiguous copy constructor that is not deleted.
704 bool hasSimpleCopyConstructor() const {
705 return !hasUserDeclaredCopyConstructor() &&
706 !data().DefaultedCopyConstructorIsDeleted;
709 /// \c true if we know for sure that this class has a single,
710 /// accessible, unambiguous move constructor that is not deleted.
711 bool hasSimpleMoveConstructor() const {
712 return !hasUserDeclaredMoveConstructor() && hasMoveConstructor() &&
713 !data().DefaultedMoveConstructorIsDeleted;
716 /// \c true if we know for sure that this class has a single,
717 /// accessible, unambiguous move assignment operator that is not deleted.
718 bool hasSimpleMoveAssignment() const {
719 return !hasUserDeclaredMoveAssignment() && hasMoveAssignment() &&
720 !data().DefaultedMoveAssignmentIsDeleted;
723 /// \c true if we know for sure that this class has an accessible
724 /// destructor that is not deleted.
725 bool hasSimpleDestructor() const {
726 return !hasUserDeclaredDestructor() &&
727 !data().DefaultedDestructorIsDeleted;
730 /// Determine whether this class has any default constructors.
731 bool hasDefaultConstructor() const {
732 return (data().DeclaredSpecialMembers & SMF_DefaultConstructor) ||
733 needsImplicitDefaultConstructor();
736 /// Determine if we need to declare a default constructor for
739 /// This value is used for lazy creation of default constructors.
740 bool needsImplicitDefaultConstructor() const {
741 return !data().UserDeclaredConstructor &&
742 !(data().DeclaredSpecialMembers & SMF_DefaultConstructor) &&
743 (!isLambda() || lambdaIsDefaultConstructibleAndAssignable());
746 /// Determine whether this class has any user-declared constructors.
748 /// When true, a default constructor will not be implicitly declared.
749 bool hasUserDeclaredConstructor() const {
750 return data().UserDeclaredConstructor;
753 /// Whether this class has a user-provided default constructor
755 bool hasUserProvidedDefaultConstructor() const {
756 return data().UserProvidedDefaultConstructor;
759 /// Determine whether this class has a user-declared copy constructor.
761 /// When false, a copy constructor will be implicitly declared.
762 bool hasUserDeclaredCopyConstructor() const {
763 return data().UserDeclaredSpecialMembers & SMF_CopyConstructor;
766 /// Determine whether this class needs an implicit copy
767 /// constructor to be lazily declared.
768 bool needsImplicitCopyConstructor() const {
769 return !(data().DeclaredSpecialMembers & SMF_CopyConstructor);
772 /// Determine whether we need to eagerly declare a defaulted copy
773 /// constructor for this class.
774 bool needsOverloadResolutionForCopyConstructor() const {
775 // C++17 [class.copy.ctor]p6:
776 // If the class definition declares a move constructor or move assignment
777 // operator, the implicitly declared copy constructor is defined as
779 // In MSVC mode, sometimes a declared move assignment does not delete an
780 // implicit copy constructor, so defer this choice to Sema.
781 if (data().UserDeclaredSpecialMembers &
782 (SMF_MoveConstructor | SMF_MoveAssignment))
784 return data().NeedOverloadResolutionForCopyConstructor;
787 /// Determine whether an implicit copy constructor for this type
788 /// would have a parameter with a const-qualified reference type.
789 bool implicitCopyConstructorHasConstParam() const {
790 return data().ImplicitCopyConstructorCanHaveConstParamForNonVBase &&
792 data().ImplicitCopyConstructorCanHaveConstParamForVBase);
795 /// Determine whether this class has a copy constructor with
796 /// a parameter type which is a reference to a const-qualified type.
797 bool hasCopyConstructorWithConstParam() const {
798 return data().HasDeclaredCopyConstructorWithConstParam ||
799 (needsImplicitCopyConstructor() &&
800 implicitCopyConstructorHasConstParam());
803 /// Whether this class has a user-declared move constructor or
804 /// assignment operator.
806 /// When false, a move constructor and assignment operator may be
807 /// implicitly declared.
808 bool hasUserDeclaredMoveOperation() const {
809 return data().UserDeclaredSpecialMembers &
810 (SMF_MoveConstructor | SMF_MoveAssignment);
813 /// Determine whether this class has had a move constructor
814 /// declared by the user.
815 bool hasUserDeclaredMoveConstructor() const {
816 return data().UserDeclaredSpecialMembers & SMF_MoveConstructor;
819 /// Determine whether this class has a move constructor.
820 bool hasMoveConstructor() const {
821 return (data().DeclaredSpecialMembers & SMF_MoveConstructor) ||
822 needsImplicitMoveConstructor();
825 /// Set that we attempted to declare an implicit copy
826 /// constructor, but overload resolution failed so we deleted it.
827 void setImplicitCopyConstructorIsDeleted() {
828 assert((data().DefaultedCopyConstructorIsDeleted ||
829 needsOverloadResolutionForCopyConstructor()) &&
830 "Copy constructor should not be deleted");
831 data().DefaultedCopyConstructorIsDeleted = true;
834 /// Set that we attempted to declare an implicit move
835 /// constructor, but overload resolution failed so we deleted it.
836 void setImplicitMoveConstructorIsDeleted() {
837 assert((data().DefaultedMoveConstructorIsDeleted ||
838 needsOverloadResolutionForMoveConstructor()) &&
839 "move constructor should not be deleted");
840 data().DefaultedMoveConstructorIsDeleted = true;
843 /// Set that we attempted to declare an implicit destructor,
844 /// but overload resolution failed so we deleted it.
845 void setImplicitDestructorIsDeleted() {
846 assert((data().DefaultedDestructorIsDeleted ||
847 needsOverloadResolutionForDestructor()) &&
848 "destructor should not be deleted");
849 data().DefaultedDestructorIsDeleted = true;
852 /// Determine whether this class should get an implicit move
853 /// constructor or if any existing special member function inhibits this.
854 bool needsImplicitMoveConstructor() const {
855 return !(data().DeclaredSpecialMembers & SMF_MoveConstructor) &&
856 !hasUserDeclaredCopyConstructor() &&
857 !hasUserDeclaredCopyAssignment() &&
858 !hasUserDeclaredMoveAssignment() &&
859 !hasUserDeclaredDestructor();
862 /// Determine whether we need to eagerly declare a defaulted move
863 /// constructor for this class.
864 bool needsOverloadResolutionForMoveConstructor() const {
865 return data().NeedOverloadResolutionForMoveConstructor;
868 /// Determine whether this class has a user-declared copy assignment
871 /// When false, a copy assignment operator will be implicitly declared.
872 bool hasUserDeclaredCopyAssignment() const {
873 return data().UserDeclaredSpecialMembers & SMF_CopyAssignment;
876 /// Determine whether this class needs an implicit copy
877 /// assignment operator to be lazily declared.
878 bool needsImplicitCopyAssignment() const {
879 return !(data().DeclaredSpecialMembers & SMF_CopyAssignment);
882 /// Determine whether we need to eagerly declare a defaulted copy
883 /// assignment operator for this class.
884 bool needsOverloadResolutionForCopyAssignment() const {
885 return data().HasMutableFields;
888 /// Determine whether an implicit copy assignment operator for this
889 /// type would have a parameter with a const-qualified reference type.
890 bool implicitCopyAssignmentHasConstParam() const {
891 return data().ImplicitCopyAssignmentHasConstParam;
894 /// Determine whether this class has a copy assignment operator with
895 /// a parameter type which is a reference to a const-qualified type or is not
897 bool hasCopyAssignmentWithConstParam() const {
898 return data().HasDeclaredCopyAssignmentWithConstParam ||
899 (needsImplicitCopyAssignment() &&
900 implicitCopyAssignmentHasConstParam());
903 /// Determine whether this class has had a move assignment
904 /// declared by the user.
905 bool hasUserDeclaredMoveAssignment() const {
906 return data().UserDeclaredSpecialMembers & SMF_MoveAssignment;
909 /// Determine whether this class has a move assignment operator.
910 bool hasMoveAssignment() const {
911 return (data().DeclaredSpecialMembers & SMF_MoveAssignment) ||
912 needsImplicitMoveAssignment();
915 /// Set that we attempted to declare an implicit move assignment
916 /// operator, but overload resolution failed so we deleted it.
917 void setImplicitMoveAssignmentIsDeleted() {
918 assert((data().DefaultedMoveAssignmentIsDeleted ||
919 needsOverloadResolutionForMoveAssignment()) &&
920 "move assignment should not be deleted");
921 data().DefaultedMoveAssignmentIsDeleted = true;
924 /// Determine whether this class should get an implicit move
925 /// assignment operator or if any existing special member function inhibits
927 bool needsImplicitMoveAssignment() const {
928 return !(data().DeclaredSpecialMembers & SMF_MoveAssignment) &&
929 !hasUserDeclaredCopyConstructor() &&
930 !hasUserDeclaredCopyAssignment() &&
931 !hasUserDeclaredMoveConstructor() &&
932 !hasUserDeclaredDestructor() &&
933 (!isLambda() || lambdaIsDefaultConstructibleAndAssignable());
936 /// Determine whether we need to eagerly declare a move assignment
937 /// operator for this class.
938 bool needsOverloadResolutionForMoveAssignment() const {
939 return data().NeedOverloadResolutionForMoveAssignment;
942 /// Determine whether this class has a user-declared destructor.
944 /// When false, a destructor will be implicitly declared.
945 bool hasUserDeclaredDestructor() const {
946 return data().UserDeclaredSpecialMembers & SMF_Destructor;
949 /// Determine whether this class needs an implicit destructor to
950 /// be lazily declared.
951 bool needsImplicitDestructor() const {
952 return !(data().DeclaredSpecialMembers & SMF_Destructor);
955 /// Determine whether we need to eagerly declare a destructor for this
957 bool needsOverloadResolutionForDestructor() const {
958 return data().NeedOverloadResolutionForDestructor;
961 /// Determine whether this class describes a lambda function object.
962 bool isLambda() const {
963 // An update record can't turn a non-lambda into a lambda.
964 auto *DD = DefinitionData;
965 return DD && DD->IsLambda;
968 /// Determine whether this class describes a generic
969 /// lambda function object (i.e. function call operator is
971 bool isGenericLambda() const;
973 /// Determine whether this lambda should have an implicit default constructor
974 /// and copy and move assignment operators.
975 bool lambdaIsDefaultConstructibleAndAssignable() const;
977 /// Retrieve the lambda call operator of the closure type
978 /// if this is a closure type.
979 CXXMethodDecl *getLambdaCallOperator() const;
981 /// Retrieve the dependent lambda call operator of the closure type
982 /// if this is a templated closure type.
983 FunctionTemplateDecl *getDependentLambdaCallOperator() const;
985 /// Retrieve the lambda static invoker, the address of which
986 /// is returned by the conversion operator, and the body of which
987 /// is forwarded to the lambda call operator.
988 CXXMethodDecl *getLambdaStaticInvoker() const;
990 /// Retrieve the generic lambda's template parameter list.
991 /// Returns null if the class does not represent a lambda or a generic
993 TemplateParameterList *getGenericLambdaTemplateParameterList() const;
995 /// Retrieve the lambda template parameters that were specified explicitly.
996 ArrayRef<NamedDecl *> getLambdaExplicitTemplateParameters() const;
998 LambdaCaptureDefault getLambdaCaptureDefault() const {
1000 return static_cast<LambdaCaptureDefault>(getLambdaData().CaptureDefault);
1003 /// For a closure type, retrieve the mapping from captured
1004 /// variables and \c this to the non-static data members that store the
1005 /// values or references of the captures.
1007 /// \param Captures Will be populated with the mapping from captured
1008 /// variables to the corresponding fields.
1010 /// \param ThisCapture Will be set to the field declaration for the
1011 /// \c this capture.
1013 /// \note No entries will be added for init-captures, as they do not capture
1015 void getCaptureFields(llvm::DenseMap<const VarDecl *, FieldDecl *> &Captures,
1016 FieldDecl *&ThisCapture) const;
1018 using capture_const_iterator = const LambdaCapture *;
1019 using capture_const_range = llvm::iterator_range<capture_const_iterator>;
1021 capture_const_range captures() const {
1022 return capture_const_range(captures_begin(), captures_end());
1025 capture_const_iterator captures_begin() const {
1026 return isLambda() ? getLambdaData().Captures : nullptr;
1029 capture_const_iterator captures_end() const {
1030 return isLambda() ? captures_begin() + getLambdaData().NumCaptures
1034 using conversion_iterator = UnresolvedSetIterator;
1036 conversion_iterator conversion_begin() const {
1037 return data().Conversions.get(getASTContext()).begin();
1040 conversion_iterator conversion_end() const {
1041 return data().Conversions.get(getASTContext()).end();
1044 /// Removes a conversion function from this class. The conversion
1045 /// function must currently be a member of this class. Furthermore,
1046 /// this class must currently be in the process of being defined.
1047 void removeConversion(const NamedDecl *Old);
1049 /// Get all conversion functions visible in current class,
1050 /// including conversion function templates.
1051 llvm::iterator_range<conversion_iterator> getVisibleConversionFunctions();
1053 /// Determine whether this class is an aggregate (C++ [dcl.init.aggr]),
1054 /// which is a class with no user-declared constructors, no private
1055 /// or protected non-static data members, no base classes, and no virtual
1056 /// functions (C++ [dcl.init.aggr]p1).
1057 bool isAggregate() const { return data().Aggregate; }
1059 /// Whether this class has any in-class initializers
1060 /// for non-static data members (including those in anonymous unions or
1062 bool hasInClassInitializer() const { return data().HasInClassInitializer; }
1064 /// Whether this class or any of its subobjects has any members of
1065 /// reference type which would make value-initialization ill-formed.
1067 /// Per C++03 [dcl.init]p5:
1068 /// - if T is a non-union class type without a user-declared constructor,
1069 /// then every non-static data member and base-class component of T is
1070 /// value-initialized [...] A program that calls for [...]
1071 /// value-initialization of an entity of reference type is ill-formed.
1072 bool hasUninitializedReferenceMember() const {
1073 return !isUnion() && !hasUserDeclaredConstructor() &&
1074 data().HasUninitializedReferenceMember;
1077 /// Whether this class is a POD-type (C++ [class]p4)
1079 /// For purposes of this function a class is POD if it is an aggregate
1080 /// that has no non-static non-POD data members, no reference data
1081 /// members, no user-defined copy assignment operator and no
1082 /// user-defined destructor.
1084 /// Note that this is the C++ TR1 definition of POD.
1085 bool isPOD() const { return data().PlainOldData; }
1087 /// True if this class is C-like, without C++-specific features, e.g.
1088 /// it contains only public fields, no bases, tag kind is not 'class', etc.
1089 bool isCLike() const;
1091 /// Determine whether this is an empty class in the sense of
1092 /// (C++11 [meta.unary.prop]).
1094 /// The CXXRecordDecl is a class type, but not a union type,
1095 /// with no non-static data members other than bit-fields of length 0,
1096 /// no virtual member functions, no virtual base classes,
1097 /// and no base class B for which is_empty<B>::value is false.
1099 /// \note This does NOT include a check for union-ness.
1100 bool isEmpty() const { return data().Empty; }
1102 bool hasPrivateFields() const {
1103 return data().HasPrivateFields;
1106 bool hasProtectedFields() const {
1107 return data().HasProtectedFields;
1110 /// Determine whether this class has direct non-static data members.
1111 bool hasDirectFields() const {
1113 return D.HasPublicFields || D.HasProtectedFields || D.HasPrivateFields;
1116 /// Whether this class is polymorphic (C++ [class.virtual]),
1117 /// which means that the class contains or inherits a virtual function.
1118 bool isPolymorphic() const { return data().Polymorphic; }
1120 /// Determine whether this class has a pure virtual function.
1122 /// The class is is abstract per (C++ [class.abstract]p2) if it declares
1123 /// a pure virtual function or inherits a pure virtual function that is
1125 bool isAbstract() const { return data().Abstract; }
1127 /// Determine whether this class is standard-layout per
1129 bool isStandardLayout() const { return data().IsStandardLayout; }
1131 /// Determine whether this class was standard-layout per
1132 /// C++11 [class]p7, specifically using the C++11 rules without any DRs.
1133 bool isCXX11StandardLayout() const { return data().IsCXX11StandardLayout; }
1135 /// Determine whether this class, or any of its class subobjects,
1136 /// contains a mutable field.
1137 bool hasMutableFields() const { return data().HasMutableFields; }
1139 /// Determine whether this class has any variant members.
1140 bool hasVariantMembers() const { return data().HasVariantMembers; }
1142 /// Determine whether this class has a trivial default constructor
1143 /// (C++11 [class.ctor]p5).
1144 bool hasTrivialDefaultConstructor() const {
1145 return hasDefaultConstructor() &&
1146 (data().HasTrivialSpecialMembers & SMF_DefaultConstructor);
1149 /// Determine whether this class has a non-trivial default constructor
1150 /// (C++11 [class.ctor]p5).
1151 bool hasNonTrivialDefaultConstructor() const {
1152 return (data().DeclaredNonTrivialSpecialMembers & SMF_DefaultConstructor) ||
1153 (needsImplicitDefaultConstructor() &&
1154 !(data().HasTrivialSpecialMembers & SMF_DefaultConstructor));
1157 /// Determine whether this class has at least one constexpr constructor
1158 /// other than the copy or move constructors.
1159 bool hasConstexprNonCopyMoveConstructor() const {
1160 return data().HasConstexprNonCopyMoveConstructor ||
1161 (needsImplicitDefaultConstructor() &&
1162 defaultedDefaultConstructorIsConstexpr());
1165 /// Determine whether a defaulted default constructor for this class
1166 /// would be constexpr.
1167 bool defaultedDefaultConstructorIsConstexpr() const {
1168 return data().DefaultedDefaultConstructorIsConstexpr &&
1169 (!isUnion() || hasInClassInitializer() || !hasVariantMembers() ||
1170 getASTContext().getLangOpts().CPlusPlus2a);
1173 /// Determine whether this class has a constexpr default constructor.
1174 bool hasConstexprDefaultConstructor() const {
1175 return data().HasConstexprDefaultConstructor ||
1176 (needsImplicitDefaultConstructor() &&
1177 defaultedDefaultConstructorIsConstexpr());
1180 /// Determine whether this class has a trivial copy constructor
1181 /// (C++ [class.copy]p6, C++11 [class.copy]p12)
1182 bool hasTrivialCopyConstructor() const {
1183 return data().HasTrivialSpecialMembers & SMF_CopyConstructor;
1186 bool hasTrivialCopyConstructorForCall() const {
1187 return data().HasTrivialSpecialMembersForCall & SMF_CopyConstructor;
1190 /// Determine whether this class has a non-trivial copy constructor
1191 /// (C++ [class.copy]p6, C++11 [class.copy]p12)
1192 bool hasNonTrivialCopyConstructor() const {
1193 return data().DeclaredNonTrivialSpecialMembers & SMF_CopyConstructor ||
1194 !hasTrivialCopyConstructor();
1197 bool hasNonTrivialCopyConstructorForCall() const {
1198 return (data().DeclaredNonTrivialSpecialMembersForCall &
1199 SMF_CopyConstructor) ||
1200 !hasTrivialCopyConstructorForCall();
1203 /// Determine whether this class has a trivial move constructor
1204 /// (C++11 [class.copy]p12)
1205 bool hasTrivialMoveConstructor() const {
1206 return hasMoveConstructor() &&
1207 (data().HasTrivialSpecialMembers & SMF_MoveConstructor);
1210 bool hasTrivialMoveConstructorForCall() const {
1211 return hasMoveConstructor() &&
1212 (data().HasTrivialSpecialMembersForCall & SMF_MoveConstructor);
1215 /// Determine whether this class has a non-trivial move constructor
1216 /// (C++11 [class.copy]p12)
1217 bool hasNonTrivialMoveConstructor() const {
1218 return (data().DeclaredNonTrivialSpecialMembers & SMF_MoveConstructor) ||
1219 (needsImplicitMoveConstructor() &&
1220 !(data().HasTrivialSpecialMembers & SMF_MoveConstructor));
1223 bool hasNonTrivialMoveConstructorForCall() const {
1224 return (data().DeclaredNonTrivialSpecialMembersForCall &
1225 SMF_MoveConstructor) ||
1226 (needsImplicitMoveConstructor() &&
1227 !(data().HasTrivialSpecialMembersForCall & SMF_MoveConstructor));
1230 /// Determine whether this class has a trivial copy assignment operator
1231 /// (C++ [class.copy]p11, C++11 [class.copy]p25)
1232 bool hasTrivialCopyAssignment() const {
1233 return data().HasTrivialSpecialMembers & SMF_CopyAssignment;
1236 /// Determine whether this class has a non-trivial copy assignment
1237 /// operator (C++ [class.copy]p11, C++11 [class.copy]p25)
1238 bool hasNonTrivialCopyAssignment() const {
1239 return data().DeclaredNonTrivialSpecialMembers & SMF_CopyAssignment ||
1240 !hasTrivialCopyAssignment();
1243 /// Determine whether this class has a trivial move assignment operator
1244 /// (C++11 [class.copy]p25)
1245 bool hasTrivialMoveAssignment() const {
1246 return hasMoveAssignment() &&
1247 (data().HasTrivialSpecialMembers & SMF_MoveAssignment);
1250 /// Determine whether this class has a non-trivial move assignment
1251 /// operator (C++11 [class.copy]p25)
1252 bool hasNonTrivialMoveAssignment() const {
1253 return (data().DeclaredNonTrivialSpecialMembers & SMF_MoveAssignment) ||
1254 (needsImplicitMoveAssignment() &&
1255 !(data().HasTrivialSpecialMembers & SMF_MoveAssignment));
1258 /// Determine whether a defaulted default constructor for this class
1259 /// would be constexpr.
1260 bool defaultedDestructorIsConstexpr() const {
1261 return data().DefaultedDestructorIsConstexpr &&
1262 getASTContext().getLangOpts().CPlusPlus2a;
1265 /// Determine whether this class has a constexpr destructor.
1266 bool hasConstexprDestructor() const;
1268 /// Determine whether this class has a trivial destructor
1269 /// (C++ [class.dtor]p3)
1270 bool hasTrivialDestructor() const {
1271 return data().HasTrivialSpecialMembers & SMF_Destructor;
1274 bool hasTrivialDestructorForCall() const {
1275 return data().HasTrivialSpecialMembersForCall & SMF_Destructor;
1278 /// Determine whether this class has a non-trivial destructor
1279 /// (C++ [class.dtor]p3)
1280 bool hasNonTrivialDestructor() const {
1281 return !(data().HasTrivialSpecialMembers & SMF_Destructor);
1284 bool hasNonTrivialDestructorForCall() const {
1285 return !(data().HasTrivialSpecialMembersForCall & SMF_Destructor);
1288 void setHasTrivialSpecialMemberForCall() {
1289 data().HasTrivialSpecialMembersForCall =
1290 (SMF_CopyConstructor | SMF_MoveConstructor | SMF_Destructor);
1293 /// Determine whether declaring a const variable with this type is ok
1294 /// per core issue 253.
1295 bool allowConstDefaultInit() const {
1296 return !data().HasUninitializedFields ||
1297 !(data().HasDefaultedDefaultConstructor ||
1298 needsImplicitDefaultConstructor());
1301 /// Determine whether this class has a destructor which has no
1302 /// semantic effect.
1304 /// Any such destructor will be trivial, public, defaulted and not deleted,
1305 /// and will call only irrelevant destructors.
1306 bool hasIrrelevantDestructor() const {
1307 return data().HasIrrelevantDestructor;
1310 /// Determine whether this class has a non-literal or/ volatile type
1311 /// non-static data member or base class.
1312 bool hasNonLiteralTypeFieldsOrBases() const {
1313 return data().HasNonLiteralTypeFieldsOrBases;
1316 /// Determine whether this class has a using-declaration that names
1317 /// a user-declared base class constructor.
1318 bool hasInheritedConstructor() const {
1319 return data().HasInheritedConstructor;
1322 /// Determine whether this class has a using-declaration that names
1323 /// a base class assignment operator.
1324 bool hasInheritedAssignment() const {
1325 return data().HasInheritedAssignment;
1328 /// Determine whether this class is considered trivially copyable per
1329 /// (C++11 [class]p6).
1330 bool isTriviallyCopyable() const;
1332 /// Determine whether this class is considered trivial.
1334 /// C++11 [class]p6:
1335 /// "A trivial class is a class that has a trivial default constructor and
1336 /// is trivially copyable."
1337 bool isTrivial() const {
1338 return isTriviallyCopyable() && hasTrivialDefaultConstructor();
1341 /// Determine whether this class is a literal type.
1343 /// C++11 [basic.types]p10:
1344 /// A class type that has all the following properties:
1345 /// - it has a trivial destructor
1346 /// - every constructor call and full-expression in the
1347 /// brace-or-equal-intializers for non-static data members (if any) is
1348 /// a constant expression.
1349 /// - it is an aggregate type or has at least one constexpr constructor
1350 /// or constructor template that is not a copy or move constructor, and
1351 /// - all of its non-static data members and base classes are of literal
1354 /// We resolve DR1361 by ignoring the second bullet. We resolve DR1452 by
1355 /// treating types with trivial default constructors as literal types.
1357 /// Only in C++17 and beyond, are lambdas literal types.
1358 bool isLiteral() const {
1359 ASTContext &Ctx = getASTContext();
1360 return (Ctx.getLangOpts().CPlusPlus2a ? hasConstexprDestructor()
1361 : hasTrivialDestructor()) &&
1362 (!isLambda() || Ctx.getLangOpts().CPlusPlus17) &&
1363 !hasNonLiteralTypeFieldsOrBases() &&
1364 (isAggregate() || isLambda() ||
1365 hasConstexprNonCopyMoveConstructor() ||
1366 hasTrivialDefaultConstructor());
1369 /// If this record is an instantiation of a member class,
1370 /// retrieves the member class from which it was instantiated.
1372 /// This routine will return non-null for (non-templated) member
1373 /// classes of class templates. For example, given:
1376 /// template<typename T>
1382 /// The declaration for X<int>::A is a (non-templated) CXXRecordDecl
1383 /// whose parent is the class template specialization X<int>. For
1384 /// this declaration, getInstantiatedFromMemberClass() will return
1385 /// the CXXRecordDecl X<T>::A. When a complete definition of
1386 /// X<int>::A is required, it will be instantiated from the
1387 /// declaration returned by getInstantiatedFromMemberClass().
1388 CXXRecordDecl *getInstantiatedFromMemberClass() const;
1390 /// If this class is an instantiation of a member class of a
1391 /// class template specialization, retrieves the member specialization
1393 MemberSpecializationInfo *getMemberSpecializationInfo() const;
1395 /// Specify that this record is an instantiation of the
1396 /// member class \p RD.
1397 void setInstantiationOfMemberClass(CXXRecordDecl *RD,
1398 TemplateSpecializationKind TSK);
1400 /// Retrieves the class template that is described by this
1401 /// class declaration.
1403 /// Every class template is represented as a ClassTemplateDecl and a
1404 /// CXXRecordDecl. The former contains template properties (such as
1405 /// the template parameter lists) while the latter contains the
1406 /// actual description of the template's
1407 /// contents. ClassTemplateDecl::getTemplatedDecl() retrieves the
1408 /// CXXRecordDecl that from a ClassTemplateDecl, while
1409 /// getDescribedClassTemplate() retrieves the ClassTemplateDecl from
1410 /// a CXXRecordDecl.
1411 ClassTemplateDecl *getDescribedClassTemplate() const;
1413 void setDescribedClassTemplate(ClassTemplateDecl *Template);
1415 /// Determine whether this particular class is a specialization or
1416 /// instantiation of a class template or member class of a class template,
1417 /// and how it was instantiated or specialized.
1418 TemplateSpecializationKind getTemplateSpecializationKind() const;
1420 /// Set the kind of specialization or template instantiation this is.
1421 void setTemplateSpecializationKind(TemplateSpecializationKind TSK);
1423 /// Retrieve the record declaration from which this record could be
1424 /// instantiated. Returns null if this class is not a template instantiation.
1425 const CXXRecordDecl *getTemplateInstantiationPattern() const;
1427 CXXRecordDecl *getTemplateInstantiationPattern() {
1428 return const_cast<CXXRecordDecl *>(const_cast<const CXXRecordDecl *>(this)
1429 ->getTemplateInstantiationPattern());
1432 /// Returns the destructor decl for this class.
1433 CXXDestructorDecl *getDestructor() const;
1435 /// Returns true if the class destructor, or any implicitly invoked
1436 /// destructors are marked noreturn.
1437 bool isAnyDestructorNoReturn() const;
1439 /// If the class is a local class [class.local], returns
1440 /// the enclosing function declaration.
1441 const FunctionDecl *isLocalClass() const {
1442 if (const auto *RD = dyn_cast<CXXRecordDecl>(getDeclContext()))
1443 return RD->isLocalClass();
1445 return dyn_cast<FunctionDecl>(getDeclContext());
1448 FunctionDecl *isLocalClass() {
1449 return const_cast<FunctionDecl*>(
1450 const_cast<const CXXRecordDecl*>(this)->isLocalClass());
1453 /// Determine whether this dependent class is a current instantiation,
1454 /// when viewed from within the given context.
1455 bool isCurrentInstantiation(const DeclContext *CurContext) const;
1457 /// Determine whether this class is derived from the class \p Base.
1459 /// This routine only determines whether this class is derived from \p Base,
1460 /// but does not account for factors that may make a Derived -> Base class
1461 /// ill-formed, such as private/protected inheritance or multiple, ambiguous
1462 /// base class subobjects.
1464 /// \param Base the base class we are searching for.
1466 /// \returns true if this class is derived from Base, false otherwise.
1467 bool isDerivedFrom(const CXXRecordDecl *Base) const;
1469 /// Determine whether this class is derived from the type \p Base.
1471 /// This routine only determines whether this class is derived from \p Base,
1472 /// but does not account for factors that may make a Derived -> Base class
1473 /// ill-formed, such as private/protected inheritance or multiple, ambiguous
1474 /// base class subobjects.
1476 /// \param Base the base class we are searching for.
1478 /// \param Paths will contain the paths taken from the current class to the
1479 /// given \p Base class.
1481 /// \returns true if this class is derived from \p Base, false otherwise.
1483 /// \todo add a separate parameter to configure IsDerivedFrom, rather than
1484 /// tangling input and output in \p Paths
1485 bool isDerivedFrom(const CXXRecordDecl *Base, CXXBasePaths &Paths) const;
1487 /// Determine whether this class is virtually derived from
1488 /// the class \p Base.
1490 /// This routine only determines whether this class is virtually
1491 /// derived from \p Base, but does not account for factors that may
1492 /// make a Derived -> Base class ill-formed, such as
1493 /// private/protected inheritance or multiple, ambiguous base class
1496 /// \param Base the base class we are searching for.
1498 /// \returns true if this class is virtually derived from Base,
1499 /// false otherwise.
1500 bool isVirtuallyDerivedFrom(const CXXRecordDecl *Base) const;
1502 /// Determine whether this class is provably not derived from
1503 /// the type \p Base.
1504 bool isProvablyNotDerivedFrom(const CXXRecordDecl *Base) const;
1506 /// Function type used by forallBases() as a callback.
1508 /// \param BaseDefinition the definition of the base class
1510 /// \returns true if this base matched the search criteria
1511 using ForallBasesCallback =
1512 llvm::function_ref<bool(const CXXRecordDecl *BaseDefinition)>;
1514 /// Determines if the given callback holds for all the direct
1515 /// or indirect base classes of this type.
1517 /// The class itself does not count as a base class. This routine
1518 /// returns false if the class has non-computable base classes.
1520 /// \param BaseMatches Callback invoked for each (direct or indirect) base
1521 /// class of this type, or if \p AllowShortCircuit is true then until a call
1524 /// \param AllowShortCircuit if false, forces the callback to be called
1525 /// for every base class, even if a dependent or non-matching base was
1527 bool forallBases(ForallBasesCallback BaseMatches,
1528 bool AllowShortCircuit = true) const;
1530 /// Function type used by lookupInBases() to determine whether a
1531 /// specific base class subobject matches the lookup criteria.
1533 /// \param Specifier the base-class specifier that describes the inheritance
1534 /// from the base class we are trying to match.
1536 /// \param Path the current path, from the most-derived class down to the
1537 /// base named by the \p Specifier.
1539 /// \returns true if this base matched the search criteria, false otherwise.
1540 using BaseMatchesCallback =
1541 llvm::function_ref<bool(const CXXBaseSpecifier *Specifier,
1542 CXXBasePath &Path)>;
1544 /// Look for entities within the base classes of this C++ class,
1545 /// transitively searching all base class subobjects.
1547 /// This routine uses the callback function \p BaseMatches to find base
1548 /// classes meeting some search criteria, walking all base class subobjects
1549 /// and populating the given \p Paths structure with the paths through the
1550 /// inheritance hierarchy that resulted in a match. On a successful search,
1551 /// the \p Paths structure can be queried to retrieve the matching paths and
1552 /// to determine if there were any ambiguities.
1554 /// \param BaseMatches callback function used to determine whether a given
1555 /// base matches the user-defined search criteria.
1557 /// \param Paths used to record the paths from this class to its base class
1558 /// subobjects that match the search criteria.
1560 /// \param LookupInDependent can be set to true to extend the search to
1561 /// dependent base classes.
1563 /// \returns true if there exists any path from this class to a base class
1564 /// subobject that matches the search criteria.
1565 bool lookupInBases(BaseMatchesCallback BaseMatches, CXXBasePaths &Paths,
1566 bool LookupInDependent = false) const;
1568 /// Base-class lookup callback that determines whether the given
1569 /// base class specifier refers to a specific class declaration.
1571 /// This callback can be used with \c lookupInBases() to determine whether
1572 /// a given derived class has is a base class subobject of a particular type.
1573 /// The base record pointer should refer to the canonical CXXRecordDecl of the
1574 /// base class that we are searching for.
1575 static bool FindBaseClass(const CXXBaseSpecifier *Specifier,
1576 CXXBasePath &Path, const CXXRecordDecl *BaseRecord);
1578 /// Base-class lookup callback that determines whether the
1579 /// given base class specifier refers to a specific class
1580 /// declaration and describes virtual derivation.
1582 /// This callback can be used with \c lookupInBases() to determine
1583 /// whether a given derived class has is a virtual base class
1584 /// subobject of a particular type. The base record pointer should
1585 /// refer to the canonical CXXRecordDecl of the base class that we
1586 /// are searching for.
1587 static bool FindVirtualBaseClass(const CXXBaseSpecifier *Specifier,
1589 const CXXRecordDecl *BaseRecord);
1591 /// Base-class lookup callback that determines whether there exists
1592 /// a tag with the given name.
1594 /// This callback can be used with \c lookupInBases() to find tag members
1595 /// of the given name within a C++ class hierarchy.
1596 static bool FindTagMember(const CXXBaseSpecifier *Specifier,
1597 CXXBasePath &Path, DeclarationName Name);
1599 /// Base-class lookup callback that determines whether there exists
1600 /// a member with the given name.
1602 /// This callback can be used with \c lookupInBases() to find members
1603 /// of the given name within a C++ class hierarchy.
1604 static bool FindOrdinaryMember(const CXXBaseSpecifier *Specifier,
1605 CXXBasePath &Path, DeclarationName Name);
1607 /// Base-class lookup callback that determines whether there exists
1608 /// a member with the given name.
1610 /// This callback can be used with \c lookupInBases() to find members
1611 /// of the given name within a C++ class hierarchy, including dependent
1614 FindOrdinaryMemberInDependentClasses(const CXXBaseSpecifier *Specifier,
1615 CXXBasePath &Path, DeclarationName Name);
1617 /// Base-class lookup callback that determines whether there exists
1618 /// an OpenMP declare reduction member with the given name.
1620 /// This callback can be used with \c lookupInBases() to find members
1621 /// of the given name within a C++ class hierarchy.
1622 static bool FindOMPReductionMember(const CXXBaseSpecifier *Specifier,
1623 CXXBasePath &Path, DeclarationName Name);
1625 /// Base-class lookup callback that determines whether there exists
1626 /// an OpenMP declare mapper member with the given name.
1628 /// This callback can be used with \c lookupInBases() to find members
1629 /// of the given name within a C++ class hierarchy.
1630 static bool FindOMPMapperMember(const CXXBaseSpecifier *Specifier,
1631 CXXBasePath &Path, DeclarationName Name);
1633 /// Base-class lookup callback that determines whether there exists
1634 /// a member with the given name that can be used in a nested-name-specifier.
1636 /// This callback can be used with \c lookupInBases() to find members of
1637 /// the given name within a C++ class hierarchy that can occur within
1638 /// nested-name-specifiers.
1639 static bool FindNestedNameSpecifierMember(const CXXBaseSpecifier *Specifier,
1641 DeclarationName Name);
1643 /// Retrieve the final overriders for each virtual member
1644 /// function in the class hierarchy where this class is the
1645 /// most-derived class in the class hierarchy.
1646 void getFinalOverriders(CXXFinalOverriderMap &FinaOverriders) const;
1648 /// Get the indirect primary bases for this class.
1649 void getIndirectPrimaryBases(CXXIndirectPrimaryBaseSet& Bases) const;
1651 /// Performs an imprecise lookup of a dependent name in this class.
1653 /// This function does not follow strict semantic rules and should be used
1654 /// only when lookup rules can be relaxed, e.g. indexing.
1655 std::vector<const NamedDecl *>
1656 lookupDependentName(const DeclarationName &Name,
1657 llvm::function_ref<bool(const NamedDecl *ND)> Filter);
1659 /// Renders and displays an inheritance diagram
1660 /// for this C++ class and all of its base classes (transitively) using
1662 void viewInheritance(ASTContext& Context) const;
1664 /// Calculates the access of a decl that is reached
1666 static AccessSpecifier MergeAccess(AccessSpecifier PathAccess,
1667 AccessSpecifier DeclAccess) {
1668 assert(DeclAccess != AS_none);
1669 if (DeclAccess == AS_private) return AS_none;
1670 return (PathAccess > DeclAccess ? PathAccess : DeclAccess);
1673 /// Indicates that the declaration of a defaulted or deleted special
1674 /// member function is now complete.
1675 void finishedDefaultedOrDeletedMember(CXXMethodDecl *MD);
1677 void setTrivialForCallFlags(CXXMethodDecl *MD);
1679 /// Indicates that the definition of this class is now complete.
1680 void completeDefinition() override;
1682 /// Indicates that the definition of this class is now complete,
1683 /// and provides a final overrider map to help determine
1685 /// \param FinalOverriders The final overrider map for this class, which can
1686 /// be provided as an optimization for abstract-class checking. If NULL,
1687 /// final overriders will be computed if they are needed to complete the
1689 void completeDefinition(CXXFinalOverriderMap *FinalOverriders);
1691 /// Determine whether this class may end up being abstract, even though
1692 /// it is not yet known to be abstract.
1694 /// \returns true if this class is not known to be abstract but has any
1695 /// base classes that are abstract. In this case, \c completeDefinition()
1696 /// will need to compute final overriders to determine whether the class is
1697 /// actually abstract.
1698 bool mayBeAbstract() const;
1700 /// If this is the closure type of a lambda expression, retrieve the
1701 /// number to be used for name mangling in the Itanium C++ ABI.
1703 /// Zero indicates that this closure type has internal linkage, so the
1704 /// mangling number does not matter, while a non-zero value indicates which
1705 /// lambda expression this is in this particular context.
1706 unsigned getLambdaManglingNumber() const {
1707 assert(isLambda() && "Not a lambda closure type!");
1708 return getLambdaData().ManglingNumber;
1711 /// The lambda is known to has internal linkage no matter whether it has name
1712 /// mangling number.
1713 bool hasKnownLambdaInternalLinkage() const {
1714 assert(isLambda() && "Not a lambda closure type!");
1715 return getLambdaData().HasKnownInternalLinkage;
1718 /// Retrieve the declaration that provides additional context for a
1719 /// lambda, when the normal declaration context is not specific enough.
1721 /// Certain contexts (default arguments of in-class function parameters and
1722 /// the initializers of data members) have separate name mangling rules for
1723 /// lambdas within the Itanium C++ ABI. For these cases, this routine provides
1724 /// the declaration in which the lambda occurs, e.g., the function parameter
1725 /// or the non-static data member. Otherwise, it returns NULL to imply that
1726 /// the declaration context suffices.
1727 Decl *getLambdaContextDecl() const;
1729 /// Set the mangling number and context declaration for a lambda
1731 void setLambdaMangling(unsigned ManglingNumber, Decl *ContextDecl,
1732 bool HasKnownInternalLinkage = false) {
1733 assert(isLambda() && "Not a lambda closure type!");
1734 getLambdaData().ManglingNumber = ManglingNumber;
1735 getLambdaData().ContextDecl = ContextDecl;
1736 getLambdaData().HasKnownInternalLinkage = HasKnownInternalLinkage;
1739 /// Returns the inheritance model used for this record.
1740 MSInheritanceAttr::Spelling getMSInheritanceModel() const;
1742 /// Calculate what the inheritance model would be for this class.
1743 MSInheritanceAttr::Spelling calculateInheritanceModel() const;
1745 /// In the Microsoft C++ ABI, use zero for the field offset of a null data
1746 /// member pointer if we can guarantee that zero is not a valid field offset,
1747 /// or if the member pointer has multiple fields. Polymorphic classes have a
1748 /// vfptr at offset zero, so we can use zero for null. If there are multiple
1749 /// fields, we can use zero even if it is a valid field offset because
1750 /// null-ness testing will check the other fields.
1751 bool nullFieldOffsetIsZero() const {
1752 return !MSInheritanceAttr::hasOnlyOneField(/*IsMemberFunction=*/false,
1753 getMSInheritanceModel()) ||
1754 (hasDefinition() && isPolymorphic());
1757 /// Controls when vtordisps will be emitted if this record is used as a
1759 MSVtorDispAttr::Mode getMSVtorDispMode() const;
1761 /// Determine whether this lambda expression was known to be dependent
1762 /// at the time it was created, even if its context does not appear to be
1765 /// This flag is a workaround for an issue with parsing, where default
1766 /// arguments are parsed before their enclosing function declarations have
1767 /// been created. This means that any lambda expressions within those
1768 /// default arguments will have as their DeclContext the context enclosing
1769 /// the function declaration, which may be non-dependent even when the
1770 /// function declaration itself is dependent. This flag indicates when we
1771 /// know that the lambda is dependent despite that.
1772 bool isDependentLambda() const {
1773 return isLambda() && getLambdaData().Dependent;
1776 TypeSourceInfo *getLambdaTypeInfo() const {
1777 return getLambdaData().MethodTyInfo;
1780 // Determine whether this type is an Interface Like type for
1781 // __interface inheritance purposes.
1782 bool isInterfaceLike() const;
1784 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1785 static bool classofKind(Kind K) {
1786 return K >= firstCXXRecord && K <= lastCXXRecord;
1790 /// Store information needed for an explicit specifier.
1791 /// used by CXXDeductionGuideDecl, CXXConstructorDecl and CXXConversionDecl.
1792 class ExplicitSpecifier {
1793 llvm::PointerIntPair<Expr *, 2, ExplicitSpecKind> ExplicitSpec{
1794 nullptr, ExplicitSpecKind::ResolvedFalse};
1797 ExplicitSpecifier() = default;
1798 ExplicitSpecifier(Expr *Expression, ExplicitSpecKind Kind)
1799 : ExplicitSpec(Expression, Kind) {}
1800 ExplicitSpecKind getKind() const { return ExplicitSpec.getInt(); }
1801 const Expr *getExpr() const { return ExplicitSpec.getPointer(); }
1802 Expr *getExpr() { return ExplicitSpec.getPointer(); }
1804 /// Return true if the ExplicitSpecifier isn't defaulted.
1805 bool isSpecified() const {
1806 return ExplicitSpec.getInt() != ExplicitSpecKind::ResolvedFalse ||
1807 ExplicitSpec.getPointer();
1810 /// Check for Equivalence of explicit specifiers.
1811 /// Return True if the explicit specifier are equivalent false otherwise.
1812 bool isEquivalent(const ExplicitSpecifier Other) const;
1813 /// Return true if the explicit specifier is already resolved to be explicit.
1814 bool isExplicit() const {
1815 return ExplicitSpec.getInt() == ExplicitSpecKind::ResolvedTrue;
1817 /// Return true if the ExplicitSpecifier isn't valid.
1818 /// This state occurs after a substitution failures.
1819 bool isInvalid() const {
1820 return ExplicitSpec.getInt() == ExplicitSpecKind::Unresolved &&
1821 !ExplicitSpec.getPointer();
1823 void setKind(ExplicitSpecKind Kind) { ExplicitSpec.setInt(Kind); }
1824 void setExpr(Expr *E) { ExplicitSpec.setPointer(E); }
1825 // getFromDecl - retrieve the explicit specifier in the given declaration.
1826 // if the given declaration has no explicit. the returned explicit specifier
1827 // is defaulted. .isSpecified() will be false.
1828 static ExplicitSpecifier getFromDecl(FunctionDecl *Function);
1829 static const ExplicitSpecifier getFromDecl(const FunctionDecl *Function) {
1830 return getFromDecl(const_cast<FunctionDecl *>(Function));
1832 static ExplicitSpecifier Invalid() {
1833 return ExplicitSpecifier(nullptr, ExplicitSpecKind::Unresolved);
1837 /// Represents a C++ deduction guide declaration.
1840 /// template<typename T> struct A { A(); A(T); };
1844 /// In this example, there will be an explicit deduction guide from the
1845 /// second line, and implicit deduction guide templates synthesized from
1846 /// the constructors of \c A.
1847 class CXXDeductionGuideDecl : public FunctionDecl {
1848 void anchor() override;
1851 CXXDeductionGuideDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
1852 ExplicitSpecifier ES,
1853 const DeclarationNameInfo &NameInfo, QualType T,
1854 TypeSourceInfo *TInfo, SourceLocation EndLocation)
1855 : FunctionDecl(CXXDeductionGuide, C, DC, StartLoc, NameInfo, T, TInfo,
1856 SC_None, false, CSK_unspecified),
1858 if (EndLocation.isValid())
1859 setRangeEnd(EndLocation);
1860 setIsCopyDeductionCandidate(false);
1863 ExplicitSpecifier ExplicitSpec;
1864 void setExplicitSpecifier(ExplicitSpecifier ES) { ExplicitSpec = ES; }
1867 friend class ASTDeclReader;
1868 friend class ASTDeclWriter;
1870 static CXXDeductionGuideDecl *
1871 Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
1872 ExplicitSpecifier ES, const DeclarationNameInfo &NameInfo, QualType T,
1873 TypeSourceInfo *TInfo, SourceLocation EndLocation);
1875 static CXXDeductionGuideDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1877 ExplicitSpecifier getExplicitSpecifier() { return ExplicitSpec; }
1878 const ExplicitSpecifier getExplicitSpecifier() const { return ExplicitSpec; }
1880 /// Return true if the declartion is already resolved to be explicit.
1881 bool isExplicit() const { return ExplicitSpec.isExplicit(); }
1883 /// Get the template for which this guide performs deduction.
1884 TemplateDecl *getDeducedTemplate() const {
1885 return getDeclName().getCXXDeductionGuideTemplate();
1888 void setIsCopyDeductionCandidate(bool isCDC = true) {
1889 FunctionDeclBits.IsCopyDeductionCandidate = isCDC;
1892 bool isCopyDeductionCandidate() const {
1893 return FunctionDeclBits.IsCopyDeductionCandidate;
1896 // Implement isa/cast/dyncast/etc.
1897 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1898 static bool classofKind(Kind K) { return K == CXXDeductionGuide; }
1901 /// Represents a static or instance method of a struct/union/class.
1903 /// In the terminology of the C++ Standard, these are the (static and
1904 /// non-static) member functions, whether virtual or not.
1905 class CXXMethodDecl : public FunctionDecl {
1906 void anchor() override;
1909 CXXMethodDecl(Kind DK, ASTContext &C, CXXRecordDecl *RD,
1910 SourceLocation StartLoc, const DeclarationNameInfo &NameInfo,
1911 QualType T, TypeSourceInfo *TInfo, StorageClass SC,
1912 bool isInline, ConstexprSpecKind ConstexprKind,
1913 SourceLocation EndLocation)
1914 : FunctionDecl(DK, C, RD, StartLoc, NameInfo, T, TInfo, SC, isInline,
1916 if (EndLocation.isValid())
1917 setRangeEnd(EndLocation);
1921 static CXXMethodDecl *Create(ASTContext &C, CXXRecordDecl *RD,
1922 SourceLocation StartLoc,
1923 const DeclarationNameInfo &NameInfo, QualType T,
1924 TypeSourceInfo *TInfo, StorageClass SC,
1925 bool isInline, ConstexprSpecKind ConstexprKind,
1926 SourceLocation EndLocation);
1928 static CXXMethodDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1930 bool isStatic() const;
1931 bool isInstance() const { return !isStatic(); }
1933 /// Returns true if the given operator is implicitly static in a record
1935 static bool isStaticOverloadedOperator(OverloadedOperatorKind OOK) {
1937 // Any allocation function for a class T is a static member
1938 // (even if not explicitly declared static).
1939 // [class.free]p6 Any deallocation function for a class X is a static member
1940 // (even if not explicitly declared static).
1941 return OOK == OO_New || OOK == OO_Array_New || OOK == OO_Delete ||
1942 OOK == OO_Array_Delete;
1945 bool isConst() const { return getType()->castAs<FunctionType>()->isConst(); }
1946 bool isVolatile() const { return getType()->castAs<FunctionType>()->isVolatile(); }
1948 bool isVirtual() const {
1949 CXXMethodDecl *CD = const_cast<CXXMethodDecl*>(this)->getCanonicalDecl();
1951 // Member function is virtual if it is marked explicitly so, or if it is
1952 // declared in __interface -- then it is automatically pure virtual.
1953 if (CD->isVirtualAsWritten() || CD->isPure())
1956 return CD->size_overridden_methods() != 0;
1959 /// If it's possible to devirtualize a call to this method, return the called
1960 /// function. Otherwise, return null.
1962 /// \param Base The object on which this virtual function is called.
1963 /// \param IsAppleKext True if we are compiling for Apple kext.
1964 CXXMethodDecl *getDevirtualizedMethod(const Expr *Base, bool IsAppleKext);
1966 const CXXMethodDecl *getDevirtualizedMethod(const Expr *Base,
1967 bool IsAppleKext) const {
1968 return const_cast<CXXMethodDecl *>(this)->getDevirtualizedMethod(
1972 /// Determine whether this is a usual deallocation function (C++
1973 /// [basic.stc.dynamic.deallocation]p2), which is an overloaded delete or
1974 /// delete[] operator with a particular signature. Populates \p PreventedBy
1975 /// with the declarations of the functions of the same kind if they were the
1976 /// reason for this function returning false. This is used by
1977 /// Sema::isUsualDeallocationFunction to reconsider the answer based on the
1979 bool isUsualDeallocationFunction(
1980 SmallVectorImpl<const FunctionDecl *> &PreventedBy) const;
1982 /// Determine whether this is a copy-assignment operator, regardless
1983 /// of whether it was declared implicitly or explicitly.
1984 bool isCopyAssignmentOperator() const;
1986 /// Determine whether this is a move assignment operator.
1987 bool isMoveAssignmentOperator() const;
1989 CXXMethodDecl *getCanonicalDecl() override {
1990 return cast<CXXMethodDecl>(FunctionDecl::getCanonicalDecl());
1992 const CXXMethodDecl *getCanonicalDecl() const {
1993 return const_cast<CXXMethodDecl*>(this)->getCanonicalDecl();
1996 CXXMethodDecl *getMostRecentDecl() {
1997 return cast<CXXMethodDecl>(
1998 static_cast<FunctionDecl *>(this)->getMostRecentDecl());
2000 const CXXMethodDecl *getMostRecentDecl() const {
2001 return const_cast<CXXMethodDecl*>(this)->getMostRecentDecl();
2004 /// True if this method is user-declared and was not
2005 /// deleted or defaulted on its first declaration.
2006 bool isUserProvided() const {
2007 auto *DeclAsWritten = this;
2008 if (auto *Pattern = getTemplateInstantiationPattern())
2009 DeclAsWritten = cast<CXXMethodDecl>(Pattern);
2010 return !(DeclAsWritten->isDeleted() ||
2011 DeclAsWritten->getCanonicalDecl()->isDefaulted());
2014 void addOverriddenMethod(const CXXMethodDecl *MD);
2016 using method_iterator = const CXXMethodDecl *const *;
2018 method_iterator begin_overridden_methods() const;
2019 method_iterator end_overridden_methods() const;
2020 unsigned size_overridden_methods() const;
2022 using overridden_method_range= ASTContext::overridden_method_range;
2024 overridden_method_range overridden_methods() const;
2026 /// Return the parent of this method declaration, which
2027 /// is the class in which this method is defined.
2028 const CXXRecordDecl *getParent() const {
2029 return cast<CXXRecordDecl>(FunctionDecl::getParent());
2032 /// Return the parent of this method declaration, which
2033 /// is the class in which this method is defined.
2034 CXXRecordDecl *getParent() {
2035 return const_cast<CXXRecordDecl *>(
2036 cast<CXXRecordDecl>(FunctionDecl::getParent()));
2039 /// Return the type of the \c this pointer.
2041 /// Should only be called for instance (i.e., non-static) methods. Note
2042 /// that for the call operator of a lambda closure type, this returns the
2043 /// desugared 'this' type (a pointer to the closure type), not the captured
2045 QualType getThisType() const;
2047 /// Return the type of the object pointed by \c this.
2049 /// See getThisType() for usage restriction.
2050 QualType getThisObjectType() const;
2052 static QualType getThisType(const FunctionProtoType *FPT,
2053 const CXXRecordDecl *Decl);
2055 static QualType getThisObjectType(const FunctionProtoType *FPT,
2056 const CXXRecordDecl *Decl);
2058 Qualifiers getMethodQualifiers() const {
2059 return getType()->castAs<FunctionProtoType>()->getMethodQuals();
2062 /// Retrieve the ref-qualifier associated with this method.
2064 /// In the following example, \c f() has an lvalue ref-qualifier, \c g()
2065 /// has an rvalue ref-qualifier, and \c h() has no ref-qualifier.
2073 RefQualifierKind getRefQualifier() const {
2074 return getType()->castAs<FunctionProtoType>()->getRefQualifier();
2077 bool hasInlineBody() const;
2079 /// Determine whether this is a lambda closure type's static member
2080 /// function that is used for the result of the lambda's conversion to
2081 /// function pointer (for a lambda with no captures).
2083 /// The function itself, if used, will have a placeholder body that will be
2084 /// supplied by IR generation to either forward to the function call operator
2085 /// or clone the function call operator.
2086 bool isLambdaStaticInvoker() const;
2088 /// Find the method in \p RD that corresponds to this one.
2090 /// Find if \p RD or one of the classes it inherits from override this method.
2091 /// If so, return it. \p RD is assumed to be a subclass of the class defining
2092 /// this method (or be the class itself), unless \p MayBeBase is set to true.
2094 getCorrespondingMethodInClass(const CXXRecordDecl *RD,
2095 bool MayBeBase = false);
2097 const CXXMethodDecl *
2098 getCorrespondingMethodInClass(const CXXRecordDecl *RD,
2099 bool MayBeBase = false) const {
2100 return const_cast<CXXMethodDecl *>(this)
2101 ->getCorrespondingMethodInClass(RD, MayBeBase);
2104 /// Find if \p RD declares a function that overrides this function, and if so,
2105 /// return it. Does not search base classes.
2106 CXXMethodDecl *getCorrespondingMethodDeclaredInClass(const CXXRecordDecl *RD,
2107 bool MayBeBase = false);
2108 const CXXMethodDecl *
2109 getCorrespondingMethodDeclaredInClass(const CXXRecordDecl *RD,
2110 bool MayBeBase = false) const {
2111 return const_cast<CXXMethodDecl *>(this)
2112 ->getCorrespondingMethodDeclaredInClass(RD, MayBeBase);
2115 // Implement isa/cast/dyncast/etc.
2116 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2117 static bool classofKind(Kind K) {
2118 return K >= firstCXXMethod && K <= lastCXXMethod;
2122 /// Represents a C++ base or member initializer.
2124 /// This is part of a constructor initializer that
2125 /// initializes one non-static member variable or one base class. For
2126 /// example, in the following, both 'A(a)' and 'f(3.14159)' are member
2131 /// class B : public A {
2134 /// B(A& a) : A(a), f(3.14159) { }
2137 class CXXCtorInitializer final {
2138 /// Either the base class name/delegating constructor type (stored as
2139 /// a TypeSourceInfo*), an normal field (FieldDecl), or an anonymous field
2140 /// (IndirectFieldDecl*) being initialized.
2141 llvm::PointerUnion3<TypeSourceInfo *, FieldDecl *, IndirectFieldDecl *>
2144 /// The source location for the field name or, for a base initializer
2145 /// pack expansion, the location of the ellipsis.
2147 /// In the case of a delegating
2148 /// constructor, it will still include the type's source location as the
2149 /// Initializee points to the CXXConstructorDecl (to allow loop detection).
2150 SourceLocation MemberOrEllipsisLocation;
2152 /// The argument used to initialize the base or member, which may
2153 /// end up constructing an object (when multiple arguments are involved).
2156 /// Location of the left paren of the ctor-initializer.
2157 SourceLocation LParenLoc;
2159 /// Location of the right paren of the ctor-initializer.
2160 SourceLocation RParenLoc;
2162 /// If the initializee is a type, whether that type makes this
2163 /// a delegating initialization.
2164 unsigned IsDelegating : 1;
2166 /// If the initializer is a base initializer, this keeps track
2167 /// of whether the base is virtual or not.
2168 unsigned IsVirtual : 1;
2170 /// Whether or not the initializer is explicitly written
2172 unsigned IsWritten : 1;
2174 /// If IsWritten is true, then this number keeps track of the textual order
2175 /// of this initializer in the original sources, counting from 0.
2176 unsigned SourceOrder : 13;
2179 /// Creates a new base-class initializer.
2181 CXXCtorInitializer(ASTContext &Context, TypeSourceInfo *TInfo, bool IsVirtual,
2182 SourceLocation L, Expr *Init, SourceLocation R,
2183 SourceLocation EllipsisLoc);
2185 /// Creates a new member initializer.
2187 CXXCtorInitializer(ASTContext &Context, FieldDecl *Member,
2188 SourceLocation MemberLoc, SourceLocation L, Expr *Init,
2191 /// Creates a new anonymous field initializer.
2193 CXXCtorInitializer(ASTContext &Context, IndirectFieldDecl *Member,
2194 SourceLocation MemberLoc, SourceLocation L, Expr *Init,
2197 /// Creates a new delegating initializer.
2199 CXXCtorInitializer(ASTContext &Context, TypeSourceInfo *TInfo,
2200 SourceLocation L, Expr *Init, SourceLocation R);
2202 /// \return Unique reproducible object identifier.
2203 int64_t getID(const ASTContext &Context) const;
2205 /// Determine whether this initializer is initializing a base class.
2206 bool isBaseInitializer() const {
2207 return Initializee.is<TypeSourceInfo*>() && !IsDelegating;
2210 /// Determine whether this initializer is initializing a non-static
2212 bool isMemberInitializer() const { return Initializee.is<FieldDecl*>(); }
2214 bool isAnyMemberInitializer() const {
2215 return isMemberInitializer() || isIndirectMemberInitializer();
2218 bool isIndirectMemberInitializer() const {
2219 return Initializee.is<IndirectFieldDecl*>();
2222 /// Determine whether this initializer is an implicit initializer
2223 /// generated for a field with an initializer defined on the member
2226 /// In-class member initializers (also known as "non-static data member
2227 /// initializations", NSDMIs) were introduced in C++11.
2228 bool isInClassMemberInitializer() const {
2229 return Init->getStmtClass() == Stmt::CXXDefaultInitExprClass;
2232 /// Determine whether this initializer is creating a delegating
2234 bool isDelegatingInitializer() const {
2235 return Initializee.is<TypeSourceInfo*>() && IsDelegating;
2238 /// Determine whether this initializer is a pack expansion.
2239 bool isPackExpansion() const {
2240 return isBaseInitializer() && MemberOrEllipsisLocation.isValid();
2243 // For a pack expansion, returns the location of the ellipsis.
2244 SourceLocation getEllipsisLoc() const {
2245 assert(isPackExpansion() && "Initializer is not a pack expansion");
2246 return MemberOrEllipsisLocation;
2249 /// If this is a base class initializer, returns the type of the
2250 /// base class with location information. Otherwise, returns an NULL
2252 TypeLoc getBaseClassLoc() const;
2254 /// If this is a base class initializer, returns the type of the base class.
2255 /// Otherwise, returns null.
2256 const Type *getBaseClass() const;
2258 /// Returns whether the base is virtual or not.
2259 bool isBaseVirtual() const {
2260 assert(isBaseInitializer() && "Must call this on base initializer!");
2265 /// Returns the declarator information for a base class or delegating
2267 TypeSourceInfo *getTypeSourceInfo() const {
2268 return Initializee.dyn_cast<TypeSourceInfo *>();
2271 /// If this is a member initializer, returns the declaration of the
2272 /// non-static data member being initialized. Otherwise, returns null.
2273 FieldDecl *getMember() const {
2274 if (isMemberInitializer())
2275 return Initializee.get<FieldDecl*>();
2279 FieldDecl *getAnyMember() const {
2280 if (isMemberInitializer())
2281 return Initializee.get<FieldDecl*>();
2282 if (isIndirectMemberInitializer())
2283 return Initializee.get<IndirectFieldDecl*>()->getAnonField();
2287 IndirectFieldDecl *getIndirectMember() const {
2288 if (isIndirectMemberInitializer())
2289 return Initializee.get<IndirectFieldDecl*>();
2293 SourceLocation getMemberLocation() const {
2294 return MemberOrEllipsisLocation;
2297 /// Determine the source location of the initializer.
2298 SourceLocation getSourceLocation() const;
2300 /// Determine the source range covering the entire initializer.
2301 SourceRange getSourceRange() const LLVM_READONLY;
2303 /// Determine whether this initializer is explicitly written
2304 /// in the source code.
2305 bool isWritten() const { return IsWritten; }
2307 /// Return the source position of the initializer, counting from 0.
2308 /// If the initializer was implicit, -1 is returned.
2309 int getSourceOrder() const {
2310 return IsWritten ? static_cast<int>(SourceOrder) : -1;
2313 /// Set the source order of this initializer.
2315 /// This can only be called once for each initializer; it cannot be called
2316 /// on an initializer having a positive number of (implicit) array indices.
2318 /// This assumes that the initializer was written in the source code, and
2319 /// ensures that isWritten() returns true.
2320 void setSourceOrder(int Pos) {
2321 assert(!IsWritten &&
2322 "setSourceOrder() used on implicit initializer");
2323 assert(SourceOrder == 0 &&
2324 "calling twice setSourceOrder() on the same initializer");
2326 "setSourceOrder() used to make an initializer implicit");
2328 SourceOrder = static_cast<unsigned>(Pos);
2331 SourceLocation getLParenLoc() const { return LParenLoc; }
2332 SourceLocation getRParenLoc() const { return RParenLoc; }
2334 /// Get the initializer.
2335 Expr *getInit() const { return static_cast<Expr *>(Init); }
2338 /// Description of a constructor that was inherited from a base class.
2339 class InheritedConstructor {
2340 ConstructorUsingShadowDecl *Shadow = nullptr;
2341 CXXConstructorDecl *BaseCtor = nullptr;
2344 InheritedConstructor() = default;
2345 InheritedConstructor(ConstructorUsingShadowDecl *Shadow,
2346 CXXConstructorDecl *BaseCtor)
2347 : Shadow(Shadow), BaseCtor(BaseCtor) {}
2349 explicit operator bool() const { return Shadow; }
2351 ConstructorUsingShadowDecl *getShadowDecl() const { return Shadow; }
2352 CXXConstructorDecl *getConstructor() const { return BaseCtor; }
2355 /// Represents a C++ constructor within a class.
2362 /// explicit X(int); // represented by a CXXConstructorDecl.
2365 class CXXConstructorDecl final
2366 : public CXXMethodDecl,
2367 private llvm::TrailingObjects<CXXConstructorDecl, InheritedConstructor,
2368 ExplicitSpecifier> {
2369 // This class stores some data in DeclContext::CXXConstructorDeclBits
2370 // to save some space. Use the provided accessors to access it.
2372 /// \name Support for base and member initializers.
2374 /// The arguments used to initialize the base or member.
2375 LazyCXXCtorInitializersPtr CtorInitializers;
2377 CXXConstructorDecl(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc,
2378 const DeclarationNameInfo &NameInfo, QualType T,
2379 TypeSourceInfo *TInfo, ExplicitSpecifier ES, bool isInline,
2380 bool isImplicitlyDeclared, ConstexprSpecKind ConstexprKind,
2381 InheritedConstructor Inherited);
2383 void anchor() override;
2385 size_t numTrailingObjects(OverloadToken<InheritedConstructor>) const {
2386 return CXXConstructorDeclBits.IsInheritingConstructor;
2388 size_t numTrailingObjects(OverloadToken<ExplicitSpecifier>) const {
2389 return CXXConstructorDeclBits.HasTrailingExplicitSpecifier;
2392 ExplicitSpecifier getExplicitSpecifierInternal() const {
2393 if (CXXConstructorDeclBits.HasTrailingExplicitSpecifier)
2394 return *getTrailingObjects<ExplicitSpecifier>();
2395 return ExplicitSpecifier(
2396 nullptr, CXXConstructorDeclBits.IsSimpleExplicit
2397 ? ExplicitSpecKind::ResolvedTrue
2398 : ExplicitSpecKind::ResolvedFalse);
2401 void setExplicitSpecifier(ExplicitSpecifier ES) {
2402 assert((!ES.getExpr() ||
2403 CXXConstructorDeclBits.HasTrailingExplicitSpecifier) &&
2404 "cannot set this explicit specifier. no trail-allocated space for "
2407 *getCanonicalDecl()->getTrailingObjects<ExplicitSpecifier>() = ES;
2409 CXXConstructorDeclBits.IsSimpleExplicit = ES.isExplicit();
2412 enum TraillingAllocKind {
2413 TAKInheritsConstructor = 1,
2414 TAKHasTailExplicit = 1 << 1,
2417 uint64_t getTraillingAllocKind() const {
2418 return numTrailingObjects(OverloadToken<InheritedConstructor>()) |
2419 (numTrailingObjects(OverloadToken<ExplicitSpecifier>()) << 1);
2423 friend class ASTDeclReader;
2424 friend class ASTDeclWriter;
2425 friend TrailingObjects;
2427 static CXXConstructorDecl *CreateDeserialized(ASTContext &C, unsigned ID,
2428 uint64_t AllocKind);
2429 static CXXConstructorDecl *
2430 Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc,
2431 const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo,
2432 ExplicitSpecifier ES, bool isInline, bool isImplicitlyDeclared,
2433 ConstexprSpecKind ConstexprKind,
2434 InheritedConstructor Inherited = InheritedConstructor());
2436 ExplicitSpecifier getExplicitSpecifier() {
2437 return getCanonicalDecl()->getExplicitSpecifierInternal();
2439 const ExplicitSpecifier getExplicitSpecifier() const {
2440 return getCanonicalDecl()->getExplicitSpecifierInternal();
2443 /// Return true if the declartion is already resolved to be explicit.
2444 bool isExplicit() const { return getExplicitSpecifier().isExplicit(); }
2446 /// Iterates through the member/base initializer list.
2447 using init_iterator = CXXCtorInitializer **;
2449 /// Iterates through the member/base initializer list.
2450 using init_const_iterator = CXXCtorInitializer *const *;
2452 using init_range = llvm::iterator_range<init_iterator>;
2453 using init_const_range = llvm::iterator_range<init_const_iterator>;
2455 init_range inits() { return init_range(init_begin(), init_end()); }
2456 init_const_range inits() const {
2457 return init_const_range(init_begin(), init_end());
2460 /// Retrieve an iterator to the first initializer.
2461 init_iterator init_begin() {
2462 const auto *ConstThis = this;
2463 return const_cast<init_iterator>(ConstThis->init_begin());
2466 /// Retrieve an iterator to the first initializer.
2467 init_const_iterator init_begin() const;
2469 /// Retrieve an iterator past the last initializer.
2470 init_iterator init_end() {
2471 return init_begin() + getNumCtorInitializers();
2474 /// Retrieve an iterator past the last initializer.
2475 init_const_iterator init_end() const {
2476 return init_begin() + getNumCtorInitializers();
2479 using init_reverse_iterator = std::reverse_iterator<init_iterator>;
2480 using init_const_reverse_iterator =
2481 std::reverse_iterator<init_const_iterator>;
2483 init_reverse_iterator init_rbegin() {
2484 return init_reverse_iterator(init_end());
2486 init_const_reverse_iterator init_rbegin() const {
2487 return init_const_reverse_iterator(init_end());
2490 init_reverse_iterator init_rend() {
2491 return init_reverse_iterator(init_begin());
2493 init_const_reverse_iterator init_rend() const {
2494 return init_const_reverse_iterator(init_begin());
2497 /// Determine the number of arguments used to initialize the member
2499 unsigned getNumCtorInitializers() const {
2500 return CXXConstructorDeclBits.NumCtorInitializers;
2503 void setNumCtorInitializers(unsigned numCtorInitializers) {
2504 CXXConstructorDeclBits.NumCtorInitializers = numCtorInitializers;
2505 // This assert added because NumCtorInitializers is stored
2506 // in CXXConstructorDeclBits as a bitfield and its width has
2507 // been shrunk from 32 bits to fit into CXXConstructorDeclBitfields.
2508 assert(CXXConstructorDeclBits.NumCtorInitializers ==
2509 numCtorInitializers && "NumCtorInitializers overflow!");
2512 void setCtorInitializers(CXXCtorInitializer **Initializers) {
2513 CtorInitializers = Initializers;
2516 /// Determine whether this constructor is a delegating constructor.
2517 bool isDelegatingConstructor() const {
2518 return (getNumCtorInitializers() == 1) &&
2519 init_begin()[0]->isDelegatingInitializer();
2522 /// When this constructor delegates to another, retrieve the target.
2523 CXXConstructorDecl *getTargetConstructor() const;
2525 /// Whether this constructor is a default
2526 /// constructor (C++ [class.ctor]p5), which can be used to
2527 /// default-initialize a class of this type.
2528 bool isDefaultConstructor() const;
2530 /// Whether this constructor is a copy constructor (C++ [class.copy]p2,
2531 /// which can be used to copy the class.
2533 /// \p TypeQuals will be set to the qualifiers on the
2534 /// argument type. For example, \p TypeQuals would be set to \c
2535 /// Qualifiers::Const for the following copy constructor:
2543 bool isCopyConstructor(unsigned &TypeQuals) const;
2545 /// Whether this constructor is a copy
2546 /// constructor (C++ [class.copy]p2, which can be used to copy the
2548 bool isCopyConstructor() const {
2549 unsigned TypeQuals = 0;
2550 return isCopyConstructor(TypeQuals);
2553 /// Determine whether this constructor is a move constructor
2554 /// (C++11 [class.copy]p3), which can be used to move values of the class.
2556 /// \param TypeQuals If this constructor is a move constructor, will be set
2557 /// to the type qualifiers on the referent of the first parameter's type.
2558 bool isMoveConstructor(unsigned &TypeQuals) const;
2560 /// Determine whether this constructor is a move constructor
2561 /// (C++11 [class.copy]p3), which can be used to move values of the class.
2562 bool isMoveConstructor() const {
2563 unsigned TypeQuals = 0;
2564 return isMoveConstructor(TypeQuals);
2567 /// Determine whether this is a copy or move constructor.
2569 /// \param TypeQuals Will be set to the type qualifiers on the reference
2570 /// parameter, if in fact this is a copy or move constructor.
2571 bool isCopyOrMoveConstructor(unsigned &TypeQuals) const;
2573 /// Determine whether this a copy or move constructor.
2574 bool isCopyOrMoveConstructor() const {
2576 return isCopyOrMoveConstructor(Quals);
2579 /// Whether this constructor is a
2580 /// converting constructor (C++ [class.conv.ctor]), which can be
2581 /// used for user-defined conversions.
2582 bool isConvertingConstructor(bool AllowExplicit) const;
2584 /// Determine whether this is a member template specialization that
2585 /// would copy the object to itself. Such constructors are never used to copy
2587 bool isSpecializationCopyingObject() const;
2589 /// Determine whether this is an implicit constructor synthesized to
2590 /// model a call to a constructor inherited from a base class.
2591 bool isInheritingConstructor() const {
2592 return CXXConstructorDeclBits.IsInheritingConstructor;
2595 /// State that this is an implicit constructor synthesized to
2596 /// model a call to a constructor inherited from a base class.
2597 void setInheritingConstructor(bool isIC = true) {
2598 CXXConstructorDeclBits.IsInheritingConstructor = isIC;
2601 /// Get the constructor that this inheriting constructor is based on.
2602 InheritedConstructor getInheritedConstructor() const {
2603 return isInheritingConstructor() ?
2604 *getTrailingObjects<InheritedConstructor>() : InheritedConstructor();
2607 CXXConstructorDecl *getCanonicalDecl() override {
2608 return cast<CXXConstructorDecl>(FunctionDecl::getCanonicalDecl());
2610 const CXXConstructorDecl *getCanonicalDecl() const {
2611 return const_cast<CXXConstructorDecl*>(this)->getCanonicalDecl();
2614 // Implement isa/cast/dyncast/etc.
2615 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2616 static bool classofKind(Kind K) { return K == CXXConstructor; }
2619 /// Represents a C++ destructor within a class.
2626 /// ~X(); // represented by a CXXDestructorDecl.
2629 class CXXDestructorDecl : public CXXMethodDecl {
2630 friend class ASTDeclReader;
2631 friend class ASTDeclWriter;
2633 // FIXME: Don't allocate storage for these except in the first declaration
2634 // of a virtual destructor.
2635 FunctionDecl *OperatorDelete = nullptr;
2636 Expr *OperatorDeleteThisArg = nullptr;
2638 CXXDestructorDecl(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc,
2639 const DeclarationNameInfo &NameInfo, QualType T,
2640 TypeSourceInfo *TInfo, bool isInline,
2641 bool isImplicitlyDeclared, ConstexprSpecKind ConstexprKind)
2642 : CXXMethodDecl(CXXDestructor, C, RD, StartLoc, NameInfo, T, TInfo,
2643 SC_None, isInline, ConstexprKind, SourceLocation()) {
2644 setImplicit(isImplicitlyDeclared);
2647 void anchor() override;
2650 static CXXDestructorDecl *Create(ASTContext &C, CXXRecordDecl *RD,
2651 SourceLocation StartLoc,
2652 const DeclarationNameInfo &NameInfo,
2653 QualType T, TypeSourceInfo *TInfo,
2654 bool isInline, bool isImplicitlyDeclared,
2655 ConstexprSpecKind ConstexprKind);
2656 static CXXDestructorDecl *CreateDeserialized(ASTContext & C, unsigned ID);
2658 void setOperatorDelete(FunctionDecl *OD, Expr *ThisArg);
2660 const FunctionDecl *getOperatorDelete() const {
2661 return getCanonicalDecl()->OperatorDelete;
2664 Expr *getOperatorDeleteThisArg() const {
2665 return getCanonicalDecl()->OperatorDeleteThisArg;
2668 CXXDestructorDecl *getCanonicalDecl() override {
2669 return cast<CXXDestructorDecl>(FunctionDecl::getCanonicalDecl());
2671 const CXXDestructorDecl *getCanonicalDecl() const {
2672 return const_cast<CXXDestructorDecl*>(this)->getCanonicalDecl();
2675 // Implement isa/cast/dyncast/etc.
2676 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2677 static bool classofKind(Kind K) { return K == CXXDestructor; }
2680 /// Represents a C++ conversion function within a class.
2687 /// operator bool();
2690 class CXXConversionDecl : public CXXMethodDecl {
2691 CXXConversionDecl(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc,
2692 const DeclarationNameInfo &NameInfo, QualType T,
2693 TypeSourceInfo *TInfo, bool isInline, ExplicitSpecifier ES,
2694 ConstexprSpecKind ConstexprKind, SourceLocation EndLocation)
2695 : CXXMethodDecl(CXXConversion, C, RD, StartLoc, NameInfo, T, TInfo,
2696 SC_None, isInline, ConstexprKind, EndLocation),
2698 void anchor() override;
2700 ExplicitSpecifier ExplicitSpec;
2702 void setExplicitSpecifier(ExplicitSpecifier ES) { ExplicitSpec = ES; }
2705 friend class ASTDeclReader;
2706 friend class ASTDeclWriter;
2708 static CXXConversionDecl *
2709 Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc,
2710 const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo,
2711 bool isInline, ExplicitSpecifier ES, ConstexprSpecKind ConstexprKind,
2712 SourceLocation EndLocation);
2713 static CXXConversionDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2715 ExplicitSpecifier getExplicitSpecifier() {
2716 return getCanonicalDecl()->ExplicitSpec;
2719 const ExplicitSpecifier getExplicitSpecifier() const {
2720 return getCanonicalDecl()->ExplicitSpec;
2723 /// Return true if the declartion is already resolved to be explicit.
2724 bool isExplicit() const { return getExplicitSpecifier().isExplicit(); }
2726 /// Returns the type that this conversion function is converting to.
2727 QualType getConversionType() const {
2728 return getType()->castAs<FunctionType>()->getReturnType();
2731 /// Determine whether this conversion function is a conversion from
2732 /// a lambda closure type to a block pointer.
2733 bool isLambdaToBlockPointerConversion() const;
2735 CXXConversionDecl *getCanonicalDecl() override {
2736 return cast<CXXConversionDecl>(FunctionDecl::getCanonicalDecl());
2738 const CXXConversionDecl *getCanonicalDecl() const {
2739 return const_cast<CXXConversionDecl*>(this)->getCanonicalDecl();
2742 // Implement isa/cast/dyncast/etc.
2743 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2744 static bool classofKind(Kind K) { return K == CXXConversion; }
2747 /// Represents a linkage specification.
2751 /// extern "C" void foo();
2753 class LinkageSpecDecl : public Decl, public DeclContext {
2754 virtual void anchor();
2755 // This class stores some data in DeclContext::LinkageSpecDeclBits to save
2756 // some space. Use the provided accessors to access it.
2758 /// Represents the language in a linkage specification.
2760 /// The values are part of the serialization ABI for
2761 /// ASTs and cannot be changed without altering that ABI. To help
2762 /// ensure a stable ABI for this, we choose the DW_LANG_ encodings
2763 /// from the dwarf standard.
2765 lang_c = llvm::dwarf::DW_LANG_C,
2766 lang_cxx = llvm::dwarf::DW_LANG_C_plus_plus,
2767 lang_cxx_11 = llvm::dwarf::DW_LANG_C_plus_plus_11,
2768 lang_cxx_14 = llvm::dwarf::DW_LANG_C_plus_plus_14
2772 /// The source location for the extern keyword.
2773 SourceLocation ExternLoc;
2775 /// The source location for the right brace (if valid).
2776 SourceLocation RBraceLoc;
2778 LinkageSpecDecl(DeclContext *DC, SourceLocation ExternLoc,
2779 SourceLocation LangLoc, LanguageIDs lang, bool HasBraces);
2782 static LinkageSpecDecl *Create(ASTContext &C, DeclContext *DC,
2783 SourceLocation ExternLoc,
2784 SourceLocation LangLoc, LanguageIDs Lang,
2786 static LinkageSpecDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2788 /// Return the language specified by this linkage specification.
2789 LanguageIDs getLanguage() const {
2790 return static_cast<LanguageIDs>(LinkageSpecDeclBits.Language);
2793 /// Set the language specified by this linkage specification.
2794 void setLanguage(LanguageIDs L) { LinkageSpecDeclBits.Language = L; }
2796 /// Determines whether this linkage specification had braces in
2797 /// its syntactic form.
2798 bool hasBraces() const {
2799 assert(!RBraceLoc.isValid() || LinkageSpecDeclBits.HasBraces);
2800 return LinkageSpecDeclBits.HasBraces;
2803 SourceLocation getExternLoc() const { return ExternLoc; }
2804 SourceLocation getRBraceLoc() const { return RBraceLoc; }
2805 void setExternLoc(SourceLocation L) { ExternLoc = L; }
2806 void setRBraceLoc(SourceLocation L) {
2808 LinkageSpecDeclBits.HasBraces = RBraceLoc.isValid();
2811 SourceLocation getEndLoc() const LLVM_READONLY {
2813 return getRBraceLoc();
2814 // No braces: get the end location of the (only) declaration in context
2816 return decls_empty() ? getLocation() : decls_begin()->getEndLoc();
2819 SourceRange getSourceRange() const override LLVM_READONLY {
2820 return SourceRange(ExternLoc, getEndLoc());
2823 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2824 static bool classofKind(Kind K) { return K == LinkageSpec; }
2826 static DeclContext *castToDeclContext(const LinkageSpecDecl *D) {
2827 return static_cast<DeclContext *>(const_cast<LinkageSpecDecl*>(D));
2830 static LinkageSpecDecl *castFromDeclContext(const DeclContext *DC) {
2831 return static_cast<LinkageSpecDecl *>(const_cast<DeclContext*>(DC));
2835 /// Represents C++ using-directive.
2839 /// using namespace std;
2842 /// \note UsingDirectiveDecl should be Decl not NamedDecl, but we provide
2843 /// artificial names for all using-directives in order to store
2844 /// them in DeclContext effectively.
2845 class UsingDirectiveDecl : public NamedDecl {
2846 /// The location of the \c using keyword.
2847 SourceLocation UsingLoc;
2849 /// The location of the \c namespace keyword.
2850 SourceLocation NamespaceLoc;
2852 /// The nested-name-specifier that precedes the namespace.
2853 NestedNameSpecifierLoc QualifierLoc;
2855 /// The namespace nominated by this using-directive.
2856 NamedDecl *NominatedNamespace;
2858 /// Enclosing context containing both using-directive and nominated
2860 DeclContext *CommonAncestor;
2862 UsingDirectiveDecl(DeclContext *DC, SourceLocation UsingLoc,
2863 SourceLocation NamespcLoc,
2864 NestedNameSpecifierLoc QualifierLoc,
2865 SourceLocation IdentLoc,
2866 NamedDecl *Nominated,
2867 DeclContext *CommonAncestor)
2868 : NamedDecl(UsingDirective, DC, IdentLoc, getName()), UsingLoc(UsingLoc),
2869 NamespaceLoc(NamespcLoc), QualifierLoc(QualifierLoc),
2870 NominatedNamespace(Nominated), CommonAncestor(CommonAncestor) {}
2872 /// Returns special DeclarationName used by using-directives.
2874 /// This is only used by DeclContext for storing UsingDirectiveDecls in
2875 /// its lookup structure.
2876 static DeclarationName getName() {
2877 return DeclarationName::getUsingDirectiveName();
2880 void anchor() override;
2883 friend class ASTDeclReader;
2885 // Friend for getUsingDirectiveName.
2886 friend class DeclContext;
2888 /// Retrieve the nested-name-specifier that qualifies the
2889 /// name of the namespace, with source-location information.
2890 NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
2892 /// Retrieve the nested-name-specifier that qualifies the
2893 /// name of the namespace.
2894 NestedNameSpecifier *getQualifier() const {
2895 return QualifierLoc.getNestedNameSpecifier();
2898 NamedDecl *getNominatedNamespaceAsWritten() { return NominatedNamespace; }
2899 const NamedDecl *getNominatedNamespaceAsWritten() const {
2900 return NominatedNamespace;
2903 /// Returns the namespace nominated by this using-directive.
2904 NamespaceDecl *getNominatedNamespace();
2906 const NamespaceDecl *getNominatedNamespace() const {
2907 return const_cast<UsingDirectiveDecl*>(this)->getNominatedNamespace();
2910 /// Returns the common ancestor context of this using-directive and
2911 /// its nominated namespace.
2912 DeclContext *getCommonAncestor() { return CommonAncestor; }
2913 const DeclContext *getCommonAncestor() const { return CommonAncestor; }
2915 /// Return the location of the \c using keyword.
2916 SourceLocation getUsingLoc() const { return UsingLoc; }
2918 // FIXME: Could omit 'Key' in name.
2919 /// Returns the location of the \c namespace keyword.
2920 SourceLocation getNamespaceKeyLocation() const { return NamespaceLoc; }
2922 /// Returns the location of this using declaration's identifier.
2923 SourceLocation getIdentLocation() const { return getLocation(); }
2925 static UsingDirectiveDecl *Create(ASTContext &C, DeclContext *DC,
2926 SourceLocation UsingLoc,
2927 SourceLocation NamespaceLoc,
2928 NestedNameSpecifierLoc QualifierLoc,
2929 SourceLocation IdentLoc,
2930 NamedDecl *Nominated,
2931 DeclContext *CommonAncestor);
2932 static UsingDirectiveDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2934 SourceRange getSourceRange() const override LLVM_READONLY {
2935 return SourceRange(UsingLoc, getLocation());
2938 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2939 static bool classofKind(Kind K) { return K == UsingDirective; }
2942 /// Represents a C++ namespace alias.
2947 /// namespace Foo = Bar;
2949 class NamespaceAliasDecl : public NamedDecl,
2950 public Redeclarable<NamespaceAliasDecl> {
2951 friend class ASTDeclReader;
2953 /// The location of the \c namespace keyword.
2954 SourceLocation NamespaceLoc;
2956 /// The location of the namespace's identifier.
2958 /// This is accessed by TargetNameLoc.
2959 SourceLocation IdentLoc;
2961 /// The nested-name-specifier that precedes the namespace.
2962 NestedNameSpecifierLoc QualifierLoc;
2964 /// The Decl that this alias points to, either a NamespaceDecl or
2965 /// a NamespaceAliasDecl.
2966 NamedDecl *Namespace;
2968 NamespaceAliasDecl(ASTContext &C, DeclContext *DC,
2969 SourceLocation NamespaceLoc, SourceLocation AliasLoc,
2970 IdentifierInfo *Alias, NestedNameSpecifierLoc QualifierLoc,
2971 SourceLocation IdentLoc, NamedDecl *Namespace)
2972 : NamedDecl(NamespaceAlias, DC, AliasLoc, Alias), redeclarable_base(C),
2973 NamespaceLoc(NamespaceLoc), IdentLoc(IdentLoc),
2974 QualifierLoc(QualifierLoc), Namespace(Namespace) {}
2976 void anchor() override;
2978 using redeclarable_base = Redeclarable<NamespaceAliasDecl>;
2980 NamespaceAliasDecl *getNextRedeclarationImpl() override;
2981 NamespaceAliasDecl *getPreviousDeclImpl() override;
2982 NamespaceAliasDecl *getMostRecentDeclImpl() override;
2985 static NamespaceAliasDecl *Create(ASTContext &C, DeclContext *DC,
2986 SourceLocation NamespaceLoc,
2987 SourceLocation AliasLoc,
2988 IdentifierInfo *Alias,
2989 NestedNameSpecifierLoc QualifierLoc,
2990 SourceLocation IdentLoc,
2991 NamedDecl *Namespace);
2993 static NamespaceAliasDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2995 using redecl_range = redeclarable_base::redecl_range;
2996 using redecl_iterator = redeclarable_base::redecl_iterator;
2998 using redeclarable_base::redecls_begin;
2999 using redeclarable_base::redecls_end;
3000 using redeclarable_base::redecls;
3001 using redeclarable_base::getPreviousDecl;
3002 using redeclarable_base::getMostRecentDecl;
3004 NamespaceAliasDecl *getCanonicalDecl() override {
3005 return getFirstDecl();
3007 const NamespaceAliasDecl *getCanonicalDecl() const {
3008 return getFirstDecl();
3011 /// Retrieve the nested-name-specifier that qualifies the
3012 /// name of the namespace, with source-location information.
3013 NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
3015 /// Retrieve the nested-name-specifier that qualifies the
3016 /// name of the namespace.
3017 NestedNameSpecifier *getQualifier() const {
3018 return QualifierLoc.getNestedNameSpecifier();
3021 /// Retrieve the namespace declaration aliased by this directive.
3022 NamespaceDecl *getNamespace() {
3023 if (auto *AD = dyn_cast<NamespaceAliasDecl>(Namespace))
3024 return AD->getNamespace();
3026 return cast<NamespaceDecl>(Namespace);
3029 const NamespaceDecl *getNamespace() const {
3030 return const_cast<NamespaceAliasDecl *>(this)->getNamespace();
3033 /// Returns the location of the alias name, i.e. 'foo' in
3034 /// "namespace foo = ns::bar;".
3035 SourceLocation getAliasLoc() const { return getLocation(); }
3037 /// Returns the location of the \c namespace keyword.
3038 SourceLocation getNamespaceLoc() const { return NamespaceLoc; }
3040 /// Returns the location of the identifier in the named namespace.
3041 SourceLocation getTargetNameLoc() const { return IdentLoc; }
3043 /// Retrieve the namespace that this alias refers to, which
3044 /// may either be a NamespaceDecl or a NamespaceAliasDecl.
3045 NamedDecl *getAliasedNamespace() const { return Namespace; }
3047 SourceRange getSourceRange() const override LLVM_READONLY {
3048 return SourceRange(NamespaceLoc, IdentLoc);
3051 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3052 static bool classofKind(Kind K) { return K == NamespaceAlias; }
3055 /// Represents a shadow declaration introduced into a scope by a
3056 /// (resolved) using declaration.
3064 /// using A::foo; // <- a UsingDecl
3065 /// // Also creates a UsingShadowDecl for A::foo() in B
3068 class UsingShadowDecl : public NamedDecl, public Redeclarable<UsingShadowDecl> {
3069 friend class UsingDecl;
3071 /// The referenced declaration.
3072 NamedDecl *Underlying = nullptr;
3074 /// The using declaration which introduced this decl or the next using
3075 /// shadow declaration contained in the aforementioned using declaration.
3076 NamedDecl *UsingOrNextShadow = nullptr;
3078 void anchor() override;
3080 using redeclarable_base = Redeclarable<UsingShadowDecl>;
3082 UsingShadowDecl *getNextRedeclarationImpl() override {
3083 return getNextRedeclaration();
3086 UsingShadowDecl *getPreviousDeclImpl() override {
3087 return getPreviousDecl();
3090 UsingShadowDecl *getMostRecentDeclImpl() override {
3091 return getMostRecentDecl();
3095 UsingShadowDecl(Kind K, ASTContext &C, DeclContext *DC, SourceLocation Loc,
3096 UsingDecl *Using, NamedDecl *Target);
3097 UsingShadowDecl(Kind K, ASTContext &C, EmptyShell);
3100 friend class ASTDeclReader;
3101 friend class ASTDeclWriter;
3103 static UsingShadowDecl *Create(ASTContext &C, DeclContext *DC,
3104 SourceLocation Loc, UsingDecl *Using,
3105 NamedDecl *Target) {
3106 return new (C, DC) UsingShadowDecl(UsingShadow, C, DC, Loc, Using, Target);
3109 static UsingShadowDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3111 using redecl_range = redeclarable_base::redecl_range;
3112 using redecl_iterator = redeclarable_base::redecl_iterator;
3114 using redeclarable_base::redecls_begin;
3115 using redeclarable_base::redecls_end;
3116 using redeclarable_base::redecls;
3117 using redeclarable_base::getPreviousDecl;
3118 using redeclarable_base::getMostRecentDecl;
3119 using redeclarable_base::isFirstDecl;
3121 UsingShadowDecl *getCanonicalDecl() override {
3122 return getFirstDecl();
3124 const UsingShadowDecl *getCanonicalDecl() const {
3125 return getFirstDecl();
3128 /// Gets the underlying declaration which has been brought into the
3130 NamedDecl *getTargetDecl() const { return Underlying; }
3132 /// Sets the underlying declaration which has been brought into the
3134 void setTargetDecl(NamedDecl *ND) {
3135 assert(ND && "Target decl is null!");
3137 // A UsingShadowDecl is never a friend or local extern declaration, even
3138 // if it is a shadow declaration for one.
3139 IdentifierNamespace =
3140 ND->getIdentifierNamespace() &
3141 ~(IDNS_OrdinaryFriend | IDNS_TagFriend | IDNS_LocalExtern);
3144 /// Gets the using declaration to which this declaration is tied.
3145 UsingDecl *getUsingDecl() const;
3147 /// The next using shadow declaration contained in the shadow decl
3148 /// chain of the using declaration which introduced this decl.
3149 UsingShadowDecl *getNextUsingShadowDecl() const {
3150 return dyn_cast_or_null<UsingShadowDecl>(UsingOrNextShadow);
3153 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3154 static bool classofKind(Kind K) {
3155 return K == Decl::UsingShadow || K == Decl::ConstructorUsingShadow;
3159 /// Represents a shadow constructor declaration introduced into a
3160 /// class by a C++11 using-declaration that names a constructor.
3164 /// struct Base { Base(int); };
3165 /// struct Derived {
3166 /// using Base::Base; // creates a UsingDecl and a ConstructorUsingShadowDecl
3169 class ConstructorUsingShadowDecl final : public UsingShadowDecl {
3170 /// If this constructor using declaration inherted the constructor
3171 /// from an indirect base class, this is the ConstructorUsingShadowDecl
3172 /// in the named direct base class from which the declaration was inherited.
3173 ConstructorUsingShadowDecl *NominatedBaseClassShadowDecl = nullptr;
3175 /// If this constructor using declaration inherted the constructor
3176 /// from an indirect base class, this is the ConstructorUsingShadowDecl
3177 /// that will be used to construct the unique direct or virtual base class
3178 /// that receives the constructor arguments.
3179 ConstructorUsingShadowDecl *ConstructedBaseClassShadowDecl = nullptr;
3181 /// \c true if the constructor ultimately named by this using shadow
3182 /// declaration is within a virtual base class subobject of the class that
3183 /// contains this declaration.
3184 unsigned IsVirtual : 1;
3186 ConstructorUsingShadowDecl(ASTContext &C, DeclContext *DC, SourceLocation Loc,
3187 UsingDecl *Using, NamedDecl *Target,
3188 bool TargetInVirtualBase)
3189 : UsingShadowDecl(ConstructorUsingShadow, C, DC, Loc, Using,
3190 Target->getUnderlyingDecl()),
3191 NominatedBaseClassShadowDecl(
3192 dyn_cast<ConstructorUsingShadowDecl>(Target)),
3193 ConstructedBaseClassShadowDecl(NominatedBaseClassShadowDecl),
3194 IsVirtual(TargetInVirtualBase) {
3195 // If we found a constructor that chains to a constructor for a virtual
3196 // base, we should directly call that virtual base constructor instead.
3197 // FIXME: This logic belongs in Sema.
3198 if (NominatedBaseClassShadowDecl &&
3199 NominatedBaseClassShadowDecl->constructsVirtualBase()) {
3200 ConstructedBaseClassShadowDecl =
3201 NominatedBaseClassShadowDecl->ConstructedBaseClassShadowDecl;
3206 ConstructorUsingShadowDecl(ASTContext &C, EmptyShell Empty)
3207 : UsingShadowDecl(ConstructorUsingShadow, C, Empty), IsVirtual(false) {}
3209 void anchor() override;
3212 friend class ASTDeclReader;
3213 friend class ASTDeclWriter;
3215 static ConstructorUsingShadowDecl *Create(ASTContext &C, DeclContext *DC,
3217 UsingDecl *Using, NamedDecl *Target,
3219 static ConstructorUsingShadowDecl *CreateDeserialized(ASTContext &C,
3222 /// Returns the parent of this using shadow declaration, which
3223 /// is the class in which this is declared.
3225 const CXXRecordDecl *getParent() const {
3226 return cast<CXXRecordDecl>(getDeclContext());
3228 CXXRecordDecl *getParent() {
3229 return cast<CXXRecordDecl>(getDeclContext());
3233 /// Get the inheriting constructor declaration for the direct base
3234 /// class from which this using shadow declaration was inherited, if there is
3235 /// one. This can be different for each redeclaration of the same shadow decl.
3236 ConstructorUsingShadowDecl *getNominatedBaseClassShadowDecl() const {
3237 return NominatedBaseClassShadowDecl;
3240 /// Get the inheriting constructor declaration for the base class
3241 /// for which we don't have an explicit initializer, if there is one.
3242 ConstructorUsingShadowDecl *getConstructedBaseClassShadowDecl() const {
3243 return ConstructedBaseClassShadowDecl;
3246 /// Get the base class that was named in the using declaration. This
3247 /// can be different for each redeclaration of this same shadow decl.
3248 CXXRecordDecl *getNominatedBaseClass() const;
3250 /// Get the base class whose constructor or constructor shadow
3251 /// declaration is passed the constructor arguments.
3252 CXXRecordDecl *getConstructedBaseClass() const {
3253 return cast<CXXRecordDecl>((ConstructedBaseClassShadowDecl
3254 ? ConstructedBaseClassShadowDecl
3256 ->getDeclContext());
3259 /// Returns \c true if the constructed base class is a virtual base
3260 /// class subobject of this declaration's class.
3261 bool constructsVirtualBase() const {
3265 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3266 static bool classofKind(Kind K) { return K == ConstructorUsingShadow; }
3269 /// Represents a C++ using-declaration.
3273 /// using someNameSpace::someIdentifier;
3275 class UsingDecl : public NamedDecl, public Mergeable<UsingDecl> {
3276 /// The source location of the 'using' keyword itself.
3277 SourceLocation UsingLocation;
3279 /// The nested-name-specifier that precedes the name.
3280 NestedNameSpecifierLoc QualifierLoc;
3282 /// Provides source/type location info for the declaration name
3283 /// embedded in the ValueDecl base class.
3284 DeclarationNameLoc DNLoc;
3286 /// The first shadow declaration of the shadow decl chain associated
3287 /// with this using declaration.
3289 /// The bool member of the pair store whether this decl has the \c typename
3291 llvm::PointerIntPair<UsingShadowDecl *, 1, bool> FirstUsingShadow;
3293 UsingDecl(DeclContext *DC, SourceLocation UL,
3294 NestedNameSpecifierLoc QualifierLoc,
3295 const DeclarationNameInfo &NameInfo, bool HasTypenameKeyword)
3296 : NamedDecl(Using, DC, NameInfo.getLoc(), NameInfo.getName()),
3297 UsingLocation(UL), QualifierLoc(QualifierLoc),
3298 DNLoc(NameInfo.getInfo()), FirstUsingShadow(nullptr, HasTypenameKeyword) {
3301 void anchor() override;
3304 friend class ASTDeclReader;
3305 friend class ASTDeclWriter;
3307 /// Return the source location of the 'using' keyword.
3308 SourceLocation getUsingLoc() const { return UsingLocation; }
3310 /// Set the source location of the 'using' keyword.
3311 void setUsingLoc(SourceLocation L) { UsingLocation = L; }
3313 /// Retrieve the nested-name-specifier that qualifies the name,
3314 /// with source-location information.
3315 NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
3317 /// Retrieve the nested-name-specifier that qualifies the name.
3318 NestedNameSpecifier *getQualifier() const {
3319 return QualifierLoc.getNestedNameSpecifier();
3322 DeclarationNameInfo getNameInfo() const {
3323 return DeclarationNameInfo(getDeclName(), getLocation(), DNLoc);
3326 /// Return true if it is a C++03 access declaration (no 'using').
3327 bool isAccessDeclaration() const { return UsingLocation.isInvalid(); }
3329 /// Return true if the using declaration has 'typename'.
3330 bool hasTypename() const { return FirstUsingShadow.getInt(); }
3332 /// Sets whether the using declaration has 'typename'.
3333 void setTypename(bool TN) { FirstUsingShadow.setInt(TN); }
3335 /// Iterates through the using shadow declarations associated with
3336 /// this using declaration.
3337 class shadow_iterator {
3338 /// The current using shadow declaration.
3339 UsingShadowDecl *Current = nullptr;
3342 using value_type = UsingShadowDecl *;
3343 using reference = UsingShadowDecl *;
3344 using pointer = UsingShadowDecl *;
3345 using iterator_category = std::forward_iterator_tag;
3346 using difference_type = std::ptrdiff_t;
3348 shadow_iterator() = default;
3349 explicit shadow_iterator(UsingShadowDecl *C) : Current(C) {}
3351 reference operator*() const { return Current; }
3352 pointer operator->() const { return Current; }
3354 shadow_iterator& operator++() {
3355 Current = Current->getNextUsingShadowDecl();
3359 shadow_iterator operator++(int) {
3360 shadow_iterator tmp(*this);
3365 friend bool operator==(shadow_iterator x, shadow_iterator y) {
3366 return x.Current == y.Current;
3368 friend bool operator!=(shadow_iterator x, shadow_iterator y) {
3369 return x.Current != y.Current;
3373 using shadow_range = llvm::iterator_range<shadow_iterator>;
3375 shadow_range shadows() const {
3376 return shadow_range(shadow_begin(), shadow_end());
3379 shadow_iterator shadow_begin() const {
3380 return shadow_iterator(FirstUsingShadow.getPointer());
3383 shadow_iterator shadow_end() const { return shadow_iterator(); }
3385 /// Return the number of shadowed declarations associated with this
3386 /// using declaration.
3387 unsigned shadow_size() const {
3388 return std::distance(shadow_begin(), shadow_end());
3391 void addShadowDecl(UsingShadowDecl *S);
3392 void removeShadowDecl(UsingShadowDecl *S);
3394 static UsingDecl *Create(ASTContext &C, DeclContext *DC,
3395 SourceLocation UsingL,
3396 NestedNameSpecifierLoc QualifierLoc,
3397 const DeclarationNameInfo &NameInfo,
3398 bool HasTypenameKeyword);
3400 static UsingDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3402 SourceRange getSourceRange() const override LLVM_READONLY;
3404 /// Retrieves the canonical declaration of this declaration.
3405 UsingDecl *getCanonicalDecl() override { return getFirstDecl(); }
3406 const UsingDecl *getCanonicalDecl() const { return getFirstDecl(); }
3408 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3409 static bool classofKind(Kind K) { return K == Using; }
3412 /// Represents a pack of using declarations that a single
3413 /// using-declarator pack-expanded into.
3416 /// template<typename ...T> struct X : T... {
3417 /// using T::operator()...;
3418 /// using T::operator T...;
3422 /// In the second case above, the UsingPackDecl will have the name
3423 /// 'operator T' (which contains an unexpanded pack), but the individual
3424 /// UsingDecls and UsingShadowDecls will have more reasonable names.
3425 class UsingPackDecl final
3426 : public NamedDecl, public Mergeable<UsingPackDecl>,
3427 private llvm::TrailingObjects<UsingPackDecl, NamedDecl *> {
3428 /// The UnresolvedUsingValueDecl or UnresolvedUsingTypenameDecl from
3429 /// which this waas instantiated.
3430 NamedDecl *InstantiatedFrom;
3432 /// The number of using-declarations created by this pack expansion.
3433 unsigned NumExpansions;
3435 UsingPackDecl(DeclContext *DC, NamedDecl *InstantiatedFrom,
3436 ArrayRef<NamedDecl *> UsingDecls)
3437 : NamedDecl(UsingPack, DC,
3438 InstantiatedFrom ? InstantiatedFrom->getLocation()
3440 InstantiatedFrom ? InstantiatedFrom->getDeclName()
3441 : DeclarationName()),
3442 InstantiatedFrom(InstantiatedFrom), NumExpansions(UsingDecls.size()) {
3443 std::uninitialized_copy(UsingDecls.begin(), UsingDecls.end(),
3444 getTrailingObjects<NamedDecl *>());
3447 void anchor() override;
3450 friend class ASTDeclReader;
3451 friend class ASTDeclWriter;
3452 friend TrailingObjects;
3454 /// Get the using declaration from which this was instantiated. This will
3455 /// always be an UnresolvedUsingValueDecl or an UnresolvedUsingTypenameDecl
3456 /// that is a pack expansion.
3457 NamedDecl *getInstantiatedFromUsingDecl() const { return InstantiatedFrom; }
3459 /// Get the set of using declarations that this pack expanded into. Note that
3460 /// some of these may still be unresolved.
3461 ArrayRef<NamedDecl *> expansions() const {
3462 return llvm::makeArrayRef(getTrailingObjects<NamedDecl *>(), NumExpansions);
3465 static UsingPackDecl *Create(ASTContext &C, DeclContext *DC,
3466 NamedDecl *InstantiatedFrom,
3467 ArrayRef<NamedDecl *> UsingDecls);
3469 static UsingPackDecl *CreateDeserialized(ASTContext &C, unsigned ID,
3470 unsigned NumExpansions);
3472 SourceRange getSourceRange() const override LLVM_READONLY {
3473 return InstantiatedFrom->getSourceRange();
3476 UsingPackDecl *getCanonicalDecl() override { return getFirstDecl(); }
3477 const UsingPackDecl *getCanonicalDecl() const { return getFirstDecl(); }
3479 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3480 static bool classofKind(Kind K) { return K == UsingPack; }
3483 /// Represents a dependent using declaration which was not marked with
3486 /// Unlike non-dependent using declarations, these *only* bring through
3487 /// non-types; otherwise they would break two-phase lookup.
3490 /// template \<class T> class A : public Base<T> {
3491 /// using Base<T>::foo;
3494 class UnresolvedUsingValueDecl : public ValueDecl,
3495 public Mergeable<UnresolvedUsingValueDecl> {
3496 /// The source location of the 'using' keyword
3497 SourceLocation UsingLocation;
3499 /// If this is a pack expansion, the location of the '...'.
3500 SourceLocation EllipsisLoc;
3502 /// The nested-name-specifier that precedes the name.
3503 NestedNameSpecifierLoc QualifierLoc;
3505 /// Provides source/type location info for the declaration name
3506 /// embedded in the ValueDecl base class.
3507 DeclarationNameLoc DNLoc;
3509 UnresolvedUsingValueDecl(DeclContext *DC, QualType Ty,
3510 SourceLocation UsingLoc,
3511 NestedNameSpecifierLoc QualifierLoc,
3512 const DeclarationNameInfo &NameInfo,
3513 SourceLocation EllipsisLoc)
3514 : ValueDecl(UnresolvedUsingValue, DC,
3515 NameInfo.getLoc(), NameInfo.getName(), Ty),
3516 UsingLocation(UsingLoc), EllipsisLoc(EllipsisLoc),
3517 QualifierLoc(QualifierLoc), DNLoc(NameInfo.getInfo()) {}
3519 void anchor() override;
3522 friend class ASTDeclReader;
3523 friend class ASTDeclWriter;
3525 /// Returns the source location of the 'using' keyword.
3526 SourceLocation getUsingLoc() const { return UsingLocation; }
3528 /// Set the source location of the 'using' keyword.
3529 void setUsingLoc(SourceLocation L) { UsingLocation = L; }
3531 /// Return true if it is a C++03 access declaration (no 'using').
3532 bool isAccessDeclaration() const { return UsingLocation.isInvalid(); }
3534 /// Retrieve the nested-name-specifier that qualifies the name,
3535 /// with source-location information.
3536 NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
3538 /// Retrieve the nested-name-specifier that qualifies the name.
3539 NestedNameSpecifier *getQualifier() const {
3540 return QualifierLoc.getNestedNameSpecifier();
3543 DeclarationNameInfo getNameInfo() const {
3544 return DeclarationNameInfo(getDeclName(), getLocation(), DNLoc);
3547 /// Determine whether this is a pack expansion.
3548 bool isPackExpansion() const {
3549 return EllipsisLoc.isValid();
3552 /// Get the location of the ellipsis if this is a pack expansion.
3553 SourceLocation getEllipsisLoc() const {
3557 static UnresolvedUsingValueDecl *
3558 Create(ASTContext &C, DeclContext *DC, SourceLocation UsingLoc,
3559 NestedNameSpecifierLoc QualifierLoc,
3560 const DeclarationNameInfo &NameInfo, SourceLocation EllipsisLoc);
3562 static UnresolvedUsingValueDecl *
3563 CreateDeserialized(ASTContext &C, unsigned ID);
3565 SourceRange getSourceRange() const override LLVM_READONLY;
3567 /// Retrieves the canonical declaration of this declaration.
3568 UnresolvedUsingValueDecl *getCanonicalDecl() override {
3569 return getFirstDecl();
3571 const UnresolvedUsingValueDecl *getCanonicalDecl() const {
3572 return getFirstDecl();
3575 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3576 static bool classofKind(Kind K) { return K == UnresolvedUsingValue; }
3579 /// Represents a dependent using declaration which was marked with
3583 /// template \<class T> class A : public Base<T> {
3584 /// using typename Base<T>::foo;
3588 /// The type associated with an unresolved using typename decl is
3589 /// currently always a typename type.
3590 class UnresolvedUsingTypenameDecl
3592 public Mergeable<UnresolvedUsingTypenameDecl> {
3593 friend class ASTDeclReader;
3595 /// The source location of the 'typename' keyword
3596 SourceLocation TypenameLocation;
3598 /// If this is a pack expansion, the location of the '...'.
3599 SourceLocation EllipsisLoc;
3601 /// The nested-name-specifier that precedes the name.
3602 NestedNameSpecifierLoc QualifierLoc;
3604 UnresolvedUsingTypenameDecl(DeclContext *DC, SourceLocation UsingLoc,
3605 SourceLocation TypenameLoc,
3606 NestedNameSpecifierLoc QualifierLoc,
3607 SourceLocation TargetNameLoc,
3608 IdentifierInfo *TargetName,
3609 SourceLocation EllipsisLoc)
3610 : TypeDecl(UnresolvedUsingTypename, DC, TargetNameLoc, TargetName,
3612 TypenameLocation(TypenameLoc), EllipsisLoc(EllipsisLoc),
3613 QualifierLoc(QualifierLoc) {}
3615 void anchor() override;
3618 /// Returns the source location of the 'using' keyword.
3619 SourceLocation getUsingLoc() const { return getBeginLoc(); }
3621 /// Returns the source location of the 'typename' keyword.
3622 SourceLocation getTypenameLoc() const { return TypenameLocation; }
3624 /// Retrieve the nested-name-specifier that qualifies the name,
3625 /// with source-location information.
3626 NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
3628 /// Retrieve the nested-name-specifier that qualifies the name.
3629 NestedNameSpecifier *getQualifier() const {
3630 return QualifierLoc.getNestedNameSpecifier();
3633 DeclarationNameInfo getNameInfo() const {
3634 return DeclarationNameInfo(getDeclName(), getLocation());
3637 /// Determine whether this is a pack expansion.
3638 bool isPackExpansion() const {
3639 return EllipsisLoc.isValid();
3642 /// Get the location of the ellipsis if this is a pack expansion.
3643 SourceLocation getEllipsisLoc() const {
3647 static UnresolvedUsingTypenameDecl *
3648 Create(ASTContext &C, DeclContext *DC, SourceLocation UsingLoc,
3649 SourceLocation TypenameLoc, NestedNameSpecifierLoc QualifierLoc,
3650 SourceLocation TargetNameLoc, DeclarationName TargetName,
3651 SourceLocation EllipsisLoc);
3653 static UnresolvedUsingTypenameDecl *
3654 CreateDeserialized(ASTContext &C, unsigned ID);
3656 /// Retrieves the canonical declaration of this declaration.
3657 UnresolvedUsingTypenameDecl *getCanonicalDecl() override {
3658 return getFirstDecl();
3660 const UnresolvedUsingTypenameDecl *getCanonicalDecl() const {
3661 return getFirstDecl();
3664 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3665 static bool classofKind(Kind K) { return K == UnresolvedUsingTypename; }
3668 /// Represents a C++11 static_assert declaration.
3669 class StaticAssertDecl : public Decl {
3670 llvm::PointerIntPair<Expr *, 1, bool> AssertExprAndFailed;
3671 StringLiteral *Message;
3672 SourceLocation RParenLoc;
3674 StaticAssertDecl(DeclContext *DC, SourceLocation StaticAssertLoc,
3675 Expr *AssertExpr, StringLiteral *Message,
3676 SourceLocation RParenLoc, bool Failed)
3677 : Decl(StaticAssert, DC, StaticAssertLoc),
3678 AssertExprAndFailed(AssertExpr, Failed), Message(Message),
3679 RParenLoc(RParenLoc) {}
3681 virtual void anchor();
3684 friend class ASTDeclReader;
3686 static StaticAssertDecl *Create(ASTContext &C, DeclContext *DC,
3687 SourceLocation StaticAssertLoc,
3688 Expr *AssertExpr, StringLiteral *Message,
3689 SourceLocation RParenLoc, bool Failed);
3690 static StaticAssertDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3692 Expr *getAssertExpr() { return AssertExprAndFailed.getPointer(); }
3693 const Expr *getAssertExpr() const { return AssertExprAndFailed.getPointer(); }
3695 StringLiteral *getMessage() { return Message; }
3696 const StringLiteral *getMessage() const { return Message; }
3698 bool isFailed() const { return AssertExprAndFailed.getInt(); }
3700 SourceLocation getRParenLoc() const { return RParenLoc; }
3702 SourceRange getSourceRange() const override LLVM_READONLY {
3703 return SourceRange(getLocation(), getRParenLoc());
3706 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3707 static bool classofKind(Kind K) { return K == StaticAssert; }
3710 /// A binding in a decomposition declaration. For instance, given:
3713 /// auto &[a, b, c] = n;
3715 /// a, b, and c are BindingDecls, whose bindings are the expressions
3716 /// x[0], x[1], and x[2] respectively, where x is the implicit
3717 /// DecompositionDecl of type 'int (&)[3]'.
3718 class BindingDecl : public ValueDecl {
3719 /// The declaration that this binding binds to part of.
3721 /// The binding represented by this declaration. References to this
3722 /// declaration are effectively equivalent to this expression (except
3723 /// that it is only evaluated once at the point of declaration of the
3725 Expr *Binding = nullptr;
3727 BindingDecl(DeclContext *DC, SourceLocation IdLoc, IdentifierInfo *Id)
3728 : ValueDecl(Decl::Binding, DC, IdLoc, Id, QualType()) {}
3730 void anchor() override;
3733 friend class ASTDeclReader;
3735 static BindingDecl *Create(ASTContext &C, DeclContext *DC,
3736 SourceLocation IdLoc, IdentifierInfo *Id);
3737 static BindingDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3739 /// Get the expression to which this declaration is bound. This may be null
3740 /// in two different cases: while parsing the initializer for the
3741 /// decomposition declaration, and when the initializer is type-dependent.
3742 Expr *getBinding() const { return Binding; }
3744 /// Get the decomposition declaration that this binding represents a
3745 /// decomposition of.
3746 ValueDecl *getDecomposedDecl() const;
3748 /// Get the variable (if any) that holds the value of evaluating the binding.
3749 /// Only present for user-defined bindings for tuple-like types.
3750 VarDecl *getHoldingVar() const;
3752 /// Set the binding for this BindingDecl, along with its declared type (which
3753 /// should be a possibly-cv-qualified form of the type of the binding, or a
3754 /// reference to such a type).
3755 void setBinding(QualType DeclaredType, Expr *Binding) {
3756 setType(DeclaredType);
3757 this->Binding = Binding;
3760 /// Set the decomposed variable for this BindingDecl.
3761 void setDecomposedDecl(ValueDecl *Decomposed) { Decomp = Decomposed; }
3763 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3764 static bool classofKind(Kind K) { return K == Decl::Binding; }
3767 /// A decomposition declaration. For instance, given:
3770 /// auto &[a, b, c] = n;
3772 /// the second line declares a DecompositionDecl of type 'int (&)[3]', and
3773 /// three BindingDecls (named a, b, and c). An instance of this class is always
3774 /// unnamed, but behaves in almost all other respects like a VarDecl.
3775 class DecompositionDecl final
3777 private llvm::TrailingObjects<DecompositionDecl, BindingDecl *> {
3778 /// The number of BindingDecl*s following this object.
3779 unsigned NumBindings;
3781 DecompositionDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
3782 SourceLocation LSquareLoc, QualType T,
3783 TypeSourceInfo *TInfo, StorageClass SC,
3784 ArrayRef<BindingDecl *> Bindings)
3785 : VarDecl(Decomposition, C, DC, StartLoc, LSquareLoc, nullptr, T, TInfo,
3787 NumBindings(Bindings.size()) {
3788 std::uninitialized_copy(Bindings.begin(), Bindings.end(),
3789 getTrailingObjects<BindingDecl *>());
3790 for (auto *B : Bindings)
3791 B->setDecomposedDecl(this);
3794 void anchor() override;
3797 friend class ASTDeclReader;
3798 friend TrailingObjects;
3800 static DecompositionDecl *Create(ASTContext &C, DeclContext *DC,
3801 SourceLocation StartLoc,
3802 SourceLocation LSquareLoc,
3803 QualType T, TypeSourceInfo *TInfo,
3805 ArrayRef<BindingDecl *> Bindings);
3806 static DecompositionDecl *CreateDeserialized(ASTContext &C, unsigned ID,
3807 unsigned NumBindings);
3809 ArrayRef<BindingDecl *> bindings() const {
3810 return llvm::makeArrayRef(getTrailingObjects<BindingDecl *>(), NumBindings);
3813 void printName(raw_ostream &os) const override;
3815 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3816 static bool classofKind(Kind K) { return K == Decomposition; }
3819 /// An instance of this class represents the declaration of a property
3820 /// member. This is a Microsoft extension to C++, first introduced in
3821 /// Visual Studio .NET 2003 as a parallel to similar features in C#
3822 /// and Managed C++.
3824 /// A property must always be a non-static class member.
3826 /// A property member superficially resembles a non-static data
3827 /// member, except preceded by a property attribute:
3828 /// __declspec(property(get=GetX, put=PutX)) int x;
3829 /// Either (but not both) of the 'get' and 'put' names may be omitted.
3831 /// A reference to a property is always an lvalue. If the lvalue
3832 /// undergoes lvalue-to-rvalue conversion, then a getter name is
3833 /// required, and that member is called with no arguments.
3834 /// If the lvalue is assigned into, then a setter name is required,
3835 /// and that member is called with one argument, the value assigned.
3836 /// Both operations are potentially overloaded. Compound assignments
3837 /// are permitted, as are the increment and decrement operators.
3839 /// The getter and putter methods are permitted to be overloaded,
3840 /// although their return and parameter types are subject to certain
3841 /// restrictions according to the type of the property.
3843 /// A property declared using an incomplete array type may
3844 /// additionally be subscripted, adding extra parameters to the getter
3845 /// and putter methods.
3846 class MSPropertyDecl : public DeclaratorDecl {
3847 IdentifierInfo *GetterId, *SetterId;
3849 MSPropertyDecl(DeclContext *DC, SourceLocation L, DeclarationName N,
3850 QualType T, TypeSourceInfo *TInfo, SourceLocation StartL,
3851 IdentifierInfo *Getter, IdentifierInfo *Setter)
3852 : DeclaratorDecl(MSProperty, DC, L, N, T, TInfo, StartL),
3853 GetterId(Getter), SetterId(Setter) {}
3855 void anchor() override;
3857 friend class ASTDeclReader;
3859 static MSPropertyDecl *Create(ASTContext &C, DeclContext *DC,
3860 SourceLocation L, DeclarationName N, QualType T,
3861 TypeSourceInfo *TInfo, SourceLocation StartL,
3862 IdentifierInfo *Getter, IdentifierInfo *Setter);
3863 static MSPropertyDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3865 static bool classof(const Decl *D) { return D->getKind() == MSProperty; }
3867 bool hasGetter() const { return GetterId != nullptr; }
3868 IdentifierInfo* getGetterId() const { return GetterId; }
3869 bool hasSetter() const { return SetterId != nullptr; }
3870 IdentifierInfo* getSetterId() const { return SetterId; }
3873 /// Insertion operator for diagnostics. This allows sending an AccessSpecifier
3874 /// into a diagnostic with <<.
3875 const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
3876 AccessSpecifier AS);
3878 const PartialDiagnostic &operator<<(const PartialDiagnostic &DB,
3879 AccessSpecifier AS);
3881 } // namespace clang
3883 #endif // LLVM_CLANG_AST_DECLCXX_H