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