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