1//===- DeclCXX.h - Classes for representing C++ declarations --*- C++ -*-=====//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10/// \file
11/// Defines the C++ Decl subclasses, other than those for templates
12/// (found in DeclTemplate.h) and friends (in DeclFriend.h).
13//
14//===----------------------------------------------------------------------===//
15
16#ifndef LLVM_CLANG_AST_DECLCXX_H
17#define LLVM_CLANG_AST_DECLCXX_H
18
19#include "clang/AST/ASTContext.h"
20#include "clang/AST/ASTUnresolvedSet.h"
21#include "clang/AST/Attr.h"
22#include "clang/AST/Decl.h"
23#include "clang/AST/DeclBase.h"
24#include "clang/AST/DeclarationName.h"
25#include "clang/AST/Expr.h"
26#include "clang/AST/ExternalASTSource.h"
27#include "clang/AST/LambdaCapture.h"
28#include "clang/AST/NestedNameSpecifier.h"
29#include "clang/AST/Redeclarable.h"
30#include "clang/AST/Stmt.h"
31#include "clang/AST/Type.h"
32#include "clang/AST/TypeLoc.h"
33#include "clang/AST/UnresolvedSet.h"
34#include "clang/Basic/LLVM.h"
35#include "clang/Basic/Lambda.h"
36#include "clang/Basic/LangOptions.h"
37#include "clang/Basic/OperatorKinds.h"
38#include "clang/Basic/SourceLocation.h"
39#include "clang/Basic/Specifiers.h"
40#include "llvm/ADT/ArrayRef.h"
41#include "llvm/ADT/DenseMap.h"
42#include "llvm/ADT/PointerIntPair.h"
43#include "llvm/ADT/PointerUnion.h"
44#include "llvm/ADT/STLExtras.h"
45#include "llvm/ADT/iterator_range.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"
50#include <cassert>
51#include <cstddef>
52#include <iterator>
53#include <memory>
54#include <vector>
55
56namespace clang {
57
58class ClassTemplateDecl;
59class ConstructorUsingShadowDecl;
60class CXXBasePath;
61class CXXBasePaths;
62class CXXConstructorDecl;
63class CXXDestructorDecl;
64class CXXFinalOverriderMap;
65class CXXIndirectPrimaryBaseSet;
66class CXXMethodDecl;
67class DiagnosticBuilder;
68class FriendDecl;
69class FunctionTemplateDecl;
70class IdentifierInfo;
71class MemberSpecializationInfo;
72class TemplateDecl;
73class TemplateParameterList;
74class UsingDecl;
75
76/// Represents any kind of function declaration, whether it is a
77/// concrete function or a function template.
78class AnyFunctionDecl {
79 NamedDecl *Function;
80
81 AnyFunctionDecl(NamedDecl *ND) : Function(ND) {}
82
83public:
84 AnyFunctionDecl(FunctionDecl *FD) : Function(FD) {}
85 AnyFunctionDecl(FunctionTemplateDecl *FTD);
86
87 /// Implicily converts any function or function template into a
88 /// named declaration.
89 operator NamedDecl *() const { return Function; }
90
91 /// Retrieve the underlying function or function template.
92 NamedDecl *get() const { return Function; }
93
94 static AnyFunctionDecl getFromNamedDecl(NamedDecl *ND) {
95 return AnyFunctionDecl(ND);
96 }
97};
98
99} // namespace clang
100
101namespace llvm {
102
103 // Provide PointerLikeTypeTraits for non-cvr pointers.
104 template<>
105 struct PointerLikeTypeTraits< ::clang::AnyFunctionDecl> {
106 static void *getAsVoidPointer(::clang::AnyFunctionDecl F) {
107 return F.get();
108 }
109
110 static ::clang::AnyFunctionDecl getFromVoidPointer(void *P) {
111 return ::clang::AnyFunctionDecl::getFromNamedDecl(
112 static_cast< ::clang::NamedDecl*>(P));
113 }
114
115 enum { NumLowBitsAvailable = 2 };
116 };
117
118} // namespace llvm
119
120namespace clang {
121
122/// Represents an access specifier followed by colon ':'.
123///
124/// An objects of this class represents sugar for the syntactic occurrence
125/// of an access specifier followed by a colon in the list of member
126/// specifiers of a C++ class definition.
127///
128/// Note that they do not represent other uses of access specifiers,
129/// such as those occurring in a list of base specifiers.
130/// Also note that this class has nothing to do with so-called
131/// "access declarations" (C++98 11.3 [class.access.dcl]).
132class AccessSpecDecl : public Decl {
133 /// The location of the ':'.
134 SourceLocation ColonLoc;
135
136 AccessSpecDecl(AccessSpecifier AS, DeclContext *DC,
137 SourceLocation ASLoc, SourceLocation ColonLoc)
138 : Decl(AccessSpec, DC, ASLoc), ColonLoc(ColonLoc) {
139 setAccess(AS);
140 }
141
142 AccessSpecDecl(EmptyShell Empty) : Decl(AccessSpec, Empty) {}
143
144 virtual void anchor();
145
146public:
147 /// The location of the access specifier.
148 SourceLocation getAccessSpecifierLoc() const { return getLocation(); }
149
150 /// Sets the location of the access specifier.
151 void setAccessSpecifierLoc(SourceLocation ASLoc) { setLocation(ASLoc); }
152
153 /// The location of the colon following the access specifier.
154 SourceLocation getColonLoc() const { return ColonLoc; }
155
156 /// Sets the location of the colon.
157 void setColonLoc(SourceLocation CLoc) { ColonLoc = CLoc; }
158
159 SourceRange getSourceRange() const override LLVM_READONLY {
160 return SourceRange(getAccessSpecifierLoc(), getColonLoc());
161 }
162
163 static AccessSpecDecl *Create(ASTContext &C, AccessSpecifier AS,
164 DeclContext *DC, SourceLocation ASLoc,
165 SourceLocation ColonLoc) {
166 return new (C, DC) AccessSpecDecl(AS, DC, ASLoc, ColonLoc);
167 }
168
169 static AccessSpecDecl *CreateDeserialized(ASTContext &C, unsigned ID);
170
171 // Implement isa/cast/dyncast/etc.
172 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
173 static bool classofKind(Kind K) { return K == AccessSpec; }
174};
175
176/// Represents a base class of a C++ class.
177///
178/// Each CXXBaseSpecifier represents a single, direct base class (or
179/// struct) of a C++ class (or struct). It specifies the type of that
180/// base class, whether it is a virtual or non-virtual base, and what
181/// level of access (public, protected, private) is used for the
182/// derivation. For example:
183///
184/// \code
185/// class A { };
186/// class B { };
187/// class C : public virtual A, protected B { };
188/// \endcode
189///
190/// In this code, C will have two CXXBaseSpecifiers, one for "public
191/// virtual A" and the other for "protected B".
192class CXXBaseSpecifier {
193 /// The source code range that covers the full base
194 /// specifier, including the "virtual" (if present) and access
195 /// specifier (if present).
196 SourceRange Range;
197
198 /// The source location of the ellipsis, if this is a pack
199 /// expansion.
200 SourceLocation EllipsisLoc;
201
202 /// Whether this is a virtual base class or not.
203 unsigned Virtual : 1;
204
205 /// Whether this is the base of a class (true) or of a struct (false).
206 ///
207 /// This determines the mapping from the access specifier as written in the
208 /// source code to the access specifier used for semantic analysis.
209 unsigned BaseOfClass : 1;
210
211 /// Access specifier as written in the source code (may be AS_none).
212 ///
213 /// The actual type of data stored here is an AccessSpecifier, but we use
214 /// "unsigned" here to work around a VC++ bug.
215 unsigned Access : 2;
216
217 /// Whether the class contains a using declaration
218 /// to inherit the named class's constructors.
219 unsigned InheritConstructors : 1;
220
221 /// The type of the base class.
222 ///
223 /// This will be a class or struct (or a typedef of such). The source code
224 /// range does not include the \c virtual or the access specifier.
225 TypeSourceInfo *BaseTypeInfo;
226
227public:
228 CXXBaseSpecifier() = default;
229 CXXBaseSpecifier(SourceRange R, bool V, bool BC, AccessSpecifier A,
230 TypeSourceInfo *TInfo, SourceLocation EllipsisLoc)
231 : Range(R), EllipsisLoc(EllipsisLoc), Virtual(V), BaseOfClass(BC),
232 Access(A), InheritConstructors(false), BaseTypeInfo(TInfo) {}
233
234 /// Retrieves the source range that contains the entire base specifier.
235 SourceRange getSourceRange() const LLVM_READONLY { return Range; }
236 SourceLocation getBeginLoc() const LLVM_READONLY { return Range.getBegin(); }
237 SourceLocation getEndLoc() const LLVM_READONLY { return Range.getEnd(); }
238
239 /// Get the location at which the base class type was written.
240 SourceLocation getBaseTypeLoc() const LLVM_READONLY {
241 return BaseTypeInfo->getTypeLoc().getBeginLoc();
242 }
243
244 /// Determines whether the base class is a virtual base class (or not).
245 bool isVirtual() const { return Virtual; }
246
247 /// Determine whether this base class is a base of a class declared
248 /// with the 'class' keyword (vs. one declared with the 'struct' keyword).
249 bool isBaseOfClass() const { return BaseOfClass; }
250
251 /// Determine whether this base specifier is a pack expansion.
252 bool isPackExpansion() const { return EllipsisLoc.isValid(); }
253
254 /// Determine whether this base class's constructors get inherited.
255 bool getInheritConstructors() const { return InheritConstructors; }
256
257 /// Set that this base class's constructors should be inherited.
258 void setInheritConstructors(bool Inherit = true) {
259 InheritConstructors = Inherit;
260 }
261
262 /// For a pack expansion, determine the location of the ellipsis.
263 SourceLocation getEllipsisLoc() const {
264 return EllipsisLoc;
265 }
266
267 /// Returns the access specifier for this base specifier.
268 ///
269 /// This is the actual base specifier as used for semantic analysis, so
270 /// the result can never be AS_none. To retrieve the access specifier as
271 /// written in the source code, use getAccessSpecifierAsWritten().
272 AccessSpecifier getAccessSpecifier() const {
273 if ((AccessSpecifier)Access == AS_none)
274 return BaseOfClass? AS_private : AS_public;
275 else
276 return (AccessSpecifier)Access;
277 }
278
279 /// Retrieves the access specifier as written in the source code
280 /// (which may mean that no access specifier was explicitly written).
281 ///
282 /// Use getAccessSpecifier() to retrieve the access specifier for use in
283 /// semantic analysis.
284 AccessSpecifier getAccessSpecifierAsWritten() const {
285 return (AccessSpecifier)Access;
286 }
287
288 /// Retrieves the type of the base class.
289 ///
290 /// This type will always be an unqualified class type.
291 QualType getType() const {
292 return BaseTypeInfo->getType().getUnqualifiedType();
293 }
294
295 /// Retrieves the type and source location of the base class.
296 TypeSourceInfo *getTypeSourceInfo() const { return BaseTypeInfo; }
297};
298
299/// Represents a C++ struct/union/class.
300class CXXRecordDecl : public RecordDecl {
301 friend class ASTDeclReader;
302 friend class ASTDeclWriter;
303 friend class ASTNodeImporter;
304 friend class ASTReader;
305 friend class ASTRecordWriter;
306 friend class ASTWriter;
307 friend class DeclContext;
308 friend class LambdaExpr;
309
310 friend void FunctionDecl::setPure(bool);
311 friend void TagDecl::startDefinition();
312
313 /// Values used in DefinitionData fields to represent special members.
314 enum SpecialMemberFlags {
315 SMF_DefaultConstructor = 0x1,
316 SMF_CopyConstructor = 0x2,
317 SMF_MoveConstructor = 0x4,
318 SMF_CopyAssignment = 0x8,
319 SMF_MoveAssignment = 0x10,
320 SMF_Destructor = 0x20,
321 SMF_All = 0x3f
322 };
323
324 struct DefinitionData {
325 /// True if this class has any user-declared constructors.
326 unsigned UserDeclaredConstructor : 1;
327
328 /// The user-declared special members which this class has.
329 unsigned UserDeclaredSpecialMembers : 6;
330
331 /// True when this class is an aggregate.
332 unsigned Aggregate : 1;
333
334 /// True when this class is a POD-type.
335 unsigned PlainOldData : 1;
336
337 /// true when this class is empty for traits purposes,
338 /// i.e. has no data members other than 0-width bit-fields, has no
339 /// virtual function/base, and doesn't inherit from a non-empty
340 /// class. Doesn't take union-ness into account.
341 unsigned Empty : 1;
342
343 /// True when this class is polymorphic, i.e., has at
344 /// least one virtual member or derives from a polymorphic class.
345 unsigned Polymorphic : 1;
346
347 /// True when this class is abstract, i.e., has at least
348 /// one pure virtual function, (that can come from a base class).
349 unsigned Abstract : 1;
350
351 /// True when this class is standard-layout, per the applicable
352 /// language rules (including DRs).
353 unsigned IsStandardLayout : 1;
354
355 /// True when this class was standard-layout under the C++11
356 /// definition.
357 ///
358 /// C++11 [class]p7. A standard-layout class is a class that:
359 /// * has no non-static data members of type non-standard-layout class (or
360 /// array of such types) or reference,
361 /// * has no virtual functions (10.3) and no virtual base classes (10.1),
362 /// * has the same access control (Clause 11) for all non-static data
363 /// members
364 /// * has no non-standard-layout base classes,
365 /// * either has no non-static data members in the most derived class and at
366 /// most one base class with non-static data members, or has no base
367 /// classes with non-static data members, and
368 /// * has no base classes of the same type as the first non-static data
369 /// member.
370 unsigned IsCXX11StandardLayout : 1;
371
372 /// True when any base class has any declared non-static data
373 /// members or bit-fields.
374 /// This is a helper bit of state used to implement IsStandardLayout more
375 /// efficiently.
376 unsigned HasBasesWithFields : 1;
377
378 /// True when any base class has any declared non-static data
379 /// members.
380 /// This is a helper bit of state used to implement IsCXX11StandardLayout
381 /// more efficiently.
382 unsigned HasBasesWithNonStaticDataMembers : 1;
383
384 /// True when there are private non-static data members.
385 unsigned HasPrivateFields : 1;
386
387 /// True when there are protected non-static data members.
388 unsigned HasProtectedFields : 1;
389
390 /// True when there are private non-static data members.
391 unsigned HasPublicFields : 1;
392
393 /// True if this class (or any subobject) has mutable fields.
394 unsigned HasMutableFields : 1;
395
396 /// True if this class (or any nested anonymous struct or union)
397 /// has variant members.
398 unsigned HasVariantMembers : 1;
399
400 /// True if there no non-field members declared by the user.
401 unsigned HasOnlyCMembers : 1;
402
403 /// True if any field has an in-class initializer, including those
404 /// within anonymous unions or structs.
405 unsigned HasInClassInitializer : 1;
406
407 /// True if any field is of reference type, and does not have an
408 /// in-class initializer.
409 ///
410 /// In this case, value-initialization of this class is illegal in C++98
411 /// even if the class has a trivial default constructor.
412 unsigned HasUninitializedReferenceMember : 1;
413
414 /// True if any non-mutable field whose type doesn't have a user-
415 /// provided default ctor also doesn't have an in-class initializer.
416 unsigned HasUninitializedFields : 1;
417
418 /// True if there are any member using-declarations that inherit
419 /// constructors from a base class.
420 unsigned HasInheritedConstructor : 1;
421
422 /// True if there are any member using-declarations named
423 /// 'operator='.
424 unsigned HasInheritedAssignment : 1;
425
426 /// These flags are \c true if a defaulted corresponding special
427 /// member can't be fully analyzed without performing overload resolution.
428 /// @{
429 unsigned NeedOverloadResolutionForCopyConstructor : 1;
430 unsigned NeedOverloadResolutionForMoveConstructor : 1;
431 unsigned NeedOverloadResolutionForMoveAssignment : 1;
432 unsigned NeedOverloadResolutionForDestructor : 1;
433 /// @}
434
435 /// These flags are \c true if an implicit defaulted corresponding
436 /// special member would be defined as deleted.
437 /// @{
438 unsigned DefaultedCopyConstructorIsDeleted : 1;
439 unsigned DefaultedMoveConstructorIsDeleted : 1;
440 unsigned DefaultedMoveAssignmentIsDeleted : 1;
441 unsigned DefaultedDestructorIsDeleted : 1;
442 /// @}
443
444 /// The trivial special members which this class has, per
445 /// C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25,
446 /// C++11 [class.dtor]p5, or would have if the member were not suppressed.
447 ///
448 /// This excludes any user-declared but not user-provided special members
449 /// which have been declared but not yet defined.
450 unsigned HasTrivialSpecialMembers : 6;
451
452 /// These bits keep track of the triviality of special functions for the
453 /// purpose of calls. Only the bits corresponding to SMF_CopyConstructor,
454 /// SMF_MoveConstructor, and SMF_Destructor are meaningful here.
455 unsigned HasTrivialSpecialMembersForCall : 6;
456
457 /// The declared special members of this class which are known to be
458 /// non-trivial.
459 ///
460 /// This excludes any user-declared but not user-provided special members
461 /// which have been declared but not yet defined, and any implicit special
462 /// members which have not yet been declared.
463 unsigned DeclaredNonTrivialSpecialMembers : 6;
464
465 /// These bits keep track of the declared special members that are
466 /// non-trivial for the purpose of calls.
467 /// Only the bits corresponding to SMF_CopyConstructor,
468 /// SMF_MoveConstructor, and SMF_Destructor are meaningful here.
469 unsigned DeclaredNonTrivialSpecialMembersForCall : 6;
470
471 /// True when this class has a destructor with no semantic effect.
472 unsigned HasIrrelevantDestructor : 1;
473
474 /// True when this class has at least one user-declared constexpr
475 /// constructor which is neither the copy nor move constructor.
476 unsigned HasConstexprNonCopyMoveConstructor : 1;
477
478 /// True if this class has a (possibly implicit) defaulted default
479 /// constructor.
480 unsigned HasDefaultedDefaultConstructor : 1;
481
482 /// True if a defaulted default constructor for this class would
483 /// be constexpr.
484 unsigned DefaultedDefaultConstructorIsConstexpr : 1;
485
486 /// True if this class has a constexpr default constructor.
487 ///
488 /// This is true for either a user-declared constexpr default constructor
489 /// or an implicitly declared constexpr default constructor.
490 unsigned HasConstexprDefaultConstructor : 1;
491
492 /// True when this class contains at least one non-static data
493 /// member or base class of non-literal or volatile type.
494 unsigned HasNonLiteralTypeFieldsOrBases : 1;
495
496 /// True when visible conversion functions are already computed
497 /// and are available.
498 unsigned ComputedVisibleConversions : 1;
499
500 /// Whether we have a C++11 user-provided default constructor (not
501 /// explicitly deleted or defaulted).
502 unsigned UserProvidedDefaultConstructor : 1;
503
504 /// The special members which have been declared for this class,
505 /// either by the user or implicitly.
506 unsigned DeclaredSpecialMembers : 6;
507
508 /// Whether an implicit copy constructor could have a const-qualified
509 /// parameter, for initializing virtual bases and for other subobjects.
510 unsigned ImplicitCopyConstructorCanHaveConstParamForVBase : 1;
511 unsigned ImplicitCopyConstructorCanHaveConstParamForNonVBase : 1;
512
513 /// Whether an implicit copy assignment operator would have a
514 /// const-qualified parameter.
515 unsigned ImplicitCopyAssignmentHasConstParam : 1;
516
517 /// Whether any declared copy constructor has a const-qualified
518 /// parameter.
519 unsigned HasDeclaredCopyConstructorWithConstParam : 1;
520
521 /// Whether any declared copy assignment operator has either a
522 /// const-qualified reference parameter or a non-reference parameter.
523 unsigned HasDeclaredCopyAssignmentWithConstParam : 1;
524
525 /// Whether this class describes a C++ lambda.
526 unsigned IsLambda : 1;
527
528 /// Whether we are currently parsing base specifiers.
529 unsigned IsParsingBaseSpecifiers : 1;
530
531 unsigned HasODRHash : 1;
532
533 /// A hash of parts of the class to help in ODR checking.
534 unsigned ODRHash = 0;
535
536 /// The number of base class specifiers in Bases.
537 unsigned NumBases = 0;
538
539 /// The number of virtual base class specifiers in VBases.
540 unsigned NumVBases = 0;
541
542 /// Base classes of this class.
543 ///
544 /// FIXME: This is wasted space for a union.
545 LazyCXXBaseSpecifiersPtr Bases;
546
547 /// direct and indirect virtual base classes of this class.
548 LazyCXXBaseSpecifiersPtr VBases;
549
550 /// The conversion functions of this C++ class (but not its
551 /// inherited conversion functions).
552 ///
553 /// Each of the entries in this overload set is a CXXConversionDecl.
554 LazyASTUnresolvedSet Conversions;
555
556 /// The conversion functions of this C++ class and all those
557 /// inherited conversion functions that are visible in this class.
558 ///
559 /// Each of the entries in this overload set is a CXXConversionDecl or a
560 /// FunctionTemplateDecl.
561 LazyASTUnresolvedSet VisibleConversions;
562
563 /// The declaration which defines this record.
564 CXXRecordDecl *Definition;
565
566 /// The first friend declaration in this class, or null if there
567 /// aren't any.
568 ///
569 /// This is actually currently stored in reverse order.
570 LazyDeclPtr FirstFriend;
571
572 DefinitionData(CXXRecordDecl *D);
573
574 /// Retrieve the set of direct base classes.
575 CXXBaseSpecifier *getBases() const {
576 if (!Bases.isOffset())
577 return Bases.get(nullptr);
578 return getBasesSlowCase();
579 }
580
581 /// Retrieve the set of virtual base classes.
582 CXXBaseSpecifier *getVBases() const {
583 if (!VBases.isOffset())
584 return VBases.get(nullptr);
585 return getVBasesSlowCase();
586 }
587
588 ArrayRef<CXXBaseSpecifier> bases() const {
589 return llvm::makeArrayRef(getBases(), NumBases);
590 }
591
592 ArrayRef<CXXBaseSpecifier> vbases() const {
593 return llvm::makeArrayRef(getVBases(), NumVBases);
594 }
595
596 private:
597 CXXBaseSpecifier *getBasesSlowCase() const;
598 CXXBaseSpecifier *getVBasesSlowCase() const;
599 };
600
601 struct DefinitionData *DefinitionData;
602
603 /// Describes a C++ closure type (generated by a lambda expression).
604 struct LambdaDefinitionData : public DefinitionData {
605 using Capture = LambdaCapture;
606
607 /// Whether this lambda is known to be dependent, even if its
608 /// context isn't dependent.
609 ///
610 /// A lambda with a non-dependent context can be dependent if it occurs
611 /// within the default argument of a function template, because the
612 /// lambda will have been created with the enclosing context as its
613 /// declaration context, rather than function. This is an unfortunate
614 /// artifact of having to parse the default arguments before.
615 unsigned Dependent : 1;
616
617 /// Whether this lambda is a generic lambda.
618 unsigned IsGenericLambda : 1;
619
620 /// The Default Capture.
621 unsigned CaptureDefault : 2;
622
623 /// The number of captures in this lambda is limited 2^NumCaptures.
624 unsigned NumCaptures : 15;
625
626 /// The number of explicit captures in this lambda.
627 unsigned NumExplicitCaptures : 13;
628
629 /// The number used to indicate this lambda expression for name
630 /// mangling in the Itanium C++ ABI.
631 unsigned ManglingNumber = 0;
632
633 /// The declaration that provides context for this lambda, if the
634 /// actual DeclContext does not suffice. This is used for lambdas that
635 /// occur within default arguments of function parameters within the class
636 /// or within a data member initializer.
637 LazyDeclPtr ContextDecl;
638
639 /// The list of captures, both explicit and implicit, for this
640 /// lambda.
641 Capture *Captures = nullptr;
642
643 /// The type of the call method.
644 TypeSourceInfo *MethodTyInfo;
645
646 LambdaDefinitionData(CXXRecordDecl *D, TypeSourceInfo *Info,
647 bool Dependent, bool IsGeneric,
648 LambdaCaptureDefault CaptureDefault)
649 : DefinitionData(D), Dependent(Dependent), IsGenericLambda(IsGeneric),
650 CaptureDefault(CaptureDefault), NumCaptures(0), NumExplicitCaptures(0),
651 MethodTyInfo(Info) {
652 IsLambda = true;
653
654 // C++1z [expr.prim.lambda]p4:
655 // This class type is not an aggregate type.
656 Aggregate = false;
657 PlainOldData = false;
658 }
659 };
660
661 struct DefinitionData *dataPtr() const {
662 // Complete the redecl chain (if necessary).
663 getMostRecentDecl();
664 return DefinitionData;
665 }
666
667 struct DefinitionData &data() const {
668 auto *DD = dataPtr();
669 assert(DD && "queried property of class with no definition");
670 return *DD;
671 }
672
673 struct LambdaDefinitionData &getLambdaData() const {
674 // No update required: a merged definition cannot change any lambda
675 // properties.
676 auto *DD = DefinitionData;
677 assert(DD && DD->IsLambda && "queried lambda property of non-lambda class");
678 return static_cast<LambdaDefinitionData&>(*DD);
679 }
680
681 /// The template or declaration that this declaration
682 /// describes or was instantiated from, respectively.
683 ///
684 /// For non-templates, this value will be null. For record
685 /// declarations that describe a class template, this will be a
686 /// pointer to a ClassTemplateDecl. For member
687 /// classes of class template specializations, this will be the
688 /// MemberSpecializationInfo referring to the member class that was
689 /// instantiated or specialized.
690 llvm::PointerUnion<ClassTemplateDecl *, MemberSpecializationInfo *>
691 TemplateOrInstantiation;
692
693 /// Called from setBases and addedMember to notify the class that a
694 /// direct or virtual base class or a member of class type has been added.
695 void addedClassSubobject(CXXRecordDecl *Base);
696
697 /// Notify the class that member has been added.
698 ///
699 /// This routine helps maintain information about the class based on which
700 /// members have been added. It will be invoked by DeclContext::addDecl()
701 /// whenever a member is added to this record.
702 void addedMember(Decl *D);
703
704 void markedVirtualFunctionPure();
705
706 /// Get the head of our list of friend declarations, possibly
707 /// deserializing the friends from an external AST source.
708 FriendDecl *getFirstFriend() const;
709
710 /// Determine whether this class has an empty base class subobject of type X
711 /// or of one of the types that might be at offset 0 within X (per the C++
712 /// "standard layout" rules).
713 bool hasSubobjectAtOffsetZeroOfEmptyBaseType(ASTContext &Ctx,
714 const CXXRecordDecl *X);
715
716protected:
717 CXXRecordDecl(Kind K, TagKind TK, const ASTContext &C, DeclContext *DC,
718 SourceLocation StartLoc, SourceLocation IdLoc,
719 IdentifierInfo *Id, CXXRecordDecl *PrevDecl);
720
721public:
722 /// Iterator that traverses the base classes of a class.
723 using base_class_iterator = CXXBaseSpecifier *;
724
725 /// Iterator that traverses the base classes of a class.
726 using base_class_const_iterator = const CXXBaseSpecifier *;
727
728 CXXRecordDecl *getCanonicalDecl() override {
729 return cast<CXXRecordDecl>(RecordDecl::getCanonicalDecl());
730 }
731
732 const CXXRecordDecl *getCanonicalDecl() const {
733 return const_cast<CXXRecordDecl*>(this)->getCanonicalDecl();
734 }
735
736 CXXRecordDecl *getPreviousDecl() {
737 return cast_or_null<CXXRecordDecl>(
738 static_cast<RecordDecl *>(this)->getPreviousDecl());
739 }
740
741 const CXXRecordDecl *getPreviousDecl() const {
742 return const_cast<CXXRecordDecl*>(this)->getPreviousDecl();
743 }
744
745 CXXRecordDecl *getMostRecentDecl() {
746 return cast<CXXRecordDecl>(
747 static_cast<RecordDecl *>(this)->getMostRecentDecl());
748 }
749
750 const CXXRecordDecl *getMostRecentDecl() const {
751 return const_cast<CXXRecordDecl*>(this)->getMostRecentDecl();
752 }
753
754 CXXRecordDecl *getMostRecentNonInjectedDecl() {
755 CXXRecordDecl *Recent =
756 static_cast<CXXRecordDecl *>(this)->getMostRecentDecl();
757 while (Recent->isInjectedClassName()) {
758 // FIXME: Does injected class name need to be in the redeclarations chain?
759 assert(Recent->getPreviousDecl());
760 Recent = Recent->getPreviousDecl();
761 }
762 return Recent;
763 }
764
765 const CXXRecordDecl *getMostRecentNonInjectedDecl() const {
766 return const_cast<CXXRecordDecl*>(this)->getMostRecentNonInjectedDecl();
767 }
768
769 CXXRecordDecl *getDefinition() const {
770 // We only need an update if we don't already know which
771 // declaration is the definition.
772 auto *DD = DefinitionData ? DefinitionData : dataPtr();
773 return DD ? DD->Definition : nullptr;
774 }
775
776 bool hasDefinition() const { return DefinitionData || dataPtr(); }
777
778 static CXXRecordDecl *Create(const ASTContext &C, TagKind TK, DeclContext *DC,
779 SourceLocation StartLoc, SourceLocation IdLoc,
780 IdentifierInfo *Id,
781 CXXRecordDecl *PrevDecl = nullptr,
782 bool DelayTypeCreation = false);
783 static CXXRecordDecl *CreateLambda(const ASTContext &C, DeclContext *DC,
784 TypeSourceInfo *Info, SourceLocation Loc,
785 bool DependentLambda, bool IsGeneric,
786 LambdaCaptureDefault CaptureDefault);
787 static CXXRecordDecl *CreateDeserialized(const ASTContext &C, unsigned ID);
788
789 bool isDynamicClass() const {
790 return data().Polymorphic || data().NumVBases != 0;
791 }
792
793 /// @returns true if class is dynamic or might be dynamic because the
794 /// definition is incomplete of dependent.
795 bool mayBeDynamicClass() const {
796 return !hasDefinition() || isDynamicClass() || hasAnyDependentBases();
797 }
798
799 /// @returns true if class is non dynamic or might be non dynamic because the
800 /// definition is incomplete of dependent.
801 bool mayBeNonDynamicClass() const {
802 return !hasDefinition() || !isDynamicClass() || hasAnyDependentBases();
803 }
804
805 void setIsParsingBaseSpecifiers() { data().IsParsingBaseSpecifiers = true; }
806
807 bool isParsingBaseSpecifiers() const {
808 return data().IsParsingBaseSpecifiers;
809 }
810
811 unsigned getODRHash() const;
812
813 /// Sets the base classes of this struct or class.
814 void setBases(CXXBaseSpecifier const * const *Bases, unsigned NumBases);
815
816 /// Retrieves the number of base classes of this class.
817 unsigned getNumBases() const { return data().NumBases; }
818
819 using base_class_range = llvm::iterator_range<base_class_iterator>;
820 using base_class_const_range =
821 llvm::iterator_range<base_class_const_iterator>;
822
823 base_class_range bases() {
824 return base_class_range(bases_begin(), bases_end());
825 }
826 base_class_const_range bases() const {
827 return base_class_const_range(bases_begin(), bases_end());
828 }
829
830 base_class_iterator bases_begin() { return data().getBases(); }
831 base_class_const_iterator bases_begin() const { return data().getBases(); }
832 base_class_iterator bases_end() { return bases_begin() + data().NumBases; }
833 base_class_const_iterator bases_end() const {
834 return bases_begin() + data().NumBases;
835 }
836
837 /// Retrieves the number of virtual base classes of this class.
838 unsigned getNumVBases() const { return data().NumVBases; }
839
840 base_class_range vbases() {
841 return base_class_range(vbases_begin(), vbases_end());
842 }
843 base_class_const_range vbases() const {
844 return base_class_const_range(vbases_begin(), vbases_end());
845 }
846
847 base_class_iterator vbases_begin() { return data().getVBases(); }
848 base_class_const_iterator vbases_begin() const { return data().getVBases(); }
849 base_class_iterator vbases_end() { return vbases_begin() + data().NumVBases; }
850 base_class_const_iterator vbases_end() const {
851 return vbases_begin() + data().NumVBases;
852 }
853
854 /// Determine whether this class has any dependent base classes which
855 /// are not the current instantiation.
856 bool hasAnyDependentBases() const;
857
858 /// Iterator access to method members. The method iterator visits
859 /// all method members of the class, including non-instance methods,
860 /// special methods, etc.
861 using method_iterator = specific_decl_iterator<CXXMethodDecl>;
862 using method_range =
863 llvm::iterator_range<specific_decl_iterator<CXXMethodDecl>>;
864
865 method_range methods() const {
866 return method_range(method_begin(), method_end());
867 }
868
869 /// Method begin iterator. Iterates in the order the methods
870 /// were declared.
871 method_iterator method_begin() const {
872 return method_iterator(decls_begin());
873 }
874
875 /// Method past-the-end iterator.
876 method_iterator method_end() const {
877 return method_iterator(decls_end());
878 }
879
880 /// Iterator access to constructor members.
881 using ctor_iterator = specific_decl_iterator<CXXConstructorDecl>;
882 using ctor_range =
883 llvm::iterator_range<specific_decl_iterator<CXXConstructorDecl>>;
884
885 ctor_range ctors() const { return ctor_range(ctor_begin(), ctor_end()); }
886
887 ctor_iterator ctor_begin() const {
888 return ctor_iterator(decls_begin());
889 }
890
891 ctor_iterator ctor_end() const {
892 return ctor_iterator(decls_end());
893 }
894
895 /// An iterator over friend declarations. All of these are defined
896 /// in DeclFriend.h.
897 class friend_iterator;
898 using friend_range = llvm::iterator_range<friend_iterator>;
899
900 friend_range friends() const;
901 friend_iterator friend_begin() const;
902 friend_iterator friend_end() const;
903 void pushFriendDecl(FriendDecl *FD);
904
905 /// Determines whether this record has any friends.
906 bool hasFriends() const {
907 return data().FirstFriend.isValid();
908 }
909
910 /// \c true if a defaulted copy constructor for this class would be
911 /// deleted.
912 bool defaultedCopyConstructorIsDeleted() const {
913 assert((!needsOverloadResolutionForCopyConstructor() ||
914 (data().DeclaredSpecialMembers & SMF_CopyConstructor)) &&
915 "this property has not yet been computed by Sema");
916 return data().DefaultedCopyConstructorIsDeleted;
917 }
918
919 /// \c true if a defaulted move constructor for this class would be
920 /// deleted.
921 bool defaultedMoveConstructorIsDeleted() const {
922 assert((!needsOverloadResolutionForMoveConstructor() ||
923 (data().DeclaredSpecialMembers & SMF_MoveConstructor)) &&
924 "this property has not yet been computed by Sema");
925 return data().DefaultedMoveConstructorIsDeleted;
926 }
927
928 /// \c true if a defaulted destructor for this class would be deleted.
929 bool defaultedDestructorIsDeleted() const {
930 assert((!needsOverloadResolutionForDestructor() ||
931 (data().DeclaredSpecialMembers & SMF_Destructor)) &&
932 "this property has not yet been computed by Sema");
933 return data().DefaultedDestructorIsDeleted;
934 }
935
936 /// \c true if we know for sure that this class has a single,
937 /// accessible, unambiguous copy constructor that is not deleted.
938 bool hasSimpleCopyConstructor() const {
939 return !hasUserDeclaredCopyConstructor() &&
940 !data().DefaultedCopyConstructorIsDeleted;
941 }
942
943 /// \c true if we know for sure that this class has a single,
944 /// accessible, unambiguous move constructor that is not deleted.
945 bool hasSimpleMoveConstructor() const {
946 return !hasUserDeclaredMoveConstructor() && hasMoveConstructor() &&
947 !data().DefaultedMoveConstructorIsDeleted;
948 }
949
950 /// \c true if we know for sure that this class has a single,
951 /// accessible, unambiguous move assignment operator that is not deleted.
952 bool hasSimpleMoveAssignment() const {
953 return !hasUserDeclaredMoveAssignment() && hasMoveAssignment() &&
954 !data().DefaultedMoveAssignmentIsDeleted;
955 }
956
957 /// \c true if we know for sure that this class has an accessible
958 /// destructor that is not deleted.
959 bool hasSimpleDestructor() const {
960 return !hasUserDeclaredDestructor() &&
961 !data().DefaultedDestructorIsDeleted;
962 }
963
964 /// Determine whether this class has any default constructors.
965 bool hasDefaultConstructor() const {
966 return (data().DeclaredSpecialMembers & SMF_DefaultConstructor) ||
967 needsImplicitDefaultConstructor();
968 }
969
970 /// Determine if we need to declare a default constructor for
971 /// this class.
972 ///
973 /// This value is used for lazy creation of default constructors.
974 bool needsImplicitDefaultConstructor() const {
975 return !data().UserDeclaredConstructor &&
976 !(data().DeclaredSpecialMembers & SMF_DefaultConstructor) &&
977 (!isLambda() || lambdaIsDefaultConstructibleAndAssignable());
978 }
979
980 /// Determine whether this class has any user-declared constructors.
981 ///
982 /// When true, a default constructor will not be implicitly declared.
983 bool hasUserDeclaredConstructor() const {
984 return data().UserDeclaredConstructor;
985 }
986
987 /// Whether this class has a user-provided default constructor
988 /// per C++11.
989 bool hasUserProvidedDefaultConstructor() const {
990 return data().UserProvidedDefaultConstructor;
991 }
992
993 /// Determine whether this class has a user-declared copy constructor.
994 ///
995 /// When false, a copy constructor will be implicitly declared.
996 bool hasUserDeclaredCopyConstructor() const {
997 return data().UserDeclaredSpecialMembers & SMF_CopyConstructor;
998 }
999
1000 /// Determine whether this class needs an implicit copy
1001 /// constructor to be lazily declared.
1002 bool needsImplicitCopyConstructor() const {
1003 return !(data().DeclaredSpecialMembers & SMF_CopyConstructor);
1004 }
1005
1006 /// Determine whether we need to eagerly declare a defaulted copy
1007 /// constructor for this class.
1008 bool needsOverloadResolutionForCopyConstructor() const {
1009 // C++17 [class.copy.ctor]p6:
1010 // If the class definition declares a move constructor or move assignment
1011 // operator, the implicitly declared copy constructor is defined as
1012 // deleted.
1013 // In MSVC mode, sometimes a declared move assignment does not delete an
1014 // implicit copy constructor, so defer this choice to Sema.
1015 if (data().UserDeclaredSpecialMembers &
1016 (SMF_MoveConstructor | SMF_MoveAssignment))
1017 return true;
1018 return data().NeedOverloadResolutionForCopyConstructor;
1019 }
1020
1021 /// Determine whether an implicit copy constructor for this type
1022 /// would have a parameter with a const-qualified reference type.
1023 bool implicitCopyConstructorHasConstParam() const {
1024 return data().ImplicitCopyConstructorCanHaveConstParamForNonVBase &&
1025 (isAbstract() ||
1026 data().ImplicitCopyConstructorCanHaveConstParamForVBase);
1027 }
1028
1029 /// Determine whether this class has a copy constructor with
1030 /// a parameter type which is a reference to a const-qualified type.
1031 bool hasCopyConstructorWithConstParam() const {
1032 return data().HasDeclaredCopyConstructorWithConstParam ||
1033 (needsImplicitCopyConstructor() &&
1034 implicitCopyConstructorHasConstParam());
1035 }
1036
1037 /// Whether this class has a user-declared move constructor or
1038 /// assignment operator.
1039 ///
1040 /// When false, a move constructor and assignment operator may be
1041 /// implicitly declared.
1042 bool hasUserDeclaredMoveOperation() const {
1043 return data().UserDeclaredSpecialMembers &
1044 (SMF_MoveConstructor | SMF_MoveAssignment);
1045 }
1046
1047 /// Determine whether this class has had a move constructor
1048 /// declared by the user.
1049 bool hasUserDeclaredMoveConstructor() const {
1050 return data().UserDeclaredSpecialMembers & SMF_MoveConstructor;
1051 }
1052
1053 /// Determine whether this class has a move constructor.
1054 bool hasMoveConstructor() const {
1055 return (data().DeclaredSpecialMembers & SMF_MoveConstructor) ||
1056 needsImplicitMoveConstructor();
1057 }
1058
1059 /// Set that we attempted to declare an implicit copy
1060 /// constructor, but overload resolution failed so we deleted it.
1061 void setImplicitCopyConstructorIsDeleted() {
1062 assert((data().DefaultedCopyConstructorIsDeleted ||
1063 needsOverloadResolutionForCopyConstructor()) &&
1064 "Copy constructor should not be deleted");
1065 data().DefaultedCopyConstructorIsDeleted = true;
1066 }
1067
1068 /// Set that we attempted to declare an implicit move
1069 /// constructor, but overload resolution failed so we deleted it.
1070 void setImplicitMoveConstructorIsDeleted() {
1071 assert((data().DefaultedMoveConstructorIsDeleted ||
1072 needsOverloadResolutionForMoveConstructor()) &&
1073 "move constructor should not be deleted");
1074 data().DefaultedMoveConstructorIsDeleted = true;
1075 }
1076
1077 /// Set that we attempted to declare an implicit destructor,
1078 /// but overload resolution failed so we deleted it.
1079 void setImplicitDestructorIsDeleted() {
1080 assert((data().DefaultedDestructorIsDeleted ||
1081 needsOverloadResolutionForDestructor()) &&
1082 "destructor should not be deleted");
1083 data().DefaultedDestructorIsDeleted = true;
1084 }
1085
1086 /// Determine whether this class should get an implicit move
1087 /// constructor or if any existing special member function inhibits this.
1088 bool needsImplicitMoveConstructor() const {
1089 return !(data().DeclaredSpecialMembers & SMF_MoveConstructor) &&
1090 !hasUserDeclaredCopyConstructor() &&
1091 !hasUserDeclaredCopyAssignment() &&
1092 !hasUserDeclaredMoveAssignment() &&
1093 !hasUserDeclaredDestructor();
1094 }
1095
1096 /// Determine whether we need to eagerly declare a defaulted move
1097 /// constructor for this class.
1098 bool needsOverloadResolutionForMoveConstructor() const {
1099 return data().NeedOverloadResolutionForMoveConstructor;
1100 }
1101
1102 /// Determine whether this class has a user-declared copy assignment
1103 /// operator.
1104 ///
1105 /// When false, a copy assignment operator will be implicitly declared.
1106 bool hasUserDeclaredCopyAssignment() const {
1107 return data().UserDeclaredSpecialMembers & SMF_CopyAssignment;
1108 }
1109
1110 /// Determine whether this class needs an implicit copy
1111 /// assignment operator to be lazily declared.
1112 bool needsImplicitCopyAssignment() const {
1113 return !(data().DeclaredSpecialMembers & SMF_CopyAssignment);
1114 }
1115
1116 /// Determine whether we need to eagerly declare a defaulted copy
1117 /// assignment operator for this class.
1118 bool needsOverloadResolutionForCopyAssignment() const {
1119 return data().HasMutableFields;
1120 }
1121
1122 /// Determine whether an implicit copy assignment operator for this
1123 /// type would have a parameter with a const-qualified reference type.
1124 bool implicitCopyAssignmentHasConstParam() const {
1125 return data().ImplicitCopyAssignmentHasConstParam;
1126 }
1127
1128 /// Determine whether this class has a copy assignment operator with
1129 /// a parameter type which is a reference to a const-qualified type or is not
1130 /// a reference.
1131 bool hasCopyAssignmentWithConstParam() const {
1132 return data().HasDeclaredCopyAssignmentWithConstParam ||
1133 (needsImplicitCopyAssignment() &&
1134 implicitCopyAssignmentHasConstParam());
1135 }
1136
1137 /// Determine whether this class has had a move assignment
1138 /// declared by the user.
1139 bool hasUserDeclaredMoveAssignment() const {
1140 return data().UserDeclaredSpecialMembers & SMF_MoveAssignment;
1141 }
1142
1143 /// Determine whether this class has a move assignment operator.
1144 bool hasMoveAssignment() const {
1145 return (data().DeclaredSpecialMembers & SMF_MoveAssignment) ||
1146 needsImplicitMoveAssignment();
1147 }
1148
1149 /// Set that we attempted to declare an implicit move assignment
1150 /// operator, but overload resolution failed so we deleted it.
1151 void setImplicitMoveAssignmentIsDeleted() {
1152 assert((data().DefaultedMoveAssignmentIsDeleted ||
1153 needsOverloadResolutionForMoveAssignment()) &&
1154 "move assignment should not be deleted");
1155 data().DefaultedMoveAssignmentIsDeleted = true;
1156 }
1157
1158 /// Determine whether this class should get an implicit move
1159 /// assignment operator or if any existing special member function inhibits
1160 /// this.
1161 bool needsImplicitMoveAssignment() const {
1162 return !(data().DeclaredSpecialMembers & SMF_MoveAssignment) &&
1163 !hasUserDeclaredCopyConstructor() &&
1164 !hasUserDeclaredCopyAssignment() &&
1165 !hasUserDeclaredMoveConstructor() &&
1166 !hasUserDeclaredDestructor() &&
1167 (!isLambda() || lambdaIsDefaultConstructibleAndAssignable());
1168 }
1169
1170 /// Determine whether we need to eagerly declare a move assignment
1171 /// operator for this class.
1172 bool needsOverloadResolutionForMoveAssignment() const {
1173 return data().NeedOverloadResolutionForMoveAssignment;
1174 }
1175
1176 /// Determine whether this class has a user-declared destructor.
1177 ///
1178 /// When false, a destructor will be implicitly declared.
1179 bool hasUserDeclaredDestructor() const {
1180 return data().UserDeclaredSpecialMembers & SMF_Destructor;
1181 }
1182
1183 /// Determine whether this class needs an implicit destructor to
1184 /// be lazily declared.
1185 bool needsImplicitDestructor() const {
1186 return !(data().DeclaredSpecialMembers & SMF_Destructor);
1187 }
1188
1189 /// Determine whether we need to eagerly declare a destructor for this
1190 /// class.
1191 bool needsOverloadResolutionForDestructor() const {
1192 return data().NeedOverloadResolutionForDestructor;
1193 }
1194
1195 /// Determine whether this class describes a lambda function object.
1196 bool isLambda() const {
1197 // An update record can't turn a non-lambda into a lambda.
1198 auto *DD = DefinitionData;
1199 return DD && DD->IsLambda;
1200 }
1201
1202 /// Determine whether this class describes a generic
1203 /// lambda function object (i.e. function call operator is
1204 /// a template).
1205 bool isGenericLambda() const;
1206
1207 /// Determine whether this lambda should have an implicit default constructor
1208 /// and copy and move assignment operators.
1209 bool lambdaIsDefaultConstructibleAndAssignable() const;
1210
1211 /// Retrieve the lambda call operator of the closure type
1212 /// if this is a closure type.
1213 CXXMethodDecl *getLambdaCallOperator() const;
1214
1215 /// Retrieve the lambda static invoker, the address of which
1216 /// is returned by the conversion operator, and the body of which
1217 /// is forwarded to the lambda call operator.
1218 CXXMethodDecl *getLambdaStaticInvoker() const;
1219
1220 /// Retrieve the generic lambda's template parameter list.
1221 /// Returns null if the class does not represent a lambda or a generic
1222 /// lambda.
1223 TemplateParameterList *getGenericLambdaTemplateParameterList() const;
1224
1225 LambdaCaptureDefault getLambdaCaptureDefault() const {
1226 assert(isLambda());
1227 return static_cast<LambdaCaptureDefault>(getLambdaData().CaptureDefault);
1228 }
1229
1230 /// For a closure type, retrieve the mapping from captured
1231 /// variables and \c this to the non-static data members that store the
1232 /// values or references of the captures.
1233 ///
1234 /// \param Captures Will be populated with the mapping from captured
1235 /// variables to the corresponding fields.
1236 ///
1237 /// \param ThisCapture Will be set to the field declaration for the
1238 /// \c this capture.
1239 ///
1240 /// \note No entries will be added for init-captures, as they do not capture
1241 /// variables.
1242 void getCaptureFields(llvm::DenseMap<const VarDecl *, FieldDecl *> &Captures,
1243 FieldDecl *&ThisCapture) const;
1244
1245 using capture_const_iterator = const LambdaCapture *;
1246 using capture_const_range = llvm::iterator_range<capture_const_iterator>;
1247
1248 capture_const_range captures() const {
1249 return capture_const_range(captures_begin(), captures_end());
1250 }
1251
1252 capture_const_iterator captures_begin() const {
1253 return isLambda() ? getLambdaData().Captures : nullptr;
1254 }
1255
1256 capture_const_iterator captures_end() const {
1257 return isLambda() ? captures_begin() + getLambdaData().NumCaptures
1258 : nullptr;
1259 }
1260
1261 using conversion_iterator = UnresolvedSetIterator;
1262
1263 conversion_iterator conversion_begin() const {
1264 return data().Conversions.get(getASTContext()).begin();
1265 }
1266
1267 conversion_iterator conversion_end() const {
1268 return data().Conversions.get(getASTContext()).end();
1269 }
1270
1271 /// Removes a conversion function from this class. The conversion
1272 /// function must currently be a member of this class. Furthermore,
1273 /// this class must currently be in the process of being defined.
1274 void removeConversion(const NamedDecl *Old);
1275
1276 /// Get all conversion functions visible in current class,
1277 /// including conversion function templates.
1278 llvm::iterator_range<conversion_iterator> getVisibleConversionFunctions();
1279
1280 /// Determine whether this class is an aggregate (C++ [dcl.init.aggr]),
1281 /// which is a class with no user-declared constructors, no private
1282 /// or protected non-static data members, no base classes, and no virtual
1283 /// functions (C++ [dcl.init.aggr]p1).
1284 bool isAggregate() const { return data().Aggregate; }
1285
1286 /// Whether this class has any in-class initializers
1287 /// for non-static data members (including those in anonymous unions or
1288 /// structs).
1289 bool hasInClassInitializer() const { return data().HasInClassInitializer; }
1290
1291 /// Whether this class or any of its subobjects has any members of
1292 /// reference type which would make value-initialization ill-formed.
1293 ///
1294 /// Per C++03 [dcl.init]p5:
1295 /// - if T is a non-union class type without a user-declared constructor,
1296 /// then every non-static data member and base-class component of T is
1297 /// value-initialized [...] A program that calls for [...]
1298 /// value-initialization of an entity of reference type is ill-formed.
1299 bool hasUninitializedReferenceMember() const {
1300 return !isUnion() && !hasUserDeclaredConstructor() &&
1301 data().HasUninitializedReferenceMember;
1302 }
1303
1304 /// Whether this class is a POD-type (C++ [class]p4)
1305 ///
1306 /// For purposes of this function a class is POD if it is an aggregate
1307 /// that has no non-static non-POD data members, no reference data
1308 /// members, no user-defined copy assignment operator and no
1309 /// user-defined destructor.
1310 ///
1311 /// Note that this is the C++ TR1 definition of POD.
1312 bool isPOD() const { return data().PlainOldData; }
1313
1314 /// True if this class is C-like, without C++-specific features, e.g.
1315 /// it contains only public fields, no bases, tag kind is not 'class', etc.
1316 bool isCLike() const;
1317
1318 /// Determine whether this is an empty class in the sense of
1319 /// (C++11 [meta.unary.prop]).
1320 ///
1321 /// The CXXRecordDecl is a class type, but not a union type,
1322 /// with no non-static data members other than bit-fields of length 0,
1323 /// no virtual member functions, no virtual base classes,
1324 /// and no base class B for which is_empty<B>::value is false.
1325 ///
1326 /// \note This does NOT include a check for union-ness.
1327 bool isEmpty() const { return data().Empty; }
1328
1329 /// Determine whether this class has direct non-static data members.
1330 bool hasDirectFields() const {
1331 auto &D = data();
1332 return D.HasPublicFields || D.HasProtectedFields || D.HasPrivateFields;
1333 }
1334
1335 /// Whether this class is polymorphic (C++ [class.virtual]),
1336 /// which means that the class contains or inherits a virtual function.
1337 bool isPolymorphic() const { return data().Polymorphic; }
1338
1339 /// Determine whether this class has a pure virtual function.
1340 ///
1341 /// The class is is abstract per (C++ [class.abstract]p2) if it declares
1342 /// a pure virtual function or inherits a pure virtual function that is
1343 /// not overridden.
1344 bool isAbstract() const { return data().Abstract; }
1345
1346 /// Determine whether this class is standard-layout per
1347 /// C++ [class]p7.
1348 bool isStandardLayout() const { return data().IsStandardLayout; }
1349
1350 /// Determine whether this class was standard-layout per
1351 /// C++11 [class]p7, specifically using the C++11 rules without any DRs.
1352 bool isCXX11StandardLayout() const { return data().IsCXX11StandardLayout; }
1353
1354 /// Determine whether this class, or any of its class subobjects,
1355 /// contains a mutable field.
1356 bool hasMutableFields() const { return data().HasMutableFields; }
1357
1358 /// Determine whether this class has any variant members.
1359 bool hasVariantMembers() const { return data().HasVariantMembers; }
1360
1361 /// Determine whether this class has a trivial default constructor
1362 /// (C++11 [class.ctor]p5).
1363 bool hasTrivialDefaultConstructor() const {
1364 return hasDefaultConstructor() &&
1365 (data().HasTrivialSpecialMembers & SMF_DefaultConstructor);
1366 }
1367
1368 /// Determine whether this class has a non-trivial default constructor
1369 /// (C++11 [class.ctor]p5).
1370 bool hasNonTrivialDefaultConstructor() const {
1371 return (data().DeclaredNonTrivialSpecialMembers & SMF_DefaultConstructor) ||
1372 (needsImplicitDefaultConstructor() &&
1373 !(data().HasTrivialSpecialMembers & SMF_DefaultConstructor));
1374 }
1375
1376 /// Determine whether this class has at least one constexpr constructor
1377 /// other than the copy or move constructors.
1378 bool hasConstexprNonCopyMoveConstructor() const {
1379 return data().HasConstexprNonCopyMoveConstructor ||
1380 (needsImplicitDefaultConstructor() &&
1381 defaultedDefaultConstructorIsConstexpr());
1382 }
1383
1384 /// Determine whether a defaulted default constructor for this class
1385 /// would be constexpr.
1386 bool defaultedDefaultConstructorIsConstexpr() const {
1387 return data().DefaultedDefaultConstructorIsConstexpr &&
1388 (!isUnion() || hasInClassInitializer() || !hasVariantMembers());
1389 }
1390
1391 /// Determine whether this class has a constexpr default constructor.
1392 bool hasConstexprDefaultConstructor() const {
1393 return data().HasConstexprDefaultConstructor ||
1394 (needsImplicitDefaultConstructor() &&
1395 defaultedDefaultConstructorIsConstexpr());
1396 }
1397
1398 /// Determine whether this class has a trivial copy constructor
1399 /// (C++ [class.copy]p6, C++11 [class.copy]p12)
1400 bool hasTrivialCopyConstructor() const {
1401 return data().HasTrivialSpecialMembers & SMF_CopyConstructor;
1402 }
1403
1404 bool hasTrivialCopyConstructorForCall() const {
1405 return data().HasTrivialSpecialMembersForCall & SMF_CopyConstructor;
1406 }
1407
1408 /// Determine whether this class has a non-trivial copy constructor
1409 /// (C++ [class.copy]p6, C++11 [class.copy]p12)
1410 bool hasNonTrivialCopyConstructor() const {
1411 return data().DeclaredNonTrivialSpecialMembers & SMF_CopyConstructor ||
1412 !hasTrivialCopyConstructor();
1413 }
1414
1415 bool hasNonTrivialCopyConstructorForCall() const {
1416 return (data().DeclaredNonTrivialSpecialMembersForCall &
1417 SMF_CopyConstructor) ||
1418 !hasTrivialCopyConstructorForCall();
1419 }
1420
1421 /// Determine whether this class has a trivial move constructor
1422 /// (C++11 [class.copy]p12)
1423 bool hasTrivialMoveConstructor() const {
1424 return hasMoveConstructor() &&
1425 (data().HasTrivialSpecialMembers & SMF_MoveConstructor);
1426 }
1427
1428 bool hasTrivialMoveConstructorForCall() const {
1429 return hasMoveConstructor() &&
1430 (data().HasTrivialSpecialMembersForCall & SMF_MoveConstructor);
1431 }
1432
1433 /// Determine whether this class has a non-trivial move constructor
1434 /// (C++11 [class.copy]p12)
1435 bool hasNonTrivialMoveConstructor() const {
1436 return (data().DeclaredNonTrivialSpecialMembers & SMF_MoveConstructor) ||
1437 (needsImplicitMoveConstructor() &&
1438 !(data().HasTrivialSpecialMembers & SMF_MoveConstructor));
1439 }
1440
1441 bool hasNonTrivialMoveConstructorForCall() const {
1442 return (data().DeclaredNonTrivialSpecialMembersForCall &
1443 SMF_MoveConstructor) ||
1444 (needsImplicitMoveConstructor() &&
1445 !(data().HasTrivialSpecialMembersForCall & SMF_MoveConstructor));
1446 }
1447
1448 /// Determine whether this class has a trivial copy assignment operator
1449 /// (C++ [class.copy]p11, C++11 [class.copy]p25)
1450 bool hasTrivialCopyAssignment() const {
1451 return data().HasTrivialSpecialMembers & SMF_CopyAssignment;
1452 }
1453
1454 /// Determine whether this class has a non-trivial copy assignment
1455 /// operator (C++ [class.copy]p11, C++11 [class.copy]p25)
1456 bool hasNonTrivialCopyAssignment() const {
1457 return data().DeclaredNonTrivialSpecialMembers & SMF_CopyAssignment ||
1458 !hasTrivialCopyAssignment();
1459 }
1460
1461 /// Determine whether this class has a trivial move assignment operator
1462 /// (C++11 [class.copy]p25)
1463 bool hasTrivialMoveAssignment() const {
1464 return hasMoveAssignment() &&
1465 (data().HasTrivialSpecialMembers & SMF_MoveAssignment);
1466 }
1467
1468 /// Determine whether this class has a non-trivial move assignment
1469 /// operator (C++11 [class.copy]p25)
1470 bool hasNonTrivialMoveAssignment() const {
1471 return (data().DeclaredNonTrivialSpecialMembers & SMF_MoveAssignment) ||
1472 (needsImplicitMoveAssignment() &&
1473 !(data().HasTrivialSpecialMembers & SMF_MoveAssignment));
1474 }
1475
1476 /// Determine whether this class has a trivial destructor
1477 /// (C++ [class.dtor]p3)
1478 bool hasTrivialDestructor() const {
1479 return data().HasTrivialSpecialMembers & SMF_Destructor;
1480 }
1481
1482 bool hasTrivialDestructorForCall() const {
1483 return data().HasTrivialSpecialMembersForCall & SMF_Destructor;
1484 }
1485
1486 /// Determine whether this class has a non-trivial destructor
1487 /// (C++ [class.dtor]p3)
1488 bool hasNonTrivialDestructor() const {
1489 return !(data().HasTrivialSpecialMembers & SMF_Destructor);
1490 }
1491
1492 bool hasNonTrivialDestructorForCall() const {
1493 return !(data().HasTrivialSpecialMembersForCall & SMF_Destructor);
1494 }
1495
1496 void setHasTrivialSpecialMemberForCall() {
1497 data().HasTrivialSpecialMembersForCall =
1498 (SMF_CopyConstructor | SMF_MoveConstructor | SMF_Destructor);
1499 }
1500
1501 /// Determine whether declaring a const variable with this type is ok
1502 /// per core issue 253.
1503 bool allowConstDefaultInit() const {
1504 return !data().HasUninitializedFields ||
1505 !(data().HasDefaultedDefaultConstructor ||
1506 needsImplicitDefaultConstructor());
1507 }
1508
1509 /// Determine whether this class has a destructor which has no
1510 /// semantic effect.
1511 ///
1512 /// Any such destructor will be trivial, public, defaulted and not deleted,
1513 /// and will call only irrelevant destructors.
1514 bool hasIrrelevantDestructor() const {
1515 return data().HasIrrelevantDestructor;
1516 }
1517
1518 /// Determine whether this class has a non-literal or/ volatile type
1519 /// non-static data member or base class.
1520 bool hasNonLiteralTypeFieldsOrBases() const {
1521 return data().HasNonLiteralTypeFieldsOrBases;
1522 }
1523
1524 /// Determine whether this class has a using-declaration that names
1525 /// a user-declared base class constructor.
1526 bool hasInheritedConstructor() const {
1527 return data().HasInheritedConstructor;
1528 }
1529
1530 /// Determine whether this class has a using-declaration that names
1531 /// a base class assignment operator.
1532 bool hasInheritedAssignment() const {
1533 return data().HasInheritedAssignment;
1534 }
1535
1536 /// Determine whether this class is considered trivially copyable per
1537 /// (C++11 [class]p6).
1538 bool isTriviallyCopyable() const;
1539
1540 /// Determine whether this class is considered trivial.
1541 ///
1542 /// C++11 [class]p6:
1543 /// "A trivial class is a class that has a trivial default constructor and
1544 /// is trivially copiable."
1545 bool isTrivial() const {
1546 return isTriviallyCopyable() && hasTrivialDefaultConstructor();
1547 }
1548
1549 /// Determine whether this class is a literal type.
1550 ///
1551 /// C++11 [basic.types]p10:
1552 /// A class type that has all the following properties:
1553 /// - it has a trivial destructor
1554 /// - every constructor call and full-expression in the
1555 /// brace-or-equal-intializers for non-static data members (if any) is
1556 /// a constant expression.
1557 /// - it is an aggregate type or has at least one constexpr constructor
1558 /// or constructor template that is not a copy or move constructor, and
1559 /// - all of its non-static data members and base classes are of literal
1560 /// types
1561 ///
1562 /// We resolve DR1361 by ignoring the second bullet. We resolve DR1452 by
1563 /// treating types with trivial default constructors as literal types.
1564 ///
1565 /// Only in C++17 and beyond, are lambdas literal types.
1566 bool isLiteral() const {
1567 return hasTrivialDestructor() &&
1568 (!isLambda() || getASTContext().getLangOpts().CPlusPlus17) &&
1569 !hasNonLiteralTypeFieldsOrBases() &&
1570 (isAggregate() || isLambda() ||
1571 hasConstexprNonCopyMoveConstructor() ||
1572 hasTrivialDefaultConstructor());
1573 }
1574
1575 /// If this record is an instantiation of a member class,
1576 /// retrieves the member class from which it was instantiated.
1577 ///
1578 /// This routine will return non-null for (non-templated) member
1579 /// classes of class templates. For example, given:
1580 ///
1581 /// \code
1582 /// template<typename T>
1583 /// struct X {
1584 /// struct A { };
1585 /// };
1586 /// \endcode
1587 ///
1588 /// The declaration for X<int>::A is a (non-templated) CXXRecordDecl
1589 /// whose parent is the class template specialization X<int>. For
1590 /// this declaration, getInstantiatedFromMemberClass() will return
1591 /// the CXXRecordDecl X<T>::A. When a complete definition of
1592 /// X<int>::A is required, it will be instantiated from the
1593 /// declaration returned by getInstantiatedFromMemberClass().
1594 CXXRecordDecl *getInstantiatedFromMemberClass() const;
1595
1596 /// If this class is an instantiation of a member class of a
1597 /// class template specialization, retrieves the member specialization
1598 /// information.
1599 MemberSpecializationInfo *getMemberSpecializationInfo() const;
1600
1601 /// Specify that this record is an instantiation of the
1602 /// member class \p RD.
1603 void setInstantiationOfMemberClass(CXXRecordDecl *RD,
1604 TemplateSpecializationKind TSK);
1605
1606 /// Retrieves the class template that is described by this
1607 /// class declaration.
1608 ///
1609 /// Every class template is represented as a ClassTemplateDecl and a
1610 /// CXXRecordDecl. The former contains template properties (such as
1611 /// the template parameter lists) while the latter contains the
1612 /// actual description of the template's
1613 /// contents. ClassTemplateDecl::getTemplatedDecl() retrieves the
1614 /// CXXRecordDecl that from a ClassTemplateDecl, while
1615 /// getDescribedClassTemplate() retrieves the ClassTemplateDecl from
1616 /// a CXXRecordDecl.
1617 ClassTemplateDecl *getDescribedClassTemplate() const;
1618
1619 void setDescribedClassTemplate(ClassTemplateDecl *Template);
1620
1621 /// Determine whether this particular class is a specialization or
1622 /// instantiation of a class template or member class of a class template,
1623 /// and how it was instantiated or specialized.
1624 TemplateSpecializationKind getTemplateSpecializationKind() const;
1625
1626 /// Set the kind of specialization or template instantiation this is.
1627 void setTemplateSpecializationKind(TemplateSpecializationKind TSK);
1628
1629 /// Retrieve the record declaration from which this record could be
1630 /// instantiated. Returns null if this class is not a template instantiation.
1631 const CXXRecordDecl *getTemplateInstantiationPattern() const;
1632
1633 CXXRecordDecl *getTemplateInstantiationPattern() {
1634 return const_cast<CXXRecordDecl *>(const_cast<const CXXRecordDecl *>(this)
1635 ->getTemplateInstantiationPattern());
1636 }
1637
1638 /// Returns the destructor decl for this class.
1639 CXXDestructorDecl *getDestructor() const;
1640
1641 /// Returns true if the class destructor, or any implicitly invoked
1642 /// destructors are marked noreturn.
1643 bool isAnyDestructorNoReturn() const;
1644
1645 /// If the class is a local class [class.local], returns
1646 /// the enclosing function declaration.
1647 const FunctionDecl *isLocalClass() const {
1648 if (const auto *RD = dyn_cast<CXXRecordDecl>(getDeclContext()))
1649 return RD->isLocalClass();
1650
1651 return dyn_cast<FunctionDecl>(getDeclContext());
1652 }
1653
1654 FunctionDecl *isLocalClass() {
1655 return const_cast<FunctionDecl*>(
1656 const_cast<const CXXRecordDecl*>(this)->isLocalClass());
1657 }
1658
1659 /// Determine whether this dependent class is a current instantiation,
1660 /// when viewed from within the given context.
1661 bool isCurrentInstantiation(const DeclContext *CurContext) const;
1662
1663 /// Determine whether this class is derived from the class \p Base.
1664 ///
1665 /// This routine only determines whether this class is derived from \p Base,
1666 /// but does not account for factors that may make a Derived -> Base class
1667 /// ill-formed, such as private/protected inheritance or multiple, ambiguous
1668 /// base class subobjects.
1669 ///
1670 /// \param Base the base class we are searching for.
1671 ///
1672 /// \returns true if this class is derived from Base, false otherwise.
1673 bool isDerivedFrom(const CXXRecordDecl *Base) const;
1674
1675 /// Determine whether this class is derived from the type \p Base.
1676 ///
1677 /// This routine only determines whether this class is derived from \p Base,
1678 /// but does not account for factors that may make a Derived -> Base class
1679 /// ill-formed, such as private/protected inheritance or multiple, ambiguous
1680 /// base class subobjects.
1681 ///
1682 /// \param Base the base class we are searching for.
1683 ///
1684 /// \param Paths will contain the paths taken from the current class to the
1685 /// given \p Base class.
1686 ///
1687 /// \returns true if this class is derived from \p Base, false otherwise.
1688 ///
1689 /// \todo add a separate parameter to configure IsDerivedFrom, rather than
1690 /// tangling input and output in \p Paths
1691 bool isDerivedFrom(const CXXRecordDecl *Base, CXXBasePaths &Paths) const;
1692
1693 /// Determine whether this class is virtually derived from
1694 /// the class \p Base.
1695 ///
1696 /// This routine only determines whether this class is virtually
1697 /// derived from \p Base, but does not account for factors that may
1698 /// make a Derived -> Base class ill-formed, such as
1699 /// private/protected inheritance or multiple, ambiguous base class
1700 /// subobjects.
1701 ///
1702 /// \param Base the base class we are searching for.
1703 ///
1704 /// \returns true if this class is virtually derived from Base,
1705 /// false otherwise.
1706 bool isVirtuallyDerivedFrom(const CXXRecordDecl *Base) const;
1707
1708 /// Determine whether this class is provably not derived from
1709 /// the type \p Base.
1710 bool isProvablyNotDerivedFrom(const CXXRecordDecl *Base) const;
1711
1712 /// Function type used by forallBases() as a callback.
1713 ///
1714 /// \param BaseDefinition the definition of the base class
1715 ///
1716 /// \returns true if this base matched the search criteria
1717 using ForallBasesCallback =
1718 llvm::function_ref<bool(const CXXRecordDecl *BaseDefinition)>;
1719
1720 /// Determines if the given callback holds for all the direct
1721 /// or indirect base classes of this type.
1722 ///
1723 /// The class itself does not count as a base class. This routine
1724 /// returns false if the class has non-computable base classes.
1725 ///
1726 /// \param BaseMatches Callback invoked for each (direct or indirect) base
1727 /// class of this type, or if \p AllowShortCircuit is true then until a call
1728 /// returns false.
1729 ///
1730 /// \param AllowShortCircuit if false, forces the callback to be called
1731 /// for every base class, even if a dependent or non-matching base was
1732 /// found.
1733 bool forallBases(ForallBasesCallback BaseMatches,
1734 bool AllowShortCircuit = true) const;
1735
1736 /// Function type used by lookupInBases() to determine whether a
1737 /// specific base class subobject matches the lookup criteria.
1738 ///
1739 /// \param Specifier the base-class specifier that describes the inheritance
1740 /// from the base class we are trying to match.
1741 ///
1742 /// \param Path the current path, from the most-derived class down to the
1743 /// base named by the \p Specifier.
1744 ///
1745 /// \returns true if this base matched the search criteria, false otherwise.
1746 using BaseMatchesCallback =
1747 llvm::function_ref<bool(const CXXBaseSpecifier *Specifier,
1748 CXXBasePath &Path)>;
1749
1750 /// Look for entities within the base classes of this C++ class,
1751 /// transitively searching all base class subobjects.
1752 ///
1753 /// This routine uses the callback function \p BaseMatches to find base
1754 /// classes meeting some search criteria, walking all base class subobjects
1755 /// and populating the given \p Paths structure with the paths through the
1756 /// inheritance hierarchy that resulted in a match. On a successful search,
1757 /// the \p Paths structure can be queried to retrieve the matching paths and
1758 /// to determine if there were any ambiguities.
1759 ///
1760 /// \param BaseMatches callback function used to determine whether a given
1761 /// base matches the user-defined search criteria.
1762 ///
1763 /// \param Paths used to record the paths from this class to its base class
1764 /// subobjects that match the search criteria.
1765 ///
1766 /// \param LookupInDependent can be set to true to extend the search to
1767 /// dependent base classes.
1768 ///
1769 /// \returns true if there exists any path from this class to a base class
1770 /// subobject that matches the search criteria.
1771 bool lookupInBases(BaseMatchesCallback BaseMatches, CXXBasePaths &Paths,
1772 bool LookupInDependent = false) const;
1773
1774 /// Base-class lookup callback that determines whether the given
1775 /// base class specifier refers to a specific class declaration.
1776 ///
1777 /// This callback can be used with \c lookupInBases() to determine whether
1778 /// a given derived class has is a base class subobject of a particular type.
1779 /// The base record pointer should refer to the canonical CXXRecordDecl of the
1780 /// base class that we are searching for.
1781 static bool FindBaseClass(const CXXBaseSpecifier *Specifier,
1782 CXXBasePath &Path, const CXXRecordDecl *BaseRecord);
1783
1784 /// Base-class lookup callback that determines whether the
1785 /// given base class specifier refers to a specific class
1786 /// declaration and describes virtual derivation.
1787 ///
1788 /// This callback can be used with \c lookupInBases() to determine
1789 /// whether a given derived class has is a virtual base class
1790 /// subobject of a particular type. The base record pointer should
1791 /// refer to the canonical CXXRecordDecl of the base class that we
1792 /// are searching for.
1793 static bool FindVirtualBaseClass(const CXXBaseSpecifier *Specifier,
1794 CXXBasePath &Path,
1795 const CXXRecordDecl *BaseRecord);
1796
1797 /// Base-class lookup callback that determines whether there exists
1798 /// a tag with the given name.
1799 ///
1800 /// This callback can be used with \c lookupInBases() to find tag members
1801 /// of the given name within a C++ class hierarchy.
1802 static bool FindTagMember(const CXXBaseSpecifier *Specifier,
1803 CXXBasePath &Path, DeclarationName Name);
1804
1805 /// Base-class lookup callback that determines whether there exists
1806 /// a member with the given name.
1807 ///
1808 /// This callback can be used with \c lookupInBases() to find members
1809 /// of the given name within a C++ class hierarchy.
1810 static bool FindOrdinaryMember(const CXXBaseSpecifier *Specifier,
1811 CXXBasePath &Path, DeclarationName Name);
1812
1813 /// Base-class lookup callback that determines whether there exists
1814 /// a member with the given name.
1815 ///
1816 /// This callback can be used with \c lookupInBases() to find members
1817 /// of the given name within a C++ class hierarchy, including dependent
1818 /// classes.
1819 static bool
1820 FindOrdinaryMemberInDependentClasses(const CXXBaseSpecifier *Specifier,
1821 CXXBasePath &Path, DeclarationName Name);
1822
1823 /// Base-class lookup callback that determines whether there exists
1824 /// an OpenMP declare reduction member with the given name.
1825 ///
1826 /// This callback can be used with \c lookupInBases() to find members
1827 /// of the given name within a C++ class hierarchy.
1828 static bool FindOMPReductionMember(const CXXBaseSpecifier *Specifier,
1829 CXXBasePath &Path, DeclarationName Name);
1830
1831 /// Base-class lookup callback that determines whether there exists
1832 /// a member with the given name that can be used in a nested-name-specifier.
1833 ///
1834 /// This callback can be used with \c lookupInBases() to find members of
1835 /// the given name within a C++ class hierarchy that can occur within
1836 /// nested-name-specifiers.
1837 static bool FindNestedNameSpecifierMember(const CXXBaseSpecifier *Specifier,
1838 CXXBasePath &Path,
1839 DeclarationName Name);
1840
1841 /// Retrieve the final overriders for each virtual member
1842 /// function in the class hierarchy where this class is the
1843 /// most-derived class in the class hierarchy.
1844 void getFinalOverriders(CXXFinalOverriderMap &FinaOverriders) const;
1845
1846 /// Get the indirect primary bases for this class.
1847 void getIndirectPrimaryBases(CXXIndirectPrimaryBaseSet& Bases) const;
1848
1849 /// Performs an imprecise lookup of a dependent name in this class.
1850 ///
1851 /// This function does not follow strict semantic rules and should be used
1852 /// only when lookup rules can be relaxed, e.g. indexing.
1853 std::vector<const NamedDecl *>
1854 lookupDependentName(const DeclarationName &Name,
1855 llvm::function_ref<bool(const NamedDecl *ND)> Filter);
1856
1857 /// Renders and displays an inheritance diagram
1858 /// for this C++ class and all of its base classes (transitively) using
1859 /// GraphViz.
1860 void viewInheritance(ASTContext& Context) const;
1861
1862 /// Calculates the access of a decl that is reached
1863 /// along a path.
1864 static AccessSpecifier MergeAccess(AccessSpecifier PathAccess,
1865 AccessSpecifier DeclAccess) {
1866 assert(DeclAccess != AS_none);
1867 if (DeclAccess == AS_private) return AS_none;
1868 return (PathAccess > DeclAccess ? PathAccess : DeclAccess);
1869 }
1870
1871 /// Indicates that the declaration of a defaulted or deleted special
1872 /// member function is now complete.
1873 void finishedDefaultedOrDeletedMember(CXXMethodDecl *MD);
1874
1875 void setTrivialForCallFlags(CXXMethodDecl *MD);
1876
1877 /// Indicates that the definition of this class is now complete.
1878 void completeDefinition() override;
1879
1880 /// Indicates that the definition of this class is now complete,
1881 /// and provides a final overrider map to help determine
1882 ///
1883 /// \param FinalOverriders The final overrider map for this class, which can
1884 /// be provided as an optimization for abstract-class checking. If NULL,
1885 /// final overriders will be computed if they are needed to complete the
1886 /// definition.
1887 void completeDefinition(CXXFinalOverriderMap *FinalOverriders);
1888
1889 /// Determine whether this class may end up being abstract, even though
1890 /// it is not yet known to be abstract.
1891 ///
1892 /// \returns true if this class is not known to be abstract but has any
1893 /// base classes that are abstract. In this case, \c completeDefinition()
1894 /// will need to compute final overriders to determine whether the class is
1895 /// actually abstract.
1896 bool mayBeAbstract() const;
1897
1898 /// If this is the closure type of a lambda expression, retrieve the
1899 /// number to be used for name mangling in the Itanium C++ ABI.
1900 ///
1901 /// Zero indicates that this closure type has internal linkage, so the
1902 /// mangling number does not matter, while a non-zero value indicates which
1903 /// lambda expression this is in this particular context.
1904 unsigned getLambdaManglingNumber() const {
1905 assert(isLambda() && "Not a lambda closure type!");
1906 return getLambdaData().ManglingNumber;
1907 }
1908
1909 /// Retrieve the declaration that provides additional context for a
1910 /// lambda, when the normal declaration context is not specific enough.
1911 ///
1912 /// Certain contexts (default arguments of in-class function parameters and
1913 /// the initializers of data members) have separate name mangling rules for
1914 /// lambdas within the Itanium C++ ABI. For these cases, this routine provides
1915 /// the declaration in which the lambda occurs, e.g., the function parameter
1916 /// or the non-static data member. Otherwise, it returns NULL to imply that
1917 /// the declaration context suffices.
1918 Decl *getLambdaContextDecl() const;
1919
1920 /// Set the mangling number and context declaration for a lambda
1921 /// class.
1922 void setLambdaMangling(unsigned ManglingNumber, Decl *ContextDecl) {
1923 getLambdaData().ManglingNumber = ManglingNumber;
1924 getLambdaData().ContextDecl = ContextDecl;
1925 }
1926
1927 /// Returns the inheritance model used for this record.
1928 MSInheritanceAttr::Spelling getMSInheritanceModel() const;
1929
1930 /// Calculate what the inheritance model would be for this class.
1931 MSInheritanceAttr::Spelling calculateInheritanceModel() const;
1932
1933 /// In the Microsoft C++ ABI, use zero for the field offset of a null data
1934 /// member pointer if we can guarantee that zero is not a valid field offset,
1935 /// or if the member pointer has multiple fields. Polymorphic classes have a
1936 /// vfptr at offset zero, so we can use zero for null. If there are multiple
1937 /// fields, we can use zero even if it is a valid field offset because
1938 /// null-ness testing will check the other fields.
1939 bool nullFieldOffsetIsZero() const {
1940 return !MSInheritanceAttr::hasOnlyOneField(/*IsMemberFunction=*/false,
1941 getMSInheritanceModel()) ||
1942 (hasDefinition() && isPolymorphic());
1943 }
1944
1945 /// Controls when vtordisps will be emitted if this record is used as a
1946 /// virtual base.
1947 MSVtorDispAttr::Mode getMSVtorDispMode() const;
1948
1949 /// Determine whether this lambda expression was known to be dependent
1950 /// at the time it was created, even if its context does not appear to be
1951 /// dependent.
1952 ///
1953 /// This flag is a workaround for an issue with parsing, where default
1954 /// arguments are parsed before their enclosing function declarations have
1955 /// been created. This means that any lambda expressions within those
1956 /// default arguments will have as their DeclContext the context enclosing
1957 /// the function declaration, which may be non-dependent even when the
1958 /// function declaration itself is dependent. This flag indicates when we
1959 /// know that the lambda is dependent despite that.
1960 bool isDependentLambda() const {
1961 return isLambda() && getLambdaData().Dependent;
1962 }
1963
1964 TypeSourceInfo *getLambdaTypeInfo() const {
1965 return getLambdaData().MethodTyInfo;
1966 }
1967
1968 // Determine whether this type is an Interface Like type for
1969 // __interface inheritance purposes.
1970 bool isInterfaceLike() const;
1971
1972 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1973 static bool classofKind(Kind K) {
1974 return K >= firstCXXRecord && K <= lastCXXRecord;
1975 }
1976};
1977
1978/// Represents a C++ deduction guide declaration.
1979///
1980/// \code
1981/// template<typename T> struct A { A(); A(T); };
1982/// A() -> A<int>;
1983/// \endcode
1984///
1985/// In this example, there will be an explicit deduction guide from the
1986/// second line, and implicit deduction guide templates synthesized from
1987/// the constructors of \c A.
1988class CXXDeductionGuideDecl : public FunctionDecl {
1989 void anchor() override;
1990
1991private:
1992 CXXDeductionGuideDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
1993 bool IsExplicit, const DeclarationNameInfo &NameInfo,
1994 QualType T, TypeSourceInfo *TInfo,
1995 SourceLocation EndLocation)
1996 : FunctionDecl(CXXDeductionGuide, C, DC, StartLoc, NameInfo, T, TInfo,
1997 SC_None, false, false) {
1998 if (EndLocation.isValid())
1999 setRangeEnd(EndLocation);
2000 setExplicitSpecified(IsExplicit);
2001 setIsCopyDeductionCandidate(false);
2002 }
2003
2004public:
2005 friend class ASTDeclReader;
2006 friend class ASTDeclWriter;
2007
2008 static CXXDeductionGuideDecl *Create(ASTContext &C, DeclContext *DC,
2009 SourceLocation StartLoc, bool IsExplicit,
2010 const DeclarationNameInfo &NameInfo,
2011 QualType T, TypeSourceInfo *TInfo,
2012 SourceLocation EndLocation);
2013
2014 static CXXDeductionGuideDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2015
2016 /// Whether this deduction guide is explicit.
2017 bool isExplicit() const { return isExplicitSpecified(); }
2018
2019 /// Get the template for which this guide performs deduction.
2020 TemplateDecl *getDeducedTemplate() const {
2021 return getDeclName().getCXXDeductionGuideTemplate();
2022 }
2023
2024 void setIsCopyDeductionCandidate(bool isCDC = true) {
2025 FunctionDeclBits.IsCopyDeductionCandidate = isCDC;
2026 }
2027
2028 bool isCopyDeductionCandidate() const {
2029 return FunctionDeclBits.IsCopyDeductionCandidate;
2030 }
2031
2032 // Implement isa/cast/dyncast/etc.
2033 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2034 static bool classofKind(Kind K) { return K == CXXDeductionGuide; }
2035};
2036
2037/// Represents a static or instance method of a struct/union/class.
2038///
2039/// In the terminology of the C++ Standard, these are the (static and
2040/// non-static) member functions, whether virtual or not.
2041class CXXMethodDecl : public FunctionDecl {
2042 void anchor() override;
2043
2044protected:
2045 CXXMethodDecl(Kind DK, ASTContext &C, CXXRecordDecl *RD,
2046 SourceLocation StartLoc, const DeclarationNameInfo &NameInfo,
2047 QualType T, TypeSourceInfo *TInfo,
2048 StorageClass SC, bool isInline,
2049 bool isConstexpr, SourceLocation EndLocation)
2050 : FunctionDecl(DK, C, RD, StartLoc, NameInfo, T, TInfo,
2051 SC, isInline, isConstexpr) {
2052 if (EndLocation.isValid())
2053 setRangeEnd(EndLocation);
2054 }
2055
2056public:
2057 static CXXMethodDecl *Create(ASTContext &C, CXXRecordDecl *RD,
2058 SourceLocation StartLoc,
2059 const DeclarationNameInfo &NameInfo,
2060 QualType T, TypeSourceInfo *TInfo,
2061 StorageClass SC,
2062 bool isInline,
2063 bool isConstexpr,
2064 SourceLocation EndLocation);
2065
2066 static CXXMethodDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2067
2068 bool isStatic() const;
2069 bool isInstance() const { return !isStatic(); }
2070
2071 /// Returns true if the given operator is implicitly static in a record
2072 /// context.
2073 static bool isStaticOverloadedOperator(OverloadedOperatorKind OOK) {
2074 // [class.free]p1:
2075 // Any allocation function for a class T is a static member
2076 // (even if not explicitly declared static).
2077 // [class.free]p6 Any deallocation function for a class X is a static member
2078 // (even if not explicitly declared static).
2079 return OOK == OO_New || OOK == OO_Array_New || OOK == OO_Delete ||
2080 OOK == OO_Array_Delete;
2081 }
2082
2083 bool isConst() const { return getType()->castAs<FunctionType>()->isConst(); }
2084 bool isVolatile() const { return getType()->castAs<FunctionType>()->isVolatile(); }
2085
2086 bool isVirtual() const {
2087 CXXMethodDecl *CD = const_cast<CXXMethodDecl*>(this)->getCanonicalDecl();
2088
2089 // Member function is virtual if it is marked explicitly so, or if it is
2090 // declared in __interface -- then it is automatically pure virtual.
2091 if (CD->isVirtualAsWritten() || CD->isPure())
2092 return true;
2093
2094 return CD->size_overridden_methods() != 0;
2095 }
2096
2097 /// If it's possible to devirtualize a call to this method, return the called
2098 /// function. Otherwise, return null.
2099
2100 /// \param Base The object on which this virtual function is called.
2101 /// \param IsAppleKext True if we are compiling for Apple kext.
2102 CXXMethodDecl *getDevirtualizedMethod(const Expr *Base, bool IsAppleKext);
2103
2104 const CXXMethodDecl *getDevirtualizedMethod(const Expr *Base,
2105 bool IsAppleKext) const {
2106 return const_cast<CXXMethodDecl *>(this)->getDevirtualizedMethod(
2107 Base, IsAppleKext);
2108 }
2109
2110 /// Determine whether this is a usual deallocation function (C++
2111 /// [basic.stc.dynamic.deallocation]p2), which is an overloaded delete or
2112 /// delete[] operator with a particular signature. Populates \p PreventedBy
2113 /// with the declarations of the functions of the same kind if they were the
2114 /// reason for this function returning false. This is used by
2115 /// Sema::isUsualDeallocationFunction to reconsider the answer based on the
2116 /// context.
2117 bool isUsualDeallocationFunction(
2118 SmallVectorImpl<const FunctionDecl *> &PreventedBy) const;
2119
2120 /// Determine whether this is a copy-assignment operator, regardless
2121 /// of whether it was declared implicitly or explicitly.
2122 bool isCopyAssignmentOperator() const;
2123
2124 /// Determine whether this is a move assignment operator.
2125 bool isMoveAssignmentOperator() const;
2126
2127 CXXMethodDecl *getCanonicalDecl() override {
2128 return cast<CXXMethodDecl>(FunctionDecl::getCanonicalDecl());
2129 }
2130 const CXXMethodDecl *getCanonicalDecl() const {
2131 return const_cast<CXXMethodDecl*>(this)->getCanonicalDecl();
2132 }
2133
2134 CXXMethodDecl *getMostRecentDecl() {
2135 return cast<CXXMethodDecl>(
2136 static_cast<FunctionDecl *>(this)->getMostRecentDecl());
2137 }
2138 const CXXMethodDecl *getMostRecentDecl() const {
2139 return const_cast<CXXMethodDecl*>(this)->getMostRecentDecl();
2140 }
2141
2142 /// True if this method is user-declared and was not
2143 /// deleted or defaulted on its first declaration.
2144 bool isUserProvided() const {
2145 auto *DeclAsWritten = this;
2146 if (auto *Pattern = getTemplateInstantiationPattern())
2147 DeclAsWritten = cast<CXXMethodDecl>(Pattern);
2148 return !(DeclAsWritten->isDeleted() ||
2149 DeclAsWritten->getCanonicalDecl()->isDefaulted());
2150 }
2151
2152 void addOverriddenMethod(const CXXMethodDecl *MD);
2153
2154 using method_iterator = const CXXMethodDecl *const *;
2155
2156 method_iterator begin_overridden_methods() const;
2157 method_iterator end_overridden_methods() const;
2158 unsigned size_overridden_methods() const;
2159
2160 using overridden_method_range= ASTContext::overridden_method_range;
2161
2162 overridden_method_range overridden_methods() const;
2163
2164 /// Returns the parent of this method declaration, which
2165 /// is the class in which this method is defined.
2166 const CXXRecordDecl *getParent() const {
2167 return cast<CXXRecordDecl>(FunctionDecl::getParent());
2168 }
2169
2170 /// Returns the parent of this method declaration, which
2171 /// is the class in which this method is defined.
2172 CXXRecordDecl *getParent() {
2173 return const_cast<CXXRecordDecl *>(
2174 cast<CXXRecordDecl>(FunctionDecl::getParent()));
2175 }
2176
2177 /// Returns the type of the \c this pointer.
2178 ///
2179 /// Should only be called for instance (i.e., non-static) methods. Note
2180 /// that for the call operator of a lambda closure type, this returns the
2181 /// desugared 'this' type (a pointer to the closure type), not the captured
2182 /// 'this' type.
2183 QualType getThisType(ASTContext &C) const;
2184
2185 unsigned getTypeQualifiers() const {
2186 return getType()->getAs<FunctionProtoType>()->getTypeQuals();
2187 }
2188
2189 /// Retrieve the ref-qualifier associated with this method.
2190 ///
2191 /// In the following example, \c f() has an lvalue ref-qualifier, \c g()
2192 /// has an rvalue ref-qualifier, and \c h() has no ref-qualifier.
2193 /// @code
2194 /// struct X {
2195 /// void f() &;
2196 /// void g() &&;
2197 /// void h();
2198 /// };
2199 /// @endcode
2200 RefQualifierKind getRefQualifier() const {
2201 return getType()->getAs<FunctionProtoType>()->getRefQualifier();
2202 }
2203
2204 bool hasInlineBody() const;
2205
2206 /// Determine whether this is a lambda closure type's static member
2207 /// function that is used for the result of the lambda's conversion to
2208 /// function pointer (for a lambda with no captures).
2209 ///
2210 /// The function itself, if used, will have a placeholder body that will be
2211 /// supplied by IR generation to either forward to the function call operator
2212 /// or clone the function call operator.
2213 bool isLambdaStaticInvoker() const;
2214
2215 /// Find the method in \p RD that corresponds to this one.
2216 ///
2217 /// Find if \p RD or one of the classes it inherits from override this method.
2218 /// If so, return it. \p RD is assumed to be a subclass of the class defining
2219 /// this method (or be the class itself), unless \p MayBeBase is set to true.
2220 CXXMethodDecl *
2221 getCorrespondingMethodInClass(const CXXRecordDecl *RD,
2222 bool MayBeBase = false);
2223
2224 const CXXMethodDecl *
2225 getCorrespondingMethodInClass(const CXXRecordDecl *RD,
2226 bool MayBeBase = false) const {
2227 return const_cast<CXXMethodDecl *>(this)
2228 ->getCorrespondingMethodInClass(RD, MayBeBase);
2229 }
2230
2231 // Implement isa/cast/dyncast/etc.
2232 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2233 static bool classofKind(Kind K) {
2234 return K >= firstCXXMethod && K <= lastCXXMethod;
2235 }
2236};
2237
2238/// Represents a C++ base or member initializer.
2239///
2240/// This is part of a constructor initializer that
2241/// initializes one non-static member variable or one base class. For
2242/// example, in the following, both 'A(a)' and 'f(3.14159)' are member
2243/// initializers:
2244///
2245/// \code
2246/// class A { };
2247/// class B : public A {
2248/// float f;
2249/// public:
2250/// B(A& a) : A(a), f(3.14159) { }
2251/// };
2252/// \endcode
2253class CXXCtorInitializer final {
2254 /// Either the base class name/delegating constructor type (stored as
2255 /// a TypeSourceInfo*), an normal field (FieldDecl), or an anonymous field
2256 /// (IndirectFieldDecl*) being initialized.
2257 llvm::PointerUnion3<TypeSourceInfo *, FieldDecl *, IndirectFieldDecl *>
2258 Initializee;
2259
2260 /// The source location for the field name or, for a base initializer
2261 /// pack expansion, the location of the ellipsis.
2262 ///
2263 /// In the case of a delegating
2264 /// constructor, it will still include the type's source location as the
2265 /// Initializee points to the CXXConstructorDecl (to allow loop detection).
2266 SourceLocation MemberOrEllipsisLocation;
2267
2268 /// The argument used to initialize the base or member, which may
2269 /// end up constructing an object (when multiple arguments are involved).
2270 Stmt *Init;
2271
2272 /// Location of the left paren of the ctor-initializer.
2273 SourceLocation LParenLoc;
2274
2275 /// Location of the right paren of the ctor-initializer.
2276 SourceLocation RParenLoc;
2277
2278 /// If the initializee is a type, whether that type makes this
2279 /// a delegating initialization.
2280 unsigned IsDelegating : 1;
2281
2282 /// If the initializer is a base initializer, this keeps track
2283 /// of whether the base is virtual or not.
2284 unsigned IsVirtual : 1;
2285
2286 /// Whether or not the initializer is explicitly written
2287 /// in the sources.
2288 unsigned IsWritten : 1;
2289
2290 /// If IsWritten is true, then this number keeps track of the textual order
2291 /// of this initializer in the original sources, counting from 0.
2292 unsigned SourceOrder : 13;
2293
2294public:
2295 /// Creates a new base-class initializer.
2296 explicit
2297 CXXCtorInitializer(ASTContext &Context, TypeSourceInfo *TInfo, bool IsVirtual,
2298 SourceLocation L, Expr *Init, SourceLocation R,
2299 SourceLocation EllipsisLoc);
2300
2301 /// Creates a new member initializer.
2302 explicit
2303 CXXCtorInitializer(ASTContext &Context, FieldDecl *Member,
2304 SourceLocation MemberLoc, SourceLocation L, Expr *Init,
2305 SourceLocation R);
2306
2307 /// Creates a new anonymous field initializer.
2308 explicit
2309 CXXCtorInitializer(ASTContext &Context, IndirectFieldDecl *Member,
2310 SourceLocation MemberLoc, SourceLocation L, Expr *Init,
2311 SourceLocation R);
2312
2313 /// Creates a new delegating initializer.
2314 explicit
2315 CXXCtorInitializer(ASTContext &Context, TypeSourceInfo *TInfo,
2316 SourceLocation L, Expr *Init, SourceLocation R);
2317
2318 /// Determine whether this initializer is initializing a base class.
2319 bool isBaseInitializer() const {
2320 return Initializee.is<TypeSourceInfo*>() && !IsDelegating;
2321 }
2322
2323 /// Determine whether this initializer is initializing a non-static
2324 /// data member.
2325 bool isMemberInitializer() const { return Initializee.is<FieldDecl*>(); }
2326
2327 bool isAnyMemberInitializer() const {
2328 return isMemberInitializer() || isIndirectMemberInitializer();
2329 }
2330
2331 bool isIndirectMemberInitializer() const {
2332 return Initializee.is<IndirectFieldDecl*>();
2333 }
2334
2335 /// Determine whether this initializer is an implicit initializer
2336 /// generated for a field with an initializer defined on the member
2337 /// declaration.
2338 ///
2339 /// In-class member initializers (also known as "non-static data member
2340 /// initializations", NSDMIs) were introduced in C++11.
2341 bool isInClassMemberInitializer() const {
2342 return Init->getStmtClass() == Stmt::CXXDefaultInitExprClass;
2343 }
2344
2345 /// Determine whether this initializer is creating a delegating
2346 /// constructor.
2347 bool isDelegatingInitializer() const {
2348 return Initializee.is<TypeSourceInfo*>() && IsDelegating;
2349 }
2350
2351 /// Determine whether this initializer is a pack expansion.
2352 bool isPackExpansion() const {
2353 return isBaseInitializer() && MemberOrEllipsisLocation.isValid();
2354 }
2355
2356 // For a pack expansion, returns the location of the ellipsis.
2357 SourceLocation getEllipsisLoc() const {
2358 assert(isPackExpansion() && "Initializer is not a pack expansion");
2359 return MemberOrEllipsisLocation;
2360 }
2361
2362 /// If this is a base class initializer, returns the type of the
2363 /// base class with location information. Otherwise, returns an NULL
2364 /// type location.
2365 TypeLoc getBaseClassLoc() const;
2366
2367 /// If this is a base class initializer, returns the type of the base class.
2368 /// Otherwise, returns null.
2369 const Type *getBaseClass() const;
2370
2371 /// Returns whether the base is virtual or not.
2372 bool isBaseVirtual() const {
2373 assert(isBaseInitializer() && "Must call this on base initializer!");
2374
2375 return IsVirtual;
2376 }
2377
2378 /// Returns the declarator information for a base class or delegating
2379 /// initializer.
2380 TypeSourceInfo *getTypeSourceInfo() const {
2381 return Initializee.dyn_cast<TypeSourceInfo *>();
2382 }
2383
2384 /// If this is a member initializer, returns the declaration of the
2385 /// non-static data member being initialized. Otherwise, returns null.
2386 FieldDecl *getMember() const {
2387 if (isMemberInitializer())
2388 return Initializee.get<FieldDecl*>();
2389 return nullptr;
2390 }
2391
2392 FieldDecl *getAnyMember() const {
2393 if (isMemberInitializer())
2394 return Initializee.get<FieldDecl*>();
2395 if (isIndirectMemberInitializer())
2396 return Initializee.get<IndirectFieldDecl*>()->getAnonField();
2397 return nullptr;
2398 }
2399
2400 IndirectFieldDecl *getIndirectMember() const {
2401 if (isIndirectMemberInitializer())
2402 return Initializee.get<IndirectFieldDecl*>();
2403 return nullptr;
2404 }
2405
2406 SourceLocation getMemberLocation() const {
2407 return MemberOrEllipsisLocation;
2408 }
2409
2410 /// Determine the source location of the initializer.
2411 SourceLocation getSourceLocation() const;
2412
2413 /// Determine the source range covering the entire initializer.
2414 SourceRange getSourceRange() const LLVM_READONLY;
2415
2416 /// Determine whether this initializer is explicitly written
2417 /// in the source code.
2418 bool isWritten() const { return IsWritten; }
2419
2420 /// Return the source position of the initializer, counting from 0.
2421 /// If the initializer was implicit, -1 is returned.
2422 int getSourceOrder() const {
2423 return IsWritten ? static_cast<int>(SourceOrder) : -1;
2424 }
2425
2426 /// Set the source order of this initializer.
2427 ///
2428 /// This can only be called once for each initializer; it cannot be called
2429 /// on an initializer having a positive number of (implicit) array indices.
2430 ///
2431 /// This assumes that the initializer was written in the source code, and
2432 /// ensures that isWritten() returns true.
2433 void setSourceOrder(int Pos) {
2434 assert(!IsWritten &&
2435 "setSourceOrder() used on implicit initializer");
2436 assert(SourceOrder == 0 &&
2437 "calling twice setSourceOrder() on the same initializer");
2438 assert(Pos >= 0 &&
2439 "setSourceOrder() used to make an initializer implicit");
2440 IsWritten = true;
2441 SourceOrder = static_cast<unsigned>(Pos);
2442 }
2443
2444 SourceLocation getLParenLoc() const { return LParenLoc; }
2445 SourceLocation getRParenLoc() const { return RParenLoc; }
2446
2447 /// Get the initializer.
2448 Expr *getInit() const { return static_cast<Expr *>(Init); }
2449};
2450
2451/// Description of a constructor that was inherited from a base class.
2452class InheritedConstructor {
2453 ConstructorUsingShadowDecl *Shadow = nullptr;
2454 CXXConstructorDecl *BaseCtor = nullptr;
2455
2456public:
2457 InheritedConstructor() = default;
2458 InheritedConstructor(ConstructorUsingShadowDecl *Shadow,
2459 CXXConstructorDecl *BaseCtor)
2460 : Shadow(Shadow), BaseCtor(BaseCtor) {}
2461
2462 explicit operator bool() const { return Shadow; }
2463
2464 ConstructorUsingShadowDecl *getShadowDecl() const { return Shadow; }
2465 CXXConstructorDecl *getConstructor() const { return BaseCtor; }
2466};
2467
2468/// Represents a C++ constructor within a class.
2469///
2470/// For example:
2471///
2472/// \code
2473/// class X {
2474/// public:
2475/// explicit X(int); // represented by a CXXConstructorDecl.
2476/// };
2477/// \endcode
2478class CXXConstructorDecl final
2479 : public CXXMethodDecl,
2480 private llvm::TrailingObjects<CXXConstructorDecl, InheritedConstructor> {
2481 // This class stores some data in DeclContext::CXXConstructorDeclBits
2482 // to save some space. Use the provided accessors to access it.
2483
2484 /// \name Support for base and member initializers.
2485 /// \{
2486 /// The arguments used to initialize the base or member.
2487 LazyCXXCtorInitializersPtr CtorInitializers;
2488
2489 CXXConstructorDecl(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc,
2490 const DeclarationNameInfo &NameInfo,
2491 QualType T, TypeSourceInfo *TInfo,
2492 bool isExplicitSpecified, bool isInline,
2493 bool isImplicitlyDeclared, bool isConstexpr,
2494 InheritedConstructor Inherited);
2495
2496 void anchor() override;
2497
2498public:
2499 friend class ASTDeclReader;
2500 friend class ASTDeclWriter;
2501 friend TrailingObjects;
2502
2503 static CXXConstructorDecl *CreateDeserialized(ASTContext &C, unsigned ID,
2504 bool InheritsConstructor);
2505 static CXXConstructorDecl *
2506 Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc,
2507 const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo,
2508 bool isExplicit, bool isInline, bool isImplicitlyDeclared,
2509 bool isConstexpr,
2510 InheritedConstructor Inherited = InheritedConstructor());
2511
2512 /// Iterates through the member/base initializer list.
2513 using init_iterator = CXXCtorInitializer **;
2514
2515 /// Iterates through the member/base initializer list.
2516 using init_const_iterator = CXXCtorInitializer *const *;
2517
2518 using init_range = llvm::iterator_range<init_iterator>;
2519 using init_const_range = llvm::iterator_range<init_const_iterator>;
2520
2521 init_range inits() { return init_range(init_begin(), init_end()); }
2522 init_const_range inits() const {
2523 return init_const_range(init_begin(), init_end());
2524 }
2525
2526 /// Retrieve an iterator to the first initializer.
2527 init_iterator init_begin() {
2528 const auto *ConstThis = this;
2529 return const_cast<init_iterator>(ConstThis->init_begin());
2530 }
2531
2532 /// Retrieve an iterator to the first initializer.
2533 init_const_iterator init_begin() const;
2534
2535 /// Retrieve an iterator past the last initializer.
2536 init_iterator init_end() {
2537 return init_begin() + getNumCtorInitializers();
2538 }
2539
2540 /// Retrieve an iterator past the last initializer.
2541 init_const_iterator init_end() const {
2542 return init_begin() + getNumCtorInitializers();
2543 }
2544
2545 using init_reverse_iterator = std::reverse_iterator<init_iterator>;
2546 using init_const_reverse_iterator =
2547 std::reverse_iterator<init_const_iterator>;
2548
2549 init_reverse_iterator init_rbegin() {
2550 return init_reverse_iterator(init_end());
2551 }
2552 init_const_reverse_iterator init_rbegin() const {
2553 return init_const_reverse_iterator(init_end());
2554 }
2555
2556 init_reverse_iterator init_rend() {
2557 return init_reverse_iterator(init_begin());
2558 }
2559 init_const_reverse_iterator init_rend() const {
2560 return init_const_reverse_iterator(init_begin());
2561 }
2562
2563 /// Determine the number of arguments used to initialize the member
2564 /// or base.
2565 unsigned getNumCtorInitializers() const {
2566 return CXXConstructorDeclBits.NumCtorInitializers;
2567 }
2568
2569 void setNumCtorInitializers(unsigned numCtorInitializers) {
2570 CXXConstructorDeclBits.NumCtorInitializers = numCtorInitializers;
2571 // This assert added because NumCtorInitializers is stored
2572 // in CXXConstructorDeclBits as a bitfield and its width has
2573 // been shrunk from 32 bits to fit into CXXConstructorDeclBitfields.
2574 assert(CXXConstructorDeclBits.NumCtorInitializers ==
2575 numCtorInitializers && "NumCtorInitializers overflow!");
2576 }
2577
2578 void setCtorInitializers(CXXCtorInitializer **Initializers) {
2579 CtorInitializers = Initializers;
2580 }
2581
2582 /// Whether this function is explicit.
2583 bool isExplicit() const {
2584 return getCanonicalDecl()->isExplicitSpecified();
2585 }
2586
2587 /// Determine whether this constructor is a delegating constructor.
2588 bool isDelegatingConstructor() const {
2589 return (getNumCtorInitializers() == 1) &&
2590 init_begin()[0]->isDelegatingInitializer();
2591 }
2592
2593 /// When this constructor delegates to another, retrieve the target.
2594 CXXConstructorDecl *getTargetConstructor() const;
2595
2596 /// Whether this constructor is a default
2597 /// constructor (C++ [class.ctor]p5), which can be used to
2598 /// default-initialize a class of this type.
2599 bool isDefaultConstructor() const;
2600
2601 /// Whether this constructor is a copy constructor (C++ [class.copy]p2,
2602 /// which can be used to copy the class.
2603 ///
2604 /// \p TypeQuals will be set to the qualifiers on the
2605 /// argument type. For example, \p TypeQuals would be set to \c
2606 /// Qualifiers::Const for the following copy constructor:
2607 ///
2608 /// \code
2609 /// class X {
2610 /// public:
2611 /// X(const X&);
2612 /// };
2613 /// \endcode
2614 bool isCopyConstructor(unsigned &TypeQuals) const;
2615
2616 /// Whether this constructor is a copy
2617 /// constructor (C++ [class.copy]p2, which can be used to copy the
2618 /// class.
2619 bool isCopyConstructor() const {
2620 unsigned TypeQuals = 0;
2621 return isCopyConstructor(TypeQuals);
2622 }
2623
2624 /// Determine whether this constructor is a move constructor
2625 /// (C++11 [class.copy]p3), which can be used to move values of the class.
2626 ///
2627 /// \param TypeQuals If this constructor is a move constructor, will be set
2628 /// to the type qualifiers on the referent of the first parameter's type.
2629 bool isMoveConstructor(unsigned &TypeQuals) const;
2630
2631 /// Determine whether this constructor is a move constructor
2632 /// (C++11 [class.copy]p3), which can be used to move values of the class.
2633 bool isMoveConstructor() const {
2634 unsigned TypeQuals = 0;
2635 return isMoveConstructor(TypeQuals);
2636 }
2637
2638 /// Determine whether this is a copy or move constructor.
2639 ///
2640 /// \param TypeQuals Will be set to the type qualifiers on the reference
2641 /// parameter, if in fact this is a copy or move constructor.
2642 bool isCopyOrMoveConstructor(unsigned &TypeQuals) const;
2643
2644 /// Determine whether this a copy or move constructor.
2645 bool isCopyOrMoveConstructor() const {
2646 unsigned Quals;
2647 return isCopyOrMoveConstructor(Quals);
2648 }
2649
2650 /// Whether this constructor is a
2651 /// converting constructor (C++ [class.conv.ctor]), which can be
2652 /// used for user-defined conversions.
2653 bool isConvertingConstructor(bool AllowExplicit) const;
2654
2655 /// Determine whether this is a member template specialization that
2656 /// would copy the object to itself. Such constructors are never used to copy
2657 /// an object.
2658 bool isSpecializationCopyingObject() const;
2659
2660 /// Determine whether this is an implicit constructor synthesized to
2661 /// model a call to a constructor inherited from a base class.
2662 bool isInheritingConstructor() const {
2663 return CXXConstructorDeclBits.IsInheritingConstructor;
2664 }
2665
2666 /// State that this is an implicit constructor synthesized to
2667 /// model a call to a constructor inherited from a base class.
2668 void setInheritingConstructor(bool isIC = true) {
2669 CXXConstructorDeclBits.IsInheritingConstructor = isIC;
2670 }
2671
2672 /// Get the constructor that this inheriting constructor is based on.
2673 InheritedConstructor getInheritedConstructor() const {
2674 return isInheritingConstructor() ?
2675 *getTrailingObjects<InheritedConstructor>() : InheritedConstructor();
2676 }
2677
2678 CXXConstructorDecl *getCanonicalDecl() override {
2679 return cast<CXXConstructorDecl>(FunctionDecl::getCanonicalDecl());
2680 }
2681 const CXXConstructorDecl *getCanonicalDecl() const {
2682 return const_cast<CXXConstructorDecl*>(this)->getCanonicalDecl();
2683 }
2684
2685 // Implement isa/cast/dyncast/etc.
2686 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2687 static bool classofKind(Kind K) { return K == CXXConstructor; }
2688};
2689
2690/// Represents a C++ destructor within a class.
2691///
2692/// For example:
2693///
2694/// \code
2695/// class X {
2696/// public:
2697/// ~X(); // represented by a CXXDestructorDecl.
2698/// };
2699/// \endcode
2700class CXXDestructorDecl : public CXXMethodDecl {
2701 friend class ASTDeclReader;
2702 friend class ASTDeclWriter;
2703
2704 // FIXME: Don't allocate storage for these except in the first declaration
2705 // of a virtual destructor.
2706 FunctionDecl *OperatorDelete = nullptr;
2707 Expr *OperatorDeleteThisArg = nullptr;
2708
2709 CXXDestructorDecl(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc,
2710 const DeclarationNameInfo &NameInfo,
2711 QualType T, TypeSourceInfo *TInfo,
2712 bool isInline, bool isImplicitlyDeclared)
2713 : CXXMethodDecl(CXXDestructor, C, RD, StartLoc, NameInfo, T, TInfo,
2714 SC_None, isInline, /*isConstexpr=*/false, SourceLocation())
2715 {
2716 setImplicit(isImplicitlyDeclared);
2717 }
2718
2719 void anchor() override;
2720
2721public:
2722 static CXXDestructorDecl *Create(ASTContext &C, CXXRecordDecl *RD,
2723 SourceLocation StartLoc,
2724 const DeclarationNameInfo &NameInfo,
2725 QualType T, TypeSourceInfo* TInfo,
2726 bool isInline,
2727 bool isImplicitlyDeclared);
2728 static CXXDestructorDecl *CreateDeserialized(ASTContext & C, unsigned ID);
2729
2730 void setOperatorDelete(FunctionDecl *OD, Expr *ThisArg);
2731
2732 const FunctionDecl *getOperatorDelete() const {
2733 return getCanonicalDecl()->OperatorDelete;
2734 }
2735
2736 Expr *getOperatorDeleteThisArg() const {
2737 return getCanonicalDecl()->OperatorDeleteThisArg;
2738 }
2739
2740 CXXDestructorDecl *getCanonicalDecl() override {
2741 return cast<CXXDestructorDecl>(FunctionDecl::getCanonicalDecl());
2742 }
2743 const CXXDestructorDecl *getCanonicalDecl() const {
2744 return const_cast<CXXDestructorDecl*>(this)->getCanonicalDecl();
2745 }
2746
2747 // Implement isa/cast/dyncast/etc.
2748 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2749 static bool classofKind(Kind K) { return K == CXXDestructor; }
2750};
2751
2752/// Represents a C++ conversion function within a class.
2753///
2754/// For example:
2755///
2756/// \code
2757/// class X {
2758/// public:
2759/// operator bool();
2760/// };
2761/// \endcode
2762class CXXConversionDecl : public CXXMethodDecl {
2763 CXXConversionDecl(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc,
2764 const DeclarationNameInfo &NameInfo, QualType T,
2765 TypeSourceInfo *TInfo, bool isInline,
2766 bool isExplicitSpecified, bool isConstexpr,
2767 SourceLocation EndLocation)
2768 : CXXMethodDecl(CXXConversion, C, RD, StartLoc, NameInfo, T, TInfo,
2769 SC_None, isInline, isConstexpr, EndLocation) {
2770 setExplicitSpecified(isExplicitSpecified);
2771 }
2772
2773 void anchor() override;
2774
2775public:
2776 friend class ASTDeclReader;
2777 friend class ASTDeclWriter;
2778
2779 static CXXConversionDecl *Create(ASTContext &C, CXXRecordDecl *RD,
2780 SourceLocation StartLoc,
2781 const DeclarationNameInfo &NameInfo,
2782 QualType T, TypeSourceInfo *TInfo,
2783 bool isInline, bool isExplicit,
2784 bool isConstexpr,
2785 SourceLocation EndLocation);
2786 static CXXConversionDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2787
2788 /// Whether this function is explicit.
2789 bool isExplicit() const {
2790 return getCanonicalDecl()->isExplicitSpecified();
2791 }
2792
2793 /// Returns the type that this conversion function is converting to.
2794 QualType getConversionType() const {
2795 return getType()->getAs<FunctionType>()->getReturnType();
2796 }
2797
2798 /// Determine whether this conversion function is a conversion from
2799 /// a lambda closure type to a block pointer.
2800 bool isLambdaToBlockPointerConversion() const;
2801
2802 CXXConversionDecl *getCanonicalDecl() override {
2803 return cast<CXXConversionDecl>(FunctionDecl::getCanonicalDecl());
2804 }
2805 const CXXConversionDecl *getCanonicalDecl() const {
2806 return const_cast<CXXConversionDecl*>(this)->getCanonicalDecl();
2807 }
2808
2809 // Implement isa/cast/dyncast/etc.
2810 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2811 static bool classofKind(Kind K) { return K == CXXConversion; }
2812};
2813
2814/// Represents a linkage specification.
2815///
2816/// For example:
2817/// \code
2818/// extern "C" void foo();
2819/// \endcode
2820class LinkageSpecDecl : public Decl, public DeclContext {
2821 virtual void anchor();
2822 // This class stores some data in DeclContext::LinkageSpecDeclBits to save
2823 // some space. Use the provided accessors to access it.
2824public:
2825 /// Represents the language in a linkage specification.
2826 ///
2827 /// The values are part of the serialization ABI for
2828 /// ASTs and cannot be changed without altering that ABI. To help
2829 /// ensure a stable ABI for this, we choose the DW_LANG_ encodings
2830 /// from the dwarf standard.
2831 enum LanguageIDs {
2832 lang_c = /* DW_LANG_C */ 0x0002,
2833 lang_cxx = /* DW_LANG_C_plus_plus */ 0x0004
2834 };
2835
2836private:
2837 /// The source location for the extern keyword.
2838 SourceLocation ExternLoc;
2839
2840 /// The source location for the right brace (if valid).
2841 SourceLocation RBraceLoc;
2842
2843 LinkageSpecDecl(DeclContext *DC, SourceLocation ExternLoc,
2844 SourceLocation LangLoc, LanguageIDs lang, bool HasBraces);
2845
2846public:
2847 static LinkageSpecDecl *Create(ASTContext &C, DeclContext *DC,
2848 SourceLocation ExternLoc,
2849 SourceLocation LangLoc, LanguageIDs Lang,
2850 bool HasBraces);
2851 static LinkageSpecDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2852
2853 /// Return the language specified by this linkage specification.
2854 LanguageIDs getLanguage() const {
2855 return static_cast<LanguageIDs>(LinkageSpecDeclBits.Language);
2856 }
2857
2858 /// Set the language specified by this linkage specification.
2859 void setLanguage(LanguageIDs L) { LinkageSpecDeclBits.Language = L; }
2860
2861 /// Determines whether this linkage specification had braces in
2862 /// its syntactic form.
2863 bool hasBraces() const {
2864 assert(!RBraceLoc.isValid() || LinkageSpecDeclBits.HasBraces);
2865 return LinkageSpecDeclBits.HasBraces;
2866 }
2867
2868 SourceLocation getExternLoc() const { return ExternLoc; }
2869 SourceLocation getRBraceLoc() const { return RBraceLoc; }
2870 void setExternLoc(SourceLocation L) { ExternLoc = L; }
2871 void setRBraceLoc(SourceLocation L) {
2872 RBraceLoc = L;
2873 LinkageSpecDeclBits.HasBraces = RBraceLoc.isValid();
2874 }
2875
2876 SourceLocation getEndLoc() const LLVM_READONLY {
2877 if (hasBraces())
2878 return getRBraceLoc();
2879 // No braces: get the end location of the (only) declaration in context
2880 // (if present).
2881 return decls_empty() ? getLocation() : decls_begin()->getEndLoc();
2882 }
2883
2884 SourceRange getSourceRange() const override LLVM_READONLY {
2885 return SourceRange(ExternLoc, getEndLoc());
2886 }
2887
2888 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2889 static bool classofKind(Kind K) { return K == LinkageSpec; }
2890
2891 static DeclContext *castToDeclContext(const LinkageSpecDecl *D) {
2892 return static_cast<DeclContext *>(const_cast<LinkageSpecDecl*>(D));
2893 }
2894
2895 static LinkageSpecDecl *castFromDeclContext(const DeclContext *DC) {
2896 return static_cast<LinkageSpecDecl *>(const_cast<DeclContext*>(DC));
2897 }
2898};
2899
2900/// Represents C++ using-directive.
2901///
2902/// For example:
2903/// \code
2904/// using namespace std;
2905/// \endcode
2906///
2907/// \note UsingDirectiveDecl should be Decl not NamedDecl, but we provide
2908/// artificial names for all using-directives in order to store
2909/// them in DeclContext effectively.
2910class UsingDirectiveDecl : public NamedDecl {
2911 /// The location of the \c using keyword.
2912 SourceLocation UsingLoc;
2913
2914 /// The location of the \c namespace keyword.
2915 SourceLocation NamespaceLoc;
2916
2917 /// The nested-name-specifier that precedes the namespace.
2918 NestedNameSpecifierLoc QualifierLoc;
2919
2920 /// The namespace nominated by this using-directive.
2921 NamedDecl *NominatedNamespace;
2922
2923 /// Enclosing context containing both using-directive and nominated
2924 /// namespace.
2925 DeclContext *CommonAncestor;
2926
2927 UsingDirectiveDecl(DeclContext *DC, SourceLocation UsingLoc,
2928 SourceLocation NamespcLoc,
2929 NestedNameSpecifierLoc QualifierLoc,
2930 SourceLocation IdentLoc,
2931 NamedDecl *Nominated,
2932 DeclContext *CommonAncestor)
2933 : NamedDecl(UsingDirective, DC, IdentLoc, getName()), UsingLoc(UsingLoc),
2934 NamespaceLoc(NamespcLoc), QualifierLoc(QualifierLoc),
2935 NominatedNamespace(Nominated), CommonAncestor(CommonAncestor) {}
2936
2937 /// Returns special DeclarationName used by using-directives.
2938 ///
2939 /// This is only used by DeclContext for storing UsingDirectiveDecls in
2940 /// its lookup structure.
2941 static DeclarationName getName() {
2942 return DeclarationName::getUsingDirectiveName();
2943 }
2944
2945 void anchor() override;
2946
2947public:
2948 friend class ASTDeclReader;
2949
2950 // Friend for getUsingDirectiveName.
2951 friend class DeclContext;
2952
2953 /// Retrieve the nested-name-specifier that qualifies the
2954 /// name of the namespace, with source-location information.
2955 NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
2956
2957 /// Retrieve the nested-name-specifier that qualifies the
2958 /// name of the namespace.
2959 NestedNameSpecifier *getQualifier() const {
2960 return QualifierLoc.getNestedNameSpecifier();
2961 }
2962
2963 NamedDecl *getNominatedNamespaceAsWritten() { return NominatedNamespace; }
2964 const NamedDecl *getNominatedNamespaceAsWritten() const {
2965 return NominatedNamespace;
2966 }
2967
2968 /// Returns the namespace nominated by this using-directive.
2969 NamespaceDecl *getNominatedNamespace();
2970
2971 const NamespaceDecl *getNominatedNamespace() const {
2972 return const_cast<UsingDirectiveDecl*>(this)->getNominatedNamespace();
2973 }
2974
2975 /// Returns the common ancestor context of this using-directive and
2976 /// its nominated namespace.
2977 DeclContext *getCommonAncestor() { return CommonAncestor; }
2978 const DeclContext *getCommonAncestor() const { return CommonAncestor; }
2979
2980 /// Return the location of the \c using keyword.
2981 SourceLocation getUsingLoc() const { return UsingLoc; }
2982
2983 // FIXME: Could omit 'Key' in name.
2984 /// Returns the location of the \c namespace keyword.
2985 SourceLocation getNamespaceKeyLocation() const { return NamespaceLoc; }
2986
2987 /// Returns the location of this using declaration's identifier.
2988 SourceLocation getIdentLocation() const { return getLocation(); }
2989
2990 static UsingDirectiveDecl *Create(ASTContext &C, DeclContext *DC,
2991 SourceLocation UsingLoc,
2992 SourceLocation NamespaceLoc,
2993 NestedNameSpecifierLoc QualifierLoc,
2994 SourceLocation IdentLoc,
2995 NamedDecl *Nominated,
2996 DeclContext *CommonAncestor);
2997 static UsingDirectiveDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2998
2999 SourceRange getSourceRange() const override LLVM_READONLY {
3000 return SourceRange(UsingLoc, getLocation());
3001 }
3002
3003 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3004 static bool classofKind(Kind K) { return K == UsingDirective; }
3005};
3006
3007/// Represents a C++ namespace alias.
3008///
3009/// For example:
3010///
3011/// \code
3012/// namespace Foo = Bar;
3013/// \endcode
3014class NamespaceAliasDecl : public NamedDecl,
3015 public Redeclarable<NamespaceAliasDecl> {
3016 friend class ASTDeclReader;
3017
3018 /// The location of the \c namespace keyword.
3019 SourceLocation NamespaceLoc;
3020
3021 /// The location of the namespace's identifier.
3022 ///
3023 /// This is accessed by TargetNameLoc.
3024 SourceLocation IdentLoc;
3025
3026 /// The nested-name-specifier that precedes the namespace.
3027 NestedNameSpecifierLoc QualifierLoc;
3028
3029 /// The Decl that this alias points to, either a NamespaceDecl or
3030 /// a NamespaceAliasDecl.
3031 NamedDecl *Namespace;
3032
3033 NamespaceAliasDecl(ASTContext &C, DeclContext *DC,
3034 SourceLocation NamespaceLoc, SourceLocation AliasLoc,
3035 IdentifierInfo *Alias, NestedNameSpecifierLoc QualifierLoc,
3036 SourceLocation IdentLoc, NamedDecl *Namespace)
3037 : NamedDecl(NamespaceAlias, DC, AliasLoc, Alias), redeclarable_base(C),
3038 NamespaceLoc(NamespaceLoc), IdentLoc(IdentLoc),
3039 QualifierLoc(QualifierLoc), Namespace(Namespace) {}
3040
3041 void anchor() override;
3042
3043 using redeclarable_base = Redeclarable<NamespaceAliasDecl>;
3044
3045 NamespaceAliasDecl *getNextRedeclarationImpl() override;
3046 NamespaceAliasDecl *getPreviousDeclImpl() override;
3047 NamespaceAliasDecl *getMostRecentDeclImpl() override;
3048
3049public:
3050 static NamespaceAliasDecl *Create(ASTContext &C, DeclContext *DC,
3051 SourceLocation NamespaceLoc,
3052 SourceLocation AliasLoc,
3053 IdentifierInfo *Alias,
3054 NestedNameSpecifierLoc QualifierLoc,
3055 SourceLocation IdentLoc,
3056 NamedDecl *Namespace);
3057
3058 static NamespaceAliasDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3059
3060 using redecl_range = redeclarable_base::redecl_range;
3061 using redecl_iterator = redeclarable_base::redecl_iterator;
3062
3063 using redeclarable_base::redecls_begin;
3064 using redeclarable_base::redecls_end;
3065 using redeclarable_base::redecls;
3066 using redeclarable_base::getPreviousDecl;
3067 using redeclarable_base::getMostRecentDecl;
3068
3069 NamespaceAliasDecl *getCanonicalDecl() override {
3070 return getFirstDecl();
3071 }
3072 const NamespaceAliasDecl *getCanonicalDecl() const {
3073 return getFirstDecl();
3074 }
3075
3076 /// Retrieve the nested-name-specifier that qualifies the
3077 /// name of the namespace, with source-location information.
3078 NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
3079
3080 /// Retrieve the nested-name-specifier that qualifies the
3081 /// name of the namespace.
3082 NestedNameSpecifier *getQualifier() const {
3083 return QualifierLoc.getNestedNameSpecifier();
3084 }
3085
3086 /// Retrieve the namespace declaration aliased by this directive.
3087 NamespaceDecl *getNamespace() {
3088 if (auto *AD = dyn_cast<NamespaceAliasDecl>(Namespace))
3089 return AD->getNamespace();
3090
3091 return cast<NamespaceDecl>(Namespace);
3092 }
3093
3094 const NamespaceDecl *getNamespace() const {
3095 return const_cast<NamespaceAliasDecl *>(this)->getNamespace();
3096 }
3097
3098 /// Returns the location of the alias name, i.e. 'foo' in
3099 /// "namespace foo = ns::bar;".
3100 SourceLocation getAliasLoc() const { return getLocation(); }
3101
3102 /// Returns the location of the \c namespace keyword.
3103 SourceLocation getNamespaceLoc() const { return NamespaceLoc; }
3104
3105 /// Returns the location of the identifier in the named namespace.
3106 SourceLocation getTargetNameLoc() const { return IdentLoc; }
3107
3108 /// Retrieve the namespace that this alias refers to, which
3109 /// may either be a NamespaceDecl or a NamespaceAliasDecl.
3110 NamedDecl *getAliasedNamespace() const { return Namespace; }
3111
3112 SourceRange getSourceRange() const override LLVM_READONLY {
3113 return SourceRange(NamespaceLoc, IdentLoc);
3114 }
3115
3116 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3117 static bool classofKind(Kind K) { return K == NamespaceAlias; }
3118};
3119
3120/// Represents a shadow declaration introduced into a scope by a
3121/// (resolved) using declaration.
3122///
3123/// For example,
3124/// \code
3125/// namespace A {
3126/// void foo();
3127/// }
3128/// namespace B {
3129/// using A::foo; // <- a UsingDecl
3130/// // Also creates a UsingShadowDecl for A::foo() in B
3131/// }
3132/// \endcode
3133class UsingShadowDecl : public NamedDecl, public Redeclarable<UsingShadowDecl> {
3134 friend class UsingDecl;
3135
3136 /// The referenced declaration.
3137 NamedDecl *Underlying = nullptr;
3138
3139 /// The using declaration which introduced this decl or the next using
3140 /// shadow declaration contained in the aforementioned using declaration.
3141 NamedDecl *UsingOrNextShadow = nullptr;
3142
3143 void anchor() override;
3144
3145 using redeclarable_base = Redeclarable<UsingShadowDecl>;
3146
3147 UsingShadowDecl *getNextRedeclarationImpl() override {
3148 return getNextRedeclaration();
3149 }
3150
3151 UsingShadowDecl *getPreviousDeclImpl() override {
3152 return getPreviousDecl();
3153 }
3154
3155 UsingShadowDecl *getMostRecentDeclImpl() override {
3156 return getMostRecentDecl();
3157 }
3158
3159protected:
3160 UsingShadowDecl(Kind K, ASTContext &C, DeclContext *DC, SourceLocation Loc,
3161 UsingDecl *Using, NamedDecl *Target);
3162 UsingShadowDecl(Kind K, ASTContext &C, EmptyShell);
3163
3164public:
3165 friend class ASTDeclReader;
3166 friend class ASTDeclWriter;
3167
3168 static UsingShadowDecl *Create(ASTContext &C, DeclContext *DC,
3169 SourceLocation Loc, UsingDecl *Using,
3170 NamedDecl *Target) {
3171 return new (C, DC) UsingShadowDecl(UsingShadow, C, DC, Loc, Using, Target);
3172 }
3173
3174 static UsingShadowDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3175
3176 using redecl_range = redeclarable_base::redecl_range;
3177 using redecl_iterator = redeclarable_base::redecl_iterator;
3178
3179 using redeclarable_base::redecls_begin;
3180 using redeclarable_base::redecls_end;
3181 using redeclarable_base::redecls;
3182 using redeclarable_base::getPreviousDecl;
3183 using redeclarable_base::getMostRecentDecl;
3184 using redeclarable_base::isFirstDecl;
3185
3186 UsingShadowDecl *getCanonicalDecl() override {
3187 return getFirstDecl();
3188 }
3189 const UsingShadowDecl *getCanonicalDecl() const {
3190 return getFirstDecl();
3191 }
3192
3193 /// Gets the underlying declaration which has been brought into the
3194 /// local scope.
3195 NamedDecl *getTargetDecl() const { return Underlying; }
3196
3197 /// Sets the underlying declaration which has been brought into the
3198 /// local scope.
3199 void setTargetDecl(NamedDecl *ND) {
3200 assert(ND && "Target decl is null!");
3201 Underlying = ND;
3202 // A UsingShadowDecl is never a friend or local extern declaration, even
3203 // if it is a shadow declaration for one.
3204 IdentifierNamespace =
3205 ND->getIdentifierNamespace() &
3206 ~(IDNS_OrdinaryFriend | IDNS_TagFriend | IDNS_LocalExtern);
3207 }
3208
3209 /// Gets the using declaration to which this declaration is tied.
3210 UsingDecl *getUsingDecl() const;
3211
3212 /// The next using shadow declaration contained in the shadow decl
3213 /// chain of the using declaration which introduced this decl.
3214 UsingShadowDecl *getNextUsingShadowDecl() const {
3215 return dyn_cast_or_null<UsingShadowDecl>(UsingOrNextShadow);
3216 }
3217
3218 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3219 static bool classofKind(Kind K) {
3220 return K == Decl::UsingShadow || K == Decl::ConstructorUsingShadow;
3221 }
3222};
3223
3224/// Represents a shadow constructor declaration introduced into a
3225/// class by a C++11 using-declaration that names a constructor.
3226///
3227/// For example:
3228/// \code
3229/// struct Base { Base(int); };
3230/// struct Derived {
3231/// using Base::Base; // creates a UsingDecl and a ConstructorUsingShadowDecl
3232/// };
3233/// \endcode
3234class ConstructorUsingShadowDecl final : public UsingShadowDecl {
3235 /// If this constructor using declaration inherted the constructor
3236 /// from an indirect base class, this is the ConstructorUsingShadowDecl
3237 /// in the named direct base class from which the declaration was inherited.
3238 ConstructorUsingShadowDecl *NominatedBaseClassShadowDecl = nullptr;
3239
3240 /// If this constructor using declaration inherted the constructor
3241 /// from an indirect base class, this is the ConstructorUsingShadowDecl
3242 /// that will be used to construct the unique direct or virtual base class
3243 /// that receives the constructor arguments.
3244 ConstructorUsingShadowDecl *ConstructedBaseClassShadowDecl = nullptr;
3245
3246 /// \c true if the constructor ultimately named by this using shadow
3247 /// declaration is within a virtual base class subobject of the class that
3248 /// contains this declaration.
3249 unsigned IsVirtual : 1;
3250
3251 ConstructorUsingShadowDecl(ASTContext &C, DeclContext *DC, SourceLocation Loc,
3252 UsingDecl *Using, NamedDecl *Target,
3253 bool TargetInVirtualBase)
3254 : UsingShadowDecl(ConstructorUsingShadow, C, DC, Loc, Using,
3255 Target->getUnderlyingDecl()),
3256 NominatedBaseClassShadowDecl(
3257 dyn_cast<ConstructorUsingShadowDecl>(Target)),
3258 ConstructedBaseClassShadowDecl(NominatedBaseClassShadowDecl),
3259 IsVirtual(TargetInVirtualBase) {
3260 // If we found a constructor that chains to a constructor for a virtual
3261 // base, we should directly call that virtual base constructor instead.
3262 // FIXME: This logic belongs in Sema.
3263 if (NominatedBaseClassShadowDecl &&
3264 NominatedBaseClassShadowDecl->constructsVirtualBase()) {
3265 ConstructedBaseClassShadowDecl =
3266 NominatedBaseClassShadowDecl->ConstructedBaseClassShadowDecl;
3267 IsVirtual = true;
3268 }
3269 }
3270
3271 ConstructorUsingShadowDecl(ASTContext &C, EmptyShell Empty)
3272 : UsingShadowDecl(ConstructorUsingShadow, C, Empty), IsVirtual(false) {}
3273
3274 void anchor() override;
3275
3276public:
3277 friend class ASTDeclReader;
3278 friend class ASTDeclWriter;
3279
3280 static ConstructorUsingShadowDecl *Create(ASTContext &C, DeclContext *DC,
3281 SourceLocation Loc,
3282 UsingDecl *Using, NamedDecl *Target,
3283 bool IsVirtual);
3284 static ConstructorUsingShadowDecl *CreateDeserialized(ASTContext &C,
3285 unsigned ID);
3286
3287 /// Returns the parent of this using shadow declaration, which
3288 /// is the class in which this is declared.
3289 //@{
3290 const CXXRecordDecl *getParent() const {
3291 return cast<CXXRecordDecl>(getDeclContext());
3292 }
3293 CXXRecordDecl *getParent() {
3294 return cast<CXXRecordDecl>(getDeclContext());
3295 }
3296 //@}
3297
3298 /// Get the inheriting constructor declaration for the direct base
3299 /// class from which this using shadow declaration was inherited, if there is
3300 /// one. This can be different for each redeclaration of the same shadow decl.
3301 ConstructorUsingShadowDecl *getNominatedBaseClassShadowDecl() const {
3302 return NominatedBaseClassShadowDecl;
3303 }
3304
3305 /// Get the inheriting constructor declaration for the base class
3306 /// for which we don't have an explicit initializer, if there is one.
3307 ConstructorUsingShadowDecl *getConstructedBaseClassShadowDecl() const {
3308 return ConstructedBaseClassShadowDecl;
3309 }
3310
3311 /// Get the base class that was named in the using declaration. This
3312 /// can be different for each redeclaration of this same shadow decl.
3313 CXXRecordDecl *getNominatedBaseClass() const;
3314
3315 /// Get the base class whose constructor or constructor shadow
3316 /// declaration is passed the constructor arguments.
3317 CXXRecordDecl *getConstructedBaseClass() const {
3318 return cast<CXXRecordDecl>((ConstructedBaseClassShadowDecl
3319 ? ConstructedBaseClassShadowDecl
3320 : getTargetDecl())
3321 ->getDeclContext());
3322 }
3323
3324 /// Returns \c true if the constructed base class is a virtual base
3325 /// class subobject of this declaration's class.
3326 bool constructsVirtualBase() const {
3327 return IsVirtual;
3328 }
3329
3330 /// Get the constructor or constructor template in the derived class
3331 /// correspnding to this using shadow declaration, if it has been implicitly
3332 /// declared already.
3333 CXXConstructorDecl *getConstructor() const;
3334 void setConstructor(NamedDecl *Ctor);
3335
3336 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3337 static bool classofKind(Kind K) { return K == ConstructorUsingShadow; }
3338};
3339
3340/// Represents a C++ using-declaration.
3341///
3342/// For example:
3343/// \code
3344/// using someNameSpace::someIdentifier;
3345/// \endcode
3346class UsingDecl : public NamedDecl, public Mergeable<UsingDecl> {
3347 /// The source location of the 'using' keyword itself.
3348 SourceLocation UsingLocation;
3349
3350 /// The nested-name-specifier that precedes the name.
3351 NestedNameSpecifierLoc QualifierLoc;
3352
3353 /// Provides source/type location info for the declaration name
3354 /// embedded in the ValueDecl base class.
3355 DeclarationNameLoc DNLoc;
3356
3357 /// The first shadow declaration of the shadow decl chain associated
3358 /// with this using declaration.
3359 ///
3360 /// The bool member of the pair store whether this decl has the \c typename
3361 /// keyword.
3362 llvm::PointerIntPair<UsingShadowDecl *, 1, bool> FirstUsingShadow;
3363
3364 UsingDecl(DeclContext *DC, SourceLocation UL,
3365 NestedNameSpecifierLoc QualifierLoc,
3366 const DeclarationNameInfo &NameInfo, bool HasTypenameKeyword)
3367 : NamedDecl(Using, DC, NameInfo.getLoc(), NameInfo.getName()),
3368 UsingLocation(UL), QualifierLoc(QualifierLoc),
3369 DNLoc(NameInfo.getInfo()), FirstUsingShadow(nullptr, HasTypenameKeyword) {
3370 }
3371
3372 void anchor() override;
3373
3374public:
3375 friend class ASTDeclReader;
3376 friend class ASTDeclWriter;
3377
3378 /// Return the source location of the 'using' keyword.
3379 SourceLocation getUsingLoc() const { return UsingLocation; }
3380
3381 /// Set the source location of the 'using' keyword.
3382 void setUsingLoc(SourceLocation L) { UsingLocation = L; }
3383
3384 /// Retrieve the nested-name-specifier that qualifies the name,
3385 /// with source-location information.
3386 NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
3387
3388 /// Retrieve the nested-name-specifier that qualifies the name.
3389 NestedNameSpecifier *getQualifier() const {
3390 return QualifierLoc.getNestedNameSpecifier();
3391 }
3392
3393 DeclarationNameInfo getNameInfo() const {
3394 return DeclarationNameInfo(getDeclName(), getLocation(), DNLoc);
3395 }
3396
3397 /// Return true if it is a C++03 access declaration (no 'using').
3398 bool isAccessDeclaration() const { return UsingLocation.isInvalid(); }
3399
3400 /// Return true if the using declaration has 'typename'.
3401 bool hasTypename() const { return FirstUsingShadow.getInt(); }
3402
3403 /// Sets whether the using declaration has 'typename'.
3404 void setTypename(bool TN) { FirstUsingShadow.setInt(TN); }
3405
3406 /// Iterates through the using shadow declarations associated with
3407 /// this using declaration.
3408 class shadow_iterator {
3409 /// The current using shadow declaration.
3410 UsingShadowDecl *Current = nullptr;
3411
3412 public:
3413 using value_type = UsingShadowDecl *;
3414 using reference = UsingShadowDecl *;
3415 using pointer = UsingShadowDecl *;
3416 using iterator_category = std::forward_iterator_tag;
3417 using difference_type = std::ptrdiff_t;
3418
3419 shadow_iterator() = default;
3420 explicit shadow_iterator(UsingShadowDecl *C) : Current(C) {}
3421
3422 reference operator*() const { return Current; }
3423 pointer operator->() const { return Current; }
3424
3425 shadow_iterator& operator++() {
3426 Current = Current->getNextUsingShadowDecl();
3427 return *this;
3428 }
3429
3430 shadow_iterator operator++(int) {
3431 shadow_iterator tmp(*this);
3432 ++(*this);
3433 return tmp;
3434 }
3435
3436 friend bool operator==(shadow_iterator x, shadow_iterator y) {
3437 return x.Current == y.Current;
3438 }
3439 friend bool operator!=(shadow_iterator x, shadow_iterator y) {
3440 return x.Current != y.Current;
3441 }
3442 };
3443
3444 using shadow_range = llvm::iterator_range<shadow_iterator>;
3445
3446 shadow_range shadows() const {
3447 return shadow_range(shadow_begin(), shadow_end());
3448 }
3449
3450 shadow_iterator shadow_begin() const {
3451 return shadow_iterator(FirstUsingShadow.getPointer());
3452 }
3453
3454 shadow_iterator shadow_end() const { return shadow_iterator(); }
3455
3456 /// Return the number of shadowed declarations associated with this
3457 /// using declaration.
3458 unsigned shadow_size() const {
3459 return std::distance(shadow_begin(), shadow_end());
3460 }
3461
3462 void addShadowDecl(UsingShadowDecl *S);
3463 void removeShadowDecl(UsingShadowDecl *S);
3464
3465 static UsingDecl *Create(ASTContext &C, DeclContext *DC,
3466 SourceLocation UsingL,
3467 NestedNameSpecifierLoc QualifierLoc,
3468 const DeclarationNameInfo &NameInfo,
3469 bool HasTypenameKeyword);
3470
3471 static UsingDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3472
3473 SourceRange getSourceRange() const override LLVM_READONLY;
3474
3475 /// Retrieves the canonical declaration of this declaration.
3476 UsingDecl *getCanonicalDecl() override { return getFirstDecl(); }
3477 const UsingDecl *getCanonicalDecl() const { return getFirstDecl(); }
3478
3479 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3480 static bool classofKind(Kind K) { return K == Using; }
3481};
3482
3483/// Represents a pack of using declarations that a single
3484/// using-declarator pack-expanded into.
3485///
3486/// \code
3487/// template<typename ...T> struct X : T... {
3488/// using T::operator()...;
3489/// using T::operator T...;
3490/// };
3491/// \endcode
3492///
3493/// In the second case above, the UsingPackDecl will have the name
3494/// 'operator T' (which contains an unexpanded pack), but the individual
3495/// UsingDecls and UsingShadowDecls will have more reasonable names.
3496class UsingPackDecl final
3497 : public NamedDecl, public Mergeable<UsingPackDecl>,
3498 private llvm::TrailingObjects<UsingPackDecl, NamedDecl *> {
3499 /// The UnresolvedUsingValueDecl or UnresolvedUsingTypenameDecl from
3500 /// which this waas instantiated.
3501 NamedDecl *InstantiatedFrom;
3502
3503 /// The number of using-declarations created by this pack expansion.
3504 unsigned NumExpansions;
3505
3506 UsingPackDecl(DeclContext *DC, NamedDecl *InstantiatedFrom,
3507 ArrayRef<NamedDecl *> UsingDecls)
3508 : NamedDecl(UsingPack, DC,
3509 InstantiatedFrom ? InstantiatedFrom->getLocation()
3510 : SourceLocation(),
3511 InstantiatedFrom ? InstantiatedFrom->getDeclName()
3512 : DeclarationName()),
3513 InstantiatedFrom(InstantiatedFrom), NumExpansions(UsingDecls.size()) {
3514 std::uninitialized_copy(UsingDecls.begin(), UsingDecls.end(),
3515 getTrailingObjects<NamedDecl *>());
3516 }
3517
3518 void anchor() override;
3519
3520public:
3521 friend class ASTDeclReader;
3522 friend class ASTDeclWriter;
3523 friend TrailingObjects;
3524
3525 /// Get the using declaration from which this was instantiated. This will
3526 /// always be an UnresolvedUsingValueDecl or an UnresolvedUsingTypenameDecl
3527 /// that is a pack expansion.
3528 NamedDecl *getInstantiatedFromUsingDecl() const { return InstantiatedFrom; }
3529
3530 /// Get the set of using declarations that this pack expanded into. Note that
3531 /// some of these may still be unresolved.
3532 ArrayRef<NamedDecl *> expansions() const {
3533 return llvm::makeArrayRef(getTrailingObjects<NamedDecl *>(), NumExpansions);
3534 }
3535
3536 static UsingPackDecl *Create(ASTContext &C, DeclContext *DC,
3537 NamedDecl *InstantiatedFrom,
3538 ArrayRef<NamedDecl *> UsingDecls);
3539
3540 static UsingPackDecl *