clang API Documentation

DeclTemplate.h
Go to the documentation of this file.
00001 //===-- DeclTemplate.h - Classes for representing C++ templates -*- C++ -*-===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 //  This file defines the C++ template declaration subclasses.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #ifndef LLVM_CLANG_AST_DECLTEMPLATE_H
00015 #define LLVM_CLANG_AST_DECLTEMPLATE_H
00016 
00017 #include "clang/AST/DeclCXX.h"
00018 #include "clang/AST/Redeclarable.h"
00019 #include "clang/AST/TemplateBase.h"
00020 #include "llvm/ADT/PointerUnion.h"
00021 #include "llvm/Support/Compiler.h"
00022 #include <limits>
00023 
00024 namespace clang {
00025 
00026 class TemplateParameterList;
00027 class TemplateDecl;
00028 class RedeclarableTemplateDecl;
00029 class FunctionTemplateDecl;
00030 class ClassTemplateDecl;
00031 class ClassTemplatePartialSpecializationDecl;
00032 class TemplateTypeParmDecl;
00033 class NonTypeTemplateParmDecl;
00034 class TemplateTemplateParmDecl;
00035 class TypeAliasTemplateDecl;
00036 
00037 /// \brief Stores a template parameter of any kind.
00038 typedef llvm::PointerUnion3<TemplateTypeParmDecl*, NonTypeTemplateParmDecl*,
00039                             TemplateTemplateParmDecl*> TemplateParameter;
00040 
00041 /// TemplateParameterList - Stores a list of template parameters for a
00042 /// TemplateDecl and its derived classes.
00043 class TemplateParameterList {
00044   /// The location of the 'template' keyword.
00045   SourceLocation TemplateLoc;
00046 
00047   /// The locations of the '<' and '>' angle brackets.
00048   SourceLocation LAngleLoc, RAngleLoc;
00049 
00050   /// The number of template parameters in this template
00051   /// parameter list.
00052   unsigned NumParams;
00053 
00054 protected:
00055   TemplateParameterList(SourceLocation TemplateLoc, SourceLocation LAngleLoc,
00056                         NamedDecl **Params, unsigned NumParams,
00057                         SourceLocation RAngleLoc);
00058 
00059 public:
00060   static TemplateParameterList *Create(const ASTContext &C,
00061                                        SourceLocation TemplateLoc,
00062                                        SourceLocation LAngleLoc,
00063                                        NamedDecl **Params,
00064                                        unsigned NumParams,
00065                                        SourceLocation RAngleLoc);
00066 
00067   /// iterator - Iterates through the template parameters in this list.
00068   typedef NamedDecl** iterator;
00069 
00070   /// const_iterator - Iterates through the template parameters in this list.
00071   typedef NamedDecl* const* const_iterator;
00072 
00073   iterator begin() { return reinterpret_cast<NamedDecl **>(this + 1); }
00074   const_iterator begin() const {
00075     return reinterpret_cast<NamedDecl * const *>(this + 1);
00076   }
00077   iterator end() { return begin() + NumParams; }
00078   const_iterator end() const { return begin() + NumParams; }
00079 
00080   unsigned size() const { return NumParams; }
00081 
00082   NamedDecl* getParam(unsigned Idx) {
00083     assert(Idx < size() && "Template parameter index out-of-range");
00084     return begin()[Idx];
00085   }
00086 
00087   const NamedDecl* getParam(unsigned Idx) const {
00088     assert(Idx < size() && "Template parameter index out-of-range");
00089     return begin()[Idx];
00090   }
00091 
00092   /// \brief Returns the minimum number of arguments needed to form a
00093   /// template specialization. This may be fewer than the number of
00094   /// template parameters, if some of the parameters have default
00095   /// arguments or if there is a parameter pack.
00096   unsigned getMinRequiredArguments() const;
00097 
00098   /// \brief Get the depth of this template parameter list in the set of
00099   /// template parameter lists.
00100   ///
00101   /// The first template parameter list in a declaration will have depth 0,
00102   /// the second template parameter list will have depth 1, etc.
00103   unsigned getDepth() const;
00104 
00105   SourceLocation getTemplateLoc() const { return TemplateLoc; }
00106   SourceLocation getLAngleLoc() const { return LAngleLoc; }
00107   SourceLocation getRAngleLoc() const { return RAngleLoc; }
00108 
00109   SourceRange getSourceRange() const LLVM_READONLY {
00110     return SourceRange(TemplateLoc, RAngleLoc);
00111   }
00112 };
00113 
00114 /// FixedSizeTemplateParameterList - Stores a list of template parameters for a
00115 /// TemplateDecl and its derived classes. Suitable for creating on the stack.
00116 template<size_t N>
00117 class FixedSizeTemplateParameterList : public TemplateParameterList {
00118   NamedDecl *Params[N];
00119 
00120 public:
00121   FixedSizeTemplateParameterList(SourceLocation TemplateLoc,
00122                                  SourceLocation LAngleLoc,
00123                                  NamedDecl **Params, SourceLocation RAngleLoc) :
00124     TemplateParameterList(TemplateLoc, LAngleLoc, Params, N, RAngleLoc) {
00125   }
00126 };
00127 
00128 /// \brief A template argument list.
00129 class TemplateArgumentList {
00130   /// \brief The template argument list.
00131   ///
00132   /// The integer value will be non-zero to indicate that this
00133   /// template argument list does own the pointer.
00134   llvm::PointerIntPair<const TemplateArgument *, 1> Arguments;
00135 
00136   /// \brief The number of template arguments in this template
00137   /// argument list.
00138   unsigned NumArguments;
00139 
00140   TemplateArgumentList(const TemplateArgumentList &Other); // DO NOT IMPL
00141   void operator=(const TemplateArgumentList &Other); // DO NOT IMPL
00142 
00143   TemplateArgumentList(const TemplateArgument *Args, unsigned NumArgs,
00144                        bool Owned)
00145     : Arguments(Args, Owned), NumArguments(NumArgs) { }
00146 
00147 public:
00148   /// \brief Type used to indicate that the template argument list itself is a
00149   /// stack object. It does not own its template arguments.
00150   enum OnStackType { OnStack };
00151 
00152   /// \brief Create a new template argument list that copies the given set of
00153   /// template arguments.
00154   static TemplateArgumentList *CreateCopy(ASTContext &Context,
00155                                           const TemplateArgument *Args,
00156                                           unsigned NumArgs);
00157 
00158   /// \brief Construct a new, temporary template argument list on the stack.
00159   ///
00160   /// The template argument list does not own the template arguments
00161   /// provided.
00162   explicit TemplateArgumentList(OnStackType,
00163                                 const TemplateArgument *Args, unsigned NumArgs)
00164     : Arguments(Args, false), NumArguments(NumArgs) { }
00165 
00166   /// \brief Produces a shallow copy of the given template argument list.
00167   ///
00168   /// This operation assumes that the input argument list outlives it.
00169   /// This takes the list as a pointer to avoid looking like a copy
00170   /// constructor, since this really really isn't safe to use that
00171   /// way.
00172   explicit TemplateArgumentList(const TemplateArgumentList *Other)
00173     : Arguments(Other->data(), false), NumArguments(Other->size()) { }
00174 
00175   /// \brief Retrieve the template argument at a given index.
00176   const TemplateArgument &get(unsigned Idx) const {
00177     assert(Idx < NumArguments && "Invalid template argument index");
00178     return data()[Idx];
00179   }
00180 
00181   /// \brief Retrieve the template argument at a given index.
00182   const TemplateArgument &operator[](unsigned Idx) const { return get(Idx); }
00183 
00184   /// \brief Retrieve the number of template arguments in this
00185   /// template argument list.
00186   unsigned size() const { return NumArguments; }
00187 
00188   /// \brief Retrieve a pointer to the template argument list.
00189   const TemplateArgument *data() const {
00190     return Arguments.getPointer();
00191   }
00192 };
00193 
00194 //===----------------------------------------------------------------------===//
00195 // Kinds of Templates
00196 //===----------------------------------------------------------------------===//
00197 
00198 /// TemplateDecl - The base class of all kinds of template declarations (e.g.,
00199 /// class, function, etc.). The TemplateDecl class stores the list of template
00200 /// parameters and a reference to the templated scoped declaration: the
00201 /// underlying AST node.
00202 class TemplateDecl : public NamedDecl {
00203   virtual void anchor();
00204 protected:
00205   // This is probably never used.
00206   TemplateDecl(Kind DK, DeclContext *DC, SourceLocation L,
00207                DeclarationName Name)
00208     : NamedDecl(DK, DC, L, Name), TemplatedDecl(0), TemplateParams(0) { }
00209 
00210   // Construct a template decl with the given name and parameters.
00211   // Used when there is not templated element (tt-params, alias?).
00212   TemplateDecl(Kind DK, DeclContext *DC, SourceLocation L,
00213                DeclarationName Name, TemplateParameterList *Params)
00214     : NamedDecl(DK, DC, L, Name), TemplatedDecl(0), TemplateParams(Params) { }
00215 
00216   // Construct a template decl with name, parameters, and templated element.
00217   TemplateDecl(Kind DK, DeclContext *DC, SourceLocation L,
00218                DeclarationName Name, TemplateParameterList *Params,
00219                NamedDecl *Decl)
00220     : NamedDecl(DK, DC, L, Name), TemplatedDecl(Decl),
00221       TemplateParams(Params) { }
00222 public:
00223   /// Get the list of template parameters
00224   TemplateParameterList *getTemplateParameters() const {
00225     return TemplateParams;
00226   }
00227 
00228   /// Get the underlying, templated declaration.
00229   NamedDecl *getTemplatedDecl() const { return TemplatedDecl; }
00230 
00231   // Implement isa/cast/dyncast/etc.
00232   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
00233   static bool classof(const TemplateDecl *D) { return true; }
00234   static bool classof(const RedeclarableTemplateDecl *D) { return true; }
00235   static bool classof(const FunctionTemplateDecl *D) { return true; }
00236   static bool classof(const ClassTemplateDecl *D) { return true; }
00237   static bool classof(const TemplateTemplateParmDecl *D) { return true; }
00238   static bool classof(const TypeAliasTemplateDecl *D) { return true; }
00239   static bool classofKind(Kind K) {
00240     return K >= firstTemplate && K <= lastTemplate;
00241   }
00242 
00243   SourceRange getSourceRange() const LLVM_READONLY {
00244     return SourceRange(TemplateParams->getTemplateLoc(),
00245                        TemplatedDecl->getSourceRange().getEnd());
00246   }
00247 
00248 protected:
00249   NamedDecl *TemplatedDecl;
00250   TemplateParameterList* TemplateParams;
00251 
00252 public:
00253   /// \brief Initialize the underlying templated declaration and
00254   /// template parameters.
00255   void init(NamedDecl *templatedDecl, TemplateParameterList* templateParams) {
00256     assert(TemplatedDecl == 0 && "TemplatedDecl already set!");
00257     assert(TemplateParams == 0 && "TemplateParams already set!");
00258     TemplatedDecl = templatedDecl;
00259     TemplateParams = templateParams;
00260   }
00261 };
00262 
00263 /// \brief Provides information about a function template specialization,
00264 /// which is a FunctionDecl that has been explicitly specialization or
00265 /// instantiated from a function template.
00266 class FunctionTemplateSpecializationInfo : public llvm::FoldingSetNode {
00267   FunctionTemplateSpecializationInfo(FunctionDecl *FD,
00268                                      FunctionTemplateDecl *Template,
00269                                      TemplateSpecializationKind TSK,
00270                                      const TemplateArgumentList *TemplateArgs,
00271                        const ASTTemplateArgumentListInfo *TemplateArgsAsWritten,
00272                                      SourceLocation POI)
00273   : Function(FD),
00274     Template(Template, TSK - 1),
00275     TemplateArguments(TemplateArgs),
00276     TemplateArgumentsAsWritten(TemplateArgsAsWritten),
00277     PointOfInstantiation(POI) { }
00278 
00279 public:
00280   static FunctionTemplateSpecializationInfo *
00281   Create(ASTContext &C, FunctionDecl *FD, FunctionTemplateDecl *Template,
00282          TemplateSpecializationKind TSK,
00283          const TemplateArgumentList *TemplateArgs,
00284          const TemplateArgumentListInfo *TemplateArgsAsWritten,
00285          SourceLocation POI);
00286 
00287   /// \brief The function template specialization that this structure
00288   /// describes.
00289   FunctionDecl *Function;
00290 
00291   /// \brief The function template from which this function template
00292   /// specialization was generated.
00293   ///
00294   /// The two bits are contain the top 4 values of TemplateSpecializationKind.
00295   llvm::PointerIntPair<FunctionTemplateDecl *, 2> Template;
00296 
00297   /// \brief The template arguments used to produce the function template
00298   /// specialization from the function template.
00299   const TemplateArgumentList *TemplateArguments;
00300 
00301   /// \brief The template arguments as written in the sources, if provided.
00302   const ASTTemplateArgumentListInfo *TemplateArgumentsAsWritten;
00303 
00304   /// \brief The point at which this function template specialization was
00305   /// first instantiated.
00306   SourceLocation PointOfInstantiation;
00307 
00308   /// \brief Retrieve the template from which this function was specialized.
00309   FunctionTemplateDecl *getTemplate() const { return Template.getPointer(); }
00310 
00311   /// \brief Determine what kind of template specialization this is.
00312   TemplateSpecializationKind getTemplateSpecializationKind() const {
00313     return (TemplateSpecializationKind)(Template.getInt() + 1);
00314   }
00315 
00316   bool isExplicitSpecialization() const {
00317     return getTemplateSpecializationKind() == TSK_ExplicitSpecialization;
00318   }
00319 
00320   /// \brief Set the template specialization kind.
00321   void setTemplateSpecializationKind(TemplateSpecializationKind TSK) {
00322     assert(TSK != TSK_Undeclared &&
00323          "Cannot encode TSK_Undeclared for a function template specialization");
00324     Template.setInt(TSK - 1);
00325   }
00326 
00327   /// \brief Retrieve the first point of instantiation of this function
00328   /// template specialization.
00329   ///
00330   /// The point of instantiation may be an invalid source location if this
00331   /// function has yet to be instantiated.
00332   SourceLocation getPointOfInstantiation() const {
00333     return PointOfInstantiation;
00334   }
00335 
00336   /// \brief Set the (first) point of instantiation of this function template
00337   /// specialization.
00338   void setPointOfInstantiation(SourceLocation POI) {
00339     PointOfInstantiation = POI;
00340   }
00341 
00342   void Profile(llvm::FoldingSetNodeID &ID) {
00343     Profile(ID, TemplateArguments->data(),
00344             TemplateArguments->size(),
00345             Function->getASTContext());
00346   }
00347 
00348   static void
00349   Profile(llvm::FoldingSetNodeID &ID, const TemplateArgument *TemplateArgs,
00350           unsigned NumTemplateArgs, ASTContext &Context) {
00351     ID.AddInteger(NumTemplateArgs);
00352     for (unsigned Arg = 0; Arg != NumTemplateArgs; ++Arg)
00353       TemplateArgs[Arg].Profile(ID, Context);
00354   }
00355 };
00356 
00357 /// \brief Provides information a specialization of a member of a class
00358 /// template, which may be a member function, static data member,
00359 /// member class or member enumeration.
00360 class MemberSpecializationInfo {
00361   // The member declaration from which this member was instantiated, and the
00362   // manner in which the instantiation occurred (in the lower two bits).
00363   llvm::PointerIntPair<NamedDecl *, 2> MemberAndTSK;
00364 
00365   // The point at which this member was first instantiated.
00366   SourceLocation PointOfInstantiation;
00367 
00368 public:
00369   explicit
00370   MemberSpecializationInfo(NamedDecl *IF, TemplateSpecializationKind TSK,
00371                            SourceLocation POI = SourceLocation())
00372     : MemberAndTSK(IF, TSK - 1), PointOfInstantiation(POI) {
00373     assert(TSK != TSK_Undeclared &&
00374            "Cannot encode undeclared template specializations for members");
00375   }
00376 
00377   /// \brief Retrieve the member declaration from which this member was
00378   /// instantiated.
00379   NamedDecl *getInstantiatedFrom() const { return MemberAndTSK.getPointer(); }
00380 
00381   /// \brief Determine what kind of template specialization this is.
00382   TemplateSpecializationKind getTemplateSpecializationKind() const {
00383     return (TemplateSpecializationKind)(MemberAndTSK.getInt() + 1);
00384   }
00385 
00386   /// \brief Set the template specialization kind.
00387   void setTemplateSpecializationKind(TemplateSpecializationKind TSK) {
00388     assert(TSK != TSK_Undeclared &&
00389            "Cannot encode undeclared template specializations for members");
00390     MemberAndTSK.setInt(TSK - 1);
00391   }
00392 
00393   /// \brief Retrieve the first point of instantiation of this member.
00394   /// If the point of instantiation is an invalid location, then this member
00395   /// has not yet been instantiated.
00396   SourceLocation getPointOfInstantiation() const {
00397     return PointOfInstantiation;
00398   }
00399 
00400   /// \brief Set the first point of instantiation.
00401   void setPointOfInstantiation(SourceLocation POI) {
00402     PointOfInstantiation = POI;
00403   }
00404 };
00405 
00406 /// \brief Provides information about a dependent function-template
00407 /// specialization declaration.  Since explicit function template
00408 /// specialization and instantiation declarations can only appear in
00409 /// namespace scope, and you can only specialize a member of a
00410 /// fully-specialized class, the only way to get one of these is in
00411 /// a friend declaration like the following:
00412 ///
00413 ///   template <class T> void foo(T);
00414 ///   template <class T> class A {
00415 ///     friend void foo<>(T);
00416 ///   };
00417 class DependentFunctionTemplateSpecializationInfo {
00418   union {
00419     // Force sizeof to be a multiple of sizeof(void*) so that the
00420     // trailing data is aligned.
00421     void *Aligner;
00422 
00423     struct {
00424       /// The number of potential template candidates.
00425       unsigned NumTemplates;
00426 
00427       /// The number of template arguments.
00428       unsigned NumArgs;
00429     } d;
00430   };
00431 
00432   /// The locations of the left and right angle brackets.
00433   SourceRange AngleLocs;
00434 
00435   FunctionTemplateDecl * const *getTemplates() const {
00436     return reinterpret_cast<FunctionTemplateDecl*const*>(this+1);
00437   }
00438 
00439 public:
00440   DependentFunctionTemplateSpecializationInfo(
00441                                  const UnresolvedSetImpl &Templates,
00442                                  const TemplateArgumentListInfo &TemplateArgs);
00443 
00444   /// \brief Returns the number of function templates that this might
00445   /// be a specialization of.
00446   unsigned getNumTemplates() const {
00447     return d.NumTemplates;
00448   }
00449 
00450   /// \brief Returns the i'th template candidate.
00451   FunctionTemplateDecl *getTemplate(unsigned I) const {
00452     assert(I < getNumTemplates() && "template index out of range");
00453     return getTemplates()[I];
00454   }
00455 
00456   /// \brief Returns the explicit template arguments that were given.
00457   const TemplateArgumentLoc *getTemplateArgs() const {
00458     return reinterpret_cast<const TemplateArgumentLoc*>(
00459                                             &getTemplates()[getNumTemplates()]);
00460   }
00461 
00462   /// \brief Returns the number of explicit template arguments that were given.
00463   unsigned getNumTemplateArgs() const {
00464     return d.NumArgs;
00465   }
00466 
00467   /// \brief Returns the nth template argument.
00468   const TemplateArgumentLoc &getTemplateArg(unsigned I) const {
00469     assert(I < getNumTemplateArgs() && "template arg index out of range");
00470     return getTemplateArgs()[I];
00471   }
00472 
00473   SourceLocation getLAngleLoc() const {
00474     return AngleLocs.getBegin();
00475   }
00476 
00477   SourceLocation getRAngleLoc() const {
00478     return AngleLocs.getEnd();
00479   }
00480 };
00481 
00482 /// Declaration of a redeclarable template.
00483 class RedeclarableTemplateDecl : public TemplateDecl, 
00484                                  public Redeclarable<RedeclarableTemplateDecl> 
00485 {
00486   typedef Redeclarable<RedeclarableTemplateDecl> redeclarable_base;
00487   virtual RedeclarableTemplateDecl *getNextRedeclaration() {
00488     return RedeclLink.getNext();
00489   }
00490   virtual RedeclarableTemplateDecl *getPreviousDeclImpl() {
00491     return getPreviousDecl();
00492   }
00493   virtual RedeclarableTemplateDecl *getMostRecentDeclImpl() {
00494     return getMostRecentDecl();
00495   }
00496 
00497 protected:
00498   template <typename EntryType> struct SpecEntryTraits {
00499     typedef EntryType DeclType;
00500 
00501     static DeclType *getMostRecentDecl(EntryType *D) {
00502       return D->getMostRecentDecl();
00503     }
00504   };
00505 
00506   template <typename EntryType,
00507             typename _SETraits = SpecEntryTraits<EntryType>,
00508             typename _DeclType = typename _SETraits::DeclType>
00509   class SpecIterator : public std::iterator<std::forward_iterator_tag,
00510                                             _DeclType*, ptrdiff_t,
00511                                             _DeclType*, _DeclType*> {
00512     typedef _SETraits SETraits;
00513     typedef _DeclType DeclType;
00514 
00515     typedef typename llvm::FoldingSetVector<EntryType>::iterator
00516       SetIteratorType;
00517 
00518     SetIteratorType SetIter;
00519 
00520   public:
00521     SpecIterator() : SetIter() {}
00522     SpecIterator(SetIteratorType SetIter) : SetIter(SetIter) {}
00523 
00524     DeclType *operator*() const {
00525       return SETraits::getMostRecentDecl(&*SetIter);
00526     }
00527     DeclType *operator->() const { return **this; }
00528 
00529     SpecIterator &operator++() { ++SetIter; return *this; }
00530     SpecIterator operator++(int) {
00531       SpecIterator tmp(*this);
00532       ++(*this);
00533       return tmp;
00534     }
00535 
00536     bool operator==(SpecIterator Other) const {
00537       return SetIter == Other.SetIter;
00538     }
00539     bool operator!=(SpecIterator Other) const {
00540       return SetIter != Other.SetIter;
00541     }
00542   };
00543 
00544   template <typename EntryType>
00545   SpecIterator<EntryType>
00546   makeSpecIterator(llvm::FoldingSetVector<EntryType> &Specs, bool isEnd) {
00547     return SpecIterator<EntryType>(isEnd ? Specs.end() : Specs.begin());
00548   }
00549 
00550   template <class EntryType> typename SpecEntryTraits<EntryType>::DeclType*
00551   findSpecializationImpl(llvm::FoldingSetVector<EntryType> &Specs,
00552                          const TemplateArgument *Args, unsigned NumArgs,
00553                          void *&InsertPos);
00554 
00555   struct CommonBase {
00556     CommonBase() : InstantiatedFromMember(0, false) { }
00557 
00558     /// \brief The template from which this was most
00559     /// directly instantiated (or null).
00560     ///
00561     /// The boolean value indicates whether this template
00562     /// was explicitly specialized.
00563     llvm::PointerIntPair<RedeclarableTemplateDecl*, 1, bool>
00564       InstantiatedFromMember;
00565   };
00566 
00567   /// \brief Pointer to the common data shared by all declarations of this
00568   /// template.
00569   CommonBase *Common;
00570   
00571   /// \brief Retrieves the "common" pointer shared by all (re-)declarations of
00572   /// the same template. Calling this routine may implicitly allocate memory
00573   /// for the common pointer.
00574   CommonBase *getCommonPtr();
00575 
00576   virtual CommonBase *newCommon(ASTContext &C) = 0;
00577 
00578   // Construct a template decl with name, parameters, and templated element.
00579   RedeclarableTemplateDecl(Kind DK, DeclContext *DC, SourceLocation L,
00580                            DeclarationName Name, TemplateParameterList *Params,
00581                            NamedDecl *Decl)
00582     : TemplateDecl(DK, DC, L, Name, Params, Decl), Common() { }
00583 
00584 public:
00585   template <class decl_type> friend class RedeclarableTemplate;
00586 
00587   /// Retrieves the canonical declaration of this template.
00588   RedeclarableTemplateDecl *getCanonicalDecl() { return getFirstDeclaration(); }
00589   const RedeclarableTemplateDecl *getCanonicalDecl() const { 
00590     return getFirstDeclaration(); 
00591   }
00592 
00593   /// \brief Determines whether this template was a specialization of a
00594   /// member template.
00595   ///
00596   /// In the following example, the function template \c X<int>::f and the
00597   /// member template \c X<int>::Inner are member specializations.
00598   ///
00599   /// \code
00600   /// template<typename T>
00601   /// struct X {
00602   ///   template<typename U> void f(T, U);
00603   ///   template<typename U> struct Inner;
00604   /// };
00605   ///
00606   /// template<> template<typename T>
00607   /// void X<int>::f(int, T);
00608   /// template<> template<typename T>
00609   /// struct X<int>::Inner { /* ... */ };
00610   /// \endcode
00611   bool isMemberSpecialization() {
00612     return getCommonPtr()->InstantiatedFromMember.getInt();
00613   }
00614 
00615   /// \brief Note that this member template is a specialization.
00616   void setMemberSpecialization() {
00617     assert(getCommonPtr()->InstantiatedFromMember.getPointer() &&
00618            "Only member templates can be member template specializations");
00619     getCommonPtr()->InstantiatedFromMember.setInt(true);
00620   }
00621 
00622   /// \brief Retrieve the member template from which this template was
00623   /// instantiated, or NULL if this template was not instantiated from a 
00624   /// member template.
00625   ///
00626   /// A template is instantiated from a member template when the member 
00627   /// template itself is part of a class template (or member thereof). For
00628   /// example, given
00629   ///
00630   /// \code
00631   /// template<typename T>
00632   /// struct X {
00633   ///   template<typename U> void f(T, U);
00634   /// };
00635   ///
00636   /// void test(X<int> x) {
00637   ///   x.f(1, 'a');
00638   /// };
00639   /// \endcode
00640   ///
00641   /// \c X<int>::f is a FunctionTemplateDecl that describes the function
00642   /// template
00643   ///
00644   /// \code
00645   /// template<typename U> void X<int>::f(int, U);
00646   /// \endcode
00647   ///
00648   /// which was itself created during the instantiation of \c X<int>. Calling
00649   /// getInstantiatedFromMemberTemplate() on this FunctionTemplateDecl will
00650   /// retrieve the FunctionTemplateDecl for the original template "f" within
00651   /// the class template \c X<T>, i.e.,
00652   ///
00653   /// \code
00654   /// template<typename T>
00655   /// template<typename U>
00656   /// void X<T>::f(T, U);
00657   /// \endcode
00658   RedeclarableTemplateDecl *getInstantiatedFromMemberTemplate() {
00659     return getCommonPtr()->InstantiatedFromMember.getPointer();
00660   }
00661 
00662   void setInstantiatedFromMemberTemplate(RedeclarableTemplateDecl *TD) {
00663     assert(!getCommonPtr()->InstantiatedFromMember.getPointer());
00664     getCommonPtr()->InstantiatedFromMember.setPointer(TD);
00665   }
00666 
00667   typedef redeclarable_base::redecl_iterator redecl_iterator;
00668   using redeclarable_base::redecls_begin;
00669   using redeclarable_base::redecls_end;
00670   using redeclarable_base::getPreviousDecl;
00671   using redeclarable_base::getMostRecentDecl;
00672 
00673   // Implement isa/cast/dyncast/etc.
00674   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
00675   static bool classof(const RedeclarableTemplateDecl *D) { return true; }
00676   static bool classof(const FunctionTemplateDecl *D) { return true; }
00677   static bool classof(const ClassTemplateDecl *D) { return true; }
00678   static bool classof(const TypeAliasTemplateDecl *D) { return true; }
00679   static bool classofKind(Kind K) {
00680     return K >= firstRedeclarableTemplate && K <= lastRedeclarableTemplate;
00681   }
00682 
00683   friend class ASTReader;
00684   friend class ASTDeclReader;
00685   friend class ASTDeclWriter;
00686 };
00687 
00688 template <> struct RedeclarableTemplateDecl::
00689 SpecEntryTraits<FunctionTemplateSpecializationInfo> {
00690   typedef FunctionDecl DeclType;
00691 
00692   static DeclType *
00693   getMostRecentDecl(FunctionTemplateSpecializationInfo *I) {
00694     return I->Function->getMostRecentDecl();
00695   }
00696 };
00697 
00698 /// Declaration of a template function.
00699 class FunctionTemplateDecl : public RedeclarableTemplateDecl {
00700   static void DeallocateCommon(void *Ptr);
00701 
00702 protected:
00703   /// \brief Data that is common to all of the declarations of a given
00704   /// function template.
00705   struct Common : CommonBase {
00706     Common() : InjectedArgs(0) { }
00707 
00708     /// \brief The function template specializations for this function
00709     /// template, including explicit specializations and instantiations.
00710     llvm::FoldingSetVector<FunctionTemplateSpecializationInfo> Specializations;
00711 
00712     /// \brief The set of "injected" template arguments used within this
00713     /// function template.
00714     ///
00715     /// This pointer refers to the template arguments (there are as
00716     /// many template arguments as template parameaters) for the function
00717     /// template, and is allocated lazily, since most function templates do not
00718     /// require the use of this information.
00719     TemplateArgument *InjectedArgs;
00720   };
00721 
00722   FunctionTemplateDecl(DeclContext *DC, SourceLocation L, DeclarationName Name,
00723                        TemplateParameterList *Params, NamedDecl *Decl)
00724     : RedeclarableTemplateDecl(FunctionTemplate, DC, L, Name, Params, Decl) { }
00725 
00726   CommonBase *newCommon(ASTContext &C);
00727 
00728   Common *getCommonPtr() {
00729     return static_cast<Common *>(RedeclarableTemplateDecl::getCommonPtr());
00730   }
00731 
00732   friend class FunctionDecl;
00733 
00734   /// \brief Retrieve the set of function template specializations of this
00735   /// function template.
00736   llvm::FoldingSetVector<FunctionTemplateSpecializationInfo> &
00737   getSpecializations() {
00738     return getCommonPtr()->Specializations;
00739   }
00740 
00741   /// \brief Add a specialization of this function template.
00742   ///
00743   /// \param InsertPos Insert position in the FoldingSetVector, must have been
00744   ///        retrieved by an earlier call to findSpecialization().
00745   void addSpecialization(FunctionTemplateSpecializationInfo* Info,
00746                          void *InsertPos);
00747 
00748 public:
00749   /// Get the underlying function declaration of the template.
00750   FunctionDecl *getTemplatedDecl() const {
00751     return static_cast<FunctionDecl*>(TemplatedDecl);
00752   }
00753 
00754   /// Returns whether this template declaration defines the primary
00755   /// pattern.
00756   bool isThisDeclarationADefinition() const {
00757     return getTemplatedDecl()->isThisDeclarationADefinition();
00758   }
00759 
00760   /// \brief Return the specialization with the provided arguments if it exists,
00761   /// otherwise return the insertion point.
00762   FunctionDecl *findSpecialization(const TemplateArgument *Args,
00763                                    unsigned NumArgs, void *&InsertPos);
00764 
00765   FunctionTemplateDecl *getCanonicalDecl() {
00766     return cast<FunctionTemplateDecl>(
00767              RedeclarableTemplateDecl::getCanonicalDecl());
00768   }
00769   const FunctionTemplateDecl *getCanonicalDecl() const {
00770     return cast<FunctionTemplateDecl>(
00771              RedeclarableTemplateDecl::getCanonicalDecl());
00772   }
00773 
00774   /// \brief Retrieve the previous declaration of this function template, or
00775   /// NULL if no such declaration exists.
00776   FunctionTemplateDecl *getPreviousDecl() {
00777     return cast_or_null<FunctionTemplateDecl>(
00778              RedeclarableTemplateDecl::getPreviousDecl());
00779   }
00780 
00781   /// \brief Retrieve the previous declaration of this function template, or
00782   /// NULL if no such declaration exists.
00783   const FunctionTemplateDecl *getPreviousDecl() const {
00784     return cast_or_null<FunctionTemplateDecl>(
00785              RedeclarableTemplateDecl::getPreviousDecl());
00786   }
00787 
00788   FunctionTemplateDecl *getInstantiatedFromMemberTemplate() {
00789     return cast_or_null<FunctionTemplateDecl>(
00790              RedeclarableTemplateDecl::getInstantiatedFromMemberTemplate());
00791   }
00792 
00793   typedef SpecIterator<FunctionTemplateSpecializationInfo> spec_iterator;
00794 
00795   spec_iterator spec_begin() {
00796     return makeSpecIterator(getSpecializations(), false);
00797   }
00798 
00799   spec_iterator spec_end() {
00800     return makeSpecIterator(getSpecializations(), true);
00801   }
00802 
00803   /// \brief Retrieve the "injected" template arguments that correspond to the
00804   /// template parameters of this function template.
00805   ///
00806   /// Although the C++ standard has no notion of the "injected" template
00807   /// arguments for a function template, the notion is convenient when
00808   /// we need to perform substitutions inside the definition of a function
00809   /// template.
00810   std::pair<const TemplateArgument *, unsigned> getInjectedTemplateArgs();
00811 
00812   /// \brief Create a function template node.
00813   static FunctionTemplateDecl *Create(ASTContext &C, DeclContext *DC,
00814                                       SourceLocation L,
00815                                       DeclarationName Name,
00816                                       TemplateParameterList *Params,
00817                                       NamedDecl *Decl);
00818 
00819   /// \brief Create an empty function template node.
00820   static FunctionTemplateDecl *CreateDeserialized(ASTContext &C, unsigned ID);
00821 
00822   // Implement isa/cast/dyncast support
00823   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
00824   static bool classof(const FunctionTemplateDecl *D) { return true; }
00825   static bool classofKind(Kind K) { return K == FunctionTemplate; }
00826 
00827   friend class ASTDeclReader;
00828   friend class ASTDeclWriter;
00829 };
00830 
00831 //===----------------------------------------------------------------------===//
00832 // Kinds of Template Parameters
00833 //===----------------------------------------------------------------------===//
00834 
00835 /// The TemplateParmPosition class defines the position of a template parameter
00836 /// within a template parameter list. Because template parameter can be listed
00837 /// sequentially for out-of-line template members, each template parameter is
00838 /// given a Depth - the nesting of template parameter scopes - and a Position -
00839 /// the occurrence within the parameter list.
00840 /// This class is inheritedly privately by different kinds of template
00841 /// parameters and is not part of the Decl hierarchy. Just a facility.
00842 class TemplateParmPosition {
00843 protected:
00844   // FIXME: This should probably never be called, but it's here as
00845   TemplateParmPosition()
00846     : Depth(0), Position(0)
00847   { /* llvm_unreachable("Cannot create positionless template parameter"); */ }
00848 
00849   TemplateParmPosition(unsigned D, unsigned P)
00850     : Depth(D), Position(P)
00851   { }
00852 
00853   // FIXME: These probably don't need to be ints. int:5 for depth, int:8 for
00854   // position? Maybe?
00855   unsigned Depth;
00856   unsigned Position;
00857 
00858 public:
00859   /// Get the nesting depth of the template parameter.
00860   unsigned getDepth() const { return Depth; }
00861   void setDepth(unsigned D) { Depth = D; }
00862 
00863   /// Get the position of the template parameter within its parameter list.
00864   unsigned getPosition() const { return Position; }
00865   void setPosition(unsigned P) { Position = P; }
00866 
00867   /// Get the index of the template parameter within its parameter list.
00868   unsigned getIndex() const { return Position; }
00869 };
00870 
00871 /// TemplateTypeParmDecl - Declaration of a template type parameter,
00872 /// e.g., "T" in
00873 /// @code
00874 /// template<typename T> class vector;
00875 /// @endcode
00876 class TemplateTypeParmDecl : public TypeDecl {
00877   /// \brief Whether this template type parameter was declaration with
00878   /// the 'typename' keyword. If false, it was declared with the
00879   /// 'class' keyword.
00880   bool Typename : 1;
00881 
00882   /// \brief Whether this template type parameter inherited its
00883   /// default argument.
00884   bool InheritedDefault : 1;
00885 
00886   /// \brief The default template argument, if any.
00887   TypeSourceInfo *DefaultArgument;
00888 
00889   TemplateTypeParmDecl(DeclContext *DC, SourceLocation KeyLoc,
00890                        SourceLocation IdLoc, IdentifierInfo *Id,
00891                        bool Typename)
00892     : TypeDecl(TemplateTypeParm, DC, IdLoc, Id, KeyLoc), Typename(Typename),
00893       InheritedDefault(false), DefaultArgument() { }
00894 
00895   /// Sema creates these on the stack during auto type deduction.
00896   friend class Sema;
00897 
00898 public:
00899   static TemplateTypeParmDecl *Create(const ASTContext &C, DeclContext *DC,
00900                                       SourceLocation KeyLoc,
00901                                       SourceLocation NameLoc,
00902                                       unsigned D, unsigned P,
00903                                       IdentifierInfo *Id, bool Typename,
00904                                       bool ParameterPack);
00905   static TemplateTypeParmDecl *CreateDeserialized(const ASTContext &C, 
00906                                                   unsigned ID);
00907 
00908   /// \brief Whether this template type parameter was declared with
00909   /// the 'typename' keyword. If not, it was declared with the 'class'
00910   /// keyword.
00911   bool wasDeclaredWithTypename() const { return Typename; }
00912 
00913   /// \brief Determine whether this template parameter has a default
00914   /// argument.
00915   bool hasDefaultArgument() const { return DefaultArgument != 0; }
00916 
00917   /// \brief Retrieve the default argument, if any.
00918   QualType getDefaultArgument() const { return DefaultArgument->getType(); }
00919 
00920   /// \brief Retrieves the default argument's source information, if any.
00921   TypeSourceInfo *getDefaultArgumentInfo() const { return DefaultArgument; }
00922 
00923   /// \brief Retrieves the location of the default argument declaration.
00924   SourceLocation getDefaultArgumentLoc() const;
00925 
00926   /// \brief Determines whether the default argument was inherited
00927   /// from a previous declaration of this template.
00928   bool defaultArgumentWasInherited() const { return InheritedDefault; }
00929 
00930   /// \brief Set the default argument for this template parameter, and
00931   /// whether that default argument was inherited from another
00932   /// declaration.
00933   void setDefaultArgument(TypeSourceInfo *DefArg, bool Inherited) {
00934     DefaultArgument = DefArg;
00935     InheritedDefault = Inherited;
00936   }
00937 
00938   /// \brief Removes the default argument of this template parameter.
00939   void removeDefaultArgument() {
00940     DefaultArgument = 0;
00941     InheritedDefault = false;
00942   }
00943 
00944   /// \brief Set whether this template type parameter was declared with
00945   /// the 'typename' or 'class' keyword.
00946   void setDeclaredWithTypename(bool withTypename) { Typename = withTypename; }
00947 
00948   /// \brief Retrieve the depth of the template parameter.
00949   unsigned getDepth() const;
00950 
00951   /// \brief Retrieve the index of the template parameter.
00952   unsigned getIndex() const;
00953 
00954   /// \brief Returns whether this is a parameter pack.
00955   bool isParameterPack() const;
00956 
00957   SourceRange getSourceRange() const LLVM_READONLY;
00958 
00959   // Implement isa/cast/dyncast/etc.
00960   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
00961   static bool classof(const TemplateTypeParmDecl *D) { return true; }
00962   static bool classofKind(Kind K) { return K == TemplateTypeParm; }
00963 };
00964 
00965 /// NonTypeTemplateParmDecl - Declares a non-type template parameter,
00966 /// e.g., "Size" in
00967 /// @code
00968 /// template<int Size> class array { };
00969 /// @endcode
00970 class NonTypeTemplateParmDecl
00971   : public DeclaratorDecl, protected TemplateParmPosition {
00972   /// \brief The default template argument, if any, and whether or not
00973   /// it was inherited.
00974   llvm::PointerIntPair<Expr*, 1, bool> DefaultArgumentAndInherited;
00975 
00976   // FIXME: Collapse this into TemplateParamPosition; or, just move depth/index
00977   // down here to save memory.
00978 
00979   /// \brief Whether this non-type template parameter is a parameter pack.
00980   bool ParameterPack;
00981 
00982   /// \brief Whether this non-type template parameter is an "expanded"
00983   /// parameter pack, meaning that its type is a pack expansion and we
00984   /// already know the set of types that expansion expands to.
00985   bool ExpandedParameterPack;
00986 
00987   /// \brief The number of types in an expanded parameter pack.
00988   unsigned NumExpandedTypes;
00989 
00990   NonTypeTemplateParmDecl(DeclContext *DC, SourceLocation StartLoc,
00991                           SourceLocation IdLoc, unsigned D, unsigned P,
00992                           IdentifierInfo *Id, QualType T,
00993                           bool ParameterPack, TypeSourceInfo *TInfo)
00994     : DeclaratorDecl(NonTypeTemplateParm, DC, IdLoc, Id, T, TInfo, StartLoc),
00995       TemplateParmPosition(D, P), DefaultArgumentAndInherited(0, false),
00996       ParameterPack(ParameterPack), ExpandedParameterPack(false),
00997       NumExpandedTypes(0)
00998   { }
00999 
01000   NonTypeTemplateParmDecl(DeclContext *DC, SourceLocation StartLoc,
01001                           SourceLocation IdLoc, unsigned D, unsigned P,
01002                           IdentifierInfo *Id, QualType T,
01003                           TypeSourceInfo *TInfo,
01004                           const QualType *ExpandedTypes,
01005                           unsigned NumExpandedTypes,
01006                           TypeSourceInfo **ExpandedTInfos);
01007 
01008   friend class ASTDeclReader;
01009 
01010 public:
01011   static NonTypeTemplateParmDecl *
01012   Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
01013          SourceLocation IdLoc, unsigned D, unsigned P, IdentifierInfo *Id,
01014          QualType T, bool ParameterPack, TypeSourceInfo *TInfo);
01015 
01016   static NonTypeTemplateParmDecl *
01017   Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
01018          SourceLocation IdLoc, unsigned D, unsigned P, IdentifierInfo *Id,
01019          QualType T, TypeSourceInfo *TInfo,
01020          const QualType *ExpandedTypes, unsigned NumExpandedTypes,
01021          TypeSourceInfo **ExpandedTInfos);
01022 
01023   static NonTypeTemplateParmDecl *CreateDeserialized(ASTContext &C, 
01024                                                      unsigned ID);
01025   static NonTypeTemplateParmDecl *CreateDeserialized(ASTContext &C, 
01026                                                      unsigned ID,
01027                                                      unsigned NumExpandedTypes);
01028     
01029   using TemplateParmPosition::getDepth;
01030   using TemplateParmPosition::setDepth;
01031   using TemplateParmPosition::getPosition;
01032   using TemplateParmPosition::setPosition;
01033   using TemplateParmPosition::getIndex;
01034 
01035   SourceRange getSourceRange() const LLVM_READONLY;
01036 
01037   /// \brief Determine whether this template parameter has a default
01038   /// argument.
01039   bool hasDefaultArgument() const {
01040     return DefaultArgumentAndInherited.getPointer() != 0;
01041   }
01042 
01043   /// \brief Retrieve the default argument, if any.
01044   Expr *getDefaultArgument() const {
01045     return DefaultArgumentAndInherited.getPointer();
01046   }
01047 
01048   /// \brief Retrieve the location of the default argument, if any.
01049   SourceLocation getDefaultArgumentLoc() const;
01050 
01051   /// \brief Determines whether the default argument was inherited
01052   /// from a previous declaration of this template.
01053   bool defaultArgumentWasInherited() const {
01054     return DefaultArgumentAndInherited.getInt();
01055   }
01056 
01057   /// \brief Set the default argument for this template parameter, and
01058   /// whether that default argument was inherited from another
01059   /// declaration.
01060   void setDefaultArgument(Expr *DefArg, bool Inherited) {
01061     DefaultArgumentAndInherited.setPointer(DefArg);
01062     DefaultArgumentAndInherited.setInt(Inherited);
01063   }
01064 
01065   /// \brief Removes the default argument of this template parameter.
01066   void removeDefaultArgument() {
01067     DefaultArgumentAndInherited.setPointer(0);
01068     DefaultArgumentAndInherited.setInt(false);
01069   }
01070 
01071   /// \brief Whether this parameter is a non-type template parameter pack.
01072   ///
01073   /// If the parameter is a parameter pack, the type may be a
01074   /// \c PackExpansionType. In the following example, the \c Dims parameter
01075   /// is a parameter pack (whose type is 'unsigned').
01076   ///
01077   /// \code
01078   /// template<typename T, unsigned ...Dims> struct multi_array;
01079   /// \endcode
01080   bool isParameterPack() const { return ParameterPack; }
01081 
01082   /// \brief Whether this parameter is a non-type template parameter pack
01083   /// that has different types at different positions.
01084   ///
01085   /// A parameter pack is an expanded parameter pack when the original
01086   /// parameter pack's type was itself a pack expansion, and that expansion
01087   /// has already been expanded. For example, given:
01088   ///
01089   /// \code
01090   /// template<typename ...Types>
01091   /// struct X {
01092   ///   template<Types ...Values>
01093   ///   struct Y { /* ... */ };
01094   /// };
01095   /// \endcode
01096   ///
01097   /// The parameter pack \c Values has a \c PackExpansionType as its type,
01098   /// which expands \c Types. When \c Types is supplied with template arguments
01099   /// by instantiating \c X, the instantiation of \c Values becomes an
01100   /// expanded parameter pack. For example, instantiating
01101   /// \c X<int, unsigned int> results in \c Values being an expanded parameter
01102   /// pack with expansion types \c int and \c unsigned int.
01103   ///
01104   /// The \c getExpansionType() and \c getExpansionTypeSourceInfo() functions
01105   /// return the expansion types.
01106   bool isExpandedParameterPack() const { return ExpandedParameterPack; }
01107 
01108   /// \brief Retrieves the number of expansion types in an expanded parameter
01109   /// pack.
01110   unsigned getNumExpansionTypes() const {
01111     assert(ExpandedParameterPack && "Not an expansion parameter pack");
01112     return NumExpandedTypes;
01113   }
01114 
01115   /// \brief Retrieve a particular expansion type within an expanded parameter
01116   /// pack.
01117   QualType getExpansionType(unsigned I) const {
01118     assert(I < NumExpandedTypes && "Out-of-range expansion type index");
01119     void * const *TypesAndInfos = reinterpret_cast<void * const*>(this + 1);
01120     return QualType::getFromOpaquePtr(TypesAndInfos[2*I]);
01121   }
01122 
01123   /// \brief Retrieve a particular expansion type source info within an
01124   /// expanded parameter pack.
01125   TypeSourceInfo *getExpansionTypeSourceInfo(unsigned I) const {
01126     assert(I < NumExpandedTypes && "Out-of-range expansion type index");
01127     void * const *TypesAndInfos = reinterpret_cast<void * const*>(this + 1);
01128     return static_cast<TypeSourceInfo *>(TypesAndInfos[2*I+1]);
01129   }
01130 
01131   // Implement isa/cast/dyncast/etc.
01132   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
01133   static bool classof(const NonTypeTemplateParmDecl *D) { return true; }
01134   static bool classofKind(Kind K) { return K == NonTypeTemplateParm; }
01135 };
01136 
01137 /// TemplateTemplateParmDecl - Declares a template template parameter,
01138 /// e.g., "T" in
01139 /// @code
01140 /// template <template <typename> class T> class container { };
01141 /// @endcode
01142 /// A template template parameter is a TemplateDecl because it defines the
01143 /// name of a template and the template parameters allowable for substitution.
01144 class TemplateTemplateParmDecl : public TemplateDecl, 
01145                                  protected TemplateParmPosition 
01146 {
01147   virtual void anchor();
01148 
01149   /// DefaultArgument - The default template argument, if any.
01150   TemplateArgumentLoc DefaultArgument;
01151   /// Whether or not the default argument was inherited.
01152   bool DefaultArgumentWasInherited;
01153 
01154   /// \brief Whether this parameter is a parameter pack.
01155   bool ParameterPack;
01156 
01157   TemplateTemplateParmDecl(DeclContext *DC, SourceLocation L,
01158                            unsigned D, unsigned P, bool ParameterPack,
01159                            IdentifierInfo *Id, TemplateParameterList *Params)
01160     : TemplateDecl(TemplateTemplateParm, DC, L, Id, Params),
01161       TemplateParmPosition(D, P), DefaultArgument(),
01162       DefaultArgumentWasInherited(false), ParameterPack(ParameterPack)
01163     { }
01164 
01165 public:
01166   static TemplateTemplateParmDecl *Create(const ASTContext &C, DeclContext *DC,
01167                                           SourceLocation L, unsigned D,
01168                                           unsigned P, bool ParameterPack,
01169                                           IdentifierInfo *Id,
01170                                           TemplateParameterList *Params);
01171 
01172   static TemplateTemplateParmDecl *CreateDeserialized(ASTContext &C, 
01173                                                       unsigned ID);
01174   
01175   using TemplateParmPosition::getDepth;
01176   using TemplateParmPosition::getPosition;
01177   using TemplateParmPosition::getIndex;
01178 
01179   /// \brief Whether this template template parameter is a template
01180   /// parameter pack.
01181   ///
01182   /// \code
01183   /// template<template <class T> ...MetaFunctions> struct Apply;
01184   /// \endcode
01185   bool isParameterPack() const { return ParameterPack; }
01186 
01187   /// \brief Determine whether this template parameter has a default
01188   /// argument.
01189   bool hasDefaultArgument() const {
01190     return !DefaultArgument.getArgument().isNull();
01191   }
01192 
01193   /// \brief Retrieve the default argument, if any.
01194   const TemplateArgumentLoc &getDefaultArgument() const {
01195     return DefaultArgument;
01196   }
01197 
01198   /// \brief Retrieve the location of the default argument, if any.
01199   SourceLocation getDefaultArgumentLoc() const;
01200 
01201   /// \brief Determines whether the default argument was inherited
01202   /// from a previous declaration of this template.
01203   bool defaultArgumentWasInherited() const {
01204     return DefaultArgumentWasInherited;
01205   }
01206 
01207   /// \brief Set the default argument for this template parameter, and
01208   /// whether that default argument was inherited from another
01209   /// declaration.
01210   void setDefaultArgument(const TemplateArgumentLoc &DefArg, bool Inherited) {
01211     DefaultArgument = DefArg;
01212     DefaultArgumentWasInherited = Inherited;
01213   }
01214 
01215   /// \brief Removes the default argument of this template parameter.
01216   void removeDefaultArgument() {
01217     DefaultArgument = TemplateArgumentLoc();
01218     DefaultArgumentWasInherited = false;
01219   }
01220 
01221   SourceRange getSourceRange() const LLVM_READONLY {
01222     SourceLocation End = getLocation();
01223     if (hasDefaultArgument() && !defaultArgumentWasInherited())
01224       End = getDefaultArgument().getSourceRange().getEnd();
01225     return SourceRange(getTemplateParameters()->getTemplateLoc(), End);
01226   }
01227 
01228   // Implement isa/cast/dyncast/etc.
01229   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
01230   static bool classof(const TemplateTemplateParmDecl *D) { return true; }
01231   static bool classofKind(Kind K) { return K == TemplateTemplateParm; }
01232 
01233   friend class ASTDeclReader;
01234   friend class ASTDeclWriter;
01235 };
01236 
01237 /// \brief Represents a class template specialization, which refers to
01238 /// a class template with a given set of template arguments.
01239 ///
01240 /// Class template specializations represent both explicit
01241 /// specialization of class templates, as in the example below, and
01242 /// implicit instantiations of class templates.
01243 ///
01244 /// \code
01245 /// template<typename T> class array;
01246 ///
01247 /// template<>
01248 /// class array<bool> { }; // class template specialization array<bool>
01249 /// \endcode
01250 class ClassTemplateSpecializationDecl
01251   : public CXXRecordDecl, public llvm::FoldingSetNode {
01252 
01253   /// \brief Structure that stores information about a class template
01254   /// specialization that was instantiated from a class template partial
01255   /// specialization.
01256   struct SpecializedPartialSpecialization {
01257     /// \brief The class template partial specialization from which this
01258     /// class template specialization was instantiated.
01259     ClassTemplatePartialSpecializationDecl *PartialSpecialization;
01260 
01261     /// \brief The template argument list deduced for the class template
01262     /// partial specialization itself.
01263     TemplateArgumentList *TemplateArgs;
01264   };
01265 
01266   /// \brief The template that this specialization specializes
01267   llvm::PointerUnion<ClassTemplateDecl *, SpecializedPartialSpecialization *>
01268     SpecializedTemplate;
01269 
01270   /// \brief Further info for explicit template specialization/instantiation.
01271   struct ExplicitSpecializationInfo {
01272     /// \brief The type-as-written.
01273     TypeSourceInfo *TypeAsWritten;
01274     /// \brief The location of the extern keyword.
01275     SourceLocation ExternLoc;
01276     /// \brief The location of the template keyword.
01277     SourceLocation TemplateKeywordLoc;
01278 
01279     ExplicitSpecializationInfo()
01280       : TypeAsWritten(0), ExternLoc(), TemplateKeywordLoc() {}
01281   };
01282 
01283   /// \brief Further info for explicit template specialization/instantiation.
01284   /// Does not apply to implicit specializations.
01285   ExplicitSpecializationInfo *ExplicitInfo;
01286 
01287   /// \brief The template arguments used to describe this specialization.
01288   TemplateArgumentList *TemplateArgs;
01289 
01290   /// \brief The point where this template was instantiated (if any)
01291   SourceLocation PointOfInstantiation;
01292 
01293   /// \brief The kind of specialization this declaration refers to.
01294   /// Really a value of type TemplateSpecializationKind.
01295   unsigned SpecializationKind : 3;
01296 
01297 protected:
01298   ClassTemplateSpecializationDecl(ASTContext &Context, Kind DK, TagKind TK,
01299                                   DeclContext *DC, SourceLocation StartLoc,
01300                                   SourceLocation IdLoc,
01301                                   ClassTemplateDecl *SpecializedTemplate,
01302                                   const TemplateArgument *Args,
01303                                   unsigned NumArgs,
01304                                   ClassTemplateSpecializationDecl *PrevDecl);
01305 
01306   explicit ClassTemplateSpecializationDecl(Kind DK);
01307 
01308 public:
01309   static ClassTemplateSpecializationDecl *
01310   Create(ASTContext &Context, TagKind TK, DeclContext *DC,
01311          SourceLocation StartLoc, SourceLocation IdLoc,
01312          ClassTemplateDecl *SpecializedTemplate,
01313          const TemplateArgument *Args,
01314          unsigned NumArgs,
01315          ClassTemplateSpecializationDecl *PrevDecl);
01316   static ClassTemplateSpecializationDecl *
01317   CreateDeserialized(ASTContext &C, unsigned ID);
01318 
01319   virtual void getNameForDiagnostic(std::string &S,
01320                                     const PrintingPolicy &Policy,
01321                                     bool Qualified) const;
01322 
01323   ClassTemplateSpecializationDecl *getMostRecentDecl() {
01324     CXXRecordDecl *Recent
01325         = cast<CXXRecordDecl>(CXXRecordDecl::getMostRecentDecl());
01326     if (!isa<ClassTemplateSpecializationDecl>(Recent)) {
01327       // FIXME: Does injected class name need to be in the redeclarations chain?
01328       assert(Recent->isInjectedClassName() && Recent->getPreviousDecl());
01329       Recent = Recent->getPreviousDecl();
01330     }
01331     return cast<ClassTemplateSpecializationDecl>(Recent);
01332   }
01333 
01334   /// \brief Retrieve the template that this specialization specializes.
01335   ClassTemplateDecl *getSpecializedTemplate() const;
01336 
01337   /// \brief Retrieve the template arguments of the class template
01338   /// specialization.
01339   const TemplateArgumentList &getTemplateArgs() const {
01340     return *TemplateArgs;
01341   }
01342 
01343   /// \brief Determine the kind of specialization that this
01344   /// declaration represents.
01345   TemplateSpecializationKind getSpecializationKind() const {
01346     return static_cast<TemplateSpecializationKind>(SpecializationKind);
01347   }
01348 
01349   bool isExplicitSpecialization() const {
01350     return getSpecializationKind() == TSK_ExplicitSpecialization;
01351   }
01352 
01353   void setSpecializationKind(TemplateSpecializationKind TSK) {
01354     SpecializationKind = TSK;
01355   }
01356 
01357   /// \brief Get the point of instantiation (if any), or null if none.
01358   SourceLocation getPointOfInstantiation() const {
01359     return PointOfInstantiation;
01360   }
01361 
01362   void setPointOfInstantiation(SourceLocation Loc) {
01363     assert(Loc.isValid() && "point of instantiation must be valid!");
01364     PointOfInstantiation = Loc;
01365   }
01366 
01367   /// \brief If this class template specialization is an instantiation of
01368   /// a template (rather than an explicit specialization), return the
01369   /// class template or class template partial specialization from which it
01370   /// was instantiated.
01371   llvm::PointerUnion<ClassTemplateDecl *,
01372                      ClassTemplatePartialSpecializationDecl *>
01373   getInstantiatedFrom() const {
01374     if (getSpecializationKind() != TSK_ImplicitInstantiation &&
01375         getSpecializationKind() != TSK_ExplicitInstantiationDefinition &&
01376         getSpecializationKind() != TSK_ExplicitInstantiationDeclaration)
01377       return llvm::PointerUnion<ClassTemplateDecl *,
01378                                 ClassTemplatePartialSpecializationDecl *>();
01379 
01380     if (SpecializedPartialSpecialization *PartialSpec
01381           = SpecializedTemplate.dyn_cast<SpecializedPartialSpecialization*>())
01382       return PartialSpec->PartialSpecialization;
01383 
01384     return const_cast<ClassTemplateDecl*>(
01385                              SpecializedTemplate.get<ClassTemplateDecl*>());
01386   }
01387 
01388   /// \brief Retrieve the class template or class template partial
01389   /// specialization which was specialized by this.
01390   llvm::PointerUnion<ClassTemplateDecl *,
01391                      ClassTemplatePartialSpecializationDecl *>
01392   getSpecializedTemplateOrPartial() const {
01393     if (SpecializedPartialSpecialization *PartialSpec
01394           = SpecializedTemplate.dyn_cast<SpecializedPartialSpecialization*>())
01395       return PartialSpec->PartialSpecialization;
01396 
01397     return const_cast<ClassTemplateDecl*>(
01398                              SpecializedTemplate.get<ClassTemplateDecl*>());
01399   }
01400 
01401   /// \brief Retrieve the set of template arguments that should be used
01402   /// to instantiate members of the class template or class template partial
01403   /// specialization from which this class template specialization was
01404   /// instantiated.
01405   ///
01406   /// \returns For a class template specialization instantiated from the primary
01407   /// template, this function will return the same template arguments as
01408   /// getTemplateArgs(). For a class template specialization instantiated from
01409   /// a class template partial specialization, this function will return the
01410   /// deduced template arguments for the class template partial specialization
01411   /// itself.
01412   const TemplateArgumentList &getTemplateInstantiationArgs() const {
01413     if (SpecializedPartialSpecialization *PartialSpec
01414         = SpecializedTemplate.dyn_cast<SpecializedPartialSpecialization*>())
01415       return *PartialSpec->TemplateArgs;
01416 
01417     return getTemplateArgs();
01418   }
01419 
01420   /// \brief Note that this class template specialization is actually an
01421   /// instantiation of the given class template partial specialization whose
01422   /// template arguments have been deduced.
01423   void setInstantiationOf(ClassTemplatePartialSpecializationDecl *PartialSpec,
01424                           TemplateArgumentList *TemplateArgs) {
01425     assert(!SpecializedTemplate.is<SpecializedPartialSpecialization*>() &&
01426            "Already set to a class template partial specialization!");
01427     SpecializedPartialSpecialization *PS
01428       = new (getASTContext()) SpecializedPartialSpecialization();
01429     PS->PartialSpecialization = PartialSpec;
01430     PS->TemplateArgs = TemplateArgs;
01431     SpecializedTemplate = PS;
01432   }
01433 
01434   /// \brief Note that this class template specialization is an instantiation
01435   /// of the given class template.
01436   void setInstantiationOf(ClassTemplateDecl *TemplDecl) {
01437     assert(!SpecializedTemplate.is<SpecializedPartialSpecialization*>() &&
01438            "Previously set to a class template partial specialization!");
01439     SpecializedTemplate = TemplDecl;
01440   }
01441 
01442   /// \brief Sets the type of this specialization as it was written by
01443   /// the user. This will be a class template specialization type.
01444   void setTypeAsWritten(TypeSourceInfo *T) {
01445     if (!ExplicitInfo)
01446       ExplicitInfo = new (getASTContext()) ExplicitSpecializationInfo;
01447     ExplicitInfo->TypeAsWritten = T;
01448   }
01449   /// \brief Gets the type of this specialization as it was written by
01450   /// the user, if it was so written.
01451   TypeSourceInfo *getTypeAsWritten() const {
01452     return ExplicitInfo ? ExplicitInfo->TypeAsWritten : 0;
01453   }
01454 
01455   /// \brief Gets the location of the extern keyword, if present.
01456   SourceLocation getExternLoc() const {
01457     return ExplicitInfo ? ExplicitInfo->ExternLoc : SourceLocation();
01458   }
01459   /// \brief Sets the location of the extern keyword.
01460   void setExternLoc(SourceLocation Loc) {
01461     if (!ExplicitInfo)
01462       ExplicitInfo = new (getASTContext()) ExplicitSpecializationInfo;
01463     ExplicitInfo->ExternLoc = Loc;
01464   }
01465 
01466   /// \brief Sets the location of the template keyword.
01467   void setTemplateKeywordLoc(SourceLocation Loc) {
01468     if (!ExplicitInfo)
01469       ExplicitInfo = new (getASTContext()) ExplicitSpecializationInfo;
01470     ExplicitInfo->TemplateKeywordLoc = Loc;
01471   }
01472   /// \brief Gets the location of the template keyword, if present.
01473   SourceLocation getTemplateKeywordLoc() const {
01474     return ExplicitInfo ? ExplicitInfo->TemplateKeywordLoc : SourceLocation();
01475   }
01476 
01477   SourceRange getSourceRange() const LLVM_READONLY;
01478 
01479   void Profile(llvm::FoldingSetNodeID &ID) const {
01480     Profile(ID, TemplateArgs->data(), TemplateArgs->size(), getASTContext());
01481   }
01482 
01483   static void
01484   Profile(llvm::FoldingSetNodeID &ID, const TemplateArgument *TemplateArgs,
01485           unsigned NumTemplateArgs, ASTContext &Context) {
01486     ID.AddInteger(NumTemplateArgs);
01487     for (unsigned Arg = 0; Arg != NumTemplateArgs; ++Arg)
01488       TemplateArgs[Arg].Profile(ID, Context);
01489   }
01490 
01491   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
01492   static bool classofKind(Kind K) {
01493     return K >= firstClassTemplateSpecialization &&
01494            K <= lastClassTemplateSpecialization;
01495   }
01496 
01497   static bool classof(const ClassTemplateSpecializationDecl *) {
01498     return true;
01499   }
01500 
01501   static bool classof(const ClassTemplatePartialSpecializationDecl *) {
01502     return true;
01503   }
01504 
01505   friend class ASTDeclReader;
01506   friend class ASTDeclWriter;
01507 };
01508 
01509 class ClassTemplatePartialSpecializationDecl
01510   : public ClassTemplateSpecializationDecl {
01511   virtual void anchor();
01512 
01513   /// \brief The list of template parameters
01514   TemplateParameterList* TemplateParams;
01515 
01516   /// \brief The source info for the template arguments as written.
01517   /// FIXME: redundant with TypeAsWritten?
01518   TemplateArgumentLoc *ArgsAsWritten;
01519   unsigned NumArgsAsWritten;
01520 
01521   /// \brief Sequence number indicating when this class template partial
01522   /// specialization was added to the set of partial specializations for
01523   /// its owning class template.
01524   unsigned SequenceNumber;
01525 
01526   /// \brief The class template partial specialization from which this
01527   /// class template partial specialization was instantiated.
01528   ///
01529   /// The boolean value will be true to indicate that this class template
01530   /// partial specialization was specialized at this level.
01531   llvm::PointerIntPair<ClassTemplatePartialSpecializationDecl *, 1, bool>
01532       InstantiatedFromMember;
01533 
01534   ClassTemplatePartialSpecializationDecl(ASTContext &Context, TagKind TK,
01535                                          DeclContext *DC,
01536                                          SourceLocation StartLoc,
01537                                          SourceLocation IdLoc,
01538                                          TemplateParameterList *Params,
01539                                          ClassTemplateDecl *SpecializedTemplate,
01540                                          const TemplateArgument *Args,
01541                                          unsigned NumArgs,
01542                                          TemplateArgumentLoc *ArgInfos,
01543                                          unsigned NumArgInfos,
01544                                ClassTemplatePartialSpecializationDecl *PrevDecl,
01545                                          unsigned SequenceNumber);
01546 
01547   ClassTemplatePartialSpecializationDecl()
01548     : ClassTemplateSpecializationDecl(ClassTemplatePartialSpecialization),
01549       TemplateParams(0), ArgsAsWritten(0),
01550       NumArgsAsWritten(0), SequenceNumber(0),
01551       InstantiatedFromMember(0, false) { }
01552 
01553 public:
01554   static ClassTemplatePartialSpecializationDecl *
01555   Create(ASTContext &Context, TagKind TK, DeclContext *DC,
01556          SourceLocation StartLoc, SourceLocation IdLoc,
01557          TemplateParameterList *Params,
01558          ClassTemplateDecl *SpecializedTemplate,
01559          const TemplateArgument *Args,
01560          unsigned NumArgs,
01561          const TemplateArgumentListInfo &ArgInfos,
01562          QualType CanonInjectedType,
01563          ClassTemplatePartialSpecializationDecl *PrevDecl,
01564          unsigned SequenceNumber);
01565 
01566   static ClassTemplatePartialSpecializationDecl *
01567   CreateDeserialized(ASTContext &C, unsigned ID);
01568 
01569   ClassTemplatePartialSpecializationDecl *getMostRecentDecl() {
01570     return cast<ClassTemplatePartialSpecializationDecl>(
01571                    ClassTemplateSpecializationDecl::getMostRecentDecl());
01572   }
01573 
01574   /// Get the list of template parameters
01575   TemplateParameterList *getTemplateParameters() const {
01576     return TemplateParams;
01577   }
01578 
01579   /// Get the template arguments as written.
01580   TemplateArgumentLoc *getTemplateArgsAsWritten() const {
01581     return ArgsAsWritten;
01582   }
01583 
01584   /// Get the number of template arguments as written.
01585   unsigned getNumTemplateArgsAsWritten() const {
01586     return NumArgsAsWritten;
01587   }
01588 
01589   /// \brief Get the sequence number for this class template partial
01590   /// specialization.
01591   unsigned getSequenceNumber() const { return SequenceNumber; }
01592 
01593   /// \brief Retrieve the member class template partial specialization from
01594   /// which this particular class template partial specialization was
01595   /// instantiated.
01596   ///
01597   /// \code
01598   /// template<typename T>
01599   /// struct Outer {
01600   ///   template<typename U> struct Inner;
01601   ///   template<typename U> struct Inner<U*> { }; // #1
01602   /// };
01603   ///
01604   /// Outer<float>::Inner<int*> ii;
01605   /// \endcode
01606   ///
01607   /// In this example, the instantiation of \c Outer<float>::Inner<int*> will
01608   /// end up instantiating the partial specialization
01609   /// \c Outer<float>::Inner<U*>, which itself was instantiated from the class
01610   /// template partial specialization \c Outer<T>::Inner<U*>. Given
01611   /// \c Outer<float>::Inner<U*>, this function would return
01612   /// \c Outer<T>::Inner<U*>.
01613   ClassTemplatePartialSpecializationDecl *getInstantiatedFromMember() {
01614     ClassTemplatePartialSpecializationDecl *First
01615       = cast<ClassTemplatePartialSpecializationDecl>(getFirstDeclaration());
01616     return First->InstantiatedFromMember.getPointer();
01617   }
01618 
01619   void setInstantiatedFromMember(
01620                           ClassTemplatePartialSpecializationDecl *PartialSpec) {
01621     ClassTemplatePartialSpecializationDecl *First
01622       = cast<ClassTemplatePartialSpecializationDecl>(getFirstDeclaration());
01623     First->InstantiatedFromMember.setPointer(PartialSpec);
01624   }
01625 
01626   /// \brief Determines whether this class template partial specialization
01627   /// template was a specialization of a member partial specialization.
01628   ///
01629   /// In the following example, the member template partial specialization
01630   /// \c X<int>::Inner<T*> is a member specialization.
01631   ///
01632   /// \code
01633   /// template<typename T>
01634   /// struct X {
01635   ///   template<typename U> struct Inner;
01636   ///   template<typename U> struct Inner<U*>;
01637   /// };
01638   ///
01639   /// template<> template<typename T>
01640   /// struct X<int>::Inner<T*> { /* ... */ };
01641   /// \endcode
01642   bool isMemberSpecialization() {
01643     ClassTemplatePartialSpecializationDecl *First
01644       = cast<ClassTemplatePartialSpecializationDecl>(getFirstDeclaration());
01645     return First->InstantiatedFromMember.getInt();
01646   }
01647 
01648   /// \brief Note that this member template is a specialization.
01649   void setMemberSpecialization() {
01650     ClassTemplatePartialSpecializationDecl *First
01651       = cast<ClassTemplatePartialSpecializationDecl>(getFirstDeclaration());
01652     assert(First->InstantiatedFromMember.getPointer() &&
01653            "Only member templates can be member template specializations");
01654     return First->InstantiatedFromMember.setInt(true);
01655   }
01656 
01657   /// Retrieves the injected specialization type for this partial
01658   /// specialization.  This is not the same as the type-decl-type for
01659   /// this partial specialization, which is an InjectedClassNameType.
01660   QualType getInjectedSpecializationType() const {
01661     assert(getTypeForDecl() && "partial specialization has no type set!");
01662     return cast<InjectedClassNameType>(getTypeForDecl())
01663              ->getInjectedSpecializationType();
01664   }
01665 
01666   // FIXME: Add Profile support!
01667 
01668   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
01669   static bool classofKind(Kind K) {
01670     return K == ClassTemplatePartialSpecialization;
01671   }
01672 
01673   static bool classof(const ClassTemplatePartialSpecializationDecl *) {
01674     return true;
01675   }
01676 
01677   friend class ASTDeclReader;
01678   friend class ASTDeclWriter;
01679 };
01680 
01681 /// Declaration of a class template.
01682 class ClassTemplateDecl : public RedeclarableTemplateDecl {
01683   static void DeallocateCommon(void *Ptr);
01684 
01685 protected:
01686   /// \brief Data that is common to all of the declarations of a given
01687   /// class template.
01688   struct Common : CommonBase {
01689     Common() : LazySpecializations() { }
01690 
01691     /// \brief The class template specializations for this class
01692     /// template, including explicit specializations and instantiations.
01693     llvm::FoldingSetVector<ClassTemplateSpecializationDecl> Specializations;
01694 
01695     /// \brief The class template partial specializations for this class
01696     /// template.
01697     llvm::FoldingSetVector<ClassTemplatePartialSpecializationDecl>
01698       PartialSpecializations;
01699 
01700     /// \brief The injected-class-name type for this class template.
01701     QualType InjectedClassNameType;
01702 
01703     /// \brief If non-null, points to an array of specializations (including
01704     /// partial specializations) known ownly by their external declaration IDs.
01705     ///
01706     /// The first value in the array is the number of of specializations/
01707     /// partial specializations that follow.
01708     uint32_t *LazySpecializations;
01709   };
01710 
01711   /// \brief Load any lazily-loaded specializations from the external source.
01712   void LoadLazySpecializations();
01713 
01714   /// \brief Retrieve the set of specializations of this class template.
01715   llvm::FoldingSetVector<ClassTemplateSpecializationDecl> &getSpecializations();
01716 
01717   /// \brief Retrieve the set of partial specializations of this class
01718   /// template.
01719   llvm::FoldingSetVector<ClassTemplatePartialSpecializationDecl> &
01720   getPartialSpecializations();
01721 
01722   ClassTemplateDecl(DeclContext *DC, SourceLocation L, DeclarationName Name,
01723                     TemplateParameterList *Params, NamedDecl *Decl)
01724     : RedeclarableTemplateDecl(ClassTemplate, DC, L, Name, Params, Decl) { }
01725 
01726   ClassTemplateDecl(EmptyShell Empty)
01727     : RedeclarableTemplateDecl(ClassTemplate, 0, SourceLocation(),
01728                                DeclarationName(), 0, 0) { }
01729 
01730   CommonBase *newCommon(ASTContext &C);
01731 
01732   Common *getCommonPtr() {
01733     return static_cast<Common *>(RedeclarableTemplateDecl::getCommonPtr());
01734   }
01735 
01736 public:
01737   /// Get the underlying class declarations of the template.
01738   CXXRecordDecl *getTemplatedDecl() const {
01739     return static_cast<CXXRecordDecl *>(TemplatedDecl);
01740   }
01741 
01742   /// Returns whether this template declaration defines the primary
01743   /// class pattern.
01744   bool isThisDeclarationADefinition() const {
01745     return getTemplatedDecl()->isThisDeclarationADefinition();
01746   }
01747 
01748   /// Create a class template node.
01749   static ClassTemplateDecl *Create(ASTContext &C, DeclContext *DC,
01750                                    SourceLocation L,
01751                                    DeclarationName Name,
01752                                    TemplateParameterList *Params,
01753                                    NamedDecl *Decl,
01754                                    ClassTemplateDecl *PrevDecl);
01755 
01756   /// Create an empty class template node.
01757   static ClassTemplateDecl *CreateDeserialized(ASTContext &C, unsigned ID);
01758 
01759   /// \brief Return the specialization with the provided arguments if it exists,
01760   /// otherwise return the insertion point.
01761   ClassTemplateSpecializationDecl *
01762   findSpecialization(const TemplateArgument *Args, unsigned NumArgs,
01763                      void *&InsertPos);
01764 
01765   /// \brief Insert the specified specialization knowing that it is not already
01766   /// in. InsertPos must be obtained from findSpecialization.
01767   void AddSpecialization(ClassTemplateSpecializationDecl *D, void *InsertPos);
01768 
01769   ClassTemplateDecl *getCanonicalDecl() {
01770     return cast<ClassTemplateDecl>(
01771              RedeclarableTemplateDecl::getCanonicalDecl());
01772   }
01773   const ClassTemplateDecl *getCanonicalDecl() const {
01774     return cast<ClassTemplateDecl>(
01775              RedeclarableTemplateDecl::getCanonicalDecl());
01776   }
01777 
01778   /// \brief Retrieve the previous declaration of this class template, or
01779   /// NULL if no such declaration exists.
01780   ClassTemplateDecl *getPreviousDecl() {
01781     return cast_or_null<ClassTemplateDecl>(
01782              RedeclarableTemplateDecl::getPreviousDecl());
01783   }
01784 
01785   /// \brief Retrieve the previous declaration of this class template, or
01786   /// NULL if no such declaration exists.
01787   const ClassTemplateDecl *getPreviousDecl() const {
01788     return cast_or_null<ClassTemplateDecl>(
01789              RedeclarableTemplateDecl::getPreviousDecl());
01790   }
01791 
01792   ClassTemplateDecl *getInstantiatedFromMemberTemplate() {
01793     return cast_or_null<ClassTemplateDecl>(
01794              RedeclarableTemplateDecl::getInstantiatedFromMemberTemplate());
01795   }
01796 
01797   /// \brief Return the partial specialization with the provided arguments if it
01798   /// exists, otherwise return the insertion point.
01799   ClassTemplatePartialSpecializationDecl *
01800   findPartialSpecialization(const TemplateArgument *Args, unsigned NumArgs,
01801                             void *&InsertPos);
01802 
01803   /// \brief Insert the specified partial specialization knowing that it is not
01804   /// already in. InsertPos must be obtained from findPartialSpecialization.
01805   void AddPartialSpecialization(ClassTemplatePartialSpecializationDecl *D,
01806                                 void *InsertPos);
01807 
01808   /// \brief Return the next partial specialization sequence number.
01809   unsigned getNextPartialSpecSequenceNumber() {
01810     return getPartialSpecializations().size();
01811   }
01812 
01813   /// \brief Retrieve the partial specializations as an ordered list.
01814   void getPartialSpecializations(
01815           SmallVectorImpl<ClassTemplatePartialSpecializationDecl *> &PS);
01816 
01817   /// \brief Find a class template partial specialization with the given
01818   /// type T.
01819   ///
01820   /// \param T a dependent type that names a specialization of this class
01821   /// template.
01822   ///
01823   /// \returns the class template partial specialization that exactly matches
01824   /// the type \p T, or NULL if no such partial specialization exists.
01825   ClassTemplatePartialSpecializationDecl *findPartialSpecialization(QualType T);
01826 
01827   /// \brief Find a class template partial specialization which was instantiated
01828   /// from the given member partial specialization.
01829   ///
01830   /// \param D a member class template partial specialization.
01831   ///
01832   /// \returns the class template partial specialization which was instantiated
01833   /// from the given member partial specialization, or NULL if no such partial
01834   /// specialization exists.
01835   ClassTemplatePartialSpecializationDecl *
01836   findPartialSpecInstantiatedFromMember(
01837                                      ClassTemplatePartialSpecializationDecl *D);
01838 
01839   /// \brief Retrieve the template specialization type of the
01840   /// injected-class-name for this class template.
01841   ///
01842   /// The injected-class-name for a class template \c X is \c
01843   /// X<template-args>, where \c template-args is formed from the
01844   /// template arguments that correspond to the template parameters of
01845   /// \c X. For example:
01846   ///
01847   /// \code
01848   /// template<typename T, int N>
01849   /// struct array {
01850   ///   typedef array this_type; // "array" is equivalent to "array<T, N>"
01851   /// };
01852   /// \endcode
01853   QualType getInjectedClassNameSpecialization();
01854 
01855   typedef SpecIterator<ClassTemplateSpecializationDecl> spec_iterator;
01856 
01857   spec_iterator spec_begin() {
01858     return makeSpecIterator(getSpecializations(), false);
01859   }
01860 
01861   spec_iterator spec_end() {
01862     return makeSpecIterator(getSpecializations(), true);
01863   }
01864 
01865   typedef SpecIterator<ClassTemplatePartialSpecializationDecl>
01866           partial_spec_iterator;
01867 
01868   partial_spec_iterator partial_spec_begin() {
01869     return makeSpecIterator(getPartialSpecializations(), false);
01870   }
01871 
01872   partial_spec_iterator partial_spec_end() {
01873     return makeSpecIterator(getPartialSpecializations(), true);
01874   }
01875 
01876   // Implement isa/cast/dyncast support
01877   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
01878   static bool classof(const ClassTemplateDecl *D) { return true; }
01879   static bool classofKind(Kind K) { return K == ClassTemplate; }
01880 
01881   friend class ASTDeclReader;
01882   friend class ASTDeclWriter;
01883 };
01884 
01885 /// Declaration of a friend template.  For example:
01886 ///
01887 /// template <typename T> class A {
01888 ///   friend class MyVector<T>; // not a friend template
01889 ///   template <typename U> friend class B; // not a friend template
01890 ///   template <typename U> friend class Foo<T>::Nested; // friend template
01891 /// };
01892 /// NOTE: This class is not currently in use.  All of the above
01893 /// will yield a FriendDecl, not a FriendTemplateDecl.
01894 class FriendTemplateDecl : public Decl {
01895   virtual void anchor();
01896 public:
01897   typedef llvm::PointerUnion<NamedDecl*,TypeSourceInfo*> FriendUnion;
01898 
01899 private:
01900   // The number of template parameters;  always non-zero.
01901   unsigned NumParams;
01902 
01903   // The parameter list.
01904   TemplateParameterList **Params;
01905 
01906   // The declaration that's a friend of this class.
01907   FriendUnion Friend;
01908 
01909   // Location of the 'friend' specifier.
01910   SourceLocation FriendLoc;
01911 
01912 
01913   FriendTemplateDecl(DeclContext *DC, SourceLocation Loc,
01914                      unsigned NParams,
01915                      TemplateParameterList **Params,
01916                      FriendUnion Friend,
01917                      SourceLocation FriendLoc)
01918     : Decl(Decl::FriendTemplate, DC, Loc),
01919       NumParams(NParams),
01920       Params(Params),
01921       Friend(Friend),
01922       FriendLoc(FriendLoc)
01923   {}
01924 
01925   FriendTemplateDecl(EmptyShell Empty)
01926     : Decl(Decl::FriendTemplate, Empty),
01927       NumParams(0),
01928       Params(0)
01929   {}
01930 
01931 public:
01932   static FriendTemplateDecl *Create(ASTContext &Context,
01933                                     DeclContext *DC, SourceLocation Loc,
01934                                     unsigned NParams,
01935                                     TemplateParameterList **Params,
01936                                     FriendUnion Friend,
01937                                     SourceLocation FriendLoc);
01938 
01939   static FriendTemplateDecl *CreateDeserialized(ASTContext &C, unsigned ID);
01940 
01941   /// If this friend declaration names a templated type (or
01942   /// a dependent member type of a templated type), return that
01943   /// type;  otherwise return null.
01944   TypeSourceInfo *getFriendType() const {
01945     return Friend.dyn_cast<TypeSourceInfo*>();
01946   }
01947 
01948   /// If this friend declaration names a templated function (or
01949   /// a member function of a templated type), return that type;
01950   /// otherwise return null.
01951   NamedDecl *getFriendDecl() const {
01952     return Friend.dyn_cast<NamedDecl*>();
01953   }
01954 
01955   /// Retrieves the location of the 'friend' keyword.
01956   SourceLocation getFriendLoc() const {
01957     return FriendLoc;
01958   }
01959 
01960   TemplateParameterList *getTemplateParameterList(unsigned i) const {
01961     assert(i <= NumParams);
01962     return Params[i];
01963   }
01964 
01965   unsigned getNumTemplateParameters() const {
01966     return NumParams;
01967   }
01968 
01969   // Implement isa/cast/dyncast/etc.
01970   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
01971   static bool classofKind(Kind K) { return K == Decl::FriendTemplate; }
01972   static bool classof(const FriendTemplateDecl *D) { return true; }
01973 
01974   friend class ASTDeclReader;
01975 };
01976 
01977 /// Declaration of an alias template.  For example:
01978 ///
01979 /// template <typename T> using V = std::map<T*, int, MyCompare<T>>;
01980 class TypeAliasTemplateDecl : public RedeclarableTemplateDecl {
01981   static void DeallocateCommon(void *Ptr);
01982 
01983 protected:
01984   typedef CommonBase Common;
01985 
01986   TypeAliasTemplateDecl(DeclContext *DC, SourceLocation L, DeclarationName Name,
01987                         TemplateParameterList *Params, NamedDecl *Decl)
01988     : RedeclarableTemplateDecl(TypeAliasTemplate, DC, L, Name, Params, Decl) { }
01989 
01990   CommonBase *newCommon(ASTContext &C);
01991 
01992   Common *getCommonPtr() {
01993     return static_cast<Common *>(RedeclarableTemplateDecl::getCommonPtr());
01994   }
01995 
01996 public:
01997   /// Get the underlying function declaration of the template.
01998   TypeAliasDecl *getTemplatedDecl() const {
01999     return static_cast<TypeAliasDecl*>(TemplatedDecl);
02000   }
02001 
02002 
02003   TypeAliasTemplateDecl *getCanonicalDecl() {
02004     return cast<TypeAliasTemplateDecl>(
02005              RedeclarableTemplateDecl::getCanonicalDecl());
02006   }
02007   const TypeAliasTemplateDecl *getCanonicalDecl() const {
02008     return cast<TypeAliasTemplateDecl>(
02009              RedeclarableTemplateDecl::getCanonicalDecl());
02010   }
02011 
02012   /// \brief Retrieve the previous declaration of this function template, or
02013   /// NULL if no such declaration exists.
02014   TypeAliasTemplateDecl *getPreviousDecl() {
02015     return cast_or_null<TypeAliasTemplateDecl>(
02016              RedeclarableTemplateDecl::getPreviousDecl());
02017   }
02018 
02019   /// \brief Retrieve the previous declaration of this function template, or
02020   /// NULL if no such declaration exists.
02021   const TypeAliasTemplateDecl *getPreviousDecl() const {
02022     return cast_or_null<TypeAliasTemplateDecl>(
02023              RedeclarableTemplateDecl::getPreviousDecl());
02024   }
02025 
02026   TypeAliasTemplateDecl *getInstantiatedFromMemberTemplate() {
02027     return cast_or_null<TypeAliasTemplateDecl>(
02028              RedeclarableTemplateDecl::getInstantiatedFromMemberTemplate());
02029   }
02030 
02031 
02032   /// \brief Create a function template node.
02033   static TypeAliasTemplateDecl *Create(ASTContext &C, DeclContext *DC,
02034                                        SourceLocation L,
02035                                        DeclarationName Name,
02036                                        TemplateParameterList *Params,
02037                                        NamedDecl *Decl);
02038 
02039   /// \brief Create an empty alias template node.
02040   static TypeAliasTemplateDecl *CreateDeserialized(ASTContext &C, unsigned ID);
02041 
02042   // Implement isa/cast/dyncast support
02043   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
02044   static bool classof(const TypeAliasTemplateDecl *D) { return true; }
02045   static bool classofKind(Kind K) { return K == TypeAliasTemplate; }
02046 
02047   friend class ASTDeclReader;
02048   friend class ASTDeclWriter;
02049 };
02050 
02051 /// Declaration of a function specialization at template class scope.
02052 /// This is a non standard extension needed to support MSVC.
02053 /// For example:
02054 /// template <class T>
02055 /// class A {
02056 ///    template <class U> void foo(U a) { }
02057 ///    template<> void foo(int a) { }
02058 /// }
02059 ///
02060 /// "template<> foo(int a)" will be saved in Specialization as a normal
02061 /// CXXMethodDecl. Then during an instantiation of class A, it will be
02062 /// transformed into an actual function specialization.
02063 class ClassScopeFunctionSpecializationDecl : public Decl {
02064   virtual void anchor();
02065 
02066   ClassScopeFunctionSpecializationDecl(DeclContext *DC, SourceLocation Loc,
02067                                        CXXMethodDecl *FD)
02068     : Decl(Decl::ClassScopeFunctionSpecialization, DC, Loc),
02069       Specialization(FD) {}
02070 
02071   ClassScopeFunctionSpecializationDecl(EmptyShell Empty)
02072     : Decl(Decl::ClassScopeFunctionSpecialization, Empty) {}
02073 
02074   CXXMethodDecl *Specialization;
02075 
02076 public:
02077   CXXMethodDecl *getSpecialization() const { return Specialization; }
02078 
02079   static ClassScopeFunctionSpecializationDecl *Create(ASTContext &C,
02080                                                       DeclContext *DC,
02081                                                       SourceLocation Loc,
02082                                                       CXXMethodDecl *FD) {
02083     return new (C) ClassScopeFunctionSpecializationDecl(DC , Loc, FD);
02084   }
02085 
02086   static ClassScopeFunctionSpecializationDecl *
02087   CreateDeserialized(ASTContext &Context, unsigned ID);
02088   
02089   // Implement isa/cast/dyncast/etc.
02090   static bool classof(const Decl *D) { return classofKind(D->getKind()); }
02091   static bool classofKind(Kind K) {
02092     return K == Decl::ClassScopeFunctionSpecialization;
02093   }
02094   static bool classof(const ClassScopeFunctionSpecializationDecl *D) {
02095     return true;
02096   }
02097 
02098   friend class ASTDeclReader;
02099   friend class ASTDeclWriter;
02100 };
02101 
02102 /// Implementation of inline functions that require the template declarations
02103 inline AnyFunctionDecl::AnyFunctionDecl(FunctionTemplateDecl *FTD)
02104   : Function(FTD) { }
02105 
02106 } /* end of namespace clang */
02107 
02108 #endif