Home | History | Annotate | Download | only in AST
      1 //===-- DeclTemplate.h - Classes for representing C++ templates -*- C++ -*-===//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 ///
     10 /// \file
     11 /// \brief Defines the C++ template declaration subclasses.
     12 ///
     13 //===----------------------------------------------------------------------===//
     14 
     15 #ifndef LLVM_CLANG_AST_DECLTEMPLATE_H
     16 #define LLVM_CLANG_AST_DECLTEMPLATE_H
     17 
     18 #include "clang/AST/DeclCXX.h"
     19 #include "clang/AST/Redeclarable.h"
     20 #include "clang/AST/TemplateBase.h"
     21 #include "llvm/ADT/PointerUnion.h"
     22 #include "llvm/Support/Compiler.h"
     23 #include "llvm/Support/TrailingObjects.h"
     24 #include <utility>
     25 
     26 namespace clang {
     27 
     28 enum BuiltinTemplateKind : int;
     29 class TemplateParameterList;
     30 class TemplateDecl;
     31 class RedeclarableTemplateDecl;
     32 class FunctionTemplateDecl;
     33 class ClassTemplateDecl;
     34 class ClassTemplatePartialSpecializationDecl;
     35 class TemplateTypeParmDecl;
     36 class NonTypeTemplateParmDecl;
     37 class TemplateTemplateParmDecl;
     38 class TypeAliasTemplateDecl;
     39 class VarTemplateDecl;
     40 class VarTemplatePartialSpecializationDecl;
     41 
     42 /// \brief Stores a template parameter of any kind.
     43 typedef llvm::PointerUnion3<TemplateTypeParmDecl*, NonTypeTemplateParmDecl*,
     44                             TemplateTemplateParmDecl*> TemplateParameter;
     45 
     46 NamedDecl *getAsNamedDecl(TemplateParameter P);
     47 
     48 /// \brief Stores a list of template parameters for a TemplateDecl and its
     49 /// derived classes.
     50 class TemplateParameterList final
     51     : private llvm::TrailingObjects<TemplateParameterList, NamedDecl *,
     52                                     Expr *> {
     53 
     54   /// The location of the 'template' keyword.
     55   SourceLocation TemplateLoc;
     56 
     57   /// The locations of the '<' and '>' angle brackets.
     58   SourceLocation LAngleLoc, RAngleLoc;
     59 
     60   /// The number of template parameters in this template
     61   /// parameter list.
     62   unsigned NumParams : 30;
     63 
     64   /// Whether this template parameter list contains an unexpanded parameter
     65   /// pack.
     66   unsigned ContainsUnexpandedParameterPack : 1;
     67 
     68   /// Whether this template parameter list has an associated requires-clause
     69   unsigned HasRequiresClause : 1;
     70 
     71 protected:
     72   size_t numTrailingObjects(OverloadToken<NamedDecl *>) const {
     73     return NumParams;
     74   }
     75 
     76   size_t numTrailingObjects(OverloadToken<Expr *>) const {
     77     return HasRequiresClause;
     78   }
     79 
     80   TemplateParameterList(SourceLocation TemplateLoc, SourceLocation LAngleLoc,
     81                         ArrayRef<NamedDecl *> Params, SourceLocation RAngleLoc,
     82                         Expr *RequiresClause);
     83 
     84 public:
     85   static TemplateParameterList *Create(const ASTContext &C,
     86                                        SourceLocation TemplateLoc,
     87                                        SourceLocation LAngleLoc,
     88                                        ArrayRef<NamedDecl *> Params,
     89                                        SourceLocation RAngleLoc,
     90                                        Expr *RequiresClause);
     91 
     92   /// \brief Iterates through the template parameters in this list.
     93   typedef NamedDecl** iterator;
     94 
     95   /// \brief Iterates through the template parameters in this list.
     96   typedef NamedDecl* const* const_iterator;
     97 
     98   iterator begin() { return getTrailingObjects<NamedDecl *>(); }
     99   const_iterator begin() const { return getTrailingObjects<NamedDecl *>(); }
    100   iterator end() { return begin() + NumParams; }
    101   const_iterator end() const { return begin() + NumParams; }
    102 
    103   unsigned size() const { return NumParams; }
    104 
    105   ArrayRef<NamedDecl*> asArray() {
    106     return llvm::makeArrayRef(begin(), end());
    107   }
    108   ArrayRef<const NamedDecl*> asArray() const {
    109     return llvm::makeArrayRef(begin(), size());
    110   }
    111 
    112   NamedDecl* getParam(unsigned Idx) {
    113     assert(Idx < size() && "Template parameter index out-of-range");
    114     return begin()[Idx];
    115   }
    116 
    117   const NamedDecl* getParam(unsigned Idx) const {
    118     assert(Idx < size() && "Template parameter index out-of-range");
    119     return begin()[Idx];
    120   }
    121 
    122   /// \brief Returns the minimum number of arguments needed to form a
    123   /// template specialization.
    124   ///
    125   /// This may be fewer than the number of template parameters, if some of
    126   /// the parameters have default arguments or if there is a parameter pack.
    127   unsigned getMinRequiredArguments() const;
    128 
    129   /// \brief Get the depth of this template parameter list in the set of
    130   /// template parameter lists.
    131   ///
    132   /// The first template parameter list in a declaration will have depth 0,
    133   /// the second template parameter list will have depth 1, etc.
    134   unsigned getDepth() const;
    135 
    136   /// \brief Determine whether this template parameter list contains an
    137   /// unexpanded parameter pack.
    138   bool containsUnexpandedParameterPack() const {
    139     return ContainsUnexpandedParameterPack;
    140   }
    141 
    142   /// \brief The constraint-expression of the associated requires-clause.
    143   Expr *getRequiresClause() {
    144     return HasRequiresClause ? *getTrailingObjects<Expr *>() : nullptr;
    145   }
    146 
    147   /// \brief The constraint-expression of the associated requires-clause.
    148   const Expr *getRequiresClause() const {
    149     return HasRequiresClause ? *getTrailingObjects<Expr *>() : nullptr;
    150   }
    151 
    152   SourceLocation getTemplateLoc() const { return TemplateLoc; }
    153   SourceLocation getLAngleLoc() const { return LAngleLoc; }
    154   SourceLocation getRAngleLoc() const { return RAngleLoc; }
    155 
    156   SourceRange getSourceRange() const LLVM_READONLY {
    157     return SourceRange(TemplateLoc, RAngleLoc);
    158   }
    159 
    160   friend TrailingObjects;
    161 
    162   template <size_t N, bool HasRequiresClause>
    163   friend class FixedSizeTemplateParameterListStorage;
    164 
    165 public:
    166   // FIXME: workaround for MSVC 2013; remove when no longer needed
    167   using FixedSizeStorageOwner = TrailingObjects::FixedSizeStorageOwner;
    168 };
    169 
    170 /// \brief Stores a list of template parameters and the associated
    171 /// requires-clause (if any) for a TemplateDecl and its derived classes.
    172 /// Suitable for creating on the stack.
    173 template <size_t N, bool HasRequiresClause>
    174 class FixedSizeTemplateParameterListStorage
    175     : public TemplateParameterList::FixedSizeStorageOwner {
    176   typename TemplateParameterList::FixedSizeStorage<
    177       NamedDecl *, Expr *>::with_counts<
    178       N, HasRequiresClause ? 1u : 0u
    179       >::type storage;
    180 
    181 public:
    182   FixedSizeTemplateParameterListStorage(SourceLocation TemplateLoc,
    183                                         SourceLocation LAngleLoc,
    184                                         ArrayRef<NamedDecl *> Params,
    185                                         SourceLocation RAngleLoc,
    186                                         Expr *RequiresClause)
    187       : FixedSizeStorageOwner(
    188             (assert(N == Params.size()),
    189              assert(HasRequiresClause == static_cast<bool>(RequiresClause)),
    190              new (static_cast<void *>(&storage)) TemplateParameterList(
    191                  TemplateLoc, LAngleLoc, Params, RAngleLoc, RequiresClause))) {}
    192 };
    193 
    194 /// \brief A template argument list.
    195 class TemplateArgumentList final
    196     : private llvm::TrailingObjects<TemplateArgumentList, TemplateArgument> {
    197   /// \brief The template argument list.
    198   const TemplateArgument *Arguments;
    199 
    200   /// \brief The number of template arguments in this template
    201   /// argument list.
    202   unsigned NumArguments;
    203 
    204   TemplateArgumentList(const TemplateArgumentList &Other) = delete;
    205   void operator=(const TemplateArgumentList &Other) = delete;
    206 
    207   // Constructs an instance with an internal Argument list, containing
    208   // a copy of the Args array. (Called by CreateCopy)
    209   TemplateArgumentList(ArrayRef<TemplateArgument> Args);
    210 
    211 public:
    212   /// \brief Type used to indicate that the template argument list itself is a
    213   /// stack object. It does not own its template arguments.
    214   enum OnStackType { OnStack };
    215 
    216   /// \brief Create a new template argument list that copies the given set of
    217   /// template arguments.
    218   static TemplateArgumentList *CreateCopy(ASTContext &Context,
    219                                           ArrayRef<TemplateArgument> Args);
    220 
    221   /// \brief Construct a new, temporary template argument list on the stack.
    222   ///
    223   /// The template argument list does not own the template arguments
    224   /// provided.
    225   explicit TemplateArgumentList(OnStackType, ArrayRef<TemplateArgument> Args)
    226       : Arguments(Args.data()), NumArguments(Args.size()) {}
    227 
    228   /// \brief Produces a shallow copy of the given template argument list.
    229   ///
    230   /// This operation assumes that the input argument list outlives it.
    231   /// This takes the list as a pointer to avoid looking like a copy
    232   /// constructor, since this really really isn't safe to use that
    233   /// way.
    234   explicit TemplateArgumentList(const TemplateArgumentList *Other)
    235       : Arguments(Other->data()), NumArguments(Other->size()) {}
    236 
    237   /// \brief Retrieve the template argument at a given index.
    238   const TemplateArgument &get(unsigned Idx) const {
    239     assert(Idx < NumArguments && "Invalid template argument index");
    240     return data()[Idx];
    241   }
    242 
    243   /// \brief Retrieve the template argument at a given index.
    244   const TemplateArgument &operator[](unsigned Idx) const { return get(Idx); }
    245 
    246   /// \brief Produce this as an array ref.
    247   ArrayRef<TemplateArgument> asArray() const {
    248     return llvm::makeArrayRef(data(), size());
    249   }
    250 
    251   /// \brief Retrieve the number of template arguments in this
    252   /// template argument list.
    253   unsigned size() const { return NumArguments; }
    254 
    255   /// \brief Retrieve a pointer to the template argument list.
    256   const TemplateArgument *data() const { return Arguments; }
    257 
    258   friend TrailingObjects;
    259 };
    260 
    261 void *allocateDefaultArgStorageChain(const ASTContext &C);
    262 
    263 /// Storage for a default argument. This is conceptually either empty, or an
    264 /// argument value, or a pointer to a previous declaration that had a default
    265 /// argument.
    266 ///
    267 /// However, this is complicated by modules: while we require all the default
    268 /// arguments for a template to be equivalent, there may be more than one, and
    269 /// we need to track all the originating parameters to determine if the default
    270 /// argument is visible.
    271 template<typename ParmDecl, typename ArgType>
    272 class DefaultArgStorage {
    273   /// Storage for both the value *and* another parameter from which we inherit
    274   /// the default argument. This is used when multiple default arguments for a
    275   /// parameter are merged together from different modules.
    276   struct Chain {
    277     ParmDecl *PrevDeclWithDefaultArg;
    278     ArgType Value;
    279   };
    280   static_assert(sizeof(Chain) == sizeof(void *) * 2,
    281                 "non-pointer argument type?");
    282 
    283   llvm::PointerUnion3<ArgType, ParmDecl*, Chain*> ValueOrInherited;
    284 
    285   static ParmDecl *getParmOwningDefaultArg(ParmDecl *Parm) {
    286     const DefaultArgStorage &Storage = Parm->getDefaultArgStorage();
    287     if (auto *Prev = Storage.ValueOrInherited.template dyn_cast<ParmDecl*>())
    288       Parm = Prev;
    289     assert(!Parm->getDefaultArgStorage()
    290                 .ValueOrInherited.template is<ParmDecl *>() &&
    291            "should only be one level of indirection");
    292     return Parm;
    293   }
    294 
    295 public:
    296   DefaultArgStorage() : ValueOrInherited(ArgType()) {}
    297 
    298   /// Determine whether there is a default argument for this parameter.
    299   bool isSet() const { return !ValueOrInherited.isNull(); }
    300   /// Determine whether the default argument for this parameter was inherited
    301   /// from a previous declaration of the same entity.
    302   bool isInherited() const { return ValueOrInherited.template is<ParmDecl*>(); }
    303   /// Get the default argument's value. This does not consider whether the
    304   /// default argument is visible.
    305   ArgType get() const {
    306     const DefaultArgStorage *Storage = this;
    307     if (auto *Prev = ValueOrInherited.template dyn_cast<ParmDecl*>())
    308       Storage = &Prev->getDefaultArgStorage();
    309     if (auto *C = Storage->ValueOrInherited.template dyn_cast<Chain*>())
    310       return C->Value;
    311     return Storage->ValueOrInherited.template get<ArgType>();
    312   }
    313   /// Get the parameter from which we inherit the default argument, if any.
    314   /// This is the parameter on which the default argument was actually written.
    315   const ParmDecl *getInheritedFrom() const {
    316     if (auto *D = ValueOrInherited.template dyn_cast<ParmDecl*>())
    317       return D;
    318     if (auto *C = ValueOrInherited.template dyn_cast<Chain*>())
    319       return C->PrevDeclWithDefaultArg;
    320     return nullptr;
    321   }
    322   /// Set the default argument.
    323   void set(ArgType Arg) {
    324     assert(!isSet() && "default argument already set");
    325     ValueOrInherited = Arg;
    326   }
    327   /// Set that the default argument was inherited from another parameter.
    328   void setInherited(const ASTContext &C, ParmDecl *InheritedFrom) {
    329     assert(!isInherited() && "default argument already inherited");
    330     InheritedFrom = getParmOwningDefaultArg(InheritedFrom);
    331     if (!isSet())
    332       ValueOrInherited = InheritedFrom;
    333     else
    334       ValueOrInherited = new (allocateDefaultArgStorageChain(C))
    335           Chain{InheritedFrom, ValueOrInherited.template get<ArgType>()};
    336   }
    337   /// Remove the default argument, even if it was inherited.
    338   void clear() {
    339     ValueOrInherited = ArgType();
    340   }
    341 };
    342 
    343 //===----------------------------------------------------------------------===//
    344 // Kinds of Templates
    345 //===----------------------------------------------------------------------===//
    346 
    347 /// \brief Stores the template parameter list and associated constraints for
    348 /// \c TemplateDecl objects that track associated constraints.
    349 class ConstrainedTemplateDeclInfo {
    350   friend TemplateDecl;
    351 
    352 public:
    353   ConstrainedTemplateDeclInfo() : TemplateParams(), AssociatedConstraints() {}
    354 
    355   TemplateParameterList *getTemplateParameters() const {
    356     return TemplateParams;
    357   }
    358 
    359   Expr *getAssociatedConstraints() const { return AssociatedConstraints; }
    360 
    361 protected:
    362   void setTemplateParameters(TemplateParameterList *TParams) {
    363     TemplateParams = TParams;
    364   }
    365 
    366   void setAssociatedConstraints(Expr *AC) { AssociatedConstraints = AC; }
    367 
    368   TemplateParameterList *TemplateParams;
    369   Expr *AssociatedConstraints;
    370 };
    371 
    372 
    373 /// \brief The base class of all kinds of template declarations (e.g.,
    374 /// class, function, etc.).
    375 ///
    376 /// The TemplateDecl class stores the list of template parameters and a
    377 /// reference to the templated scoped declaration: the underlying AST node.
    378 class TemplateDecl : public NamedDecl {
    379   void anchor() override;
    380 protected:
    381   // Construct a template decl with the given name and parameters.
    382   // Used when there is no templated element (e.g., for tt-params).
    383   TemplateDecl(ConstrainedTemplateDeclInfo *CTDI, Kind DK, DeclContext *DC,
    384                SourceLocation L, DeclarationName Name,
    385                TemplateParameterList *Params)
    386       : NamedDecl(DK, DC, L, Name), TemplatedDecl(nullptr, false),
    387         TemplateParams(CTDI) {
    388     this->setTemplateParameters(Params);
    389   }
    390 
    391   TemplateDecl(Kind DK, DeclContext *DC, SourceLocation L, DeclarationName Name,
    392                TemplateParameterList *Params)
    393       : TemplateDecl(nullptr, DK, DC, L, Name, Params) {}
    394 
    395   // Construct a template decl with name, parameters, and templated element.
    396   TemplateDecl(ConstrainedTemplateDeclInfo *CTDI, Kind DK, DeclContext *DC,
    397                SourceLocation L, DeclarationName Name,
    398                TemplateParameterList *Params, NamedDecl *Decl)
    399       : NamedDecl(DK, DC, L, Name), TemplatedDecl(Decl, false),
    400         TemplateParams(CTDI) {
    401     this->setTemplateParameters(Params);
    402   }
    403 
    404   TemplateDecl(Kind DK, DeclContext *DC, SourceLocation L, DeclarationName Name,
    405                TemplateParameterList *Params, NamedDecl *Decl)
    406       : TemplateDecl(nullptr, DK, DC, L, Name, Params, Decl) {}
    407 
    408 public:
    409   /// Get the list of template parameters
    410   TemplateParameterList *getTemplateParameters() const {
    411     const auto *const CTDI =
    412         TemplateParams.dyn_cast<ConstrainedTemplateDeclInfo *>();
    413     return CTDI ? CTDI->getTemplateParameters()
    414                 : TemplateParams.get<TemplateParameterList *>();
    415   }
    416 
    417   /// Get the constraint-expression from the associated requires-clause (if any)
    418   const Expr *getRequiresClause() const {
    419     const TemplateParameterList *const TP = getTemplateParameters();
    420     return TP ? TP->getRequiresClause() : nullptr;
    421   }
    422 
    423   Expr *getAssociatedConstraints() const {
    424     const TemplateDecl *const C = cast<TemplateDecl>(getCanonicalDecl());
    425     const auto *const CTDI =
    426         C->TemplateParams.dyn_cast<ConstrainedTemplateDeclInfo *>();
    427     return CTDI ? CTDI->getAssociatedConstraints() : nullptr;
    428   }
    429 
    430   /// Get the underlying, templated declaration.
    431   NamedDecl *getTemplatedDecl() const { return TemplatedDecl.getPointer(); }
    432 
    433   // Implement isa/cast/dyncast/etc.
    434   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
    435   static bool classofKind(Kind K) {
    436     return K >= firstTemplate && K <= lastTemplate;
    437   }
    438 
    439   SourceRange getSourceRange() const override LLVM_READONLY {
    440     return SourceRange(getTemplateParameters()->getTemplateLoc(),
    441                        TemplatedDecl.getPointer()->getSourceRange().getEnd());
    442   }
    443 
    444   /// Whether this is a (C++ Concepts TS) function or variable concept.
    445   bool isConcept() const { return TemplatedDecl.getInt(); }
    446   void setConcept() { TemplatedDecl.setInt(true); }
    447 
    448 protected:
    449   /// \brief The named declaration from which this template was instantiated.
    450   /// (or null).
    451   ///
    452   /// The boolean value will be true to indicate that this template
    453   /// (function or variable) is a concept.
    454   llvm::PointerIntPair<NamedDecl *, 1, bool> TemplatedDecl;
    455 
    456   /// \brief The template parameter list and optional requires-clause
    457   /// associated with this declaration; alternatively, a
    458   /// \c ConstrainedTemplateDeclInfo if the associated constraints of the
    459   /// template are being tracked by this particular declaration.
    460   llvm::PointerUnion<TemplateParameterList *,
    461                      ConstrainedTemplateDeclInfo *>
    462       TemplateParams;
    463 
    464   void setTemplateParameters(TemplateParameterList *TParams) {
    465     if (auto *const CTDI =
    466             TemplateParams.dyn_cast<ConstrainedTemplateDeclInfo *>()) {
    467       CTDI->setTemplateParameters(TParams);
    468     } else {
    469       TemplateParams = TParams;
    470     }
    471   }
    472 
    473   void setAssociatedConstraints(Expr *AC) {
    474     assert(isCanonicalDecl() &&
    475            "Attaching associated constraints to non-canonical Decl");
    476     TemplateParams.get<ConstrainedTemplateDeclInfo *>()
    477         ->setAssociatedConstraints(AC);
    478   }
    479 
    480 public:
    481   /// \brief Initialize the underlying templated declaration and
    482   /// template parameters.
    483   void init(NamedDecl *templatedDecl, TemplateParameterList* templateParams) {
    484     assert(!TemplatedDecl.getPointer() && "TemplatedDecl already set!");
    485     assert(!TemplateParams && "TemplateParams already set!");
    486     TemplatedDecl.setPointer(templatedDecl);
    487     TemplateParams = templateParams;
    488   }
    489 };
    490 
    491 /// \brief Provides information about a function template specialization,
    492 /// which is a FunctionDecl that has been explicitly specialization or
    493 /// instantiated from a function template.
    494 class FunctionTemplateSpecializationInfo : public llvm::FoldingSetNode {
    495   FunctionTemplateSpecializationInfo(FunctionDecl *FD,
    496                                      FunctionTemplateDecl *Template,
    497                                      TemplateSpecializationKind TSK,
    498                                      const TemplateArgumentList *TemplateArgs,
    499                        const ASTTemplateArgumentListInfo *TemplateArgsAsWritten,
    500                                      SourceLocation POI)
    501   : Function(FD),
    502     Template(Template, TSK - 1),
    503     TemplateArguments(TemplateArgs),
    504     TemplateArgumentsAsWritten(TemplateArgsAsWritten),
    505     PointOfInstantiation(POI) { }
    506 
    507 public:
    508   static FunctionTemplateSpecializationInfo *
    509   Create(ASTContext &C, FunctionDecl *FD, FunctionTemplateDecl *Template,
    510          TemplateSpecializationKind TSK,
    511          const TemplateArgumentList *TemplateArgs,
    512          const TemplateArgumentListInfo *TemplateArgsAsWritten,
    513          SourceLocation POI);
    514 
    515   /// \brief The function template specialization that this structure
    516   /// describes.
    517   FunctionDecl *Function;
    518 
    519   /// \brief The function template from which this function template
    520   /// specialization was generated.
    521   ///
    522   /// The two bits contain the top 4 values of TemplateSpecializationKind.
    523   llvm::PointerIntPair<FunctionTemplateDecl *, 2> Template;
    524 
    525   /// \brief The template arguments used to produce the function template
    526   /// specialization from the function template.
    527   const TemplateArgumentList *TemplateArguments;
    528 
    529   /// \brief The template arguments as written in the sources, if provided.
    530   const ASTTemplateArgumentListInfo *TemplateArgumentsAsWritten;
    531 
    532   /// \brief The point at which this function template specialization was
    533   /// first instantiated.
    534   SourceLocation PointOfInstantiation;
    535 
    536   /// \brief Retrieve the template from which this function was specialized.
    537   FunctionTemplateDecl *getTemplate() const { return Template.getPointer(); }
    538 
    539   /// \brief Determine what kind of template specialization this is.
    540   TemplateSpecializationKind getTemplateSpecializationKind() const {
    541     return (TemplateSpecializationKind)(Template.getInt() + 1);
    542   }
    543 
    544   bool isExplicitSpecialization() const {
    545     return getTemplateSpecializationKind() == TSK_ExplicitSpecialization;
    546   }
    547 
    548   /// \brief True if this declaration is an explicit specialization,
    549   /// explicit instantiation declaration, or explicit instantiation
    550   /// definition.
    551   bool isExplicitInstantiationOrSpecialization() const {
    552     return isTemplateExplicitInstantiationOrSpecialization(
    553         getTemplateSpecializationKind());
    554   }
    555 
    556   /// \brief Set the template specialization kind.
    557   void setTemplateSpecializationKind(TemplateSpecializationKind TSK) {
    558     assert(TSK != TSK_Undeclared &&
    559          "Cannot encode TSK_Undeclared for a function template specialization");
    560     Template.setInt(TSK - 1);
    561   }
    562 
    563   /// \brief Retrieve the first point of instantiation of this function
    564   /// template specialization.
    565   ///
    566   /// The point of instantiation may be an invalid source location if this
    567   /// function has yet to be instantiated.
    568   SourceLocation getPointOfInstantiation() const {
    569     return PointOfInstantiation;
    570   }
    571 
    572   /// \brief Set the (first) point of instantiation of this function template
    573   /// specialization.
    574   void setPointOfInstantiation(SourceLocation POI) {
    575     PointOfInstantiation = POI;
    576   }
    577 
    578   void Profile(llvm::FoldingSetNodeID &ID) {
    579     Profile(ID, TemplateArguments->asArray(),
    580             Function->getASTContext());
    581   }
    582 
    583   static void
    584   Profile(llvm::FoldingSetNodeID &ID, ArrayRef<TemplateArgument> TemplateArgs,
    585           ASTContext &Context) {
    586     ID.AddInteger(TemplateArgs.size());
    587     for (const TemplateArgument &TemplateArg : TemplateArgs)
    588       TemplateArg.Profile(ID, Context);
    589   }
    590 };
    591 
    592 /// \brief Provides information a specialization of a member of a class
    593 /// template, which may be a member function, static data member,
    594 /// member class or member enumeration.
    595 class MemberSpecializationInfo {
    596   // The member declaration from which this member was instantiated, and the
    597   // manner in which the instantiation occurred (in the lower two bits).
    598   llvm::PointerIntPair<NamedDecl *, 2> MemberAndTSK;
    599 
    600   // The point at which this member was first instantiated.
    601   SourceLocation PointOfInstantiation;
    602 
    603 public:
    604   explicit
    605   MemberSpecializationInfo(NamedDecl *IF, TemplateSpecializationKind TSK,
    606                            SourceLocation POI = SourceLocation())
    607     : MemberAndTSK(IF, TSK - 1), PointOfInstantiation(POI) {
    608     assert(TSK != TSK_Undeclared &&
    609            "Cannot encode undeclared template specializations for members");
    610   }
    611 
    612   /// \brief Retrieve the member declaration from which this member was
    613   /// instantiated.
    614   NamedDecl *getInstantiatedFrom() const { return MemberAndTSK.getPointer(); }
    615 
    616   /// \brief Determine what kind of template specialization this is.
    617   TemplateSpecializationKind getTemplateSpecializationKind() const {
    618     return (TemplateSpecializationKind)(MemberAndTSK.getInt() + 1);
    619   }
    620 
    621   bool isExplicitSpecialization() const {
    622     return getTemplateSpecializationKind() == TSK_ExplicitSpecialization;
    623   }
    624 
    625   /// \brief Set the template specialization kind.
    626   void setTemplateSpecializationKind(TemplateSpecializationKind TSK) {
    627     assert(TSK != TSK_Undeclared &&
    628            "Cannot encode undeclared template specializations for members");
    629     MemberAndTSK.setInt(TSK - 1);
    630   }
    631 
    632   /// \brief Retrieve the first point of instantiation of this member.
    633   /// If the point of instantiation is an invalid location, then this member
    634   /// has not yet been instantiated.
    635   SourceLocation getPointOfInstantiation() const {
    636     return PointOfInstantiation;
    637   }
    638 
    639   /// \brief Set the first point of instantiation.
    640   void setPointOfInstantiation(SourceLocation POI) {
    641     PointOfInstantiation = POI;
    642   }
    643 };
    644 
    645 /// \brief Provides information about a dependent function-template
    646 /// specialization declaration.
    647 ///
    648 /// Since explicit function template specialization and instantiation
    649 /// declarations can only appear in namespace scope, and you can only
    650 /// specialize a member of a fully-specialized class, the only way to
    651 /// get one of these is in a friend declaration like the following:
    652 ///
    653 /// \code
    654 ///   template \<class T> void foo(T);
    655 ///   template \<class T> class A {
    656 ///     friend void foo<>(T);
    657 ///   };
    658 /// \endcode
    659 class DependentFunctionTemplateSpecializationInfo final
    660     : private llvm::TrailingObjects<DependentFunctionTemplateSpecializationInfo,
    661                                     TemplateArgumentLoc,
    662                                     FunctionTemplateDecl *> {
    663   /// The number of potential template candidates.
    664   unsigned NumTemplates;
    665 
    666   /// The number of template arguments.
    667   unsigned NumArgs;
    668 
    669   /// The locations of the left and right angle brackets.
    670   SourceRange AngleLocs;
    671 
    672   size_t numTrailingObjects(OverloadToken<TemplateArgumentLoc>) const {
    673     return NumArgs;
    674   }
    675   size_t numTrailingObjects(OverloadToken<FunctionTemplateDecl *>) const {
    676     return NumTemplates;
    677   }
    678 
    679   DependentFunctionTemplateSpecializationInfo(
    680                                  const UnresolvedSetImpl &Templates,
    681                                  const TemplateArgumentListInfo &TemplateArgs);
    682 
    683 public:
    684   static DependentFunctionTemplateSpecializationInfo *
    685   Create(ASTContext &Context, const UnresolvedSetImpl &Templates,
    686          const TemplateArgumentListInfo &TemplateArgs);
    687 
    688   /// \brief Returns the number of function templates that this might
    689   /// be a specialization of.
    690   unsigned getNumTemplates() const { return NumTemplates; }
    691 
    692   /// \brief Returns the i'th template candidate.
    693   FunctionTemplateDecl *getTemplate(unsigned I) const {
    694     assert(I < getNumTemplates() && "template index out of range");
    695     return getTrailingObjects<FunctionTemplateDecl *>()[I];
    696   }
    697 
    698   /// \brief Returns the explicit template arguments that were given.
    699   const TemplateArgumentLoc *getTemplateArgs() const {
    700     return getTrailingObjects<TemplateArgumentLoc>();
    701   }
    702 
    703   /// \brief Returns the number of explicit template arguments that were given.
    704   unsigned getNumTemplateArgs() const { return NumArgs; }
    705 
    706   /// \brief Returns the nth template argument.
    707   const TemplateArgumentLoc &getTemplateArg(unsigned I) const {
    708     assert(I < getNumTemplateArgs() && "template arg index out of range");
    709     return getTemplateArgs()[I];
    710   }
    711 
    712   SourceLocation getLAngleLoc() const {
    713     return AngleLocs.getBegin();
    714   }
    715 
    716   SourceLocation getRAngleLoc() const {
    717     return AngleLocs.getEnd();
    718   }
    719 
    720   friend TrailingObjects;
    721 };
    722 
    723 /// Declaration of a redeclarable template.
    724 class RedeclarableTemplateDecl : public TemplateDecl,
    725                                  public Redeclarable<RedeclarableTemplateDecl>
    726 {
    727   typedef Redeclarable<RedeclarableTemplateDecl> redeclarable_base;
    728   RedeclarableTemplateDecl *getNextRedeclarationImpl() override {
    729     return getNextRedeclaration();
    730   }
    731   RedeclarableTemplateDecl *getPreviousDeclImpl() override {
    732     return getPreviousDecl();
    733   }
    734   RedeclarableTemplateDecl *getMostRecentDeclImpl() override {
    735     return getMostRecentDecl();
    736   }
    737 
    738 protected:
    739   template <typename EntryType> struct SpecEntryTraits {
    740     typedef EntryType DeclType;
    741 
    742     static DeclType *getDecl(EntryType *D) {
    743       return D;
    744     }
    745     static ArrayRef<TemplateArgument> getTemplateArgs(EntryType *D) {
    746       return D->getTemplateArgs().asArray();
    747     }
    748   };
    749 
    750   template <typename EntryType, typename SETraits = SpecEntryTraits<EntryType>,
    751             typename DeclType = typename SETraits::DeclType>
    752   struct SpecIterator
    753       : llvm::iterator_adaptor_base<
    754             SpecIterator<EntryType, SETraits, DeclType>,
    755             typename llvm::FoldingSetVector<EntryType>::iterator,
    756             typename std::iterator_traits<typename llvm::FoldingSetVector<
    757                 EntryType>::iterator>::iterator_category,
    758             DeclType *, ptrdiff_t, DeclType *, DeclType *> {
    759     SpecIterator() {}
    760     explicit SpecIterator(
    761         typename llvm::FoldingSetVector<EntryType>::iterator SetIter)
    762         : SpecIterator::iterator_adaptor_base(std::move(SetIter)) {}
    763 
    764     DeclType *operator*() const {
    765       return SETraits::getDecl(&*this->I)->getMostRecentDecl();
    766     }
    767     DeclType *operator->() const { return **this; }
    768   };
    769 
    770   template <typename EntryType>
    771   static SpecIterator<EntryType>
    772   makeSpecIterator(llvm::FoldingSetVector<EntryType> &Specs, bool isEnd) {
    773     return SpecIterator<EntryType>(isEnd ? Specs.end() : Specs.begin());
    774   }
    775 
    776   template <class EntryType> typename SpecEntryTraits<EntryType>::DeclType*
    777   findSpecializationImpl(llvm::FoldingSetVector<EntryType> &Specs,
    778                          ArrayRef<TemplateArgument> Args, void *&InsertPos);
    779 
    780   template <class Derived, class EntryType>
    781   void addSpecializationImpl(llvm::FoldingSetVector<EntryType> &Specs,
    782                              EntryType *Entry, void *InsertPos);
    783 
    784   struct CommonBase {
    785     CommonBase() : InstantiatedFromMember(nullptr, false) { }
    786 
    787     /// \brief The template from which this was most
    788     /// directly instantiated (or null).
    789     ///
    790     /// The boolean value indicates whether this template
    791     /// was explicitly specialized.
    792     llvm::PointerIntPair<RedeclarableTemplateDecl*, 1, bool>
    793       InstantiatedFromMember;
    794   };
    795 
    796   /// \brief Pointer to the common data shared by all declarations of this
    797   /// template.
    798   mutable CommonBase *Common;
    799 
    800   /// \brief Retrieves the "common" pointer shared by all (re-)declarations of
    801   /// the same template. Calling this routine may implicitly allocate memory
    802   /// for the common pointer.
    803   CommonBase *getCommonPtr() const;
    804 
    805   virtual CommonBase *newCommon(ASTContext &C) const = 0;
    806 
    807   // Construct a template decl with name, parameters, and templated element.
    808   RedeclarableTemplateDecl(ConstrainedTemplateDeclInfo *CTDI, Kind DK,
    809                            ASTContext &C, DeclContext *DC, SourceLocation L,
    810                            DeclarationName Name, TemplateParameterList *Params,
    811                            NamedDecl *Decl)
    812       : TemplateDecl(CTDI, DK, DC, L, Name, Params, Decl), redeclarable_base(C),
    813         Common() {}
    814 
    815   RedeclarableTemplateDecl(Kind DK, ASTContext &C, DeclContext *DC,
    816                            SourceLocation L, DeclarationName Name,
    817                            TemplateParameterList *Params, NamedDecl *Decl)
    818       : RedeclarableTemplateDecl(nullptr, DK, C, DC, L, Name, Params, Decl) {}
    819 
    820 public:
    821   template <class decl_type> friend class RedeclarableTemplate;
    822 
    823   /// \brief Retrieves the canonical declaration of this template.
    824   RedeclarableTemplateDecl *getCanonicalDecl() override {
    825     return getFirstDecl();
    826   }
    827   const RedeclarableTemplateDecl *getCanonicalDecl() const {
    828     return getFirstDecl();
    829   }
    830 
    831   /// \brief Determines whether this template was a specialization of a
    832   /// member template.
    833   ///
    834   /// In the following example, the function template \c X<int>::f and the
    835   /// member template \c X<int>::Inner are member specializations.
    836   ///
    837   /// \code
    838   /// template<typename T>
    839   /// struct X {
    840   ///   template<typename U> void f(T, U);
    841   ///   template<typename U> struct Inner;
    842   /// };
    843   ///
    844   /// template<> template<typename T>
    845   /// void X<int>::f(int, T);
    846   /// template<> template<typename T>
    847   /// struct X<int>::Inner { /* ... */ };
    848   /// \endcode
    849   bool isMemberSpecialization() const {
    850     return getCommonPtr()->InstantiatedFromMember.getInt();
    851   }
    852 
    853   /// \brief Note that this member template is a specialization.
    854   void setMemberSpecialization() {
    855     assert(getCommonPtr()->InstantiatedFromMember.getPointer() &&
    856            "Only member templates can be member template specializations");
    857     getCommonPtr()->InstantiatedFromMember.setInt(true);
    858   }
    859 
    860   /// \brief Retrieve the member template from which this template was
    861   /// instantiated, or NULL if this template was not instantiated from a
    862   /// member template.
    863   ///
    864   /// A template is instantiated from a member template when the member
    865   /// template itself is part of a class template (or member thereof). For
    866   /// example, given
    867   ///
    868   /// \code
    869   /// template<typename T>
    870   /// struct X {
    871   ///   template<typename U> void f(T, U);
    872   /// };
    873   ///
    874   /// void test(X<int> x) {
    875   ///   x.f(1, 'a');
    876   /// };
    877   /// \endcode
    878   ///
    879   /// \c X<int>::f is a FunctionTemplateDecl that describes the function
    880   /// template
    881   ///
    882   /// \code
    883   /// template<typename U> void X<int>::f(int, U);
    884   /// \endcode
    885   ///
    886   /// which was itself created during the instantiation of \c X<int>. Calling
    887   /// getInstantiatedFromMemberTemplate() on this FunctionTemplateDecl will
    888   /// retrieve the FunctionTemplateDecl for the original template \c f within
    889   /// the class template \c X<T>, i.e.,
    890   ///
    891   /// \code
    892   /// template<typename T>
    893   /// template<typename U>
    894   /// void X<T>::f(T, U);
    895   /// \endcode
    896   RedeclarableTemplateDecl *getInstantiatedFromMemberTemplate() const {
    897     return getCommonPtr()->InstantiatedFromMember.getPointer();
    898   }
    899 
    900   void setInstantiatedFromMemberTemplate(RedeclarableTemplateDecl *TD) {
    901     assert(!getCommonPtr()->InstantiatedFromMember.getPointer());
    902     getCommonPtr()->InstantiatedFromMember.setPointer(TD);
    903   }
    904 
    905   typedef redeclarable_base::redecl_range redecl_range;
    906   typedef redeclarable_base::redecl_iterator redecl_iterator;
    907   using redeclarable_base::redecls_begin;
    908   using redeclarable_base::redecls_end;
    909   using redeclarable_base::redecls;
    910   using redeclarable_base::getPreviousDecl;
    911   using redeclarable_base::getMostRecentDecl;
    912   using redeclarable_base::isFirstDecl;
    913 
    914   // Implement isa/cast/dyncast/etc.
    915   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
    916   static bool classofKind(Kind K) {
    917     return K >= firstRedeclarableTemplate && K <= lastRedeclarableTemplate;
    918   }
    919 
    920   friend class ASTReader;
    921   friend class ASTDeclReader;
    922   friend class ASTDeclWriter;
    923 };
    924 
    925 template <> struct RedeclarableTemplateDecl::
    926 SpecEntryTraits<FunctionTemplateSpecializationInfo> {
    927   typedef FunctionDecl DeclType;
    928 
    929   static DeclType *getDecl(FunctionTemplateSpecializationInfo *I) {
    930     return I->Function;
    931   }
    932   static ArrayRef<TemplateArgument>
    933   getTemplateArgs(FunctionTemplateSpecializationInfo *I) {
    934     return I->TemplateArguments->asArray();
    935   }
    936 };
    937 
    938 /// Declaration of a template function.
    939 class FunctionTemplateDecl : public RedeclarableTemplateDecl {
    940 protected:
    941   /// \brief Data that is common to all of the declarations of a given
    942   /// function template.
    943   struct Common : CommonBase {
    944     Common() : InjectedArgs(), LazySpecializations() { }
    945 
    946     /// \brief The function template specializations for this function
    947     /// template, including explicit specializations and instantiations.
    948     llvm::FoldingSetVector<FunctionTemplateSpecializationInfo> Specializations;
    949 
    950     /// \brief The set of "injected" template arguments used within this
    951     /// function template.
    952     ///
    953     /// This pointer refers to the template arguments (there are as
    954     /// many template arguments as template parameaters) for the function
    955     /// template, and is allocated lazily, since most function templates do not
    956     /// require the use of this information.
    957     TemplateArgument *InjectedArgs;
    958 
    959     /// \brief If non-null, points to an array of specializations known only
    960     /// by their external declaration IDs.
    961     ///
    962     /// The first value in the array is the number of of specializations
    963     /// that follow.
    964     uint32_t *LazySpecializations;
    965   };
    966 
    967   FunctionTemplateDecl(ASTContext &C, DeclContext *DC, SourceLocation L,
    968                        DeclarationName Name, TemplateParameterList *Params,
    969                        NamedDecl *Decl)
    970       : RedeclarableTemplateDecl(FunctionTemplate, C, DC, L, Name, Params,
    971                                  Decl) {}
    972 
    973   CommonBase *newCommon(ASTContext &C) const override;
    974 
    975   Common *getCommonPtr() const {
    976     return static_cast<Common *>(RedeclarableTemplateDecl::getCommonPtr());
    977   }
    978 
    979   friend class FunctionDecl;
    980 
    981   /// \brief Retrieve the set of function template specializations of this
    982   /// function template.
    983   llvm::FoldingSetVector<FunctionTemplateSpecializationInfo> &
    984   getSpecializations() const;
    985 
    986   /// \brief Add a specialization of this function template.
    987   ///
    988   /// \param InsertPos Insert position in the FoldingSetVector, must have been
    989   ///        retrieved by an earlier call to findSpecialization().
    990   void addSpecialization(FunctionTemplateSpecializationInfo* Info,
    991                          void *InsertPos);
    992 
    993 public:
    994   /// \brief Load any lazily-loaded specializations from the external source.
    995   void LoadLazySpecializations() const;
    996 
    997   /// Get the underlying function declaration of the template.
    998   FunctionDecl *getTemplatedDecl() const {
    999     return static_cast<FunctionDecl *>(TemplatedDecl.getPointer());
   1000   }
   1001 
   1002   /// Returns whether this template declaration defines the primary
   1003   /// pattern.
   1004   bool isThisDeclarationADefinition() const {
   1005     return getTemplatedDecl()->isThisDeclarationADefinition();
   1006   }
   1007 
   1008   /// \brief Return the specialization with the provided arguments if it exists,
   1009   /// otherwise return the insertion point.
   1010   FunctionDecl *findSpecialization(ArrayRef<TemplateArgument> Args,
   1011                                    void *&InsertPos);
   1012 
   1013   FunctionTemplateDecl *getCanonicalDecl() override {
   1014     return cast<FunctionTemplateDecl>(
   1015              RedeclarableTemplateDecl::getCanonicalDecl());
   1016   }
   1017   const FunctionTemplateDecl *getCanonicalDecl() const {
   1018     return cast<FunctionTemplateDecl>(
   1019              RedeclarableTemplateDecl::getCanonicalDecl());
   1020   }
   1021 
   1022   /// \brief Retrieve the previous declaration of this function template, or
   1023   /// NULL if no such declaration exists.
   1024   FunctionTemplateDecl *getPreviousDecl() {
   1025     return cast_or_null<FunctionTemplateDecl>(
   1026              static_cast<RedeclarableTemplateDecl *>(this)->getPreviousDecl());
   1027   }
   1028 
   1029   /// \brief Retrieve the previous declaration of this function template, or
   1030   /// NULL if no such declaration exists.
   1031   const FunctionTemplateDecl *getPreviousDecl() const {
   1032     return cast_or_null<FunctionTemplateDecl>(
   1033        static_cast<const RedeclarableTemplateDecl *>(this)->getPreviousDecl());
   1034   }
   1035 
   1036   FunctionTemplateDecl *getMostRecentDecl() {
   1037     return cast<FunctionTemplateDecl>(
   1038         static_cast<RedeclarableTemplateDecl *>(this)
   1039             ->getMostRecentDecl());
   1040   }
   1041   const FunctionTemplateDecl *getMostRecentDecl() const {
   1042     return const_cast<FunctionTemplateDecl*>(this)->getMostRecentDecl();
   1043   }
   1044 
   1045   FunctionTemplateDecl *getInstantiatedFromMemberTemplate() const {
   1046     return cast_or_null<FunctionTemplateDecl>(
   1047              RedeclarableTemplateDecl::getInstantiatedFromMemberTemplate());
   1048   }
   1049 
   1050   typedef SpecIterator<FunctionTemplateSpecializationInfo> spec_iterator;
   1051   typedef llvm::iterator_range<spec_iterator> spec_range;
   1052 
   1053   spec_range specializations() const {
   1054     return spec_range(spec_begin(), spec_end());
   1055   }
   1056   spec_iterator spec_begin() const {
   1057     return makeSpecIterator(getSpecializations(), false);
   1058   }
   1059 
   1060   spec_iterator spec_end() const {
   1061     return makeSpecIterator(getSpecializations(), true);
   1062   }
   1063 
   1064   /// \brief Retrieve the "injected" template arguments that correspond to the
   1065   /// template parameters of this function template.
   1066   ///
   1067   /// Although the C++ standard has no notion of the "injected" template
   1068   /// arguments for a function template, the notion is convenient when
   1069   /// we need to perform substitutions inside the definition of a function
   1070   /// template.
   1071   ArrayRef<TemplateArgument> getInjectedTemplateArgs();
   1072 
   1073   /// \brief Create a function template node.
   1074   static FunctionTemplateDecl *Create(ASTContext &C, DeclContext *DC,
   1075                                       SourceLocation L,
   1076                                       DeclarationName Name,
   1077                                       TemplateParameterList *Params,
   1078                                       NamedDecl *Decl);
   1079 
   1080   /// \brief Create an empty function template node.
   1081   static FunctionTemplateDecl *CreateDeserialized(ASTContext &C, unsigned ID);
   1082 
   1083   // Implement isa/cast/dyncast support
   1084   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
   1085   static bool classofKind(Kind K) { return K == FunctionTemplate; }
   1086 
   1087   friend class ASTDeclReader;
   1088   friend class ASTDeclWriter;
   1089 };
   1090 
   1091 //===----------------------------------------------------------------------===//
   1092 // Kinds of Template Parameters
   1093 //===----------------------------------------------------------------------===//
   1094 
   1095 /// \brief Defines the position of a template parameter within a template
   1096 /// parameter list.
   1097 ///
   1098 /// Because template parameter can be listed
   1099 /// sequentially for out-of-line template members, each template parameter is
   1100 /// given a Depth - the nesting of template parameter scopes - and a Position -
   1101 /// the occurrence within the parameter list.
   1102 /// This class is inheritedly privately by different kinds of template
   1103 /// parameters and is not part of the Decl hierarchy. Just a facility.
   1104 class TemplateParmPosition {
   1105   TemplateParmPosition() = delete;
   1106 
   1107 protected:
   1108   TemplateParmPosition(unsigned D, unsigned P)
   1109     : Depth(D), Position(P)
   1110   { }
   1111 
   1112   // FIXME: These probably don't need to be ints. int:5 for depth, int:8 for
   1113   // position? Maybe?
   1114   unsigned Depth;
   1115   unsigned Position;
   1116 
   1117 public:
   1118   /// Get the nesting depth of the template parameter.
   1119   unsigned getDepth() const { return Depth; }
   1120   void setDepth(unsigned D) { Depth = D; }
   1121 
   1122   /// Get the position of the template parameter within its parameter list.
   1123   unsigned getPosition() const { return Position; }
   1124   void setPosition(unsigned P) { Position = P; }
   1125 
   1126   /// Get the index of the template parameter within its parameter list.
   1127   unsigned getIndex() const { return Position; }
   1128 };
   1129 
   1130 /// \brief Declaration of a template type parameter.
   1131 ///
   1132 /// For example, "T" in
   1133 /// \code
   1134 /// template<typename T> class vector;
   1135 /// \endcode
   1136 class TemplateTypeParmDecl : public TypeDecl {
   1137   /// \brief Whether this template type parameter was declaration with
   1138   /// the 'typename' keyword.
   1139   ///
   1140   /// If false, it was declared with the 'class' keyword.
   1141   bool Typename : 1;
   1142 
   1143   /// \brief The default template argument, if any.
   1144   typedef DefaultArgStorage<TemplateTypeParmDecl, TypeSourceInfo *>
   1145       DefArgStorage;
   1146   DefArgStorage DefaultArgument;
   1147 
   1148   TemplateTypeParmDecl(DeclContext *DC, SourceLocation KeyLoc,
   1149                        SourceLocation IdLoc, IdentifierInfo *Id,
   1150                        bool Typename)
   1151     : TypeDecl(TemplateTypeParm, DC, IdLoc, Id, KeyLoc), Typename(Typename),
   1152       DefaultArgument() { }
   1153 
   1154   /// Sema creates these on the stack during auto type deduction.
   1155   friend class Sema;
   1156 
   1157 public:
   1158   static TemplateTypeParmDecl *Create(const ASTContext &C, DeclContext *DC,
   1159                                       SourceLocation KeyLoc,
   1160                                       SourceLocation NameLoc,
   1161                                       unsigned D, unsigned P,
   1162                                       IdentifierInfo *Id, bool Typename,
   1163                                       bool ParameterPack);
   1164   static TemplateTypeParmDecl *CreateDeserialized(const ASTContext &C,
   1165                                                   unsigned ID);
   1166 
   1167   /// \brief Whether this template type parameter was declared with
   1168   /// the 'typename' keyword.
   1169   ///
   1170   /// If not, it was declared with the 'class' keyword.
   1171   bool wasDeclaredWithTypename() const { return Typename; }
   1172 
   1173   const DefArgStorage &getDefaultArgStorage() const { return DefaultArgument; }
   1174 
   1175   /// \brief Determine whether this template parameter has a default
   1176   /// argument.
   1177   bool hasDefaultArgument() const { return DefaultArgument.isSet(); }
   1178 
   1179   /// \brief Retrieve the default argument, if any.
   1180   QualType getDefaultArgument() const {
   1181     return DefaultArgument.get()->getType();
   1182   }
   1183 
   1184   /// \brief Retrieves the default argument's source information, if any.
   1185   TypeSourceInfo *getDefaultArgumentInfo() const {
   1186     return DefaultArgument.get();
   1187   }
   1188 
   1189   /// \brief Retrieves the location of the default argument declaration.
   1190   SourceLocation getDefaultArgumentLoc() const;
   1191 
   1192   /// \brief Determines whether the default argument was inherited
   1193   /// from a previous declaration of this template.
   1194   bool defaultArgumentWasInherited() const {
   1195     return DefaultArgument.isInherited();
   1196   }
   1197 
   1198   /// \brief Set the default argument for this template parameter.
   1199   void setDefaultArgument(TypeSourceInfo *DefArg) {
   1200     DefaultArgument.set(DefArg);
   1201   }
   1202   /// \brief Set that this default argument was inherited from another
   1203   /// parameter.
   1204   void setInheritedDefaultArgument(const ASTContext &C,
   1205                                    TemplateTypeParmDecl *Prev) {
   1206     DefaultArgument.setInherited(C, Prev);
   1207   }
   1208 
   1209   /// \brief Removes the default argument of this template parameter.
   1210   void removeDefaultArgument() {
   1211     DefaultArgument.clear();
   1212   }
   1213 
   1214   /// \brief Set whether this template type parameter was declared with
   1215   /// the 'typename' or 'class' keyword.
   1216   void setDeclaredWithTypename(bool withTypename) { Typename = withTypename; }
   1217 
   1218   /// \brief Retrieve the depth of the template parameter.
   1219   unsigned getDepth() const;
   1220 
   1221   /// \brief Retrieve the index of the template parameter.
   1222   unsigned getIndex() const;
   1223 
   1224   /// \brief Returns whether this is a parameter pack.
   1225   bool isParameterPack() const;
   1226 
   1227   SourceRange getSourceRange() const override LLVM_READONLY;
   1228 
   1229   // Implement isa/cast/dyncast/etc.
   1230   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
   1231   static bool classofKind(Kind K) { return K == TemplateTypeParm; }
   1232 };
   1233 
   1234 /// NonTypeTemplateParmDecl - Declares a non-type template parameter,
   1235 /// e.g., "Size" in
   1236 /// @code
   1237 /// template<int Size> class array { };
   1238 /// @endcode
   1239 class NonTypeTemplateParmDecl final
   1240     : public DeclaratorDecl,
   1241       protected TemplateParmPosition,
   1242       private llvm::TrailingObjects<NonTypeTemplateParmDecl,
   1243                                     std::pair<QualType, TypeSourceInfo *>> {
   1244   /// \brief The default template argument, if any, and whether or not
   1245   /// it was inherited.
   1246   typedef DefaultArgStorage<NonTypeTemplateParmDecl, Expr*> DefArgStorage;
   1247   DefArgStorage DefaultArgument;
   1248 
   1249   // FIXME: Collapse this into TemplateParamPosition; or, just move depth/index
   1250   // down here to save memory.
   1251 
   1252   /// \brief Whether this non-type template parameter is a parameter pack.
   1253   bool ParameterPack;
   1254 
   1255   /// \brief Whether this non-type template parameter is an "expanded"
   1256   /// parameter pack, meaning that its type is a pack expansion and we
   1257   /// already know the set of types that expansion expands to.
   1258   bool ExpandedParameterPack;
   1259 
   1260   /// \brief The number of types in an expanded parameter pack.
   1261   unsigned NumExpandedTypes;
   1262 
   1263   size_t numTrailingObjects(
   1264       OverloadToken<std::pair<QualType, TypeSourceInfo *>>) const {
   1265     return NumExpandedTypes;
   1266   }
   1267 
   1268   NonTypeTemplateParmDecl(DeclContext *DC, SourceLocation StartLoc,
   1269                           SourceLocation IdLoc, unsigned D, unsigned P,
   1270                           IdentifierInfo *Id, QualType T,
   1271                           bool ParameterPack, TypeSourceInfo *TInfo)
   1272     : DeclaratorDecl(NonTypeTemplateParm, DC, IdLoc, Id, T, TInfo, StartLoc),
   1273       TemplateParmPosition(D, P), ParameterPack(ParameterPack),
   1274       ExpandedParameterPack(false), NumExpandedTypes(0)
   1275   { }
   1276 
   1277   NonTypeTemplateParmDecl(DeclContext *DC, SourceLocation StartLoc,
   1278                           SourceLocation IdLoc, unsigned D, unsigned P,
   1279                           IdentifierInfo *Id, QualType T,
   1280                           TypeSourceInfo *TInfo,
   1281                           ArrayRef<QualType> ExpandedTypes,
   1282                           ArrayRef<TypeSourceInfo *> ExpandedTInfos);
   1283 
   1284   friend class ASTDeclReader;
   1285   friend TrailingObjects;
   1286 
   1287 public:
   1288   static NonTypeTemplateParmDecl *
   1289   Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
   1290          SourceLocation IdLoc, unsigned D, unsigned P, IdentifierInfo *Id,
   1291          QualType T, bool ParameterPack, TypeSourceInfo *TInfo);
   1292 
   1293   static NonTypeTemplateParmDecl *
   1294   Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
   1295          SourceLocation IdLoc, unsigned D, unsigned P, IdentifierInfo *Id,
   1296          QualType T, TypeSourceInfo *TInfo, ArrayRef<QualType> ExpandedTypes,
   1297          ArrayRef<TypeSourceInfo *> ExpandedTInfos);
   1298 
   1299   static NonTypeTemplateParmDecl *CreateDeserialized(ASTContext &C,
   1300                                                      unsigned ID);
   1301   static NonTypeTemplateParmDecl *CreateDeserialized(ASTContext &C,
   1302                                                      unsigned ID,
   1303                                                      unsigned NumExpandedTypes);
   1304 
   1305   using TemplateParmPosition::getDepth;
   1306   using TemplateParmPosition::setDepth;
   1307   using TemplateParmPosition::getPosition;
   1308   using TemplateParmPosition::setPosition;
   1309   using TemplateParmPosition::getIndex;
   1310 
   1311   SourceRange getSourceRange() const override LLVM_READONLY;
   1312 
   1313   const DefArgStorage &getDefaultArgStorage() const { return DefaultArgument; }
   1314 
   1315   /// \brief Determine whether this template parameter has a default
   1316   /// argument.
   1317   bool hasDefaultArgument() const { return DefaultArgument.isSet(); }
   1318 
   1319   /// \brief Retrieve the default argument, if any.
   1320   Expr *getDefaultArgument() const { return DefaultArgument.get(); }
   1321 
   1322   /// \brief Retrieve the location of the default argument, if any.
   1323   SourceLocation getDefaultArgumentLoc() const;
   1324 
   1325   /// \brief Determines whether the default argument was inherited
   1326   /// from a previous declaration of this template.
   1327   bool defaultArgumentWasInherited() const {
   1328     return DefaultArgument.isInherited();
   1329   }
   1330 
   1331   /// \brief Set the default argument for this template parameter, and
   1332   /// whether that default argument was inherited from another
   1333   /// declaration.
   1334   void setDefaultArgument(Expr *DefArg) { DefaultArgument.set(DefArg); }
   1335   void setInheritedDefaultArgument(const ASTContext &C,
   1336                                    NonTypeTemplateParmDecl *Parm) {
   1337     DefaultArgument.setInherited(C, Parm);
   1338   }
   1339 
   1340   /// \brief Removes the default argument of this template parameter.
   1341   void removeDefaultArgument() { DefaultArgument.clear(); }
   1342 
   1343   /// \brief Whether this parameter is a non-type template parameter pack.
   1344   ///
   1345   /// If the parameter is a parameter pack, the type may be a
   1346   /// \c PackExpansionType. In the following example, the \c Dims parameter
   1347   /// is a parameter pack (whose type is 'unsigned').
   1348   ///
   1349   /// \code
   1350   /// template<typename T, unsigned ...Dims> struct multi_array;
   1351   /// \endcode
   1352   bool isParameterPack() const { return ParameterPack; }
   1353 
   1354   /// \brief Whether this parameter pack is a pack expansion.
   1355   ///
   1356   /// A non-type template parameter pack is a pack expansion if its type
   1357   /// contains an unexpanded parameter pack. In this case, we will have
   1358   /// built a PackExpansionType wrapping the type.
   1359   bool isPackExpansion() const {
   1360     return ParameterPack && getType()->getAs<PackExpansionType>();
   1361   }
   1362 
   1363   /// \brief Whether this parameter is a non-type template parameter pack
   1364   /// that has a known list of different types at different positions.
   1365   ///
   1366   /// A parameter pack is an expanded parameter pack when the original
   1367   /// parameter pack's type was itself a pack expansion, and that expansion
   1368   /// has already been expanded. For example, given:
   1369   ///
   1370   /// \code
   1371   /// template<typename ...Types>
   1372   /// struct X {
   1373   ///   template<Types ...Values>
   1374   ///   struct Y { /* ... */ };
   1375   /// };
   1376   /// \endcode
   1377   ///
   1378   /// The parameter pack \c Values has a \c PackExpansionType as its type,
   1379   /// which expands \c Types. When \c Types is supplied with template arguments
   1380   /// by instantiating \c X, the instantiation of \c Values becomes an
   1381   /// expanded parameter pack. For example, instantiating
   1382   /// \c X<int, unsigned int> results in \c Values being an expanded parameter
   1383   /// pack with expansion types \c int and \c unsigned int.
   1384   ///
   1385   /// The \c getExpansionType() and \c getExpansionTypeSourceInfo() functions
   1386   /// return the expansion types.
   1387   bool isExpandedParameterPack() const { return ExpandedParameterPack; }
   1388 
   1389   /// \brief Retrieves the number of expansion types in an expanded parameter
   1390   /// pack.
   1391   unsigned getNumExpansionTypes() const {
   1392     assert(ExpandedParameterPack && "Not an expansion parameter pack");
   1393     return NumExpandedTypes;
   1394   }
   1395 
   1396   /// \brief Retrieve a particular expansion type within an expanded parameter
   1397   /// pack.
   1398   QualType getExpansionType(unsigned I) const {
   1399     assert(I < NumExpandedTypes && "Out-of-range expansion type index");
   1400     auto TypesAndInfos =
   1401         getTrailingObjects<std::pair<QualType, TypeSourceInfo *>>();
   1402     return TypesAndInfos[I].first;
   1403   }
   1404 
   1405   /// \brief Retrieve a particular expansion type source info within an
   1406   /// expanded parameter pack.
   1407   TypeSourceInfo *getExpansionTypeSourceInfo(unsigned I) const {
   1408     assert(I < NumExpandedTypes && "Out-of-range expansion type index");
   1409     auto TypesAndInfos =
   1410         getTrailingObjects<std::pair<QualType, TypeSourceInfo *>>();
   1411     return TypesAndInfos[I].second;
   1412   }
   1413 
   1414   // Implement isa/cast/dyncast/etc.
   1415   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
   1416   static bool classofKind(Kind K) { return K == NonTypeTemplateParm; }
   1417 };
   1418 
   1419 /// TemplateTemplateParmDecl - Declares a template template parameter,
   1420 /// e.g., "T" in
   1421 /// @code
   1422 /// template <template <typename> class T> class container { };
   1423 /// @endcode
   1424 /// A template template parameter is a TemplateDecl because it defines the
   1425 /// name of a template and the template parameters allowable for substitution.
   1426 class TemplateTemplateParmDecl final
   1427     : public TemplateDecl,
   1428       protected TemplateParmPosition,
   1429       private llvm::TrailingObjects<TemplateTemplateParmDecl,
   1430                                     TemplateParameterList *> {
   1431   void anchor() override;
   1432 
   1433   /// \brief The default template argument, if any.
   1434   typedef DefaultArgStorage<TemplateTemplateParmDecl, TemplateArgumentLoc *>
   1435       DefArgStorage;
   1436   DefArgStorage DefaultArgument;
   1437 
   1438   /// \brief Whether this parameter is a parameter pack.
   1439   bool ParameterPack;
   1440 
   1441   /// \brief Whether this template template parameter is an "expanded"
   1442   /// parameter pack, meaning that it is a pack expansion and we
   1443   /// already know the set of template parameters that expansion expands to.
   1444   bool ExpandedParameterPack;
   1445 
   1446   /// \brief The number of parameters in an expanded parameter pack.
   1447   unsigned NumExpandedParams;
   1448 
   1449   TemplateTemplateParmDecl(DeclContext *DC, SourceLocation L,
   1450                            unsigned D, unsigned P, bool ParameterPack,
   1451                            IdentifierInfo *Id, TemplateParameterList *Params)
   1452     : TemplateDecl(TemplateTemplateParm, DC, L, Id, Params),
   1453       TemplateParmPosition(D, P), ParameterPack(ParameterPack),
   1454       ExpandedParameterPack(false), NumExpandedParams(0)
   1455     { }
   1456 
   1457   TemplateTemplateParmDecl(DeclContext *DC, SourceLocation L,
   1458                            unsigned D, unsigned P,
   1459                            IdentifierInfo *Id, TemplateParameterList *Params,
   1460                            ArrayRef<TemplateParameterList *> Expansions);
   1461 
   1462 public:
   1463   static TemplateTemplateParmDecl *Create(const ASTContext &C, DeclContext *DC,
   1464                                           SourceLocation L, unsigned D,
   1465                                           unsigned P, bool ParameterPack,
   1466                                           IdentifierInfo *Id,
   1467                                           TemplateParameterList *Params);
   1468   static TemplateTemplateParmDecl *Create(const ASTContext &C, DeclContext *DC,
   1469                                           SourceLocation L, unsigned D,
   1470                                           unsigned P,
   1471                                           IdentifierInfo *Id,
   1472                                           TemplateParameterList *Params,
   1473                                  ArrayRef<TemplateParameterList *> Expansions);
   1474 
   1475   static TemplateTemplateParmDecl *CreateDeserialized(ASTContext &C,
   1476                                                       unsigned ID);
   1477   static TemplateTemplateParmDecl *CreateDeserialized(ASTContext &C,
   1478                                                       unsigned ID,
   1479                                                       unsigned NumExpansions);
   1480 
   1481   using TemplateParmPosition::getDepth;
   1482   using TemplateParmPosition::setDepth;
   1483   using TemplateParmPosition::getPosition;
   1484   using TemplateParmPosition::setPosition;
   1485   using TemplateParmPosition::getIndex;
   1486 
   1487   /// \brief Whether this template template parameter is a template
   1488   /// parameter pack.
   1489   ///
   1490   /// \code
   1491   /// template<template <class T> ...MetaFunctions> struct Apply;
   1492   /// \endcode
   1493   bool isParameterPack() const { return ParameterPack; }
   1494 
   1495   /// \brief Whether this parameter pack is a pack expansion.
   1496   ///
   1497   /// A template template parameter pack is a pack expansion if its template
   1498   /// parameter list contains an unexpanded parameter pack.
   1499   bool isPackExpansion() const {
   1500     return ParameterPack &&
   1501            getTemplateParameters()->containsUnexpandedParameterPack();
   1502   }
   1503 
   1504   /// \brief Whether this parameter is a template template parameter pack that
   1505   /// has a known list of different template parameter lists at different
   1506   /// positions.
   1507   ///
   1508   /// A parameter pack is an expanded parameter pack when the original parameter
   1509   /// pack's template parameter list was itself a pack expansion, and that
   1510   /// expansion has already been expanded. For exampe, given:
   1511   ///
   1512   /// \code
   1513   /// template<typename...Types> struct Outer {
   1514   ///   template<template<Types> class...Templates> struct Inner;
   1515   /// };
   1516   /// \endcode
   1517   ///
   1518   /// The parameter pack \c Templates is a pack expansion, which expands the
   1519   /// pack \c Types. When \c Types is supplied with template arguments by
   1520   /// instantiating \c Outer, the instantiation of \c Templates is an expanded
   1521   /// parameter pack.
   1522   bool isExpandedParameterPack() const { return ExpandedParameterPack; }
   1523 
   1524   /// \brief Retrieves the number of expansion template parameters in
   1525   /// an expanded parameter pack.
   1526   unsigned getNumExpansionTemplateParameters() const {
   1527     assert(ExpandedParameterPack && "Not an expansion parameter pack");
   1528     return NumExpandedParams;
   1529   }
   1530 
   1531   /// \brief Retrieve a particular expansion type within an expanded parameter
   1532   /// pack.
   1533   TemplateParameterList *getExpansionTemplateParameters(unsigned I) const {
   1534     assert(I < NumExpandedParams && "Out-of-range expansion type index");
   1535     return getTrailingObjects<TemplateParameterList *>()[I];
   1536   }
   1537 
   1538   const DefArgStorage &getDefaultArgStorage() const { return DefaultArgument; }
   1539 
   1540   /// \brief Determine whether this template parameter has a default
   1541   /// argument.
   1542   bool hasDefaultArgument() const { return DefaultArgument.isSet(); }
   1543 
   1544   /// \brief Retrieve the default argument, if any.
   1545   const TemplateArgumentLoc &getDefaultArgument() const {
   1546     static const TemplateArgumentLoc None;
   1547     return DefaultArgument.isSet() ? *DefaultArgument.get() : None;
   1548   }
   1549 
   1550   /// \brief Retrieve the location of the default argument, if any.
   1551   SourceLocation getDefaultArgumentLoc() const;
   1552 
   1553   /// \brief Determines whether the default argument was inherited
   1554   /// from a previous declaration of this template.
   1555   bool defaultArgumentWasInherited() const {
   1556     return DefaultArgument.isInherited();
   1557   }
   1558 
   1559   /// \brief Set the default argument for this template parameter, and
   1560   /// whether that default argument was inherited from another
   1561   /// declaration.
   1562   void setDefaultArgument(const ASTContext &C,
   1563                           const TemplateArgumentLoc &DefArg);
   1564   void setInheritedDefaultArgument(const ASTContext &C,
   1565                                    TemplateTemplateParmDecl *Prev) {
   1566     DefaultArgument.setInherited(C, Prev);
   1567   }
   1568 
   1569   /// \brief Removes the default argument of this template parameter.
   1570   void removeDefaultArgument() { DefaultArgument.clear(); }
   1571 
   1572   SourceRange getSourceRange() const override LLVM_READONLY {
   1573     SourceLocation End = getLocation();
   1574     if (hasDefaultArgument() && !defaultArgumentWasInherited())
   1575       End = getDefaultArgument().getSourceRange().getEnd();
   1576     return SourceRange(getTemplateParameters()->getTemplateLoc(), End);
   1577   }
   1578 
   1579   // Implement isa/cast/dyncast/etc.
   1580   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
   1581   static bool classofKind(Kind K) { return K == TemplateTemplateParm; }
   1582 
   1583   friend class ASTDeclReader;
   1584   friend class ASTDeclWriter;
   1585   friend TrailingObjects;
   1586 };
   1587 
   1588 /// \brief Represents the builtin template declaration which is used to
   1589 /// implement __make_integer_seq and other builtin templates.  It serves
   1590 /// no real purpose beyond existing as a place to hold template parameters.
   1591 class BuiltinTemplateDecl : public TemplateDecl {
   1592   void anchor() override;
   1593 
   1594   BuiltinTemplateDecl(const ASTContext &C, DeclContext *DC,
   1595                       DeclarationName Name, BuiltinTemplateKind BTK);
   1596 
   1597   BuiltinTemplateKind BTK;
   1598 
   1599 public:
   1600   // Implement isa/cast/dyncast support
   1601   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
   1602   static bool classofKind(Kind K) { return K == BuiltinTemplate; }
   1603 
   1604   static BuiltinTemplateDecl *Create(const ASTContext &C, DeclContext *DC,
   1605                                      DeclarationName Name,
   1606                                      BuiltinTemplateKind BTK) {
   1607     return new (C, DC) BuiltinTemplateDecl(C, DC, Name, BTK);
   1608   }
   1609 
   1610   SourceRange getSourceRange() const override LLVM_READONLY {
   1611     return SourceRange();
   1612   }
   1613 
   1614   BuiltinTemplateKind getBuiltinTemplateKind() const { return BTK; }
   1615 };
   1616 
   1617 /// \brief Represents a class template specialization, which refers to
   1618 /// a class template with a given set of template arguments.
   1619 ///
   1620 /// Class template specializations represent both explicit
   1621 /// specialization of class templates, as in the example below, and
   1622 /// implicit instantiations of class templates.
   1623 ///
   1624 /// \code
   1625 /// template<typename T> class array;
   1626 ///
   1627 /// template<>
   1628 /// class array<bool> { }; // class template specialization array<bool>
   1629 /// \endcode
   1630 class ClassTemplateSpecializationDecl
   1631   : public CXXRecordDecl, public llvm::FoldingSetNode {
   1632 
   1633   /// \brief Structure that stores information about a class template
   1634   /// specialization that was instantiated from a class template partial
   1635   /// specialization.
   1636   struct SpecializedPartialSpecialization {
   1637     /// \brief The class template partial specialization from which this
   1638     /// class template specialization was instantiated.
   1639     ClassTemplatePartialSpecializationDecl *PartialSpecialization;
   1640 
   1641     /// \brief The template argument list deduced for the class template
   1642     /// partial specialization itself.
   1643     const TemplateArgumentList *TemplateArgs;
   1644   };
   1645 
   1646   /// \brief The template that this specialization specializes
   1647   llvm::PointerUnion<ClassTemplateDecl *, SpecializedPartialSpecialization *>
   1648     SpecializedTemplate;
   1649 
   1650   /// \brief Further info for explicit template specialization/instantiation.
   1651   struct ExplicitSpecializationInfo {
   1652     /// \brief The type-as-written.
   1653     TypeSourceInfo *TypeAsWritten;
   1654     /// \brief The location of the extern keyword.
   1655     SourceLocation ExternLoc;
   1656     /// \brief The location of the template keyword.
   1657     SourceLocation TemplateKeywordLoc;
   1658 
   1659     ExplicitSpecializationInfo()
   1660       : TypeAsWritten(nullptr), ExternLoc(), TemplateKeywordLoc() {}
   1661   };
   1662 
   1663   /// \brief Further info for explicit template specialization/instantiation.
   1664   /// Does not apply to implicit specializations.
   1665   ExplicitSpecializationInfo *ExplicitInfo;
   1666 
   1667   /// \brief The template arguments used to describe this specialization.
   1668   const TemplateArgumentList *TemplateArgs;
   1669 
   1670   /// \brief The point where this template was instantiated (if any)
   1671   SourceLocation PointOfInstantiation;
   1672 
   1673   /// \brief The kind of specialization this declaration refers to.
   1674   /// Really a value of type TemplateSpecializationKind.
   1675   unsigned SpecializationKind : 3;
   1676 
   1677 protected:
   1678   ClassTemplateSpecializationDecl(ASTContext &Context, Kind DK, TagKind TK,
   1679                                   DeclContext *DC, SourceLocation StartLoc,
   1680                                   SourceLocation IdLoc,
   1681                                   ClassTemplateDecl *SpecializedTemplate,
   1682                                   ArrayRef<TemplateArgument> Args,
   1683                                   ClassTemplateSpecializationDecl *PrevDecl);
   1684 
   1685   explicit ClassTemplateSpecializationDecl(ASTContext &C, Kind DK);
   1686 
   1687 public:
   1688   static ClassTemplateSpecializationDecl *
   1689   Create(ASTContext &Context, TagKind TK, DeclContext *DC,
   1690          SourceLocation StartLoc, SourceLocation IdLoc,
   1691          ClassTemplateDecl *SpecializedTemplate,
   1692          ArrayRef<TemplateArgument> Args,
   1693          ClassTemplateSpecializationDecl *PrevDecl);
   1694   static ClassTemplateSpecializationDecl *
   1695   CreateDeserialized(ASTContext &C, unsigned ID);
   1696 
   1697   void getNameForDiagnostic(raw_ostream &OS, const PrintingPolicy &Policy,
   1698                             bool Qualified) const override;
   1699 
   1700   // FIXME: This is broken. CXXRecordDecl::getMostRecentDecl() returns a
   1701   // different "most recent" declaration from this function for the same
   1702   // declaration, because we don't override getMostRecentDeclImpl(). But
   1703   // it's not clear that we should override that, because the most recent
   1704   // declaration as a CXXRecordDecl sometimes is the injected-class-name.
   1705   ClassTemplateSpecializationDecl *getMostRecentDecl() {
   1706     CXXRecordDecl *Recent = static_cast<CXXRecordDecl *>(
   1707                               this)->getMostRecentDecl();
   1708     while (!isa<ClassTemplateSpecializationDecl>(Recent)) {
   1709       // FIXME: Does injected class name need to be in the redeclarations chain?
   1710       assert(Recent->isInjectedClassName() && Recent->getPreviousDecl());
   1711       Recent = Recent->getPreviousDecl();
   1712     }
   1713     return cast<ClassTemplateSpecializationDecl>(Recent);
   1714   }
   1715 
   1716   /// \brief Retrieve the template that this specialization specializes.
   1717   ClassTemplateDecl *getSpecializedTemplate() const;
   1718 
   1719   /// \brief Retrieve the template arguments of the class template
   1720   /// specialization.
   1721   const TemplateArgumentList &getTemplateArgs() const {
   1722     return *TemplateArgs;
   1723   }
   1724 
   1725   /// \brief Determine the kind of specialization that this
   1726   /// declaration represents.
   1727   TemplateSpecializationKind getSpecializationKind() const {
   1728     return static_cast<TemplateSpecializationKind>(SpecializationKind);
   1729   }
   1730 
   1731   bool isExplicitSpecialization() const {
   1732     return getSpecializationKind() == TSK_ExplicitSpecialization;
   1733   }
   1734 
   1735   /// \brief True if this declaration is an explicit specialization,
   1736   /// explicit instantiation declaration, or explicit instantiation
   1737   /// definition.
   1738   bool isExplicitInstantiationOrSpecialization() const {
   1739     return isTemplateExplicitInstantiationOrSpecialization(
   1740         getTemplateSpecializationKind());
   1741   }
   1742 
   1743   void setSpecializationKind(TemplateSpecializationKind TSK) {
   1744     SpecializationKind = TSK;
   1745   }
   1746 
   1747   /// \brief Get the point of instantiation (if any), or null if none.
   1748   SourceLocation getPointOfInstantiation() const {
   1749     return PointOfInstantiation;
   1750   }
   1751 
   1752   void setPointOfInstantiation(SourceLocation Loc) {
   1753     assert(Loc.isValid() && "point of instantiation must be valid!");
   1754     PointOfInstantiation = Loc;
   1755   }
   1756 
   1757   /// \brief If this class template specialization is an instantiation of
   1758   /// a template (rather than an explicit specialization), return the
   1759   /// class template or class template partial specialization from which it
   1760   /// was instantiated.
   1761   llvm::PointerUnion<ClassTemplateDecl *,
   1762                      ClassTemplatePartialSpecializationDecl *>
   1763   getInstantiatedFrom() const {
   1764     if (!isTemplateInstantiation(getSpecializationKind()))
   1765       return llvm::PointerUnion<ClassTemplateDecl *,
   1766                                 ClassTemplatePartialSpecializationDecl *>();
   1767 
   1768     return getSpecializedTemplateOrPartial();
   1769   }
   1770 
   1771   /// \brief Retrieve the class template or class template partial
   1772   /// specialization which was specialized by this.
   1773   llvm::PointerUnion<ClassTemplateDecl *,
   1774                      ClassTemplatePartialSpecializationDecl *>
   1775   getSpecializedTemplateOrPartial() const {
   1776     if (SpecializedPartialSpecialization *PartialSpec
   1777           = SpecializedTemplate.dyn_cast<SpecializedPartialSpecialization*>())
   1778       return PartialSpec->PartialSpecialization;
   1779 
   1780     return SpecializedTemplate.get<ClassTemplateDecl*>();
   1781   }
   1782 
   1783   /// \brief Retrieve the set of template arguments that should be used
   1784   /// to instantiate members of the class template or class template partial
   1785   /// specialization from which this class template specialization was
   1786   /// instantiated.
   1787   ///
   1788   /// \returns For a class template specialization instantiated from the primary
   1789   /// template, this function will return the same template arguments as
   1790   /// getTemplateArgs(). For a class template specialization instantiated from
   1791   /// a class template partial specialization, this function will return the
   1792   /// deduced template arguments for the class template partial specialization
   1793   /// itself.
   1794   const TemplateArgumentList &getTemplateInstantiationArgs() const {
   1795     if (SpecializedPartialSpecialization *PartialSpec
   1796         = SpecializedTemplate.dyn_cast<SpecializedPartialSpecialization*>())
   1797       return *PartialSpec->TemplateArgs;
   1798 
   1799     return getTemplateArgs();
   1800   }
   1801 
   1802   /// \brief Note that this class template specialization is actually an
   1803   /// instantiation of the given class template partial specialization whose
   1804   /// template arguments have been deduced.
   1805   void setInstantiationOf(ClassTemplatePartialSpecializationDecl *PartialSpec,
   1806                           const TemplateArgumentList *TemplateArgs) {
   1807     assert(!SpecializedTemplate.is<SpecializedPartialSpecialization*>() &&
   1808            "Already set to a class template partial specialization!");
   1809     SpecializedPartialSpecialization *PS
   1810       = new (getASTContext()) SpecializedPartialSpecialization();
   1811     PS->PartialSpecialization = PartialSpec;
   1812     PS->TemplateArgs = TemplateArgs;
   1813     SpecializedTemplate = PS;
   1814   }
   1815 
   1816   /// \brief Note that this class template specialization is an instantiation
   1817   /// of the given class template.
   1818   void setInstantiationOf(ClassTemplateDecl *TemplDecl) {
   1819     assert(!SpecializedTemplate.is<SpecializedPartialSpecialization*>() &&
   1820            "Previously set to a class template partial specialization!");
   1821     SpecializedTemplate = TemplDecl;
   1822   }
   1823 
   1824   /// \brief Sets the type of this specialization as it was written by
   1825   /// the user. This will be a class template specialization type.
   1826   void setTypeAsWritten(TypeSourceInfo *T) {
   1827     if (!ExplicitInfo)
   1828       ExplicitInfo = new (getASTContext()) ExplicitSpecializationInfo;
   1829     ExplicitInfo->TypeAsWritten = T;
   1830   }
   1831   /// \brief Gets the type of this specialization as it was written by
   1832   /// the user, if it was so written.
   1833   TypeSourceInfo *getTypeAsWritten() const {
   1834     return ExplicitInfo ? ExplicitInfo->TypeAsWritten : nullptr;
   1835   }
   1836 
   1837   /// \brief Gets the location of the extern keyword, if present.
   1838   SourceLocation getExternLoc() const {
   1839     return ExplicitInfo ? ExplicitInfo->ExternLoc : SourceLocation();
   1840   }
   1841   /// \brief Sets the location of the extern keyword.
   1842   void setExternLoc(SourceLocation Loc) {
   1843     if (!ExplicitInfo)
   1844       ExplicitInfo = new (getASTContext()) ExplicitSpecializationInfo;
   1845     ExplicitInfo->ExternLoc = Loc;
   1846   }
   1847 
   1848   /// \brief Sets the location of the template keyword.
   1849   void setTemplateKeywordLoc(SourceLocation Loc) {
   1850     if (!ExplicitInfo)
   1851       ExplicitInfo = new (getASTContext()) ExplicitSpecializationInfo;
   1852     ExplicitInfo->TemplateKeywordLoc = Loc;
   1853   }
   1854   /// \brief Gets the location of the template keyword, if present.
   1855   SourceLocation getTemplateKeywordLoc() const {
   1856     return ExplicitInfo ? ExplicitInfo->TemplateKeywordLoc : SourceLocation();
   1857   }
   1858 
   1859   SourceRange getSourceRange() const override LLVM_READONLY;
   1860 
   1861   void Profile(llvm::FoldingSetNodeID &ID) const {
   1862     Profile(ID, TemplateArgs->asArray(), getASTContext());
   1863   }
   1864 
   1865   static void
   1866   Profile(llvm::FoldingSetNodeID &ID, ArrayRef<TemplateArgument> TemplateArgs,
   1867           ASTContext &Context) {
   1868     ID.AddInteger(TemplateArgs.size());
   1869     for (const TemplateArgument &TemplateArg : TemplateArgs)
   1870       TemplateArg.Profile(ID, Context);
   1871   }
   1872 
   1873   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
   1874   static bool classofKind(Kind K) {
   1875     return K >= firstClassTemplateSpecialization &&
   1876            K <= lastClassTemplateSpecialization;
   1877   }
   1878 
   1879   friend class ASTDeclReader;
   1880   friend class ASTDeclWriter;
   1881 };
   1882 
   1883 class ClassTemplatePartialSpecializationDecl
   1884   : public ClassTemplateSpecializationDecl {
   1885   void anchor() override;
   1886 
   1887   /// \brief The list of template parameters
   1888   TemplateParameterList* TemplateParams;
   1889 
   1890   /// \brief The source info for the template arguments as written.
   1891   /// FIXME: redundant with TypeAsWritten?
   1892   const ASTTemplateArgumentListInfo *ArgsAsWritten;
   1893 
   1894   /// \brief The class template partial specialization from which this
   1895   /// class template partial specialization was instantiated.
   1896   ///
   1897   /// The boolean value will be true to indicate that this class template
   1898   /// partial specialization was specialized at this level.
   1899   llvm::PointerIntPair<ClassTemplatePartialSpecializationDecl *, 1, bool>
   1900       InstantiatedFromMember;
   1901 
   1902   ClassTemplatePartialSpecializationDecl(ASTContext &Context, TagKind TK,
   1903                                          DeclContext *DC,
   1904                                          SourceLocation StartLoc,
   1905                                          SourceLocation IdLoc,
   1906                                          TemplateParameterList *Params,
   1907                                          ClassTemplateDecl *SpecializedTemplate,
   1908                                          ArrayRef<TemplateArgument> Args,
   1909                                const ASTTemplateArgumentListInfo *ArgsAsWritten,
   1910                                ClassTemplatePartialSpecializationDecl *PrevDecl);
   1911 
   1912   ClassTemplatePartialSpecializationDecl(ASTContext &C)
   1913     : ClassTemplateSpecializationDecl(C, ClassTemplatePartialSpecialization),
   1914       TemplateParams(nullptr), ArgsAsWritten(nullptr),
   1915       InstantiatedFromMember(nullptr, false) {}
   1916 
   1917 public:
   1918   static ClassTemplatePartialSpecializationDecl *
   1919   Create(ASTContext &Context, TagKind TK, DeclContext *DC,
   1920          SourceLocation StartLoc, SourceLocation IdLoc,
   1921          TemplateParameterList *Params,
   1922          ClassTemplateDecl *SpecializedTemplate,
   1923          ArrayRef<TemplateArgument> Args,
   1924          const TemplateArgumentListInfo &ArgInfos,
   1925          QualType CanonInjectedType,
   1926          ClassTemplatePartialSpecializationDecl *PrevDecl);
   1927 
   1928   static ClassTemplatePartialSpecializationDecl *
   1929   CreateDeserialized(ASTContext &C, unsigned ID);
   1930 
   1931   ClassTemplatePartialSpecializationDecl *getMostRecentDecl() {
   1932     return cast<ClassTemplatePartialSpecializationDecl>(
   1933              static_cast<ClassTemplateSpecializationDecl *>(
   1934                this)->getMostRecentDecl());
   1935   }
   1936 
   1937   /// Get the list of template parameters
   1938   TemplateParameterList *getTemplateParameters() const {
   1939     return TemplateParams;
   1940   }
   1941 
   1942   /// Get the template arguments as written.
   1943   const ASTTemplateArgumentListInfo *getTemplateArgsAsWritten() const {
   1944     return ArgsAsWritten;
   1945   }
   1946 
   1947   /// \brief Retrieve the member class template partial specialization from
   1948   /// which this particular class template partial specialization was
   1949   /// instantiated.
   1950   ///
   1951   /// \code
   1952   /// template<typename T>
   1953   /// struct Outer {
   1954   ///   template<typename U> struct Inner;
   1955   ///   template<typename U> struct Inner<U*> { }; // #1
   1956   /// };
   1957   ///
   1958   /// Outer<float>::Inner<int*> ii;
   1959   /// \endcode
   1960   ///
   1961   /// In this example, the instantiation of \c Outer<float>::Inner<int*> will
   1962   /// end up instantiating the partial specialization
   1963   /// \c Outer<float>::Inner<U*>, which itself was instantiated from the class
   1964   /// template partial specialization \c Outer<T>::Inner<U*>. Given
   1965   /// \c Outer<float>::Inner<U*>, this function would return
   1966   /// \c Outer<T>::Inner<U*>.
   1967   ClassTemplatePartialSpecializationDecl *getInstantiatedFromMember() const {
   1968     const ClassTemplatePartialSpecializationDecl *First =
   1969         cast<ClassTemplatePartialSpecializationDecl>(getFirstDecl());
   1970     return First->InstantiatedFromMember.getPointer();
   1971   }
   1972   ClassTemplatePartialSpecializationDecl *
   1973   getInstantiatedFromMemberTemplate() const {
   1974     return getInstantiatedFromMember();
   1975   }
   1976 
   1977   void setInstantiatedFromMember(
   1978                           ClassTemplatePartialSpecializationDecl *PartialSpec) {
   1979     ClassTemplatePartialSpecializationDecl *First =
   1980         cast<ClassTemplatePartialSpecializationDecl>(getFirstDecl());
   1981     First->InstantiatedFromMember.setPointer(PartialSpec);
   1982   }
   1983 
   1984   /// \brief Determines whether this class template partial specialization
   1985   /// template was a specialization of a member partial specialization.
   1986   ///
   1987   /// In the following example, the member template partial specialization
   1988   /// \c X<int>::Inner<T*> is a member specialization.
   1989   ///
   1990   /// \code
   1991   /// template<typename T>
   1992   /// struct X {
   1993   ///   template<typename U> struct Inner;
   1994   ///   template<typename U> struct Inner<U*>;
   1995   /// };
   1996   ///
   1997   /// template<> template<typename T>
   1998   /// struct X<int>::Inner<T*> { /* ... */ };
   1999   /// \endcode
   2000   bool isMemberSpecialization() {
   2001     ClassTemplatePartialSpecializationDecl *First =
   2002         cast<ClassTemplatePartialSpecializationDecl>(getFirstDecl());
   2003     return First->InstantiatedFromMember.getInt();
   2004   }
   2005 
   2006   /// \brief Note that this member template is a specialization.
   2007   void setMemberSpecialization() {
   2008     ClassTemplatePartialSpecializationDecl *First =
   2009         cast<ClassTemplatePartialSpecializationDecl>(getFirstDecl());
   2010     assert(First->InstantiatedFromMember.getPointer() &&
   2011            "Only member templates can be member template specializations");
   2012     return First->InstantiatedFromMember.setInt(true);
   2013   }
   2014 
   2015   /// Retrieves the injected specialization type for this partial
   2016   /// specialization.  This is not the same as the type-decl-type for
   2017   /// this partial specialization, which is an InjectedClassNameType.
   2018   QualType getInjectedSpecializationType() const {
   2019     assert(getTypeForDecl() && "partial specialization has no type set!");
   2020     return cast<InjectedClassNameType>(getTypeForDecl())
   2021              ->getInjectedSpecializationType();
   2022   }
   2023 
   2024   // FIXME: Add Profile support!
   2025 
   2026   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
   2027   static bool classofKind(Kind K) {
   2028     return K == ClassTemplatePartialSpecialization;
   2029   }
   2030 
   2031   friend class ASTDeclReader;
   2032   friend class ASTDeclWriter;
   2033 };
   2034 
   2035 /// Declaration of a class template.
   2036 class ClassTemplateDecl : public RedeclarableTemplateDecl {
   2037 protected:
   2038   /// \brief Data that is common to all of the declarations of a given
   2039   /// class template.
   2040   struct Common : CommonBase {
   2041     Common() : LazySpecializations() { }
   2042 
   2043     /// \brief The class template specializations for this class
   2044     /// template, including explicit specializations and instantiations.
   2045     llvm::FoldingSetVector<ClassTemplateSpecializationDecl> Specializations;
   2046 
   2047     /// \brief The class template partial specializations for this class
   2048     /// template.
   2049     llvm::FoldingSetVector<ClassTemplatePartialSpecializationDecl>
   2050       PartialSpecializations;
   2051 
   2052     /// \brief The injected-class-name type for this class template.
   2053     QualType InjectedClassNameType;
   2054 
   2055     /// \brief If non-null, points to an array of specializations (including
   2056     /// partial specializations) known only by their external declaration IDs.
   2057     ///
   2058     /// The first value in the array is the number of of specializations/
   2059     /// partial specializations that follow.
   2060     uint32_t *LazySpecializations;
   2061   };
   2062 
   2063   /// \brief Retrieve the set of specializations of this class template.
   2064   llvm::FoldingSetVector<ClassTemplateSpecializationDecl> &
   2065   getSpecializations() const;
   2066 
   2067   /// \brief Retrieve the set of partial specializations of this class
   2068   /// template.
   2069   llvm::FoldingSetVector<ClassTemplatePartialSpecializationDecl> &
   2070   getPartialSpecializations();
   2071 
   2072   ClassTemplateDecl(ConstrainedTemplateDeclInfo *CTDI, ASTContext &C,
   2073                     DeclContext *DC, SourceLocation L, DeclarationName Name,
   2074                     TemplateParameterList *Params, NamedDecl *Decl)
   2075       : RedeclarableTemplateDecl(CTDI, ClassTemplate, C, DC, L, Name, Params,
   2076                                  Decl) {}
   2077 
   2078   ClassTemplateDecl(ASTContext &C, DeclContext *DC, SourceLocation L,
   2079                     DeclarationName Name, TemplateParameterList *Params,
   2080                     NamedDecl *Decl)
   2081       : ClassTemplateDecl(nullptr, C, DC, L, Name, Params, Decl) {}
   2082 
   2083   CommonBase *newCommon(ASTContext &C) const override;
   2084 
   2085   Common *getCommonPtr() const {
   2086     return static_cast<Common *>(RedeclarableTemplateDecl::getCommonPtr());
   2087   }
   2088 
   2089 public:
   2090   /// \brief Load any lazily-loaded specializations from the external source.
   2091   void LoadLazySpecializations() const;
   2092 
   2093   /// \brief Get the underlying class declarations of the template.
   2094   CXXRecordDecl *getTemplatedDecl() const {
   2095     return static_cast<CXXRecordDecl *>(TemplatedDecl.getPointer());
   2096   }
   2097 
   2098   /// \brief Returns whether this template declaration defines the primary
   2099   /// class pattern.
   2100   bool isThisDeclarationADefinition() const {
   2101     return getTemplatedDecl()->isThisDeclarationADefinition();
   2102   }
   2103 
   2104   // FIXME: remove default argument for AssociatedConstraints
   2105   /// \brief Create a class template node.
   2106   static ClassTemplateDecl *Create(ASTContext &C, DeclContext *DC,
   2107                                    SourceLocation L,
   2108                                    DeclarationName Name,
   2109                                    TemplateParameterList *Params,
   2110                                    NamedDecl *Decl,
   2111                                    Expr *AssociatedConstraints = nullptr);
   2112 
   2113   /// \brief Create an empty class template node.
   2114   static ClassTemplateDecl *CreateDeserialized(ASTContext &C, unsigned ID);
   2115 
   2116   /// \brief Return the specialization with the provided arguments if it exists,
   2117   /// otherwise return the insertion point.
   2118   ClassTemplateSpecializationDecl *
   2119   findSpecialization(ArrayRef<TemplateArgument> Args, void *&InsertPos);
   2120 
   2121   /// \brief Insert the specified specialization knowing that it is not already
   2122   /// in. InsertPos must be obtained from findSpecialization.
   2123   void AddSpecialization(ClassTemplateSpecializationDecl *D, void *InsertPos);
   2124 
   2125   ClassTemplateDecl *getCanonicalDecl() override {
   2126     return cast<ClassTemplateDecl>(
   2127              RedeclarableTemplateDecl::getCanonicalDecl());
   2128   }
   2129   const ClassTemplateDecl *getCanonicalDecl() const {
   2130     return cast<ClassTemplateDecl>(
   2131              RedeclarableTemplateDecl::getCanonicalDecl());
   2132   }
   2133 
   2134   /// \brief Retrieve the previous declaration of this class template, or
   2135   /// NULL if no such declaration exists.
   2136   ClassTemplateDecl *getPreviousDecl() {
   2137     return cast_or_null<ClassTemplateDecl>(
   2138              static_cast<RedeclarableTemplateDecl *>(this)->getPreviousDecl());
   2139   }
   2140 
   2141   /// \brief Retrieve the previous declaration of this class template, or
   2142   /// NULL if no such declaration exists.
   2143   const ClassTemplateDecl *getPreviousDecl() const {
   2144     return cast_or_null<ClassTemplateDecl>(
   2145              static_cast<const RedeclarableTemplateDecl *>(
   2146                this)->getPreviousDecl());
   2147   }
   2148 
   2149   ClassTemplateDecl *getMostRecentDecl() {
   2150     return cast<ClassTemplateDecl>(
   2151         static_cast<RedeclarableTemplateDecl *>(this)->getMostRecentDecl());
   2152   }
   2153   const ClassTemplateDecl *getMostRecentDecl() const {
   2154     return const_cast<ClassTemplateDecl*>(this)->getMostRecentDecl();
   2155   }
   2156 
   2157   ClassTemplateDecl *getInstantiatedFromMemberTemplate() const {
   2158     return cast_or_null<ClassTemplateDecl>(
   2159              RedeclarableTemplateDecl::getInstantiatedFromMemberTemplate());
   2160   }
   2161 
   2162   /// \brief Return the partial specialization with the provided arguments if it
   2163   /// exists, otherwise return the insertion point.
   2164   ClassTemplatePartialSpecializationDecl *
   2165   findPartialSpecialization(ArrayRef<TemplateArgument> Args, void *&InsertPos);
   2166 
   2167   /// \brief Insert the specified partial specialization knowing that it is not
   2168   /// already in. InsertPos must be obtained from findPartialSpecialization.
   2169   void AddPartialSpecialization(ClassTemplatePartialSpecializationDecl *D,
   2170                                 void *InsertPos);
   2171 
   2172   /// \brief Retrieve the partial specializations as an ordered list.
   2173   void getPartialSpecializations(
   2174           SmallVectorImpl<ClassTemplatePartialSpecializationDecl *> &PS);
   2175 
   2176   /// \brief Find a class template partial specialization with the given
   2177   /// type T.
   2178   ///
   2179   /// \param T a dependent type that names a specialization of this class
   2180   /// template.
   2181   ///
   2182   /// \returns the class template partial specialization that exactly matches
   2183   /// the type \p T, or NULL if no such partial specialization exists.
   2184   ClassTemplatePartialSpecializationDecl *findPartialSpecialization(QualType T);
   2185 
   2186   /// \brief Find a class template partial specialization which was instantiated
   2187   /// from the given member partial specialization.
   2188   ///
   2189   /// \param D a member class template partial specialization.
   2190   ///
   2191   /// \returns the class template partial specialization which was instantiated
   2192   /// from the given member partial specialization, or NULL if no such partial
   2193   /// specialization exists.
   2194   ClassTemplatePartialSpecializationDecl *
   2195   findPartialSpecInstantiatedFromMember(
   2196                                      ClassTemplatePartialSpecializationDecl *D);
   2197 
   2198   /// \brief Retrieve the template specialization type of the
   2199   /// injected-class-name for this class template.
   2200   ///
   2201   /// The injected-class-name for a class template \c X is \c
   2202   /// X<template-args>, where \c template-args is formed from the
   2203   /// template arguments that correspond to the template parameters of
   2204   /// \c X. For example:
   2205   ///
   2206   /// \code
   2207   /// template<typename T, int N>
   2208   /// struct array {
   2209   ///   typedef array this_type; // "array" is equivalent to "array<T, N>"
   2210   /// };
   2211   /// \endcode
   2212   QualType getInjectedClassNameSpecialization();
   2213 
   2214   typedef SpecIterator<ClassTemplateSpecializationDecl> spec_iterator;
   2215   typedef llvm::iterator_range<spec_iterator> spec_range;
   2216 
   2217   spec_range specializations() const {
   2218     return spec_range(spec_begin(), spec_end());
   2219   }
   2220 
   2221   spec_iterator spec_begin() const {
   2222     return makeSpecIterator(getSpecializations(), false);
   2223   }
   2224 
   2225   spec_iterator spec_end() const {
   2226     return makeSpecIterator(getSpecializations(), true);
   2227   }
   2228 
   2229   // Implement isa/cast/dyncast support
   2230   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
   2231   static bool classofKind(Kind K) { return K == ClassTemplate; }
   2232 
   2233   friend class ASTDeclReader;
   2234   friend class ASTDeclWriter;
   2235 };
   2236 
   2237 /// \brief Declaration of a friend template.
   2238 ///
   2239 /// For example:
   2240 /// \code
   2241 /// template \<typename T> class A {
   2242 ///   friend class MyVector<T>; // not a friend template
   2243 ///   template \<typename U> friend class B; // not a friend template
   2244 ///   template \<typename U> friend class Foo<T>::Nested; // friend template
   2245 /// };
   2246 /// \endcode
   2247 ///
   2248 /// \note This class is not currently in use.  All of the above
   2249 /// will yield a FriendDecl, not a FriendTemplateDecl.
   2250 class FriendTemplateDecl : public Decl {
   2251   virtual void anchor();
   2252 public:
   2253   typedef llvm::PointerUnion<NamedDecl*,TypeSourceInfo*> FriendUnion;
   2254 
   2255 private:
   2256   // The number of template parameters;  always non-zero.
   2257   unsigned NumParams;
   2258 
   2259   // The parameter list.
   2260   TemplateParameterList **Params;
   2261 
   2262   // The declaration that's a friend of this class.
   2263   FriendUnion Friend;
   2264 
   2265   // Location of the 'friend' specifier.
   2266   SourceLocation FriendLoc;
   2267 
   2268   FriendTemplateDecl(DeclContext *DC, SourceLocation Loc,
   2269                      MutableArrayRef<TemplateParameterList *> Params,
   2270                      FriendUnion Friend, SourceLocation FriendLoc)
   2271       : Decl(Decl::FriendTemplate, DC, Loc), NumParams(Params.size()),
   2272         Params(Params.data()), Friend(Friend), FriendLoc(FriendLoc) {}
   2273 
   2274   FriendTemplateDecl(EmptyShell Empty)
   2275     : Decl(Decl::FriendTemplate, Empty),
   2276       NumParams(0),
   2277       Params(nullptr)
   2278   {}
   2279 
   2280 public:
   2281   static FriendTemplateDecl *
   2282   Create(ASTContext &Context, DeclContext *DC, SourceLocation Loc,
   2283          MutableArrayRef<TemplateParameterList *> Params, FriendUnion Friend,
   2284          SourceLocation FriendLoc);
   2285 
   2286   static FriendTemplateDecl *CreateDeserialized(ASTContext &C, unsigned ID);
   2287 
   2288   /// If this friend declaration names a templated type (or
   2289   /// a dependent member type of a templated type), return that
   2290   /// type;  otherwise return null.
   2291   TypeSourceInfo *getFriendType() const {
   2292     return Friend.dyn_cast<TypeSourceInfo*>();
   2293   }
   2294 
   2295   /// If this friend declaration names a templated function (or
   2296   /// a member function of a templated type), return that type;
   2297   /// otherwise return null.
   2298   NamedDecl *getFriendDecl() const {
   2299     return Friend.dyn_cast<NamedDecl*>();
   2300   }
   2301 
   2302   /// \brief Retrieves the location of the 'friend' keyword.
   2303   SourceLocation getFriendLoc() const {
   2304     return FriendLoc;
   2305   }
   2306 
   2307   TemplateParameterList *getTemplateParameterList(unsigned i) const {
   2308     assert(i <= NumParams);
   2309     return Params[i];
   2310   }
   2311 
   2312   unsigned getNumTemplateParameters() const {
   2313     return NumParams;
   2314   }
   2315 
   2316   // Implement isa/cast/dyncast/etc.
   2317   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
   2318   static bool classofKind(Kind K) { return K == Decl::FriendTemplate; }
   2319 
   2320   friend class ASTDeclReader;
   2321 };
   2322 
   2323 /// \brief Declaration of an alias template.
   2324 ///
   2325 /// For example:
   2326 /// \code
   2327 /// template \<typename T> using V = std::map<T*, int, MyCompare<T>>;
   2328 /// \endcode
   2329 class TypeAliasTemplateDecl : public RedeclarableTemplateDecl {
   2330 protected:
   2331   typedef CommonBase Common;
   2332 
   2333   TypeAliasTemplateDecl(ASTContext &C, DeclContext *DC, SourceLocation L,
   2334                         DeclarationName Name, TemplateParameterList *Params,
   2335                         NamedDecl *Decl)
   2336       : RedeclarableTemplateDecl(TypeAliasTemplate, C, DC, L, Name, Params,
   2337                                  Decl) {}
   2338 
   2339   CommonBase *newCommon(ASTContext &C) const override;
   2340 
   2341   Common *getCommonPtr() {
   2342     return static_cast<Common *>(RedeclarableTemplateDecl::getCommonPtr());
   2343   }
   2344 
   2345 public:
   2346   /// Get the underlying function declaration of the template.
   2347   TypeAliasDecl *getTemplatedDecl() const {
   2348     return static_cast<TypeAliasDecl *>(TemplatedDecl.getPointer());
   2349   }
   2350 
   2351 
   2352   TypeAliasTemplateDecl *getCanonicalDecl() override {
   2353     return cast<TypeAliasTemplateDecl>(
   2354              RedeclarableTemplateDecl::getCanonicalDecl());
   2355   }
   2356   const TypeAliasTemplateDecl *getCanonicalDecl() const {
   2357     return cast<TypeAliasTemplateDecl>(
   2358              RedeclarableTemplateDecl::getCanonicalDecl());
   2359   }
   2360 
   2361   /// \brief Retrieve the previous declaration of this function template, or
   2362   /// NULL if no such declaration exists.
   2363   TypeAliasTemplateDecl *getPreviousDecl() {
   2364     return cast_or_null<TypeAliasTemplateDecl>(
   2365              static_cast<RedeclarableTemplateDecl *>(this)->getPreviousDecl());
   2366   }
   2367 
   2368   /// \brief Retrieve the previous declaration of this function template, or
   2369   /// NULL if no such declaration exists.
   2370   const TypeAliasTemplateDecl *getPreviousDecl() const {
   2371     return cast_or_null<TypeAliasTemplateDecl>(
   2372              static_cast<const RedeclarableTemplateDecl *>(
   2373                this)->getPreviousDecl());
   2374   }
   2375 
   2376   TypeAliasTemplateDecl *getInstantiatedFromMemberTemplate() const {
   2377     return cast_or_null<TypeAliasTemplateDecl>(
   2378              RedeclarableTemplateDecl::getInstantiatedFromMemberTemplate());
   2379   }
   2380 
   2381 
   2382   /// \brief Create a function template node.
   2383   static TypeAliasTemplateDecl *Create(ASTContext &C, DeclContext *DC,
   2384                                        SourceLocation L,
   2385                                        DeclarationName Name,
   2386                                        TemplateParameterList *Params,
   2387                                        NamedDecl *Decl);
   2388 
   2389   /// \brief Create an empty alias template node.
   2390   static TypeAliasTemplateDecl *CreateDeserialized(ASTContext &C, unsigned ID);
   2391 
   2392   // Implement isa/cast/dyncast support
   2393   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
   2394   static bool classofKind(Kind K) { return K == TypeAliasTemplate; }
   2395 
   2396   friend class ASTDeclReader;
   2397   friend class ASTDeclWriter;
   2398 };
   2399 
   2400 /// \brief Declaration of a function specialization at template class scope.
   2401 ///
   2402 /// This is a non-standard extension needed to support MSVC.
   2403 ///
   2404 /// For example:
   2405 /// \code
   2406 /// template <class T>
   2407 /// class A {
   2408 ///    template <class U> void foo(U a) { }
   2409 ///    template<> void foo(int a) { }
   2410 /// }
   2411 /// \endcode
   2412 ///
   2413 /// "template<> foo(int a)" will be saved in Specialization as a normal
   2414 /// CXXMethodDecl. Then during an instantiation of class A, it will be
   2415 /// transformed into an actual function specialization.
   2416 class ClassScopeFunctionSpecializationDecl : public Decl {
   2417   virtual void anchor();
   2418 
   2419   ClassScopeFunctionSpecializationDecl(DeclContext *DC, SourceLocation Loc,
   2420                                        CXXMethodDecl *FD, bool Args,
   2421                                        TemplateArgumentListInfo TemplArgs)
   2422       : Decl(Decl::ClassScopeFunctionSpecialization, DC, Loc),
   2423         Specialization(FD), HasExplicitTemplateArgs(Args),
   2424         TemplateArgs(std::move(TemplArgs)) {}
   2425 
   2426   ClassScopeFunctionSpecializationDecl(EmptyShell Empty)
   2427     : Decl(Decl::ClassScopeFunctionSpecialization, Empty) {}
   2428 
   2429   CXXMethodDecl *Specialization;
   2430   bool HasExplicitTemplateArgs;
   2431   TemplateArgumentListInfo TemplateArgs;
   2432 
   2433 public:
   2434   CXXMethodDecl *getSpecialization() const { return Specialization; }
   2435   bool hasExplicitTemplateArgs() const { return HasExplicitTemplateArgs; }
   2436   const TemplateArgumentListInfo& templateArgs() const { return TemplateArgs; }
   2437 
   2438   static ClassScopeFunctionSpecializationDecl *Create(ASTContext &C,
   2439                                                       DeclContext *DC,
   2440                                                       SourceLocation Loc,
   2441                                                       CXXMethodDecl *FD,
   2442                                                    bool HasExplicitTemplateArgs,
   2443                                         TemplateArgumentListInfo TemplateArgs) {
   2444     return new (C, DC) ClassScopeFunctionSpecializationDecl(
   2445         DC, Loc, FD, HasExplicitTemplateArgs, std::move(TemplateArgs));
   2446   }
   2447 
   2448   static ClassScopeFunctionSpecializationDecl *
   2449   CreateDeserialized(ASTContext &Context, unsigned ID);
   2450 
   2451   // Implement isa/cast/dyncast/etc.
   2452   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
   2453   static bool classofKind(Kind K) {
   2454     return K == Decl::ClassScopeFunctionSpecialization;
   2455   }
   2456 
   2457   friend class ASTDeclReader;
   2458   friend class ASTDeclWriter;
   2459 };
   2460 
   2461 /// Implementation of inline functions that require the template declarations
   2462 inline AnyFunctionDecl::AnyFunctionDecl(FunctionTemplateDecl *FTD)
   2463   : Function(FTD) { }
   2464 
   2465 /// \brief Represents a variable template specialization, which refers to
   2466 /// a variable template with a given set of template arguments.
   2467 ///
   2468 /// Variable template specializations represent both explicit
   2469 /// specializations of variable templates, as in the example below, and
   2470 /// implicit instantiations of variable templates.
   2471 ///
   2472 /// \code
   2473 /// template<typename T> constexpr T pi = T(3.1415926535897932385);
   2474 ///
   2475 /// template<>
   2476 /// constexpr float pi<float>; // variable template specialization pi<float>
   2477 /// \endcode
   2478 class VarTemplateSpecializationDecl : public VarDecl,
   2479                                       public llvm::FoldingSetNode {
   2480 
   2481   /// \brief Structure that stores information about a variable template
   2482   /// specialization that was instantiated from a variable template partial
   2483   /// specialization.
   2484   struct SpecializedPartialSpecialization {
   2485     /// \brief The variable template partial specialization from which this
   2486     /// variable template specialization was instantiated.
   2487     VarTemplatePartialSpecializationDecl *PartialSpecialization;
   2488 
   2489     /// \brief The template argument list deduced for the variable template
   2490     /// partial specialization itself.
   2491     const TemplateArgumentList *TemplateArgs;
   2492   };
   2493 
   2494   /// \brief The template that this specialization specializes.
   2495   llvm::PointerUnion<VarTemplateDecl *, SpecializedPartialSpecialization *>
   2496   SpecializedTemplate;
   2497 
   2498   /// \brief Further info for explicit template specialization/instantiation.
   2499   struct ExplicitSpecializationInfo {
   2500     /// \brief The type-as-written.
   2501     TypeSourceInfo *TypeAsWritten;
   2502     /// \brief The location of the extern keyword.
   2503     SourceLocation ExternLoc;
   2504     /// \brief The location of the template keyword.
   2505     SourceLocation TemplateKeywordLoc;
   2506 
   2507     ExplicitSpecializationInfo()
   2508         : TypeAsWritten(nullptr), ExternLoc(), TemplateKeywordLoc() {}
   2509   };
   2510 
   2511   /// \brief Further info for explicit template specialization/instantiation.
   2512   /// Does not apply to implicit specializations.
   2513   ExplicitSpecializationInfo *ExplicitInfo;
   2514 
   2515   /// \brief The template arguments used to describe this specialization.
   2516   const TemplateArgumentList *TemplateArgs;
   2517   TemplateArgumentListInfo TemplateArgsInfo;
   2518 
   2519   /// \brief The point where this template was instantiated (if any).
   2520   SourceLocation PointOfInstantiation;
   2521 
   2522   /// \brief The kind of specialization this declaration refers to.
   2523   /// Really a value of type TemplateSpecializationKind.
   2524   unsigned SpecializationKind : 3;
   2525 
   2526 protected:
   2527   VarTemplateSpecializationDecl(Kind DK, ASTContext &Context, DeclContext *DC,
   2528                                 SourceLocation StartLoc, SourceLocation IdLoc,
   2529                                 VarTemplateDecl *SpecializedTemplate,
   2530                                 QualType T, TypeSourceInfo *TInfo,
   2531                                 StorageClass S,
   2532                                 ArrayRef<TemplateArgument> Args);
   2533 
   2534   explicit VarTemplateSpecializationDecl(Kind DK, ASTContext &Context);
   2535 
   2536 public:
   2537   static VarTemplateSpecializationDecl *
   2538   Create(ASTContext &Context, DeclContext *DC, SourceLocation StartLoc,
   2539          SourceLocation IdLoc, VarTemplateDecl *SpecializedTemplate, QualType T,
   2540          TypeSourceInfo *TInfo, StorageClass S,
   2541          ArrayRef<TemplateArgument> Args);
   2542   static VarTemplateSpecializationDecl *CreateDeserialized(ASTContext &C,
   2543                                                            unsigned ID);
   2544 
   2545   void getNameForDiagnostic(raw_ostream &OS, const PrintingPolicy &Policy,
   2546                             bool Qualified) const override;
   2547 
   2548   VarTemplateSpecializationDecl *getMostRecentDecl() {
   2549     VarDecl *Recent = static_cast<VarDecl *>(this)->getMostRecentDecl();
   2550     return cast<VarTemplateSpecializationDecl>(Recent);
   2551   }
   2552 
   2553   /// \brief Retrieve the template that this specialization specializes.
   2554   VarTemplateDecl *getSpecializedTemplate() const;
   2555 
   2556   /// \brief Retrieve the template arguments of the variable template
   2557   /// specialization.
   2558   const TemplateArgumentList &getTemplateArgs() const { return *TemplateArgs; }
   2559 
   2560   // TODO: Always set this when creating the new specialization?
   2561   void setTemplateArgsInfo(const TemplateArgumentListInfo &ArgsInfo);
   2562 
   2563   const TemplateArgumentListInfo &getTemplateArgsInfo() const {
   2564     return TemplateArgsInfo;
   2565   }
   2566 
   2567   /// \brief Determine the kind of specialization that this
   2568   /// declaration represents.
   2569   TemplateSpecializationKind getSpecializationKind() const {
   2570     return static_cast<TemplateSpecializationKind>(SpecializationKind);
   2571   }
   2572 
   2573   bool isExplicitSpecialization() const {
   2574     return getSpecializationKind() == TSK_ExplicitSpecialization;
   2575   }
   2576 
   2577   /// \brief True if this declaration is an explicit specialization,
   2578   /// explicit instantiation declaration, or explicit instantiation
   2579   /// definition.
   2580   bool isExplicitInstantiationOrSpecialization() const {
   2581     return isTemplateExplicitInstantiationOrSpecialization(
   2582         getTemplateSpecializationKind());
   2583   }
   2584 
   2585   void setSpecializationKind(TemplateSpecializationKind TSK) {
   2586     SpecializationKind = TSK;
   2587   }
   2588 
   2589   /// \brief Get the point of instantiation (if any), or null if none.
   2590   SourceLocation getPointOfInstantiation() const {
   2591     return PointOfInstantiation;
   2592   }
   2593 
   2594   void setPointOfInstantiation(SourceLocation Loc) {
   2595     assert(Loc.isValid() && "point of instantiation must be valid!");
   2596     PointOfInstantiation = Loc;
   2597   }
   2598 
   2599   /// \brief If this variable template specialization is an instantiation of
   2600   /// a template (rather than an explicit specialization), return the
   2601   /// variable template or variable template partial specialization from which
   2602   /// it was instantiated.
   2603   llvm::PointerUnion<VarTemplateDecl *, VarTemplatePartialSpecializationDecl *>
   2604   getInstantiatedFrom() const {
   2605     if (!isTemplateInstantiation(getSpecializationKind()))
   2606       return llvm::PointerUnion<VarTemplateDecl *,
   2607                                 VarTemplatePartialSpecializationDecl *>();
   2608 
   2609     return getSpecializedTemplateOrPartial();
   2610   }
   2611 
   2612   /// \brief Retrieve the variable template or variable template partial
   2613   /// specialization which was specialized by this.
   2614   llvm::PointerUnion<VarTemplateDecl *, VarTemplatePartialSpecializationDecl *>
   2615   getSpecializedTemplateOrPartial() const {
   2616     if (SpecializedPartialSpecialization *PartialSpec =
   2617             SpecializedTemplate.dyn_cast<SpecializedPartialSpecialization *>())
   2618       return PartialSpec->PartialSpecialization;
   2619 
   2620     return SpecializedTemplate.get<VarTemplateDecl *>();
   2621   }
   2622 
   2623   /// \brief Retrieve the set of template arguments that should be used
   2624   /// to instantiate the initializer of the variable template or variable
   2625   /// template partial specialization from which this variable template
   2626   /// specialization was instantiated.
   2627   ///
   2628   /// \returns For a variable template specialization instantiated from the
   2629   /// primary template, this function will return the same template arguments
   2630   /// as getTemplateArgs(). For a variable template specialization instantiated
   2631   /// from a variable template partial specialization, this function will the
   2632   /// return deduced template arguments for the variable template partial
   2633   /// specialization itself.
   2634   const TemplateArgumentList &getTemplateInstantiationArgs() const {
   2635     if (SpecializedPartialSpecialization *PartialSpec =
   2636             SpecializedTemplate.dyn_cast<SpecializedPartialSpecialization *>())
   2637       return *PartialSpec->TemplateArgs;
   2638 
   2639     return getTemplateArgs();
   2640   }
   2641 
   2642   /// \brief Note that this variable template specialization is actually an
   2643   /// instantiation of the given variable template partial specialization whose
   2644   /// template arguments have been deduced.
   2645   void setInstantiationOf(VarTemplatePartialSpecializationDecl *PartialSpec,
   2646                           const TemplateArgumentList *TemplateArgs) {
   2647     assert(!SpecializedTemplate.is<SpecializedPartialSpecialization *>() &&
   2648            "Already set to a variable template partial specialization!");
   2649     SpecializedPartialSpecialization *PS =
   2650         new (getASTContext()) SpecializedPartialSpecialization();
   2651     PS->PartialSpecialization = PartialSpec;
   2652     PS->TemplateArgs = TemplateArgs;
   2653     SpecializedTemplate = PS;
   2654   }
   2655 
   2656   /// \brief Note that this variable template specialization is an instantiation
   2657   /// of the given variable template.
   2658   void setInstantiationOf(VarTemplateDecl *TemplDecl) {
   2659     assert(!SpecializedTemplate.is<SpecializedPartialSpecialization *>() &&
   2660            "Previously set to a variable template partial specialization!");
   2661     SpecializedTemplate = TemplDecl;
   2662   }
   2663 
   2664   /// \brief Sets the type of this specialization as it was written by
   2665   /// the user.
   2666   void setTypeAsWritten(TypeSourceInfo *T) {
   2667     if (!ExplicitInfo)
   2668       ExplicitInfo = new (getASTContext()) ExplicitSpecializationInfo;
   2669     ExplicitInfo->TypeAsWritten = T;
   2670   }
   2671   /// \brief Gets the type of this specialization as it was written by
   2672   /// the user, if it was so written.
   2673   TypeSourceInfo *getTypeAsWritten() const {
   2674     return ExplicitInfo ? ExplicitInfo->TypeAsWritten : nullptr;
   2675   }
   2676 
   2677   /// \brief Gets the location of the extern keyword, if present.
   2678   SourceLocation getExternLoc() const {
   2679     return ExplicitInfo ? ExplicitInfo->ExternLoc : SourceLocation();
   2680   }
   2681   /// \brief Sets the location of the extern keyword.
   2682   void setExternLoc(SourceLocation Loc) {
   2683     if (!ExplicitInfo)
   2684       ExplicitInfo = new (getASTContext()) ExplicitSpecializationInfo;
   2685     ExplicitInfo->ExternLoc = Loc;
   2686   }
   2687 
   2688   /// \brief Sets the location of the template keyword.
   2689   void setTemplateKeywordLoc(SourceLocation Loc) {
   2690     if (!ExplicitInfo)
   2691       ExplicitInfo = new (getASTContext()) ExplicitSpecializationInfo;
   2692     ExplicitInfo->TemplateKeywordLoc = Loc;
   2693   }
   2694   /// \brief Gets the location of the template keyword, if present.
   2695   SourceLocation getTemplateKeywordLoc() const {
   2696     return ExplicitInfo ? ExplicitInfo->TemplateKeywordLoc : SourceLocation();
   2697   }
   2698 
   2699   void Profile(llvm::FoldingSetNodeID &ID) const {
   2700     Profile(ID, TemplateArgs->asArray(), getASTContext());
   2701   }
   2702 
   2703   static void Profile(llvm::FoldingSetNodeID &ID,
   2704                       ArrayRef<TemplateArgument> TemplateArgs,
   2705                       ASTContext &Context) {
   2706     ID.AddInteger(TemplateArgs.size());
   2707     for (const TemplateArgument &TemplateArg : TemplateArgs)
   2708       TemplateArg.Profile(ID, Context);
   2709   }
   2710 
   2711   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
   2712   static bool classofKind(Kind K) {
   2713     return K >= firstVarTemplateSpecialization &&
   2714            K <= lastVarTemplateSpecialization;
   2715   }
   2716 
   2717   friend class ASTDeclReader;
   2718   friend class ASTDeclWriter;
   2719 };
   2720 
   2721 class VarTemplatePartialSpecializationDecl
   2722     : public VarTemplateSpecializationDecl {
   2723   void anchor() override;
   2724 
   2725   /// \brief The list of template parameters
   2726   TemplateParameterList *TemplateParams;
   2727 
   2728   /// \brief The source info for the template arguments as written.
   2729   /// FIXME: redundant with TypeAsWritten?
   2730   const ASTTemplateArgumentListInfo *ArgsAsWritten;
   2731 
   2732   /// \brief The variable template partial specialization from which this
   2733   /// variable template partial specialization was instantiated.
   2734   ///
   2735   /// The boolean value will be true to indicate that this variable template
   2736   /// partial specialization was specialized at this level.
   2737   llvm::PointerIntPair<VarTemplatePartialSpecializationDecl *, 1, bool>
   2738   InstantiatedFromMember;
   2739 
   2740   VarTemplatePartialSpecializationDecl(
   2741       ASTContext &Context, DeclContext *DC, SourceLocation StartLoc,
   2742       SourceLocation IdLoc, TemplateParameterList *Params,
   2743       VarTemplateDecl *SpecializedTemplate, QualType T, TypeSourceInfo *TInfo,
   2744       StorageClass S, ArrayRef<TemplateArgument> Args,
   2745       const ASTTemplateArgumentListInfo *ArgInfos);
   2746 
   2747   VarTemplatePartialSpecializationDecl(ASTContext &Context)
   2748     : VarTemplateSpecializationDecl(VarTemplatePartialSpecialization, Context),
   2749       TemplateParams(nullptr), ArgsAsWritten(nullptr),
   2750       InstantiatedFromMember(nullptr, false) {}
   2751 
   2752 public:
   2753   static VarTemplatePartialSpecializationDecl *
   2754   Create(ASTContext &Context, DeclContext *DC, SourceLocation StartLoc,
   2755          SourceLocation IdLoc, TemplateParameterList *Params,
   2756          VarTemplateDecl *SpecializedTemplate, QualType T,
   2757          TypeSourceInfo *TInfo, StorageClass S, ArrayRef<TemplateArgument> Args,
   2758          const TemplateArgumentListInfo &ArgInfos);
   2759 
   2760   static VarTemplatePartialSpecializationDecl *CreateDeserialized(ASTContext &C,
   2761                                                                   unsigned ID);
   2762 
   2763   VarTemplatePartialSpecializationDecl *getMostRecentDecl() {
   2764     return cast<VarTemplatePartialSpecializationDecl>(
   2765              static_cast<VarTemplateSpecializationDecl *>(
   2766                this)->getMostRecentDecl());
   2767   }
   2768 
   2769   /// Get the list of template parameters
   2770   TemplateParameterList *getTemplateParameters() const {
   2771     return TemplateParams;
   2772   }
   2773 
   2774   /// Get the template arguments as written.
   2775   const ASTTemplateArgumentListInfo *getTemplateArgsAsWritten() const {
   2776     return ArgsAsWritten;
   2777   }
   2778 
   2779   /// \brief Retrieve the member variable template partial specialization from
   2780   /// which this particular variable template partial specialization was
   2781   /// instantiated.
   2782   ///
   2783   /// \code
   2784   /// template<typename T>
   2785   /// struct Outer {
   2786   ///   template<typename U> U Inner;
   2787   ///   template<typename U> U* Inner<U*> = (U*)(0); // #1
   2788   /// };
   2789   ///
   2790   /// template int* Outer<float>::Inner<int*>;
   2791   /// \endcode
   2792   ///
   2793   /// In this example, the instantiation of \c Outer<float>::Inner<int*> will
   2794   /// end up instantiating the partial specialization
   2795   /// \c Outer<float>::Inner<U*>, which itself was instantiated from the
   2796   /// variable template partial specialization \c Outer<T>::Inner<U*>. Given
   2797   /// \c Outer<float>::Inner<U*>, this function would return
   2798   /// \c Outer<T>::Inner<U*>.
   2799   VarTemplatePartialSpecializationDecl *getInstantiatedFromMember() const {
   2800     const VarTemplatePartialSpecializationDecl *First =
   2801         cast<VarTemplatePartialSpecializationDecl>(getFirstDecl());
   2802     return First->InstantiatedFromMember.getPointer();
   2803   }
   2804 
   2805   void
   2806   setInstantiatedFromMember(VarTemplatePartialSpecializationDecl *PartialSpec) {
   2807     VarTemplatePartialSpecializationDecl *First =
   2808         cast<VarTemplatePartialSpecializationDecl>(getFirstDecl());
   2809     First->InstantiatedFromMember.setPointer(PartialSpec);
   2810   }
   2811 
   2812   /// \brief Determines whether this variable template partial specialization
   2813   /// was a specialization of a member partial specialization.
   2814   ///
   2815   /// In the following example, the member template partial specialization
   2816   /// \c X<int>::Inner<T*> is a member specialization.
   2817   ///
   2818   /// \code
   2819   /// template<typename T>
   2820   /// struct X {
   2821   ///   template<typename U> U Inner;
   2822   ///   template<typename U> U* Inner<U*> = (U*)(0);
   2823   /// };
   2824   ///
   2825   /// template<> template<typename T>
   2826   /// U* X<int>::Inner<T*> = (T*)(0) + 1;
   2827   /// \endcode
   2828   bool isMemberSpecialization() {
   2829     VarTemplatePartialSpecializationDecl *First =
   2830         cast<VarTemplatePartialSpecializationDecl>(getFirstDecl());
   2831     return First->InstantiatedFromMember.getInt();
   2832   }
   2833 
   2834   /// \brief Note that this member template is a specialization.
   2835   void setMemberSpecialization() {
   2836     VarTemplatePartialSpecializationDecl *First =
   2837         cast<VarTemplatePartialSpecializationDecl>(getFirstDecl());
   2838     assert(First->InstantiatedFromMember.getPointer() &&
   2839            "Only member templates can be member template specializations");
   2840     return First->InstantiatedFromMember.setInt(true);
   2841   }
   2842 
   2843   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
   2844   static bool classofKind(Kind K) {
   2845     return K == VarTemplatePartialSpecialization;
   2846   }
   2847 
   2848   friend class ASTDeclReader;
   2849   friend class ASTDeclWriter;
   2850 };
   2851 
   2852 /// Declaration of a variable template.
   2853 class VarTemplateDecl : public RedeclarableTemplateDecl {
   2854 protected:
   2855   /// \brief Data that is common to all of the declarations of a given
   2856   /// variable template.
   2857   struct Common : CommonBase {
   2858     Common() : LazySpecializations() {}
   2859 
   2860     /// \brief The variable template specializations for this variable
   2861     /// template, including explicit specializations and instantiations.
   2862     llvm::FoldingSetVector<VarTemplateSpecializationDecl> Specializations;
   2863 
   2864     /// \brief The variable template partial specializations for this variable
   2865     /// template.
   2866     llvm::FoldingSetVector<VarTemplatePartialSpecializationDecl>
   2867     PartialSpecializations;
   2868 
   2869     /// \brief If non-null, points to an array of specializations (including
   2870     /// partial specializations) known ownly by their external declaration IDs.
   2871     ///
   2872     /// The first value in the array is the number of of specializations/
   2873     /// partial specializations that follow.
   2874     uint32_t *LazySpecializations;
   2875   };
   2876 
   2877   /// \brief Retrieve the set of specializations of this variable template.
   2878   llvm::FoldingSetVector<VarTemplateSpecializationDecl> &
   2879   getSpecializations() const;
   2880 
   2881   /// \brief Retrieve the set of partial specializations of this class
   2882   /// template.
   2883   llvm::FoldingSetVector<VarTemplatePartialSpecializationDecl> &
   2884   getPartialSpecializations();
   2885 
   2886   VarTemplateDecl(ASTContext &C, DeclContext *DC, SourceLocation L,
   2887                   DeclarationName Name, TemplateParameterList *Params,
   2888                   NamedDecl *Decl)
   2889       : RedeclarableTemplateDecl(VarTemplate, C, DC, L, Name, Params, Decl) {}
   2890 
   2891   CommonBase *newCommon(ASTContext &C) const override;
   2892 
   2893   Common *getCommonPtr() const {
   2894     return static_cast<Common *>(RedeclarableTemplateDecl::getCommonPtr());
   2895   }
   2896 
   2897 public:
   2898   /// \brief Load any lazily-loaded specializations from the external source.
   2899   void LoadLazySpecializations() const;
   2900 
   2901   /// \brief Get the underlying variable declarations of the template.
   2902   VarDecl *getTemplatedDecl() const {
   2903     return static_cast<VarDecl *>(TemplatedDecl.getPointer());
   2904   }
   2905 
   2906   /// \brief Returns whether this template declaration defines the primary
   2907   /// variable pattern.
   2908   bool isThisDeclarationADefinition() const {
   2909     return getTemplatedDecl()->isThisDeclarationADefinition();
   2910   }
   2911 
   2912   VarTemplateDecl *getDefinition();
   2913 
   2914   /// \brief Create a variable template node.
   2915   static VarTemplateDecl *Create(ASTContext &C, DeclContext *DC,
   2916                                  SourceLocation L, DeclarationName Name,
   2917                                  TemplateParameterList *Params,
   2918                                  VarDecl *Decl);
   2919 
   2920   /// \brief Create an empty variable template node.
   2921   static VarTemplateDecl *CreateDeserialized(ASTContext &C, unsigned ID);
   2922 
   2923   /// \brief Return the specialization with the provided arguments if it exists,
   2924   /// otherwise return the insertion point.
   2925   VarTemplateSpecializationDecl *
   2926   findSpecialization(ArrayRef<TemplateArgument> Args, void *&InsertPos);
   2927 
   2928   /// \brief Insert the specified specialization knowing that it is not already
   2929   /// in. InsertPos must be obtained from findSpecialization.
   2930   void AddSpecialization(VarTemplateSpecializationDecl *D, void *InsertPos);
   2931 
   2932   VarTemplateDecl *getCanonicalDecl() override {
   2933     return cast<VarTemplateDecl>(RedeclarableTemplateDecl::getCanonicalDecl());
   2934   }
   2935   const VarTemplateDecl *getCanonicalDecl() const {
   2936     return cast<VarTemplateDecl>(RedeclarableTemplateDecl::getCanonicalDecl());
   2937   }
   2938 
   2939   /// \brief Retrieve the previous declaration of this variable template, or
   2940   /// NULL if no such declaration exists.
   2941   VarTemplateDecl *getPreviousDecl() {
   2942     return cast_or_null<VarTemplateDecl>(
   2943         static_cast<RedeclarableTemplateDecl *>(this)->getPreviousDecl());
   2944   }
   2945 
   2946   /// \brief Retrieve the previous declaration of this variable template, or
   2947   /// NULL if no such declaration exists.
   2948   const VarTemplateDecl *getPreviousDecl() const {
   2949     return cast_or_null<VarTemplateDecl>(
   2950             static_cast<const RedeclarableTemplateDecl *>(
   2951               this)->getPreviousDecl());
   2952   }
   2953 
   2954   VarTemplateDecl *getMostRecentDecl() {
   2955     return cast<VarTemplateDecl>(
   2956         static_cast<RedeclarableTemplateDecl *>(this)->getMostRecentDecl());
   2957   }
   2958   const VarTemplateDecl *getMostRecentDecl() const {
   2959     return const_cast<VarTemplateDecl *>(this)->getMostRecentDecl();
   2960   }
   2961 
   2962   VarTemplateDecl *getInstantiatedFromMemberTemplate() const {
   2963     return cast_or_null<VarTemplateDecl>(
   2964         RedeclarableTemplateDecl::getInstantiatedFromMemberTemplate());
   2965   }
   2966 
   2967   /// \brief Return the partial specialization with the provided arguments if it
   2968   /// exists, otherwise return the insertion point.
   2969   VarTemplatePartialSpecializationDecl *
   2970   findPartialSpecialization(ArrayRef<TemplateArgument> Args, void *&InsertPos);
   2971 
   2972   /// \brief Insert the specified partial specialization knowing that it is not
   2973   /// already in. InsertPos must be obtained from findPartialSpecialization.
   2974   void AddPartialSpecialization(VarTemplatePartialSpecializationDecl *D,
   2975                                 void *InsertPos);
   2976 
   2977   /// \brief Retrieve the partial specializations as an ordered list.
   2978   void getPartialSpecializations(
   2979       SmallVectorImpl<VarTemplatePartialSpecializationDecl *> &PS);
   2980 
   2981   /// \brief Find a variable template partial specialization which was
   2982   /// instantiated
   2983   /// from the given member partial specialization.
   2984   ///
   2985   /// \param D a member variable template partial specialization.
   2986   ///
   2987   /// \returns the variable template partial specialization which was
   2988   /// instantiated
   2989   /// from the given member partial specialization, or NULL if no such partial
   2990   /// specialization exists.
   2991   VarTemplatePartialSpecializationDecl *findPartialSpecInstantiatedFromMember(
   2992       VarTemplatePartialSpecializationDecl *D);
   2993 
   2994   typedef SpecIterator<VarTemplateSpecializationDecl> spec_iterator;
   2995   typedef llvm::iterator_range<spec_iterator> spec_range;
   2996 
   2997   spec_range specializations() const {
   2998     return spec_range(spec_begin(), spec_end());
   2999   }
   3000 
   3001   spec_iterator spec_begin() const {
   3002     return makeSpecIterator(getSpecializations(), false);
   3003   }
   3004 
   3005   spec_iterator spec_end() const {
   3006     return makeSpecIterator(getSpecializations(), true);
   3007   }
   3008 
   3009   // Implement isa/cast/dyncast support
   3010   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
   3011   static bool classofKind(Kind K) { return K == VarTemplate; }
   3012 
   3013   friend class ASTDeclReader;
   3014   friend class ASTDeclWriter;
   3015 };
   3016 
   3017 inline NamedDecl *getAsNamedDecl(TemplateParameter P) {
   3018   if (auto *PD = P.dyn_cast<TemplateTypeParmDecl*>())
   3019     return PD;
   3020   if (auto *PD = P.dyn_cast<NonTypeTemplateParmDecl*>())
   3021     return PD;
   3022   return P.get<TemplateTemplateParmDecl*>();
   3023 }
   3024 
   3025 inline TemplateDecl *getAsTypeTemplateDecl(Decl *D) {
   3026   auto *TD = dyn_cast<TemplateDecl>(D);
   3027   return TD && (isa<ClassTemplateDecl>(TD) ||
   3028                 isa<ClassTemplatePartialSpecializationDecl>(TD) ||
   3029                 isa<TypeAliasTemplateDecl>(TD) ||
   3030                 isa<TemplateTemplateParmDecl>(TD))
   3031              ? TD
   3032              : nullptr;
   3033 }
   3034 
   3035 } /* end of namespace clang */
   3036 
   3037 #endif
   3038