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