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