DeclTemplate.h revision f1c66b40213784a1c4612f04c14cafa2b0e89988
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//  This file defines the C++ template declaration subclasses.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_AST_DECLTEMPLATE_H
15#define LLVM_CLANG_AST_DECLTEMPLATE_H
16
17#include "clang/AST/DeclCXX.h"
18#include "clang/AST/Redeclarable.h"
19#include "clang/AST/TemplateBase.h"
20#include "llvm/ADT/PointerUnion.h"
21#include "llvm/Support/Compiler.h"
22#include <limits>
23
24namespace clang {
25
26class TemplateParameterList;
27class TemplateDecl;
28class RedeclarableTemplateDecl;
29class FunctionTemplateDecl;
30class ClassTemplateDecl;
31class ClassTemplatePartialSpecializationDecl;
32class TemplateTypeParmDecl;
33class NonTypeTemplateParmDecl;
34class TemplateTemplateParmDecl;
35class TypeAliasTemplateDecl;
36
37/// \brief Stores a template parameter of any kind.
38typedef llvm::PointerUnion3<TemplateTypeParmDecl*, NonTypeTemplateParmDecl*,
39                            TemplateTemplateParmDecl*> TemplateParameter;
40
41/// TemplateParameterList - Stores a list of template parameters for a
42/// TemplateDecl and its derived classes.
43class TemplateParameterList {
44  /// The location of the 'template' keyword.
45  SourceLocation TemplateLoc;
46
47  /// The locations of the '<' and '>' angle brackets.
48  SourceLocation LAngleLoc, RAngleLoc;
49
50  /// The number of template parameters in this template
51  /// parameter list.
52  unsigned NumParams;
53
54protected:
55  TemplateParameterList(SourceLocation TemplateLoc, SourceLocation LAngleLoc,
56                        NamedDecl **Params, unsigned NumParams,
57                        SourceLocation RAngleLoc);
58
59public:
60  static TemplateParameterList *Create(const ASTContext &C,
61                                       SourceLocation TemplateLoc,
62                                       SourceLocation LAngleLoc,
63                                       NamedDecl **Params,
64                                       unsigned NumParams,
65                                       SourceLocation RAngleLoc);
66
67  /// iterator - Iterates through the template parameters in this list.
68  typedef NamedDecl** iterator;
69
70  /// const_iterator - Iterates through the template parameters in this list.
71  typedef NamedDecl* const* const_iterator;
72
73  iterator begin() { return reinterpret_cast<NamedDecl **>(this + 1); }
74  const_iterator begin() const {
75    return reinterpret_cast<NamedDecl * const *>(this + 1);
76  }
77  iterator end() { return begin() + NumParams; }
78  const_iterator end() const { return begin() + NumParams; }
79
80  unsigned size() const { return NumParams; }
81
82  NamedDecl* getParam(unsigned Idx) {
83    assert(Idx < size() && "Template parameter index out-of-range");
84    return begin()[Idx];
85  }
86
87  const NamedDecl* getParam(unsigned Idx) const {
88    assert(Idx < size() && "Template parameter index out-of-range");
89    return begin()[Idx];
90  }
91
92  /// \brief Returns the minimum number of arguments needed to form a
93  /// template specialization. This may be fewer than the number of
94  /// template parameters, if some of the parameters have default
95  /// arguments or if there is a parameter pack.
96  unsigned getMinRequiredArguments() const;
97
98  /// \brief Get the depth of this template parameter list in the set of
99  /// template parameter lists.
100  ///
101  /// The first template parameter list in a declaration will have depth 0,
102  /// the second template parameter list will have depth 1, etc.
103  unsigned getDepth() const;
104
105  SourceLocation getTemplateLoc() const { return TemplateLoc; }
106  SourceLocation getLAngleLoc() const { return LAngleLoc; }
107  SourceLocation getRAngleLoc() const { return RAngleLoc; }
108
109  SourceRange getSourceRange() const LLVM_READONLY {
110    return SourceRange(TemplateLoc, RAngleLoc);
111  }
112};
113
114/// FixedSizeTemplateParameterList - Stores a list of template parameters for a
115/// TemplateDecl and its derived classes. Suitable for creating on the stack.
116template<size_t N>
117class FixedSizeTemplateParameterList : public TemplateParameterList {
118  NamedDecl *Params[N];
119
120public:
121  FixedSizeTemplateParameterList(SourceLocation TemplateLoc,
122                                 SourceLocation LAngleLoc,
123                                 NamedDecl **Params, SourceLocation RAngleLoc) :
124    TemplateParameterList(TemplateLoc, LAngleLoc, Params, N, RAngleLoc) {
125  }
126};
127
128/// \brief A template argument list.
129class TemplateArgumentList {
130  /// \brief The template argument list.
131  ///
132  /// The integer value will be non-zero to indicate that this
133  /// template argument list does own the pointer.
134  llvm::PointerIntPair<const TemplateArgument *, 1> Arguments;
135
136  /// \brief The number of template arguments in this template
137  /// argument list.
138  unsigned NumArguments;
139
140  TemplateArgumentList(const TemplateArgumentList &Other); // DO NOT IMPL
141  void operator=(const TemplateArgumentList &Other); // DO NOT IMPL
142
143  TemplateArgumentList(const TemplateArgument *Args, unsigned NumArgs,
144                       bool Owned)
145    : Arguments(Args, Owned), NumArguments(NumArgs) { }
146
147public:
148  /// \brief Type used to indicate that the template argument list itself is a
149  /// stack object. It does not own its template arguments.
150  enum OnStackType { OnStack };
151
152  /// \brief Create a new template argument list that copies the given set of
153  /// template arguments.
154  static TemplateArgumentList *CreateCopy(ASTContext &Context,
155                                          const TemplateArgument *Args,
156                                          unsigned NumArgs);
157
158  /// \brief Construct a new, temporary template argument list on the stack.
159  ///
160  /// The template argument list does not own the template arguments
161  /// provided.
162  explicit TemplateArgumentList(OnStackType,
163                                const TemplateArgument *Args, unsigned NumArgs)
164    : Arguments(Args, false), NumArguments(NumArgs) { }
165
166  /// \brief Produces a shallow copy of the given template argument list.
167  ///
168  /// This operation assumes that the input argument list outlives it.
169  /// This takes the list as a pointer to avoid looking like a copy
170  /// constructor, since this really really isn't safe to use that
171  /// way.
172  explicit TemplateArgumentList(const TemplateArgumentList *Other)
173    : Arguments(Other->data(), false), NumArguments(Other->size()) { }
174
175  /// \brief Retrieve the template argument at a given index.
176  const TemplateArgument &get(unsigned Idx) const {
177    assert(Idx < NumArguments && "Invalid template argument index");
178    return data()[Idx];
179  }
180
181  /// \brief Retrieve the template argument at a given index.
182  const TemplateArgument &operator[](unsigned Idx) const { return get(Idx); }
183
184  /// \brief Retrieve the number of template arguments in this
185  /// template argument list.
186  unsigned size() const { return NumArguments; }
187
188  /// \brief Retrieve a pointer to the template argument list.
189  const TemplateArgument *data() const {
190    return Arguments.getPointer();
191  }
192};
193
194//===----------------------------------------------------------------------===//
195// Kinds of Templates
196//===----------------------------------------------------------------------===//
197
198/// TemplateDecl - The base class of all kinds of template declarations (e.g.,
199/// class, function, etc.). The TemplateDecl class stores the list of template
200/// parameters and a reference to the templated scoped declaration: the
201/// underlying AST node.
202class TemplateDecl : public NamedDecl {
203  virtual void anchor();
204protected:
205  // This is probably never used.
206  TemplateDecl(Kind DK, DeclContext *DC, SourceLocation L,
207               DeclarationName Name)
208    : NamedDecl(DK, DC, L, Name), TemplatedDecl(0), TemplateParams(0) { }
209
210  // Construct a template decl with the given name and parameters.
211  // Used when there is not templated element (tt-params, alias?).
212  TemplateDecl(Kind DK, DeclContext *DC, SourceLocation L,
213               DeclarationName Name, TemplateParameterList *Params)
214    : NamedDecl(DK, DC, L, Name), TemplatedDecl(0), TemplateParams(Params) { }
215
216  // Construct a template decl with name, parameters, and templated element.
217  TemplateDecl(Kind DK, DeclContext *DC, SourceLocation L,
218               DeclarationName Name, TemplateParameterList *Params,
219               NamedDecl *Decl)
220    : NamedDecl(DK, DC, L, Name), TemplatedDecl(Decl),
221      TemplateParams(Params) { }
222public:
223  /// Get the list of template parameters
224  TemplateParameterList *getTemplateParameters() const {
225    return TemplateParams;
226  }
227
228  /// Get the underlying, templated declaration.
229  NamedDecl *getTemplatedDecl() const { return TemplatedDecl; }
230
231  // Implement isa/cast/dyncast/etc.
232  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
233  static bool classof(const TemplateDecl *D) { return true; }
234  static bool classof(const RedeclarableTemplateDecl *D) { return true; }
235  static bool classof(const FunctionTemplateDecl *D) { return true; }
236  static bool classof(const ClassTemplateDecl *D) { return true; }
237  static bool classof(const TemplateTemplateParmDecl *D) { return true; }
238  static bool classof(const TypeAliasTemplateDecl *D) { return true; }
239  static bool classofKind(Kind K) {
240    return K >= firstTemplate && K <= lastTemplate;
241  }
242
243  SourceRange getSourceRange() const LLVM_READONLY {
244    return SourceRange(TemplateParams->getTemplateLoc(),
245                       TemplatedDecl->getSourceRange().getEnd());
246  }
247
248protected:
249  NamedDecl *TemplatedDecl;
250  TemplateParameterList* TemplateParams;
251
252public:
253  /// \brief Initialize the underlying templated declaration and
254  /// template parameters.
255  void init(NamedDecl *templatedDecl, TemplateParameterList* templateParams) {
256    assert(TemplatedDecl == 0 && "TemplatedDecl already set!");
257    assert(TemplateParams == 0 && "TemplateParams already set!");
258    TemplatedDecl = templatedDecl;
259    TemplateParams = templateParams;
260  }
261};
262
263/// \brief Provides information about a function template specialization,
264/// which is a FunctionDecl that has been explicitly specialization or
265/// instantiated from a function template.
266class FunctionTemplateSpecializationInfo : public llvm::FoldingSetNode {
267  FunctionTemplateSpecializationInfo(FunctionDecl *FD,
268                                     FunctionTemplateDecl *Template,
269                                     TemplateSpecializationKind TSK,
270                                     const TemplateArgumentList *TemplateArgs,
271                       const ASTTemplateArgumentListInfo *TemplateArgsAsWritten,
272                                     SourceLocation POI)
273  : Function(FD),
274    Template(Template, TSK - 1),
275    TemplateArguments(TemplateArgs),
276    TemplateArgumentsAsWritten(TemplateArgsAsWritten),
277    PointOfInstantiation(POI) { }
278
279public:
280  static FunctionTemplateSpecializationInfo *
281  Create(ASTContext &C, FunctionDecl *FD, FunctionTemplateDecl *Template,
282         TemplateSpecializationKind TSK,
283         const TemplateArgumentList *TemplateArgs,
284         const TemplateArgumentListInfo *TemplateArgsAsWritten,
285         SourceLocation POI);
286
287  /// \brief The function template specialization that this structure
288  /// describes.
289  FunctionDecl *Function;
290
291  /// \brief The function template from which this function template
292  /// specialization was generated.
293  ///
294  /// The two bits are contain the top 4 values of TemplateSpecializationKind.
295  llvm::PointerIntPair<FunctionTemplateDecl *, 2> Template;
296
297  /// \brief The template arguments used to produce the function template
298  /// specialization from the function template.
299  const TemplateArgumentList *TemplateArguments;
300
301  /// \brief The template arguments as written in the sources, if provided.
302  const ASTTemplateArgumentListInfo *TemplateArgumentsAsWritten;
303
304  /// \brief The point at which this function template specialization was
305  /// first instantiated.
306  SourceLocation PointOfInstantiation;
307
308  /// \brief Retrieve the template from which this function was specialized.
309  FunctionTemplateDecl *getTemplate() const { return Template.getPointer(); }
310
311  /// \brief Determine what kind of template specialization this is.
312  TemplateSpecializationKind getTemplateSpecializationKind() const {
313    return (TemplateSpecializationKind)(Template.getInt() + 1);
314  }
315
316  bool isExplicitSpecialization() const {
317    return getTemplateSpecializationKind() == TSK_ExplicitSpecialization;
318  }
319
320  /// \brief Set the template specialization kind.
321  void setTemplateSpecializationKind(TemplateSpecializationKind TSK) {
322    assert(TSK != TSK_Undeclared &&
323         "Cannot encode TSK_Undeclared for a function template specialization");
324    Template.setInt(TSK - 1);
325  }
326
327  /// \brief Retrieve the first point of instantiation of this function
328  /// template specialization.
329  ///
330  /// The point of instantiation may be an invalid source location if this
331  /// function has yet to be instantiated.
332  SourceLocation getPointOfInstantiation() const {
333    return PointOfInstantiation;
334  }
335
336  /// \brief Set the (first) point of instantiation of this function template
337  /// specialization.
338  void setPointOfInstantiation(SourceLocation POI) {
339    PointOfInstantiation = POI;
340  }
341
342  void Profile(llvm::FoldingSetNodeID &ID) {
343    Profile(ID, TemplateArguments->data(),
344            TemplateArguments->size(),
345            Function->getASTContext());
346  }
347
348  static void
349  Profile(llvm::FoldingSetNodeID &ID, const TemplateArgument *TemplateArgs,
350          unsigned NumTemplateArgs, ASTContext &Context) {
351    ID.AddInteger(NumTemplateArgs);
352    for (unsigned Arg = 0; Arg != NumTemplateArgs; ++Arg)
353      TemplateArgs[Arg].Profile(ID, Context);
354  }
355};
356
357/// \brief Provides information a specialization of a member of a class
358/// template, which may be a member function, static data member,
359/// member class or member enumeration.
360class MemberSpecializationInfo {
361  // The member declaration from which this member was instantiated, and the
362  // manner in which the instantiation occurred (in the lower two bits).
363  llvm::PointerIntPair<NamedDecl *, 2> MemberAndTSK;
364
365  // The point at which this member was first instantiated.
366  SourceLocation PointOfInstantiation;
367
368public:
369  explicit
370  MemberSpecializationInfo(NamedDecl *IF, TemplateSpecializationKind TSK,
371                           SourceLocation POI = SourceLocation())
372    : MemberAndTSK(IF, TSK - 1), PointOfInstantiation(POI) {
373    assert(TSK != TSK_Undeclared &&
374           "Cannot encode undeclared template specializations for members");
375  }
376
377  /// \brief Retrieve the member declaration from which this member was
378  /// instantiated.
379  NamedDecl *getInstantiatedFrom() const { return MemberAndTSK.getPointer(); }
380
381  /// \brief Determine what kind of template specialization this is.
382  TemplateSpecializationKind getTemplateSpecializationKind() const {
383    return (TemplateSpecializationKind)(MemberAndTSK.getInt() + 1);
384  }
385
386  /// \brief Set the template specialization kind.
387  void setTemplateSpecializationKind(TemplateSpecializationKind TSK) {
388    assert(TSK != TSK_Undeclared &&
389           "Cannot encode undeclared template specializations for members");
390    MemberAndTSK.setInt(TSK - 1);
391  }
392
393  /// \brief Retrieve the first point of instantiation of this member.
394  /// If the point of instantiation is an invalid location, then this member
395  /// has not yet been instantiated.
396  SourceLocation getPointOfInstantiation() const {
397    return PointOfInstantiation;
398  }
399
400  /// \brief Set the first point of instantiation.
401  void setPointOfInstantiation(SourceLocation POI) {
402    PointOfInstantiation = POI;
403  }
404};
405
406/// \brief Provides information about a dependent function-template
407/// specialization declaration.  Since explicit function template
408/// specialization and instantiation declarations can only appear in
409/// namespace scope, and you can only specialize a member of a
410/// fully-specialized class, the only way to get one of these is in
411/// a friend declaration like the following:
412///
413///   template <class T> void foo(T);
414///   template <class T> class A {
415///     friend void foo<>(T);
416///   };
417class DependentFunctionTemplateSpecializationInfo {
418  union {
419    // Force sizeof to be a multiple of sizeof(void*) so that the
420    // trailing data is aligned.
421    void *Aligner;
422
423    struct {
424      /// The number of potential template candidates.
425      unsigned NumTemplates;
426
427      /// The number of template arguments.
428      unsigned NumArgs;
429    } d;
430  };
431
432  /// The locations of the left and right angle brackets.
433  SourceRange AngleLocs;
434
435  FunctionTemplateDecl * const *getTemplates() const {
436    return reinterpret_cast<FunctionTemplateDecl*const*>(this+1);
437  }
438
439public:
440  DependentFunctionTemplateSpecializationInfo(
441                                 const UnresolvedSetImpl &Templates,
442                                 const TemplateArgumentListInfo &TemplateArgs);
443
444  /// \brief Returns the number of function templates that this might
445  /// be a specialization of.
446  unsigned getNumTemplates() const {
447    return d.NumTemplates;
448  }
449
450  /// \brief Returns the i'th template candidate.
451  FunctionTemplateDecl *getTemplate(unsigned I) const {
452    assert(I < getNumTemplates() && "template index out of range");
453    return getTemplates()[I];
454  }
455
456  /// \brief Returns the explicit template arguments that were given.
457  const TemplateArgumentLoc *getTemplateArgs() const {
458    return reinterpret_cast<const TemplateArgumentLoc*>(
459                                            &getTemplates()[getNumTemplates()]);
460  }
461
462  /// \brief Returns the number of explicit template arguments that were given.
463  unsigned getNumTemplateArgs() const {
464    return d.NumArgs;
465  }
466
467  /// \brief Returns the nth template argument.
468  const TemplateArgumentLoc &getTemplateArg(unsigned I) const {
469    assert(I < getNumTemplateArgs() && "template arg index out of range");
470    return getTemplateArgs()[I];
471  }
472
473  SourceLocation getLAngleLoc() const {
474    return AngleLocs.getBegin();
475  }
476
477  SourceLocation getRAngleLoc() const {
478    return AngleLocs.getEnd();
479  }
480};
481
482/// Declaration of a redeclarable template.
483class RedeclarableTemplateDecl : public TemplateDecl,
484                                 public Redeclarable<RedeclarableTemplateDecl>
485{
486  typedef Redeclarable<RedeclarableTemplateDecl> redeclarable_base;
487  virtual RedeclarableTemplateDecl *getNextRedeclaration() {
488    return RedeclLink.getNext();
489  }
490  virtual RedeclarableTemplateDecl *getPreviousDeclImpl() {
491    return getPreviousDecl();
492  }
493  virtual RedeclarableTemplateDecl *getMostRecentDeclImpl() {
494    return getMostRecentDecl();
495  }
496
497protected:
498  template <typename EntryType> struct SpecEntryTraits {
499    typedef EntryType DeclType;
500
501    static DeclType *getMostRecentDecl(EntryType *D) {
502      return D->getMostRecentDecl();
503    }
504  };
505
506  template <typename EntryType,
507            typename _SETraits = SpecEntryTraits<EntryType>,
508            typename _DeclType = typename _SETraits::DeclType>
509  class SpecIterator : public std::iterator<std::forward_iterator_tag,
510                                            _DeclType*, ptrdiff_t,
511                                            _DeclType*, _DeclType*> {
512    typedef _SETraits SETraits;
513    typedef _DeclType DeclType;
514
515    typedef typename llvm::FoldingSet<EntryType>::iterator SetIteratorType;
516
517    SetIteratorType SetIter;
518
519  public:
520    SpecIterator() : SetIter() {}
521    SpecIterator(SetIteratorType SetIter) : SetIter(SetIter) {}
522
523    DeclType *operator*() const {
524      return SETraits::getMostRecentDecl(&*SetIter);
525    }
526    DeclType *operator->() const { return **this; }
527
528    SpecIterator &operator++() { ++SetIter; return *this; }
529    SpecIterator operator++(int) {
530      SpecIterator tmp(*this);
531      ++(*this);
532      return tmp;
533    }
534
535    bool operator==(SpecIterator Other) const {
536      return SetIter == Other.SetIter;
537    }
538    bool operator!=(SpecIterator Other) const {
539      return SetIter != Other.SetIter;
540    }
541  };
542
543  template <typename EntryType>
544  SpecIterator<EntryType> makeSpecIterator(llvm::FoldingSet<EntryType> &Specs,
545                                           bool isEnd) {
546    return SpecIterator<EntryType>(isEnd ? Specs.end() : Specs.begin());
547  }
548
549  template <class EntryType> typename SpecEntryTraits<EntryType>::DeclType*
550  findSpecializationImpl(llvm::FoldingSet<EntryType> &Specs,
551                         const TemplateArgument *Args, unsigned NumArgs,
552                         void *&InsertPos);
553
554  struct CommonBase {
555    CommonBase() : InstantiatedFromMember(0, false) { }
556
557    /// \brief The template from which this was most
558    /// directly instantiated (or null).
559    ///
560    /// The boolean value indicates whether this template
561    /// was explicitly specialized.
562    llvm::PointerIntPair<RedeclarableTemplateDecl*, 1, bool>
563      InstantiatedFromMember;
564  };
565
566  /// \brief Pointer to the common data shared by all declarations of this
567  /// template.
568  CommonBase *Common;
569
570  /// \brief Retrieves the "common" pointer shared by all (re-)declarations of
571  /// the same template. Calling this routine may implicitly allocate memory
572  /// for the common pointer.
573  CommonBase *getCommonPtr();
574
575  virtual CommonBase *newCommon(ASTContext &C) = 0;
576
577  // Construct a template decl with name, parameters, and templated element.
578  RedeclarableTemplateDecl(Kind DK, DeclContext *DC, SourceLocation L,
579                           DeclarationName Name, TemplateParameterList *Params,
580                           NamedDecl *Decl)
581    : TemplateDecl(DK, DC, L, Name, Params, Decl), Common() { }
582
583public:
584  template <class decl_type> friend class RedeclarableTemplate;
585
586  /// Retrieves the canonical declaration of this template.
587  RedeclarableTemplateDecl *getCanonicalDecl() { return getFirstDeclaration(); }
588  const RedeclarableTemplateDecl *getCanonicalDecl() const {
589    return getFirstDeclaration();
590  }
591
592  /// \brief Determines whether this template was a specialization of a
593  /// member template.
594  ///
595  /// In the following example, the function template \c X<int>::f and the
596  /// member template \c X<int>::Inner are member specializations.
597  ///
598  /// \code
599  /// template<typename T>
600  /// struct X {
601  ///   template<typename U> void f(T, U);
602  ///   template<typename U> struct Inner;
603  /// };
604  ///
605  /// template<> template<typename T>
606  /// void X<int>::f(int, T);
607  /// template<> template<typename T>
608  /// struct X<int>::Inner { /* ... */ };
609  /// \endcode
610  bool isMemberSpecialization() {
611    return getCommonPtr()->InstantiatedFromMember.getInt();
612  }
613
614  /// \brief Note that this member template is a specialization.
615  void setMemberSpecialization() {
616    assert(getCommonPtr()->InstantiatedFromMember.getPointer() &&
617           "Only member templates can be member template specializations");
618    getCommonPtr()->InstantiatedFromMember.setInt(true);
619  }
620
621  /// \brief Retrieve the previous declaration of this template, or
622  /// NULL if no such declaration exists.
623  RedeclarableTemplateDecl *getInstantiatedFromMemberTemplate() {
624    return getCommonPtr()->InstantiatedFromMember.getPointer();
625  }
626
627  void setInstantiatedFromMemberTemplate(RedeclarableTemplateDecl *TD) {
628    assert(!getCommonPtr()->InstantiatedFromMember.getPointer());
629    getCommonPtr()->InstantiatedFromMember.setPointer(TD);
630  }
631
632  typedef redeclarable_base::redecl_iterator redecl_iterator;
633  using redeclarable_base::redecls_begin;
634  using redeclarable_base::redecls_end;
635  using redeclarable_base::getPreviousDecl;
636  using redeclarable_base::getMostRecentDecl;
637
638  // Implement isa/cast/dyncast/etc.
639  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
640  static bool classof(const RedeclarableTemplateDecl *D) { return true; }
641  static bool classof(const FunctionTemplateDecl *D) { return true; }
642  static bool classof(const ClassTemplateDecl *D) { return true; }
643  static bool classof(const TypeAliasTemplateDecl *D) { return true; }
644  static bool classofKind(Kind K) {
645    return K >= firstRedeclarableTemplate && K <= lastRedeclarableTemplate;
646  }
647
648  friend class ASTReader;
649  friend class ASTDeclReader;
650  friend class ASTDeclWriter;
651};
652
653template <> struct RedeclarableTemplateDecl::
654SpecEntryTraits<FunctionTemplateSpecializationInfo> {
655  typedef FunctionDecl DeclType;
656
657  static DeclType *
658  getMostRecentDecl(FunctionTemplateSpecializationInfo *I) {
659    return I->Function->getMostRecentDecl();
660  }
661};
662
663/// Declaration of a template function.
664class FunctionTemplateDecl : public RedeclarableTemplateDecl {
665  static void DeallocateCommon(void *Ptr);
666
667protected:
668  /// \brief Data that is common to all of the declarations of a given
669  /// function template.
670  struct Common : CommonBase {
671    Common() : InjectedArgs(0) { }
672
673    /// \brief The function template specializations for this function
674    /// template, including explicit specializations and instantiations.
675    llvm::FoldingSet<FunctionTemplateSpecializationInfo> Specializations;
676
677    /// \brief The set of "injected" template arguments used within this
678    /// function template.
679    ///
680    /// This pointer refers to the template arguments (there are as
681    /// many template arguments as template parameaters) for the function
682    /// template, and is allocated lazily, since most function templates do not
683    /// require the use of this information.
684    TemplateArgument *InjectedArgs;
685  };
686
687  FunctionTemplateDecl(DeclContext *DC, SourceLocation L, DeclarationName Name,
688                       TemplateParameterList *Params, NamedDecl *Decl)
689    : RedeclarableTemplateDecl(FunctionTemplate, DC, L, Name, Params, Decl) { }
690
691  CommonBase *newCommon(ASTContext &C);
692
693  Common *getCommonPtr() {
694    return static_cast<Common *>(RedeclarableTemplateDecl::getCommonPtr());
695  }
696
697  friend class FunctionDecl;
698
699  /// \brief Retrieve the set of function template specializations of this
700  /// function template.
701  llvm::FoldingSet<FunctionTemplateSpecializationInfo> &getSpecializations() {
702    return getCommonPtr()->Specializations;
703  }
704
705  /// \brief Add a specialization of this function template.
706  ///
707  /// \param InsertPos Insert position in the FoldingSet, must have been
708  ///        retrieved by an earlier call to findSpecialization().
709  void addSpecialization(FunctionTemplateSpecializationInfo* Info,
710                         void *InsertPos);
711
712public:
713  /// Get the underlying function declaration of the template.
714  FunctionDecl *getTemplatedDecl() const {
715    return static_cast<FunctionDecl*>(TemplatedDecl);
716  }
717
718  /// Returns whether this template declaration defines the primary
719  /// pattern.
720  bool isThisDeclarationADefinition() const {
721    return getTemplatedDecl()->isThisDeclarationADefinition();
722  }
723
724  /// \brief Return the specialization with the provided arguments if it exists,
725  /// otherwise return the insertion point.
726  FunctionDecl *findSpecialization(const TemplateArgument *Args,
727                                   unsigned NumArgs, void *&InsertPos);
728
729  FunctionTemplateDecl *getCanonicalDecl() {
730    return cast<FunctionTemplateDecl>(
731             RedeclarableTemplateDecl::getCanonicalDecl());
732  }
733  const FunctionTemplateDecl *getCanonicalDecl() const {
734    return cast<FunctionTemplateDecl>(
735             RedeclarableTemplateDecl::getCanonicalDecl());
736  }
737
738  /// \brief Retrieve the previous declaration of this function template, or
739  /// NULL if no such declaration exists.
740  FunctionTemplateDecl *getPreviousDecl() {
741    return cast_or_null<FunctionTemplateDecl>(
742             RedeclarableTemplateDecl::getPreviousDecl());
743  }
744
745  /// \brief Retrieve the previous declaration of this function template, or
746  /// NULL if no such declaration exists.
747  const FunctionTemplateDecl *getPreviousDecl() const {
748    return cast_or_null<FunctionTemplateDecl>(
749             RedeclarableTemplateDecl::getPreviousDecl());
750  }
751
752  FunctionTemplateDecl *getInstantiatedFromMemberTemplate() {
753    return cast_or_null<FunctionTemplateDecl>(
754             RedeclarableTemplateDecl::getInstantiatedFromMemberTemplate());
755  }
756
757  typedef SpecIterator<FunctionTemplateSpecializationInfo> spec_iterator;
758
759  spec_iterator spec_begin() {
760    return makeSpecIterator(getSpecializations(), false);
761  }
762
763  spec_iterator spec_end() {
764    return makeSpecIterator(getSpecializations(), true);
765  }
766
767  /// \brief Retrieve the "injected" template arguments that correspond to the
768  /// template parameters of this function template.
769  ///
770  /// Although the C++ standard has no notion of the "injected" template
771  /// arguments for a function template, the notion is convenient when
772  /// we need to perform substitutions inside the definition of a function
773  /// template.
774  std::pair<const TemplateArgument *, unsigned> getInjectedTemplateArgs();
775
776  /// \brief Create a function template node.
777  static FunctionTemplateDecl *Create(ASTContext &C, DeclContext *DC,
778                                      SourceLocation L,
779                                      DeclarationName Name,
780                                      TemplateParameterList *Params,
781                                      NamedDecl *Decl);
782
783  /// \brief Create an empty function template node.
784  static FunctionTemplateDecl *CreateDeserialized(ASTContext &C, unsigned ID);
785
786  // Implement isa/cast/dyncast support
787  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
788  static bool classof(const FunctionTemplateDecl *D) { return true; }
789  static bool classofKind(Kind K) { return K == FunctionTemplate; }
790
791  friend class ASTDeclReader;
792  friend class ASTDeclWriter;
793};
794
795//===----------------------------------------------------------------------===//
796// Kinds of Template Parameters
797//===----------------------------------------------------------------------===//
798
799/// The TemplateParmPosition class defines the position of a template parameter
800/// within a template parameter list. Because template parameter can be listed
801/// sequentially for out-of-line template members, each template parameter is
802/// given a Depth - the nesting of template parameter scopes - and a Position -
803/// the occurrence within the parameter list.
804/// This class is inheritedly privately by different kinds of template
805/// parameters and is not part of the Decl hierarchy. Just a facility.
806class TemplateParmPosition {
807protected:
808  // FIXME: This should probably never be called, but it's here as
809  TemplateParmPosition()
810    : Depth(0), Position(0)
811  { /* llvm_unreachable("Cannot create positionless template parameter"); */ }
812
813  TemplateParmPosition(unsigned D, unsigned P)
814    : Depth(D), Position(P)
815  { }
816
817  // FIXME: These probably don't need to be ints. int:5 for depth, int:8 for
818  // position? Maybe?
819  unsigned Depth;
820  unsigned Position;
821
822public:
823  /// Get the nesting depth of the template parameter.
824  unsigned getDepth() const { return Depth; }
825  void setDepth(unsigned D) { Depth = D; }
826
827  /// Get the position of the template parameter within its parameter list.
828  unsigned getPosition() const { return Position; }
829  void setPosition(unsigned P) { Position = P; }
830
831  /// Get the index of the template parameter within its parameter list.
832  unsigned getIndex() const { return Position; }
833};
834
835/// TemplateTypeParmDecl - Declaration of a template type parameter,
836/// e.g., "T" in
837/// @code
838/// template<typename T> class vector;
839/// @endcode
840class TemplateTypeParmDecl : public TypeDecl {
841  /// \brief Whether this template type parameter was declaration with
842  /// the 'typename' keyword. If false, it was declared with the
843  /// 'class' keyword.
844  bool Typename : 1;
845
846  /// \brief Whether this template type parameter inherited its
847  /// default argument.
848  bool InheritedDefault : 1;
849
850  /// \brief The default template argument, if any.
851  TypeSourceInfo *DefaultArgument;
852
853  TemplateTypeParmDecl(DeclContext *DC, SourceLocation KeyLoc,
854                       SourceLocation IdLoc, IdentifierInfo *Id,
855                       bool Typename)
856    : TypeDecl(TemplateTypeParm, DC, IdLoc, Id, KeyLoc), Typename(Typename),
857      InheritedDefault(false), DefaultArgument() { }
858
859  /// Sema creates these on the stack during auto type deduction.
860  friend class Sema;
861
862public:
863  static TemplateTypeParmDecl *Create(const ASTContext &C, DeclContext *DC,
864                                      SourceLocation KeyLoc,
865                                      SourceLocation NameLoc,
866                                      unsigned D, unsigned P,
867                                      IdentifierInfo *Id, bool Typename,
868                                      bool ParameterPack);
869  static TemplateTypeParmDecl *CreateDeserialized(const ASTContext &C,
870                                                  unsigned ID);
871
872  /// \brief Whether this template type parameter was declared with
873  /// the 'typename' keyword. If not, it was declared with the 'class'
874  /// keyword.
875  bool wasDeclaredWithTypename() const { return Typename; }
876
877  /// \brief Determine whether this template parameter has a default
878  /// argument.
879  bool hasDefaultArgument() const { return DefaultArgument != 0; }
880
881  /// \brief Retrieve the default argument, if any.
882  QualType getDefaultArgument() const { return DefaultArgument->getType(); }
883
884  /// \brief Retrieves the default argument's source information, if any.
885  TypeSourceInfo *getDefaultArgumentInfo() const { return DefaultArgument; }
886
887  /// \brief Retrieves the location of the default argument declaration.
888  SourceLocation getDefaultArgumentLoc() const;
889
890  /// \brief Determines whether the default argument was inherited
891  /// from a previous declaration of this template.
892  bool defaultArgumentWasInherited() const { return InheritedDefault; }
893
894  /// \brief Set the default argument for this template parameter, and
895  /// whether that default argument was inherited from another
896  /// declaration.
897  void setDefaultArgument(TypeSourceInfo *DefArg, bool Inherited) {
898    DefaultArgument = DefArg;
899    InheritedDefault = Inherited;
900  }
901
902  /// \brief Removes the default argument of this template parameter.
903  void removeDefaultArgument() {
904    DefaultArgument = 0;
905    InheritedDefault = false;
906  }
907
908  /// \brief Set whether this template type parameter was declared with
909  /// the 'typename' or 'class' keyword.
910  void setDeclaredWithTypename(bool withTypename) { Typename = withTypename; }
911
912  /// \brief Retrieve the depth of the template parameter.
913  unsigned getDepth() const;
914
915  /// \brief Retrieve the index of the template parameter.
916  unsigned getIndex() const;
917
918  /// \brief Returns whether this is a parameter pack.
919  bool isParameterPack() const;
920
921  SourceRange getSourceRange() const LLVM_READONLY;
922
923  // Implement isa/cast/dyncast/etc.
924  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
925  static bool classof(const TemplateTypeParmDecl *D) { return true; }
926  static bool classofKind(Kind K) { return K == TemplateTypeParm; }
927};
928
929/// NonTypeTemplateParmDecl - Declares a non-type template parameter,
930/// e.g., "Size" in
931/// @code
932/// template<int Size> class array { };
933/// @endcode
934class NonTypeTemplateParmDecl
935  : public DeclaratorDecl, protected TemplateParmPosition {
936  /// \brief The default template argument, if any, and whether or not
937  /// it was inherited.
938  llvm::PointerIntPair<Expr*, 1, bool> DefaultArgumentAndInherited;
939
940  // FIXME: Collapse this into TemplateParamPosition; or, just move depth/index
941  // down here to save memory.
942
943  /// \brief Whether this non-type template parameter is a parameter pack.
944  bool ParameterPack;
945
946  /// \brief Whether this non-type template parameter is an "expanded"
947  /// parameter pack, meaning that its type is a pack expansion and we
948  /// already know the set of types that expansion expands to.
949  bool ExpandedParameterPack;
950
951  /// \brief The number of types in an expanded parameter pack.
952  unsigned NumExpandedTypes;
953
954  NonTypeTemplateParmDecl(DeclContext *DC, SourceLocation StartLoc,
955                          SourceLocation IdLoc, unsigned D, unsigned P,
956                          IdentifierInfo *Id, QualType T,
957                          bool ParameterPack, TypeSourceInfo *TInfo)
958    : DeclaratorDecl(NonTypeTemplateParm, DC, IdLoc, Id, T, TInfo, StartLoc),
959      TemplateParmPosition(D, P), DefaultArgumentAndInherited(0, false),
960      ParameterPack(ParameterPack), ExpandedParameterPack(false),
961      NumExpandedTypes(0)
962  { }
963
964  NonTypeTemplateParmDecl(DeclContext *DC, SourceLocation StartLoc,
965                          SourceLocation IdLoc, unsigned D, unsigned P,
966                          IdentifierInfo *Id, QualType T,
967                          TypeSourceInfo *TInfo,
968                          const QualType *ExpandedTypes,
969                          unsigned NumExpandedTypes,
970                          TypeSourceInfo **ExpandedTInfos);
971
972  friend class ASTDeclReader;
973
974public:
975  static NonTypeTemplateParmDecl *
976  Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
977         SourceLocation IdLoc, unsigned D, unsigned P, IdentifierInfo *Id,
978         QualType T, bool ParameterPack, TypeSourceInfo *TInfo);
979
980  static NonTypeTemplateParmDecl *
981  Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
982         SourceLocation IdLoc, unsigned D, unsigned P, IdentifierInfo *Id,
983         QualType T, TypeSourceInfo *TInfo,
984         const QualType *ExpandedTypes, unsigned NumExpandedTypes,
985         TypeSourceInfo **ExpandedTInfos);
986
987  static NonTypeTemplateParmDecl *CreateDeserialized(ASTContext &C,
988                                                     unsigned ID);
989  static NonTypeTemplateParmDecl *CreateDeserialized(ASTContext &C,
990                                                     unsigned ID,
991                                                     unsigned NumExpandedTypes);
992
993  using TemplateParmPosition::getDepth;
994  using TemplateParmPosition::setDepth;
995  using TemplateParmPosition::getPosition;
996  using TemplateParmPosition::setPosition;
997  using TemplateParmPosition::getIndex;
998
999  SourceRange getSourceRange() const LLVM_READONLY;
1000
1001  /// \brief Determine whether this template parameter has a default
1002  /// argument.
1003  bool hasDefaultArgument() const {
1004    return DefaultArgumentAndInherited.getPointer() != 0;
1005  }
1006
1007  /// \brief Retrieve the default argument, if any.
1008  Expr *getDefaultArgument() const {
1009    return DefaultArgumentAndInherited.getPointer();
1010  }
1011
1012  /// \brief Retrieve the location of the default argument, if any.
1013  SourceLocation getDefaultArgumentLoc() const;
1014
1015  /// \brief Determines whether the default argument was inherited
1016  /// from a previous declaration of this template.
1017  bool defaultArgumentWasInherited() const {
1018    return DefaultArgumentAndInherited.getInt();
1019  }
1020
1021  /// \brief Set the default argument for this template parameter, and
1022  /// whether that default argument was inherited from another
1023  /// declaration.
1024  void setDefaultArgument(Expr *DefArg, bool Inherited) {
1025    DefaultArgumentAndInherited.setPointer(DefArg);
1026    DefaultArgumentAndInherited.setInt(Inherited);
1027  }
1028
1029  /// \brief Removes the default argument of this template parameter.
1030  void removeDefaultArgument() {
1031    DefaultArgumentAndInherited.setPointer(0);
1032    DefaultArgumentAndInherited.setInt(false);
1033  }
1034
1035  /// \brief Whether this parameter is a non-type template parameter pack.
1036  ///
1037  /// If the parameter is a parameter pack, the type may be a
1038  /// \c PackExpansionType. In the following example, the \c Dims parameter
1039  /// is a parameter pack (whose type is 'unsigned').
1040  ///
1041  /// \code
1042  /// template<typename T, unsigned ...Dims> struct multi_array;
1043  /// \endcode
1044  bool isParameterPack() const { return ParameterPack; }
1045
1046  /// \brief Whether this parameter is a non-type template parameter pack
1047  /// that has different types at different positions.
1048  ///
1049  /// A parameter pack is an expanded parameter pack when the original
1050  /// parameter pack's type was itself a pack expansion, and that expansion
1051  /// has already been expanded. For example, given:
1052  ///
1053  /// \code
1054  /// template<typename ...Types>
1055  /// struct X {
1056  ///   template<Types ...Values>
1057  ///   struct Y { /* ... */ };
1058  /// };
1059  /// \endcode
1060  ///
1061  /// The parameter pack \c Values has a \c PackExpansionType as its type,
1062  /// which expands \c Types. When \c Types is supplied with template arguments
1063  /// by instantiating \c X, the instantiation of \c Values becomes an
1064  /// expanded parameter pack. For example, instantiating
1065  /// \c X<int, unsigned int> results in \c Values being an expanded parameter
1066  /// pack with expansion types \c int and \c unsigned int.
1067  ///
1068  /// The \c getExpansionType() and \c getExpansionTypeSourceInfo() functions
1069  /// return the expansion types.
1070  bool isExpandedParameterPack() const { return ExpandedParameterPack; }
1071
1072  /// \brief Retrieves the number of expansion types in an expanded parameter
1073  /// pack.
1074  unsigned getNumExpansionTypes() const {
1075    assert(ExpandedParameterPack && "Not an expansion parameter pack");
1076    return NumExpandedTypes;
1077  }
1078
1079  /// \brief Retrieve a particular expansion type within an expanded parameter
1080  /// pack.
1081  QualType getExpansionType(unsigned I) const {
1082    assert(I < NumExpandedTypes && "Out-of-range expansion type index");
1083    void * const *TypesAndInfos = reinterpret_cast<void * const*>(this + 1);
1084    return QualType::getFromOpaquePtr(TypesAndInfos[2*I]);
1085  }
1086
1087  /// \brief Retrieve a particular expansion type source info within an
1088  /// expanded parameter pack.
1089  TypeSourceInfo *getExpansionTypeSourceInfo(unsigned I) const {
1090    assert(I < NumExpandedTypes && "Out-of-range expansion type index");
1091    void * const *TypesAndInfos = reinterpret_cast<void * const*>(this + 1);
1092    return static_cast<TypeSourceInfo *>(TypesAndInfos[2*I+1]);
1093  }
1094
1095  // Implement isa/cast/dyncast/etc.
1096  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1097  static bool classof(const NonTypeTemplateParmDecl *D) { return true; }
1098  static bool classofKind(Kind K) { return K == NonTypeTemplateParm; }
1099};
1100
1101/// TemplateTemplateParmDecl - Declares a template template parameter,
1102/// e.g., "T" in
1103/// @code
1104/// template <template <typename> class T> class container { };
1105/// @endcode
1106/// A template template parameter is a TemplateDecl because it defines the
1107/// name of a template and the template parameters allowable for substitution.
1108class TemplateTemplateParmDecl : public TemplateDecl,
1109                                 protected TemplateParmPosition
1110{
1111  virtual void anchor();
1112
1113  /// DefaultArgument - The default template argument, if any.
1114  TemplateArgumentLoc DefaultArgument;
1115  /// Whether or not the default argument was inherited.
1116  bool DefaultArgumentWasInherited;
1117
1118  /// \brief Whether this parameter is a parameter pack.
1119  bool ParameterPack;
1120
1121  TemplateTemplateParmDecl(DeclContext *DC, SourceLocation L,
1122                           unsigned D, unsigned P, bool ParameterPack,
1123                           IdentifierInfo *Id, TemplateParameterList *Params)
1124    : TemplateDecl(TemplateTemplateParm, DC, L, Id, Params),
1125      TemplateParmPosition(D, P), DefaultArgument(),
1126      DefaultArgumentWasInherited(false), ParameterPack(ParameterPack)
1127    { }
1128
1129public:
1130  static TemplateTemplateParmDecl *Create(const ASTContext &C, DeclContext *DC,
1131                                          SourceLocation L, unsigned D,
1132                                          unsigned P, bool ParameterPack,
1133                                          IdentifierInfo *Id,
1134                                          TemplateParameterList *Params);
1135
1136  static TemplateTemplateParmDecl *CreateDeserialized(ASTContext &C,
1137                                                      unsigned ID);
1138
1139  using TemplateParmPosition::getDepth;
1140  using TemplateParmPosition::getPosition;
1141  using TemplateParmPosition::getIndex;
1142
1143  /// \brief Whether this template template parameter is a template
1144  /// parameter pack.
1145  ///
1146  /// \code
1147  /// template<template <class T> ...MetaFunctions> struct Apply;
1148  /// \endcode
1149  bool isParameterPack() const { return ParameterPack; }
1150
1151  /// \brief Determine whether this template parameter has a default
1152  /// argument.
1153  bool hasDefaultArgument() const {
1154    return !DefaultArgument.getArgument().isNull();
1155  }
1156
1157  /// \brief Retrieve the default argument, if any.
1158  const TemplateArgumentLoc &getDefaultArgument() const {
1159    return DefaultArgument;
1160  }
1161
1162  /// \brief Retrieve the location of the default argument, if any.
1163  SourceLocation getDefaultArgumentLoc() const;
1164
1165  /// \brief Determines whether the default argument was inherited
1166  /// from a previous declaration of this template.
1167  bool defaultArgumentWasInherited() const {
1168    return DefaultArgumentWasInherited;
1169  }
1170
1171  /// \brief Set the default argument for this template parameter, and
1172  /// whether that default argument was inherited from another
1173  /// declaration.
1174  void setDefaultArgument(const TemplateArgumentLoc &DefArg, bool Inherited) {
1175    DefaultArgument = DefArg;
1176    DefaultArgumentWasInherited = Inherited;
1177  }
1178
1179  /// \brief Removes the default argument of this template parameter.
1180  void removeDefaultArgument() {
1181    DefaultArgument = TemplateArgumentLoc();
1182    DefaultArgumentWasInherited = false;
1183  }
1184
1185  SourceRange getSourceRange() const LLVM_READONLY {
1186    SourceLocation End = getLocation();
1187    if (hasDefaultArgument() && !defaultArgumentWasInherited())
1188      End = getDefaultArgument().getSourceRange().getEnd();
1189    return SourceRange(getTemplateParameters()->getTemplateLoc(), End);
1190  }
1191
1192  // Implement isa/cast/dyncast/etc.
1193  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1194  static bool classof(const TemplateTemplateParmDecl *D) { return true; }
1195  static bool classofKind(Kind K) { return K == TemplateTemplateParm; }
1196
1197  friend class ASTDeclReader;
1198  friend class ASTDeclWriter;
1199};
1200
1201/// \brief Represents a class template specialization, which refers to
1202/// a class template with a given set of template arguments.
1203///
1204/// Class template specializations represent both explicit
1205/// specialization of class templates, as in the example below, and
1206/// implicit instantiations of class templates.
1207///
1208/// \code
1209/// template<typename T> class array;
1210///
1211/// template<>
1212/// class array<bool> { }; // class template specialization array<bool>
1213/// \endcode
1214class ClassTemplateSpecializationDecl
1215  : public CXXRecordDecl, public llvm::FoldingSetNode {
1216
1217  /// \brief Structure that stores information about a class template
1218  /// specialization that was instantiated from a class template partial
1219  /// specialization.
1220  struct SpecializedPartialSpecialization {
1221    /// \brief The class template partial specialization from which this
1222    /// class template specialization was instantiated.
1223    ClassTemplatePartialSpecializationDecl *PartialSpecialization;
1224
1225    /// \brief The template argument list deduced for the class template
1226    /// partial specialization itself.
1227    TemplateArgumentList *TemplateArgs;
1228  };
1229
1230  /// \brief The template that this specialization specializes
1231  llvm::PointerUnion<ClassTemplateDecl *, SpecializedPartialSpecialization *>
1232    SpecializedTemplate;
1233
1234  /// \brief Further info for explicit template specialization/instantiation.
1235  struct ExplicitSpecializationInfo {
1236    /// \brief The type-as-written.
1237    TypeSourceInfo *TypeAsWritten;
1238    /// \brief The location of the extern keyword.
1239    SourceLocation ExternLoc;
1240    /// \brief The location of the template keyword.
1241    SourceLocation TemplateKeywordLoc;
1242
1243    ExplicitSpecializationInfo()
1244      : TypeAsWritten(0), ExternLoc(), TemplateKeywordLoc() {}
1245  };
1246
1247  /// \brief Further info for explicit template specialization/instantiation.
1248  /// Does not apply to implicit specializations.
1249  ExplicitSpecializationInfo *ExplicitInfo;
1250
1251  /// \brief The template arguments used to describe this specialization.
1252  TemplateArgumentList *TemplateArgs;
1253
1254  /// \brief The point where this template was instantiated (if any)
1255  SourceLocation PointOfInstantiation;
1256
1257  /// \brief The kind of specialization this declaration refers to.
1258  /// Really a value of type TemplateSpecializationKind.
1259  unsigned SpecializationKind : 3;
1260
1261protected:
1262  ClassTemplateSpecializationDecl(ASTContext &Context, Kind DK, TagKind TK,
1263                                  DeclContext *DC, SourceLocation StartLoc,
1264                                  SourceLocation IdLoc,
1265                                  ClassTemplateDecl *SpecializedTemplate,
1266                                  const TemplateArgument *Args,
1267                                  unsigned NumArgs,
1268                                  ClassTemplateSpecializationDecl *PrevDecl);
1269
1270  explicit ClassTemplateSpecializationDecl(Kind DK);
1271
1272public:
1273  static ClassTemplateSpecializationDecl *
1274  Create(ASTContext &Context, TagKind TK, DeclContext *DC,
1275         SourceLocation StartLoc, SourceLocation IdLoc,
1276         ClassTemplateDecl *SpecializedTemplate,
1277         const TemplateArgument *Args,
1278         unsigned NumArgs,
1279         ClassTemplateSpecializationDecl *PrevDecl);
1280  static ClassTemplateSpecializationDecl *
1281  CreateDeserialized(ASTContext &C, unsigned ID);
1282
1283  virtual void getNameForDiagnostic(std::string &S,
1284                                    const PrintingPolicy &Policy,
1285                                    bool Qualified) const;
1286
1287  ClassTemplateSpecializationDecl *getMostRecentDecl() {
1288    CXXRecordDecl *Recent
1289        = cast<CXXRecordDecl>(CXXRecordDecl::getMostRecentDecl());
1290    if (!isa<ClassTemplateSpecializationDecl>(Recent)) {
1291      // FIXME: Does injected class name need to be in the redeclarations chain?
1292      assert(Recent->isInjectedClassName() && Recent->getPreviousDecl());
1293      Recent = Recent->getPreviousDecl();
1294    }
1295    return cast<ClassTemplateSpecializationDecl>(Recent);
1296  }
1297
1298  /// \brief Retrieve the template that this specialization specializes.
1299  ClassTemplateDecl *getSpecializedTemplate() const;
1300
1301  /// \brief Retrieve the template arguments of the class template
1302  /// specialization.
1303  const TemplateArgumentList &getTemplateArgs() const {
1304    return *TemplateArgs;
1305  }
1306
1307  /// \brief Determine the kind of specialization that this
1308  /// declaration represents.
1309  TemplateSpecializationKind getSpecializationKind() const {
1310    return static_cast<TemplateSpecializationKind>(SpecializationKind);
1311  }
1312
1313  bool isExplicitSpecialization() const {
1314    return getSpecializationKind() == TSK_ExplicitSpecialization;
1315  }
1316
1317  void setSpecializationKind(TemplateSpecializationKind TSK) {
1318    SpecializationKind = TSK;
1319  }
1320
1321  /// \brief Get the point of instantiation (if any), or null if none.
1322  SourceLocation getPointOfInstantiation() const {
1323    return PointOfInstantiation;
1324  }
1325
1326  void setPointOfInstantiation(SourceLocation Loc) {
1327    assert(Loc.isValid() && "point of instantiation must be valid!");
1328    PointOfInstantiation = Loc;
1329  }
1330
1331  /// \brief If this class template specialization is an instantiation of
1332  /// a template (rather than an explicit specialization), return the
1333  /// class template or class template partial specialization from which it
1334  /// was instantiated.
1335  llvm::PointerUnion<ClassTemplateDecl *,
1336                     ClassTemplatePartialSpecializationDecl *>
1337  getInstantiatedFrom() const {
1338    if (getSpecializationKind() != TSK_ImplicitInstantiation &&
1339        getSpecializationKind() != TSK_ExplicitInstantiationDefinition &&
1340        getSpecializationKind() != TSK_ExplicitInstantiationDeclaration)
1341      return llvm::PointerUnion<ClassTemplateDecl *,
1342                                ClassTemplatePartialSpecializationDecl *>();
1343
1344    if (SpecializedPartialSpecialization *PartialSpec
1345          = SpecializedTemplate.dyn_cast<SpecializedPartialSpecialization*>())
1346      return PartialSpec->PartialSpecialization;
1347
1348    return const_cast<ClassTemplateDecl*>(
1349                             SpecializedTemplate.get<ClassTemplateDecl*>());
1350  }
1351
1352  /// \brief Retrieve the class template or class template partial
1353  /// specialization which was specialized by this.
1354  llvm::PointerUnion<ClassTemplateDecl *,
1355                     ClassTemplatePartialSpecializationDecl *>
1356  getSpecializedTemplateOrPartial() const {
1357    if (SpecializedPartialSpecialization *PartialSpec
1358          = SpecializedTemplate.dyn_cast<SpecializedPartialSpecialization*>())
1359      return PartialSpec->PartialSpecialization;
1360
1361    return const_cast<ClassTemplateDecl*>(
1362                             SpecializedTemplate.get<ClassTemplateDecl*>());
1363  }
1364
1365  /// \brief Retrieve the set of template arguments that should be used
1366  /// to instantiate members of the class template or class template partial
1367  /// specialization from which this class template specialization was
1368  /// instantiated.
1369  ///
1370  /// \returns For a class template specialization instantiated from the primary
1371  /// template, this function will return the same template arguments as
1372  /// getTemplateArgs(). For a class template specialization instantiated from
1373  /// a class template partial specialization, this function will return the
1374  /// deduced template arguments for the class template partial specialization
1375  /// itself.
1376  const TemplateArgumentList &getTemplateInstantiationArgs() const {
1377    if (SpecializedPartialSpecialization *PartialSpec
1378        = SpecializedTemplate.dyn_cast<SpecializedPartialSpecialization*>())
1379      return *PartialSpec->TemplateArgs;
1380
1381    return getTemplateArgs();
1382  }
1383
1384  /// \brief Note that this class template specialization is actually an
1385  /// instantiation of the given class template partial specialization whose
1386  /// template arguments have been deduced.
1387  void setInstantiationOf(ClassTemplatePartialSpecializationDecl *PartialSpec,
1388                          TemplateArgumentList *TemplateArgs) {
1389    assert(!SpecializedTemplate.is<SpecializedPartialSpecialization*>() &&
1390           "Already set to a class template partial specialization!");
1391    SpecializedPartialSpecialization *PS
1392      = new (getASTContext()) SpecializedPartialSpecialization();
1393    PS->PartialSpecialization = PartialSpec;
1394    PS->TemplateArgs = TemplateArgs;
1395    SpecializedTemplate = PS;
1396  }
1397
1398  /// \brief Note that this class template specialization is an instantiation
1399  /// of the given class template.
1400  void setInstantiationOf(ClassTemplateDecl *TemplDecl) {
1401    assert(!SpecializedTemplate.is<SpecializedPartialSpecialization*>() &&
1402           "Previously set to a class template partial specialization!");
1403    SpecializedTemplate = TemplDecl;
1404  }
1405
1406  /// \brief Sets the type of this specialization as it was written by
1407  /// the user. This will be a class template specialization type.
1408  void setTypeAsWritten(TypeSourceInfo *T) {
1409    if (!ExplicitInfo)
1410      ExplicitInfo = new (getASTContext()) ExplicitSpecializationInfo;
1411    ExplicitInfo->TypeAsWritten = T;
1412  }
1413  /// \brief Gets the type of this specialization as it was written by
1414  /// the user, if it was so written.
1415  TypeSourceInfo *getTypeAsWritten() const {
1416    return ExplicitInfo ? ExplicitInfo->TypeAsWritten : 0;
1417  }
1418
1419  /// \brief Gets the location of the extern keyword, if present.
1420  SourceLocation getExternLoc() const {
1421    return ExplicitInfo ? ExplicitInfo->ExternLoc : SourceLocation();
1422  }
1423  /// \brief Sets the location of the extern keyword.
1424  void setExternLoc(SourceLocation Loc) {
1425    if (!ExplicitInfo)
1426      ExplicitInfo = new (getASTContext()) ExplicitSpecializationInfo;
1427    ExplicitInfo->ExternLoc = Loc;
1428  }
1429
1430  /// \brief Sets the location of the template keyword.
1431  void setTemplateKeywordLoc(SourceLocation Loc) {
1432    if (!ExplicitInfo)
1433      ExplicitInfo = new (getASTContext()) ExplicitSpecializationInfo;
1434    ExplicitInfo->TemplateKeywordLoc = Loc;
1435  }
1436  /// \brief Gets the location of the template keyword, if present.
1437  SourceLocation getTemplateKeywordLoc() const {
1438    return ExplicitInfo ? ExplicitInfo->TemplateKeywordLoc : SourceLocation();
1439  }
1440
1441  SourceRange getSourceRange() const LLVM_READONLY;
1442
1443  void Profile(llvm::FoldingSetNodeID &ID) const {
1444    Profile(ID, TemplateArgs->data(), TemplateArgs->size(), getASTContext());
1445  }
1446
1447  static void
1448  Profile(llvm::FoldingSetNodeID &ID, const TemplateArgument *TemplateArgs,
1449          unsigned NumTemplateArgs, ASTContext &Context) {
1450    ID.AddInteger(NumTemplateArgs);
1451    for (unsigned Arg = 0; Arg != NumTemplateArgs; ++Arg)
1452      TemplateArgs[Arg].Profile(ID, Context);
1453  }
1454
1455  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1456  static bool classofKind(Kind K) {
1457    return K >= firstClassTemplateSpecialization &&
1458           K <= lastClassTemplateSpecialization;
1459  }
1460
1461  static bool classof(const ClassTemplateSpecializationDecl *) {
1462    return true;
1463  }
1464
1465  static bool classof(const ClassTemplatePartialSpecializationDecl *) {
1466    return true;
1467  }
1468
1469  friend class ASTDeclReader;
1470  friend class ASTDeclWriter;
1471};
1472
1473class ClassTemplatePartialSpecializationDecl
1474  : public ClassTemplateSpecializationDecl {
1475  virtual void anchor();
1476
1477  /// \brief The list of template parameters
1478  TemplateParameterList* TemplateParams;
1479
1480  /// \brief The source info for the template arguments as written.
1481  /// FIXME: redundant with TypeAsWritten?
1482  TemplateArgumentLoc *ArgsAsWritten;
1483  unsigned NumArgsAsWritten;
1484
1485  /// \brief Sequence number indicating when this class template partial
1486  /// specialization was added to the set of partial specializations for
1487  /// its owning class template.
1488  unsigned SequenceNumber;
1489
1490  /// \brief The class template partial specialization from which this
1491  /// class template partial specialization was instantiated.
1492  ///
1493  /// The boolean value will be true to indicate that this class template
1494  /// partial specialization was specialized at this level.
1495  llvm::PointerIntPair<ClassTemplatePartialSpecializationDecl *, 1, bool>
1496      InstantiatedFromMember;
1497
1498  ClassTemplatePartialSpecializationDecl(ASTContext &Context, TagKind TK,
1499                                         DeclContext *DC,
1500                                         SourceLocation StartLoc,
1501                                         SourceLocation IdLoc,
1502                                         TemplateParameterList *Params,
1503                                         ClassTemplateDecl *SpecializedTemplate,
1504                                         const TemplateArgument *Args,
1505                                         unsigned NumArgs,
1506                                         TemplateArgumentLoc *ArgInfos,
1507                                         unsigned NumArgInfos,
1508                               ClassTemplatePartialSpecializationDecl *PrevDecl,
1509                                         unsigned SequenceNumber);
1510
1511  ClassTemplatePartialSpecializationDecl()
1512    : ClassTemplateSpecializationDecl(ClassTemplatePartialSpecialization),
1513      TemplateParams(0), ArgsAsWritten(0),
1514      NumArgsAsWritten(0), SequenceNumber(0),
1515      InstantiatedFromMember(0, false) { }
1516
1517public:
1518  static ClassTemplatePartialSpecializationDecl *
1519  Create(ASTContext &Context, TagKind TK, DeclContext *DC,
1520         SourceLocation StartLoc, SourceLocation IdLoc,
1521         TemplateParameterList *Params,
1522         ClassTemplateDecl *SpecializedTemplate,
1523         const TemplateArgument *Args,
1524         unsigned NumArgs,
1525         const TemplateArgumentListInfo &ArgInfos,
1526         QualType CanonInjectedType,
1527         ClassTemplatePartialSpecializationDecl *PrevDecl,
1528         unsigned SequenceNumber);
1529
1530  static ClassTemplatePartialSpecializationDecl *
1531  CreateDeserialized(ASTContext &C, unsigned ID);
1532
1533  ClassTemplatePartialSpecializationDecl *getMostRecentDecl() {
1534    return cast<ClassTemplatePartialSpecializationDecl>(
1535                   ClassTemplateSpecializationDecl::getMostRecentDecl());
1536  }
1537
1538  /// Get the list of template parameters
1539  TemplateParameterList *getTemplateParameters() const {
1540    return TemplateParams;
1541  }
1542
1543  /// Get the template arguments as written.
1544  TemplateArgumentLoc *getTemplateArgsAsWritten() const {
1545    return ArgsAsWritten;
1546  }
1547
1548  /// Get the number of template arguments as written.
1549  unsigned getNumTemplateArgsAsWritten() const {
1550    return NumArgsAsWritten;
1551  }
1552
1553  /// \brief Get the sequence number for this class template partial
1554  /// specialization.
1555  unsigned getSequenceNumber() const { return SequenceNumber; }
1556
1557  /// \brief Retrieve the member class template partial specialization from
1558  /// which this particular class template partial specialization was
1559  /// instantiated.
1560  ///
1561  /// \code
1562  /// template<typename T>
1563  /// struct Outer {
1564  ///   template<typename U> struct Inner;
1565  ///   template<typename U> struct Inner<U*> { }; // #1
1566  /// };
1567  ///
1568  /// Outer<float>::Inner<int*> ii;
1569  /// \endcode
1570  ///
1571  /// In this example, the instantiation of \c Outer<float>::Inner<int*> will
1572  /// end up instantiating the partial specialization
1573  /// \c Outer<float>::Inner<U*>, which itself was instantiated from the class
1574  /// template partial specialization \c Outer<T>::Inner<U*>. Given
1575  /// \c Outer<float>::Inner<U*>, this function would return
1576  /// \c Outer<T>::Inner<U*>.
1577  ClassTemplatePartialSpecializationDecl *getInstantiatedFromMember() {
1578    ClassTemplatePartialSpecializationDecl *First
1579      = cast<ClassTemplatePartialSpecializationDecl>(getFirstDeclaration());
1580    return First->InstantiatedFromMember.getPointer();
1581  }
1582
1583  void setInstantiatedFromMember(
1584                          ClassTemplatePartialSpecializationDecl *PartialSpec) {
1585    ClassTemplatePartialSpecializationDecl *First
1586      = cast<ClassTemplatePartialSpecializationDecl>(getFirstDeclaration());
1587    First->InstantiatedFromMember.setPointer(PartialSpec);
1588  }
1589
1590  /// \brief Determines whether this class template partial specialization
1591  /// template was a specialization of a member partial specialization.
1592  ///
1593  /// In the following example, the member template partial specialization
1594  /// \c X<int>::Inner<T*> is a member specialization.
1595  ///
1596  /// \code
1597  /// template<typename T>
1598  /// struct X {
1599  ///   template<typename U> struct Inner;
1600  ///   template<typename U> struct Inner<U*>;
1601  /// };
1602  ///
1603  /// template<> template<typename T>
1604  /// struct X<int>::Inner<T*> { /* ... */ };
1605  /// \endcode
1606  bool isMemberSpecialization() {
1607    ClassTemplatePartialSpecializationDecl *First
1608      = cast<ClassTemplatePartialSpecializationDecl>(getFirstDeclaration());
1609    return First->InstantiatedFromMember.getInt();
1610  }
1611
1612  /// \brief Note that this member template is a specialization.
1613  void setMemberSpecialization() {
1614    ClassTemplatePartialSpecializationDecl *First
1615      = cast<ClassTemplatePartialSpecializationDecl>(getFirstDeclaration());
1616    assert(First->InstantiatedFromMember.getPointer() &&
1617           "Only member templates can be member template specializations");
1618    return First->InstantiatedFromMember.setInt(true);
1619  }
1620
1621  /// Retrieves the injected specialization type for this partial
1622  /// specialization.  This is not the same as the type-decl-type for
1623  /// this partial specialization, which is an InjectedClassNameType.
1624  QualType getInjectedSpecializationType() const {
1625    assert(getTypeForDecl() && "partial specialization has no type set!");
1626    return cast<InjectedClassNameType>(getTypeForDecl())
1627             ->getInjectedSpecializationType();
1628  }
1629
1630  // FIXME: Add Profile support!
1631
1632  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1633  static bool classofKind(Kind K) {
1634    return K == ClassTemplatePartialSpecialization;
1635  }
1636
1637  static bool classof(const ClassTemplatePartialSpecializationDecl *) {
1638    return true;
1639  }
1640
1641  friend class ASTDeclReader;
1642  friend class ASTDeclWriter;
1643};
1644
1645/// Declaration of a class template.
1646class ClassTemplateDecl : public RedeclarableTemplateDecl {
1647  static void DeallocateCommon(void *Ptr);
1648
1649protected:
1650  /// \brief Data that is common to all of the declarations of a given
1651  /// class template.
1652  struct Common : CommonBase {
1653    Common() : LazySpecializations() { }
1654
1655    /// \brief The class template specializations for this class
1656    /// template, including explicit specializations and instantiations.
1657    llvm::FoldingSet<ClassTemplateSpecializationDecl> Specializations;
1658
1659    /// \brief The class template partial specializations for this class
1660    /// template.
1661    llvm::FoldingSet<ClassTemplatePartialSpecializationDecl>
1662      PartialSpecializations;
1663
1664    /// \brief The injected-class-name type for this class template.
1665    QualType InjectedClassNameType;
1666
1667    /// \brief If non-null, points to an array of specializations (including
1668    /// partial specializations) known ownly by their external declaration IDs.
1669    ///
1670    /// The first value in the array is the number of of specializations/
1671    /// partial specializations that follow.
1672    uint32_t *LazySpecializations;
1673  };
1674
1675  /// \brief Load any lazily-loaded specializations from the external source.
1676  void LoadLazySpecializations();
1677
1678  /// \brief Retrieve the set of specializations of this class template.
1679  llvm::FoldingSet<ClassTemplateSpecializationDecl> &getSpecializations();
1680
1681  /// \brief Retrieve the set of partial specializations of this class
1682  /// template.
1683  llvm::FoldingSet<ClassTemplatePartialSpecializationDecl> &
1684  getPartialSpecializations();
1685
1686  ClassTemplateDecl(DeclContext *DC, SourceLocation L, DeclarationName Name,
1687                    TemplateParameterList *Params, NamedDecl *Decl)
1688    : RedeclarableTemplateDecl(ClassTemplate, DC, L, Name, Params, Decl) { }
1689
1690  ClassTemplateDecl(EmptyShell Empty)
1691    : RedeclarableTemplateDecl(ClassTemplate, 0, SourceLocation(),
1692                               DeclarationName(), 0, 0) { }
1693
1694  CommonBase *newCommon(ASTContext &C);
1695
1696  Common *getCommonPtr() {
1697    return static_cast<Common *>(RedeclarableTemplateDecl::getCommonPtr());
1698  }
1699
1700public:
1701  /// Get the underlying class declarations of the template.
1702  CXXRecordDecl *getTemplatedDecl() const {
1703    return static_cast<CXXRecordDecl *>(TemplatedDecl);
1704  }
1705
1706  /// Returns whether this template declaration defines the primary
1707  /// class pattern.
1708  bool isThisDeclarationADefinition() const {
1709    return getTemplatedDecl()->isThisDeclarationADefinition();
1710  }
1711
1712  /// Create a class template node.
1713  static ClassTemplateDecl *Create(ASTContext &C, DeclContext *DC,
1714                                   SourceLocation L,
1715                                   DeclarationName Name,
1716                                   TemplateParameterList *Params,
1717                                   NamedDecl *Decl,
1718                                   ClassTemplateDecl *PrevDecl);
1719
1720  /// Create an empty class template node.
1721  static ClassTemplateDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1722
1723  /// \brief Return the specialization with the provided arguments if it exists,
1724  /// otherwise return the insertion point.
1725  ClassTemplateSpecializationDecl *
1726  findSpecialization(const TemplateArgument *Args, unsigned NumArgs,
1727                     void *&InsertPos);
1728
1729  /// \brief Insert the specified specialization knowing that it is not already
1730  /// in. InsertPos must be obtained from findSpecialization.
1731  void AddSpecialization(ClassTemplateSpecializationDecl *D, void *InsertPos);
1732
1733  ClassTemplateDecl *getCanonicalDecl() {
1734    return cast<ClassTemplateDecl>(
1735             RedeclarableTemplateDecl::getCanonicalDecl());
1736  }
1737  const ClassTemplateDecl *getCanonicalDecl() const {
1738    return cast<ClassTemplateDecl>(
1739             RedeclarableTemplateDecl::getCanonicalDecl());
1740  }
1741
1742  /// \brief Retrieve the previous declaration of this class template, or
1743  /// NULL if no such declaration exists.
1744  ClassTemplateDecl *getPreviousDecl() {
1745    return cast_or_null<ClassTemplateDecl>(
1746             RedeclarableTemplateDecl::getPreviousDecl());
1747  }
1748
1749  /// \brief Retrieve the previous declaration of this class template, or
1750  /// NULL if no such declaration exists.
1751  const ClassTemplateDecl *getPreviousDecl() const {
1752    return cast_or_null<ClassTemplateDecl>(
1753             RedeclarableTemplateDecl::getPreviousDecl());
1754  }
1755
1756  ClassTemplateDecl *getInstantiatedFromMemberTemplate() {
1757    return cast_or_null<ClassTemplateDecl>(
1758             RedeclarableTemplateDecl::getInstantiatedFromMemberTemplate());
1759  }
1760
1761  /// \brief Return the partial specialization with the provided arguments if it
1762  /// exists, otherwise return the insertion point.
1763  ClassTemplatePartialSpecializationDecl *
1764  findPartialSpecialization(const TemplateArgument *Args, unsigned NumArgs,
1765                            void *&InsertPos);
1766
1767  /// \brief Insert the specified partial specialization knowing that it is not
1768  /// already in. InsertPos must be obtained from findPartialSpecialization.
1769  void AddPartialSpecialization(ClassTemplatePartialSpecializationDecl *D,
1770                                void *InsertPos);
1771
1772  /// \brief Return the next partial specialization sequence number.
1773  unsigned getNextPartialSpecSequenceNumber() {
1774    return getPartialSpecializations().size();
1775  }
1776
1777  /// \brief Retrieve the partial specializations as an ordered list.
1778  void getPartialSpecializations(
1779          SmallVectorImpl<ClassTemplatePartialSpecializationDecl *> &PS);
1780
1781  /// \brief Find a class template partial specialization with the given
1782  /// type T.
1783  ///
1784  /// \param T a dependent type that names a specialization of this class
1785  /// template.
1786  ///
1787  /// \returns the class template partial specialization that exactly matches
1788  /// the type \p T, or NULL if no such partial specialization exists.
1789  ClassTemplatePartialSpecializationDecl *findPartialSpecialization(QualType T);
1790
1791  /// \brief Find a class template partial specialization which was instantiated
1792  /// from the given member partial specialization.
1793  ///
1794  /// \param D a member class template partial specialization.
1795  ///
1796  /// \returns the class template partial specialization which was instantiated
1797  /// from the given member partial specialization, or NULL if no such partial
1798  /// specialization exists.
1799  ClassTemplatePartialSpecializationDecl *
1800  findPartialSpecInstantiatedFromMember(
1801                                     ClassTemplatePartialSpecializationDecl *D);
1802
1803  /// \brief Retrieve the template specialization type of the
1804  /// injected-class-name for this class template.
1805  ///
1806  /// The injected-class-name for a class template \c X is \c
1807  /// X<template-args>, where \c template-args is formed from the
1808  /// template arguments that correspond to the template parameters of
1809  /// \c X. For example:
1810  ///
1811  /// \code
1812  /// template<typename T, int N>
1813  /// struct array {
1814  ///   typedef array this_type; // "array" is equivalent to "array<T, N>"
1815  /// };
1816  /// \endcode
1817  QualType getInjectedClassNameSpecialization();
1818
1819  typedef SpecIterator<ClassTemplateSpecializationDecl> spec_iterator;
1820
1821  spec_iterator spec_begin() {
1822    return makeSpecIterator(getSpecializations(), false);
1823  }
1824
1825  spec_iterator spec_end() {
1826    return makeSpecIterator(getSpecializations(), true);
1827  }
1828
1829  typedef SpecIterator<ClassTemplatePartialSpecializationDecl>
1830          partial_spec_iterator;
1831
1832  partial_spec_iterator partial_spec_begin() {
1833    return makeSpecIterator(getPartialSpecializations(), false);
1834  }
1835
1836  partial_spec_iterator partial_spec_end() {
1837    return makeSpecIterator(getPartialSpecializations(), true);
1838  }
1839
1840  // Implement isa/cast/dyncast support
1841  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1842  static bool classof(const ClassTemplateDecl *D) { return true; }
1843  static bool classofKind(Kind K) { return K == ClassTemplate; }
1844
1845  friend class ASTDeclReader;
1846  friend class ASTDeclWriter;
1847};
1848
1849/// Declaration of a friend template.  For example:
1850///
1851/// template <typename T> class A {
1852///   friend class MyVector<T>; // not a friend template
1853///   template <typename U> friend class B; // not a friend template
1854///   template <typename U> friend class Foo<T>::Nested; // friend template
1855/// };
1856/// NOTE: This class is not currently in use.  All of the above
1857/// will yield a FriendDecl, not a FriendTemplateDecl.
1858class FriendTemplateDecl : public Decl {
1859  virtual void anchor();
1860public:
1861  typedef llvm::PointerUnion<NamedDecl*,TypeSourceInfo*> FriendUnion;
1862
1863private:
1864  // The number of template parameters;  always non-zero.
1865  unsigned NumParams;
1866
1867  // The parameter list.
1868  TemplateParameterList **Params;
1869
1870  // The declaration that's a friend of this class.
1871  FriendUnion Friend;
1872
1873  // Location of the 'friend' specifier.
1874  SourceLocation FriendLoc;
1875
1876
1877  FriendTemplateDecl(DeclContext *DC, SourceLocation Loc,
1878                     unsigned NParams,
1879                     TemplateParameterList **Params,
1880                     FriendUnion Friend,
1881                     SourceLocation FriendLoc)
1882    : Decl(Decl::FriendTemplate, DC, Loc),
1883      NumParams(NParams),
1884      Params(Params),
1885      Friend(Friend),
1886      FriendLoc(FriendLoc)
1887  {}
1888
1889  FriendTemplateDecl(EmptyShell Empty)
1890    : Decl(Decl::FriendTemplate, Empty),
1891      NumParams(0),
1892      Params(0)
1893  {}
1894
1895public:
1896  static FriendTemplateDecl *Create(ASTContext &Context,
1897                                    DeclContext *DC, SourceLocation Loc,
1898                                    unsigned NParams,
1899                                    TemplateParameterList **Params,
1900                                    FriendUnion Friend,
1901                                    SourceLocation FriendLoc);
1902
1903  static FriendTemplateDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1904
1905  /// If this friend declaration names a templated type (or
1906  /// a dependent member type of a templated type), return that
1907  /// type;  otherwise return null.
1908  TypeSourceInfo *getFriendType() const {
1909    return Friend.dyn_cast<TypeSourceInfo*>();
1910  }
1911
1912  /// If this friend declaration names a templated function (or
1913  /// a member function of a templated type), return that type;
1914  /// otherwise return null.
1915  NamedDecl *getFriendDecl() const {
1916    return Friend.dyn_cast<NamedDecl*>();
1917  }
1918
1919  /// Retrieves the location of the 'friend' keyword.
1920  SourceLocation getFriendLoc() const {
1921    return FriendLoc;
1922  }
1923
1924  TemplateParameterList *getTemplateParameterList(unsigned i) const {
1925    assert(i <= NumParams);
1926    return Params[i];
1927  }
1928
1929  unsigned getNumTemplateParameters() const {
1930    return NumParams;
1931  }
1932
1933  // Implement isa/cast/dyncast/etc.
1934  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1935  static bool classofKind(Kind K) { return K == Decl::FriendTemplate; }
1936  static bool classof(const FriendTemplateDecl *D) { return true; }
1937
1938  friend class ASTDeclReader;
1939};
1940
1941/// Declaration of an alias template.  For example:
1942///
1943/// template <typename T> using V = std::map<T*, int, MyCompare<T>>;
1944class TypeAliasTemplateDecl : public RedeclarableTemplateDecl {
1945  static void DeallocateCommon(void *Ptr);
1946
1947protected:
1948  typedef CommonBase Common;
1949
1950  TypeAliasTemplateDecl(DeclContext *DC, SourceLocation L, DeclarationName Name,
1951                        TemplateParameterList *Params, NamedDecl *Decl)
1952    : RedeclarableTemplateDecl(TypeAliasTemplate, DC, L, Name, Params, Decl) { }
1953
1954  CommonBase *newCommon(ASTContext &C);
1955
1956  Common *getCommonPtr() {
1957    return static_cast<Common *>(RedeclarableTemplateDecl::getCommonPtr());
1958  }
1959
1960public:
1961  /// Get the underlying function declaration of the template.
1962  TypeAliasDecl *getTemplatedDecl() const {
1963    return static_cast<TypeAliasDecl*>(TemplatedDecl);
1964  }
1965
1966
1967  TypeAliasTemplateDecl *getCanonicalDecl() {
1968    return cast<TypeAliasTemplateDecl>(
1969             RedeclarableTemplateDecl::getCanonicalDecl());
1970  }
1971  const TypeAliasTemplateDecl *getCanonicalDecl() const {
1972    return cast<TypeAliasTemplateDecl>(
1973             RedeclarableTemplateDecl::getCanonicalDecl());
1974  }
1975
1976  /// \brief Retrieve the previous declaration of this function template, or
1977  /// NULL if no such declaration exists.
1978  TypeAliasTemplateDecl *getPreviousDecl() {
1979    return cast_or_null<TypeAliasTemplateDecl>(
1980             RedeclarableTemplateDecl::getPreviousDecl());
1981  }
1982
1983  /// \brief Retrieve the previous declaration of this function template, or
1984  /// NULL if no such declaration exists.
1985  const TypeAliasTemplateDecl *getPreviousDecl() const {
1986    return cast_or_null<TypeAliasTemplateDecl>(
1987             RedeclarableTemplateDecl::getPreviousDecl());
1988  }
1989
1990  TypeAliasTemplateDecl *getInstantiatedFromMemberTemplate() {
1991    return cast_or_null<TypeAliasTemplateDecl>(
1992             RedeclarableTemplateDecl::getInstantiatedFromMemberTemplate());
1993  }
1994
1995
1996  /// \brief Create a function template node.
1997  static TypeAliasTemplateDecl *Create(ASTContext &C, DeclContext *DC,
1998                                       SourceLocation L,
1999                                       DeclarationName Name,
2000                                       TemplateParameterList *Params,
2001                                       NamedDecl *Decl);
2002
2003  /// \brief Create an empty alias template node.
2004  static TypeAliasTemplateDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2005
2006  // Implement isa/cast/dyncast support
2007  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2008  static bool classof(const TypeAliasTemplateDecl *D) { return true; }
2009  static bool classofKind(Kind K) { return K == TypeAliasTemplate; }
2010
2011  friend class ASTDeclReader;
2012  friend class ASTDeclWriter;
2013};
2014
2015/// Declaration of a function specialization at template class scope.
2016/// This is a non standard extension needed to support MSVC.
2017/// For example:
2018/// template <class T>
2019/// class A {
2020///    template <class U> void foo(U a) { }
2021///    template<> void foo(int a) { }
2022/// }
2023///
2024/// "template<> foo(int a)" will be saved in Specialization as a normal
2025/// CXXMethodDecl. Then during an instantiation of class A, it will be
2026/// transformed into an actual function specialization.
2027class ClassScopeFunctionSpecializationDecl : public Decl {
2028  virtual void anchor();
2029
2030  ClassScopeFunctionSpecializationDecl(DeclContext *DC, SourceLocation Loc,
2031                                       CXXMethodDecl *FD)
2032    : Decl(Decl::ClassScopeFunctionSpecialization, DC, Loc),
2033      Specialization(FD) {}
2034
2035  ClassScopeFunctionSpecializationDecl(EmptyShell Empty)
2036    : Decl(Decl::ClassScopeFunctionSpecialization, Empty) {}
2037
2038  CXXMethodDecl *Specialization;
2039
2040public:
2041  CXXMethodDecl *getSpecialization() const { return Specialization; }
2042
2043  static ClassScopeFunctionSpecializationDecl *Create(ASTContext &C,
2044                                                      DeclContext *DC,
2045                                                      SourceLocation Loc,
2046                                                      CXXMethodDecl *FD) {
2047    return new (C) ClassScopeFunctionSpecializationDecl(DC , Loc, FD);
2048  }
2049
2050  static ClassScopeFunctionSpecializationDecl *
2051  CreateDeserialized(ASTContext &Context, unsigned ID);
2052
2053  // Implement isa/cast/dyncast/etc.
2054  static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2055  static bool classofKind(Kind K) {
2056    return K == Decl::ClassScopeFunctionSpecialization;
2057  }
2058  static bool classof(const ClassScopeFunctionSpecializationDecl *D) {
2059    return true;
2060  }
2061
2062  friend class ASTDeclReader;
2063  friend class ASTDeclWriter;
2064};
2065
2066/// Implementation of inline functions that require the template declarations
2067inline AnyFunctionDecl::AnyFunctionDecl(FunctionTemplateDecl *FTD)
2068  : Function(FTD) { }
2069
2070} /* end of namespace clang */
2071
2072#endif
2073