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