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