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