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