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