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