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