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