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