Subversion Repositories QNX 8.QNX8 LLVM/Clang compiler suite

Rev

Blame | Last modification | View Log | Download | RSS feed

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