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