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