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