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