1 //===- DeclTemplate.h - Classes for representing C++ templates --*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 /// \brief Defines the C++ template declaration subclasses.
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_CLANG_AST_DECLTEMPLATE_H
16 #define LLVM_CLANG_AST_DECLTEMPLATE_H
18 #include "clang/AST/Decl.h"
19 #include "clang/AST/DeclBase.h"
20 #include "clang/AST/DeclCXX.h"
21 #include "clang/AST/DeclarationName.h"
22 #include "clang/AST/Redeclarable.h"
23 #include "clang/AST/TemplateBase.h"
24 #include "clang/AST/Type.h"
25 #include "clang/Basic/LLVM.h"
26 #include "clang/Basic/SourceLocation.h"
27 #include "clang/Basic/Specifiers.h"
28 #include "llvm/ADT/ArrayRef.h"
29 #include "llvm/ADT/FoldingSet.h"
30 #include "llvm/ADT/PointerIntPair.h"
31 #include "llvm/ADT/PointerUnion.h"
32 #include "llvm/ADT/iterator.h"
33 #include "llvm/ADT/iterator_range.h"
34 #include "llvm/Support/Casting.h"
35 #include "llvm/Support/Compiler.h"
36 #include "llvm/Support/TrailingObjects.h"
45 enum BuiltinTemplateKind : int;
46 class ClassTemplateDecl;
47 class ClassTemplatePartialSpecializationDecl;
49 class FunctionTemplateDecl;
51 class NonTypeTemplateParmDecl;
53 class TemplateTemplateParmDecl;
54 class TemplateTypeParmDecl;
55 class UnresolvedSetImpl;
56 class VarTemplateDecl;
57 class VarTemplatePartialSpecializationDecl;
59 /// \brief Stores a template parameter of any kind.
60 using TemplateParameter =
61 llvm::PointerUnion3<TemplateTypeParmDecl *, NonTypeTemplateParmDecl *,
62 TemplateTemplateParmDecl *>;
64 NamedDecl *getAsNamedDecl(TemplateParameter P);
66 /// \brief Stores a list of template parameters for a TemplateDecl and its
68 class TemplateParameterList final
69 : private llvm::TrailingObjects<TemplateParameterList, NamedDecl *,
71 /// The location of the 'template' keyword.
72 SourceLocation TemplateLoc;
74 /// The locations of the '<' and '>' angle brackets.
75 SourceLocation LAngleLoc, RAngleLoc;
77 /// The number of template parameters in this template
79 unsigned NumParams : 30;
81 /// Whether this template parameter list contains an unexpanded parameter
83 unsigned ContainsUnexpandedParameterPack : 1;
85 /// Whether this template parameter list has an associated requires-clause
86 unsigned HasRequiresClause : 1;
89 TemplateParameterList(SourceLocation TemplateLoc, SourceLocation LAngleLoc,
90 ArrayRef<NamedDecl *> Params, SourceLocation RAngleLoc,
91 Expr *RequiresClause);
93 size_t numTrailingObjects(OverloadToken<NamedDecl *>) const {
97 size_t numTrailingObjects(OverloadToken<Expr *>) const {
98 return HasRequiresClause;
102 template <size_t N, bool HasRequiresClause>
103 friend class FixedSizeTemplateParameterListStorage;
104 friend TrailingObjects;
106 static TemplateParameterList *Create(const ASTContext &C,
107 SourceLocation TemplateLoc,
108 SourceLocation LAngleLoc,
109 ArrayRef<NamedDecl *> Params,
110 SourceLocation RAngleLoc,
111 Expr *RequiresClause);
113 /// \brief Iterates through the template parameters in this list.
114 using iterator = NamedDecl **;
116 /// \brief Iterates through the template parameters in this list.
117 using const_iterator = NamedDecl * const *;
119 iterator begin() { return getTrailingObjects<NamedDecl *>(); }
120 const_iterator begin() const { return getTrailingObjects<NamedDecl *>(); }
121 iterator end() { return begin() + NumParams; }
122 const_iterator end() const { return begin() + NumParams; }
124 unsigned size() const { return NumParams; }
126 ArrayRef<NamedDecl*> asArray() {
127 return llvm::makeArrayRef(begin(), end());
129 ArrayRef<const NamedDecl*> asArray() const {
130 return llvm::makeArrayRef(begin(), size());
133 NamedDecl* getParam(unsigned Idx) {
134 assert(Idx < size() && "Template parameter index out-of-range");
137 const NamedDecl* getParam(unsigned Idx) const {
138 assert(Idx < size() && "Template parameter index out-of-range");
142 /// \brief Returns the minimum number of arguments needed to form a
143 /// template specialization.
145 /// This may be fewer than the number of template parameters, if some of
146 /// the parameters have default arguments or if there is a parameter pack.
147 unsigned getMinRequiredArguments() const;
149 /// \brief Get the depth of this template parameter list in the set of
150 /// template parameter lists.
152 /// The first template parameter list in a declaration will have depth 0,
153 /// the second template parameter list will have depth 1, etc.
154 unsigned getDepth() const;
156 /// \brief Determine whether this template parameter list contains an
157 /// unexpanded parameter pack.
158 bool containsUnexpandedParameterPack() const {
159 return ContainsUnexpandedParameterPack;
162 /// \brief The constraint-expression of the associated requires-clause.
163 Expr *getRequiresClause() {
164 return HasRequiresClause ? *getTrailingObjects<Expr *>() : nullptr;
167 /// \brief The constraint-expression of the associated requires-clause.
168 const Expr *getRequiresClause() const {
169 return HasRequiresClause ? *getTrailingObjects<Expr *>() : nullptr;
172 SourceLocation getTemplateLoc() const { return TemplateLoc; }
173 SourceLocation getLAngleLoc() const { return LAngleLoc; }
174 SourceLocation getRAngleLoc() const { return RAngleLoc; }
176 SourceRange getSourceRange() const LLVM_READONLY {
177 return SourceRange(TemplateLoc, RAngleLoc);
181 // FIXME: workaround for MSVC 2013; remove when no longer needed
182 using FixedSizeStorageOwner = TrailingObjects::FixedSizeStorageOwner;
185 /// \brief Stores a list of template parameters and the associated
186 /// requires-clause (if any) for a TemplateDecl and its derived classes.
187 /// Suitable for creating on the stack.
188 template <size_t N, bool HasRequiresClause>
189 class FixedSizeTemplateParameterListStorage
190 : public TemplateParameterList::FixedSizeStorageOwner {
191 typename TemplateParameterList::FixedSizeStorage<
192 NamedDecl *, Expr *>::with_counts<
193 N, HasRequiresClause ? 1u : 0u
197 FixedSizeTemplateParameterListStorage(SourceLocation TemplateLoc,
198 SourceLocation LAngleLoc,
199 ArrayRef<NamedDecl *> Params,
200 SourceLocation RAngleLoc,
201 Expr *RequiresClause)
202 : FixedSizeStorageOwner(
203 (assert(N == Params.size()),
204 assert(HasRequiresClause == static_cast<bool>(RequiresClause)),
205 new (static_cast<void *>(&storage)) TemplateParameterList(
206 TemplateLoc, LAngleLoc, Params, RAngleLoc, RequiresClause))) {}
209 /// \brief A template argument list.
210 class TemplateArgumentList final
211 : private llvm::TrailingObjects<TemplateArgumentList, TemplateArgument> {
212 /// \brief The template argument list.
213 const TemplateArgument *Arguments;
215 /// \brief The number of template arguments in this template
217 unsigned NumArguments;
219 // Constructs an instance with an internal Argument list, containing
220 // a copy of the Args array. (Called by CreateCopy)
221 TemplateArgumentList(ArrayRef<TemplateArgument> Args);
224 friend TrailingObjects;
226 TemplateArgumentList(const TemplateArgumentList &) = delete;
227 TemplateArgumentList &operator=(const TemplateArgumentList &) = delete;
229 /// \brief Type used to indicate that the template argument list itself is a
230 /// stack object. It does not own its template arguments.
231 enum OnStackType { OnStack };
233 /// \brief Create a new template argument list that copies the given set of
234 /// template arguments.
235 static TemplateArgumentList *CreateCopy(ASTContext &Context,
236 ArrayRef<TemplateArgument> Args);
238 /// \brief Construct a new, temporary template argument list on the stack.
240 /// The template argument list does not own the template arguments
242 explicit TemplateArgumentList(OnStackType, ArrayRef<TemplateArgument> Args)
243 : Arguments(Args.data()), NumArguments(Args.size()) {}
245 /// \brief Produces a shallow copy of the given template argument list.
247 /// This operation assumes that the input argument list outlives it.
248 /// This takes the list as a pointer to avoid looking like a copy
249 /// constructor, since this really really isn't safe to use that
251 explicit TemplateArgumentList(const TemplateArgumentList *Other)
252 : Arguments(Other->data()), NumArguments(Other->size()) {}
254 /// \brief Retrieve the template argument at a given index.
255 const TemplateArgument &get(unsigned Idx) const {
256 assert(Idx < NumArguments && "Invalid template argument index");
260 /// \brief Retrieve the template argument at a given index.
261 const TemplateArgument &operator[](unsigned Idx) const { return get(Idx); }
263 /// \brief Produce this as an array ref.
264 ArrayRef<TemplateArgument> asArray() const {
265 return llvm::makeArrayRef(data(), size());
268 /// \brief Retrieve the number of template arguments in this
269 /// template argument list.
270 unsigned size() const { return NumArguments; }
272 /// \brief Retrieve a pointer to the template argument list.
273 const TemplateArgument *data() const { return Arguments; }
276 void *allocateDefaultArgStorageChain(const ASTContext &C);
278 /// Storage for a default argument. This is conceptually either empty, or an
279 /// argument value, or a pointer to a previous declaration that had a default
282 /// However, this is complicated by modules: while we require all the default
283 /// arguments for a template to be equivalent, there may be more than one, and
284 /// we need to track all the originating parameters to determine if the default
285 /// argument is visible.
286 template<typename ParmDecl, typename ArgType>
287 class DefaultArgStorage {
288 /// Storage for both the value *and* another parameter from which we inherit
289 /// the default argument. This is used when multiple default arguments for a
290 /// parameter are merged together from different modules.
292 ParmDecl *PrevDeclWithDefaultArg;
295 static_assert(sizeof(Chain) == sizeof(void *) * 2,
296 "non-pointer argument type?");
298 llvm::PointerUnion3<ArgType, ParmDecl*, Chain*> ValueOrInherited;
300 static ParmDecl *getParmOwningDefaultArg(ParmDecl *Parm) {
301 const DefaultArgStorage &Storage = Parm->getDefaultArgStorage();
302 if (auto *Prev = Storage.ValueOrInherited.template dyn_cast<ParmDecl*>())
304 assert(!Parm->getDefaultArgStorage()
305 .ValueOrInherited.template is<ParmDecl *>() &&
306 "should only be one level of indirection");
311 DefaultArgStorage() : ValueOrInherited(ArgType()) {}
313 /// Determine whether there is a default argument for this parameter.
314 bool isSet() const { return !ValueOrInherited.isNull(); }
316 /// Determine whether the default argument for this parameter was inherited
317 /// from a previous declaration of the same entity.
318 bool isInherited() const { return ValueOrInherited.template is<ParmDecl*>(); }
320 /// Get the default argument's value. This does not consider whether the
321 /// default argument is visible.
322 ArgType get() const {
323 const DefaultArgStorage *Storage = this;
324 if (auto *Prev = ValueOrInherited.template dyn_cast<ParmDecl*>())
325 Storage = &Prev->getDefaultArgStorage();
326 if (auto *C = Storage->ValueOrInherited.template dyn_cast<Chain*>())
328 return Storage->ValueOrInherited.template get<ArgType>();
331 /// Get the parameter from which we inherit the default argument, if any.
332 /// This is the parameter on which the default argument was actually written.
333 const ParmDecl *getInheritedFrom() const {
334 if (auto *D = ValueOrInherited.template dyn_cast<ParmDecl*>())
336 if (auto *C = ValueOrInherited.template dyn_cast<Chain*>())
337 return C->PrevDeclWithDefaultArg;
341 /// Set the default argument.
342 void set(ArgType Arg) {
343 assert(!isSet() && "default argument already set");
344 ValueOrInherited = Arg;
347 /// Set that the default argument was inherited from another parameter.
348 void setInherited(const ASTContext &C, ParmDecl *InheritedFrom) {
349 assert(!isInherited() && "default argument already inherited");
350 InheritedFrom = getParmOwningDefaultArg(InheritedFrom);
352 ValueOrInherited = InheritedFrom;
354 ValueOrInherited = new (allocateDefaultArgStorageChain(C))
355 Chain{InheritedFrom, ValueOrInherited.template get<ArgType>()};
358 /// Remove the default argument, even if it was inherited.
360 ValueOrInherited = ArgType();
364 //===----------------------------------------------------------------------===//
365 // Kinds of Templates
366 //===----------------------------------------------------------------------===//
368 /// \brief Stores the template parameter list and associated constraints for
369 /// \c TemplateDecl objects that track associated constraints.
370 class ConstrainedTemplateDeclInfo {
374 ConstrainedTemplateDeclInfo() = default;
376 TemplateParameterList *getTemplateParameters() const {
377 return TemplateParams;
380 Expr *getAssociatedConstraints() const { return AssociatedConstraints; }
383 void setTemplateParameters(TemplateParameterList *TParams) {
384 TemplateParams = TParams;
387 void setAssociatedConstraints(Expr *AC) { AssociatedConstraints = AC; }
389 TemplateParameterList *TemplateParams = nullptr;
390 Expr *AssociatedConstraints = nullptr;
394 /// \brief The base class of all kinds of template declarations (e.g.,
395 /// class, function, etc.).
397 /// The TemplateDecl class stores the list of template parameters and a
398 /// reference to the templated scoped declaration: the underlying AST node.
399 class TemplateDecl : public NamedDecl {
400 void anchor() override;
403 // Construct a template decl with the given name and parameters.
404 // Used when there is no templated element (e.g., for tt-params).
405 TemplateDecl(ConstrainedTemplateDeclInfo *CTDI, Kind DK, DeclContext *DC,
406 SourceLocation L, DeclarationName Name,
407 TemplateParameterList *Params)
408 : NamedDecl(DK, DC, L, Name), TemplatedDecl(nullptr),
409 TemplateParams(CTDI) {
410 this->setTemplateParameters(Params);
413 TemplateDecl(Kind DK, DeclContext *DC, SourceLocation L, DeclarationName Name,
414 TemplateParameterList *Params)
415 : TemplateDecl(nullptr, DK, DC, L, Name, Params) {}
417 // Construct a template decl with name, parameters, and templated element.
418 TemplateDecl(ConstrainedTemplateDeclInfo *CTDI, Kind DK, DeclContext *DC,
419 SourceLocation L, DeclarationName Name,
420 TemplateParameterList *Params, NamedDecl *Decl)
421 : NamedDecl(DK, DC, L, Name), TemplatedDecl(Decl),
422 TemplateParams(CTDI) {
423 this->setTemplateParameters(Params);
426 TemplateDecl(Kind DK, DeclContext *DC, SourceLocation L, DeclarationName Name,
427 TemplateParameterList *Params, NamedDecl *Decl)
428 : TemplateDecl(nullptr, DK, DC, L, Name, Params, Decl) {}
431 /// Get the list of template parameters
432 TemplateParameterList *getTemplateParameters() const {
433 const auto *const CTDI =
434 TemplateParams.dyn_cast<ConstrainedTemplateDeclInfo *>();
435 return CTDI ? CTDI->getTemplateParameters()
436 : TemplateParams.get<TemplateParameterList *>();
439 /// Get the constraint-expression from the associated requires-clause (if any)
440 const Expr *getRequiresClause() const {
441 const TemplateParameterList *const TP = getTemplateParameters();
442 return TP ? TP->getRequiresClause() : nullptr;
445 Expr *getAssociatedConstraints() const {
446 const TemplateDecl *const C = cast<TemplateDecl>(getCanonicalDecl());
447 const auto *const CTDI =
448 C->TemplateParams.dyn_cast<ConstrainedTemplateDeclInfo *>();
449 return CTDI ? CTDI->getAssociatedConstraints() : nullptr;
452 /// Get the underlying, templated declaration.
453 NamedDecl *getTemplatedDecl() const { return TemplatedDecl; }
455 // Implement isa/cast/dyncast/etc.
456 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
458 static bool classofKind(Kind K) {
459 return K >= firstTemplate && K <= lastTemplate;
462 SourceRange getSourceRange() const override LLVM_READONLY {
463 return SourceRange(getTemplateParameters()->getTemplateLoc(),
464 TemplatedDecl->getSourceRange().getEnd());
468 NamedDecl *TemplatedDecl;
469 /// \brief The template parameter list and optional requires-clause
470 /// associated with this declaration; alternatively, a
471 /// \c ConstrainedTemplateDeclInfo if the associated constraints of the
472 /// template are being tracked by this particular declaration.
473 llvm::PointerUnion<TemplateParameterList *,
474 ConstrainedTemplateDeclInfo *>
477 void setTemplateParameters(TemplateParameterList *TParams) {
478 if (auto *const CTDI =
479 TemplateParams.dyn_cast<ConstrainedTemplateDeclInfo *>()) {
480 CTDI->setTemplateParameters(TParams);
482 TemplateParams = TParams;
486 void setAssociatedConstraints(Expr *AC) {
487 assert(isCanonicalDecl() &&
488 "Attaching associated constraints to non-canonical Decl");
489 TemplateParams.get<ConstrainedTemplateDeclInfo *>()
490 ->setAssociatedConstraints(AC);
494 /// \brief Initialize the underlying templated declaration and
495 /// template parameters.
496 void init(NamedDecl *templatedDecl, TemplateParameterList* templateParams) {
497 assert(!TemplatedDecl && "TemplatedDecl already set!");
498 assert(!TemplateParams && "TemplateParams already set!");
499 TemplatedDecl = templatedDecl;
500 TemplateParams = templateParams;
504 /// \brief Provides information about a function template specialization,
505 /// which is a FunctionDecl that has been explicitly specialization or
506 /// instantiated from a function template.
507 class FunctionTemplateSpecializationInfo : public llvm::FoldingSetNode {
508 FunctionTemplateSpecializationInfo(FunctionDecl *FD,
509 FunctionTemplateDecl *Template,
510 TemplateSpecializationKind TSK,
511 const TemplateArgumentList *TemplateArgs,
512 const ASTTemplateArgumentListInfo *TemplateArgsAsWritten,
514 : Function(FD), Template(Template, TSK - 1),
515 TemplateArguments(TemplateArgs),
516 TemplateArgumentsAsWritten(TemplateArgsAsWritten),
517 PointOfInstantiation(POI) {}
520 static FunctionTemplateSpecializationInfo *
521 Create(ASTContext &C, FunctionDecl *FD, FunctionTemplateDecl *Template,
522 TemplateSpecializationKind TSK,
523 const TemplateArgumentList *TemplateArgs,
524 const TemplateArgumentListInfo *TemplateArgsAsWritten,
527 /// \brief The function template specialization that this structure
529 FunctionDecl *Function;
531 /// \brief The function template from which this function template
532 /// specialization was generated.
534 /// The two bits contain the top 4 values of TemplateSpecializationKind.
535 llvm::PointerIntPair<FunctionTemplateDecl *, 2> Template;
537 /// \brief The template arguments used to produce the function template
538 /// specialization from the function template.
539 const TemplateArgumentList *TemplateArguments;
541 /// \brief The template arguments as written in the sources, if provided.
542 const ASTTemplateArgumentListInfo *TemplateArgumentsAsWritten;
544 /// \brief The point at which this function template specialization was
545 /// first instantiated.
546 SourceLocation PointOfInstantiation;
548 /// \brief Retrieve the template from which this function was specialized.
549 FunctionTemplateDecl *getTemplate() const { return Template.getPointer(); }
551 /// \brief Determine what kind of template specialization this is.
552 TemplateSpecializationKind getTemplateSpecializationKind() const {
553 return (TemplateSpecializationKind)(Template.getInt() + 1);
556 bool isExplicitSpecialization() const {
557 return getTemplateSpecializationKind() == TSK_ExplicitSpecialization;
560 /// \brief True if this declaration is an explicit specialization,
561 /// explicit instantiation declaration, or explicit instantiation
563 bool isExplicitInstantiationOrSpecialization() const {
564 return isTemplateExplicitInstantiationOrSpecialization(
565 getTemplateSpecializationKind());
568 /// \brief Set the template specialization kind.
569 void setTemplateSpecializationKind(TemplateSpecializationKind TSK) {
570 assert(TSK != TSK_Undeclared &&
571 "Cannot encode TSK_Undeclared for a function template specialization");
572 Template.setInt(TSK - 1);
575 /// \brief Retrieve the first point of instantiation of this function
576 /// template specialization.
578 /// The point of instantiation may be an invalid source location if this
579 /// function has yet to be instantiated.
580 SourceLocation getPointOfInstantiation() const {
581 return PointOfInstantiation;
584 /// \brief Set the (first) point of instantiation of this function template
586 void setPointOfInstantiation(SourceLocation POI) {
587 PointOfInstantiation = POI;
590 void Profile(llvm::FoldingSetNodeID &ID) {
591 Profile(ID, TemplateArguments->asArray(),
592 Function->getASTContext());
596 Profile(llvm::FoldingSetNodeID &ID, ArrayRef<TemplateArgument> TemplateArgs,
597 ASTContext &Context) {
598 ID.AddInteger(TemplateArgs.size());
599 for (const TemplateArgument &TemplateArg : TemplateArgs)
600 TemplateArg.Profile(ID, Context);
604 /// \brief Provides information a specialization of a member of a class
605 /// template, which may be a member function, static data member,
606 /// member class or member enumeration.
607 class MemberSpecializationInfo {
608 // The member declaration from which this member was instantiated, and the
609 // manner in which the instantiation occurred (in the lower two bits).
610 llvm::PointerIntPair<NamedDecl *, 2> MemberAndTSK;
612 // The point at which this member was first instantiated.
613 SourceLocation PointOfInstantiation;
617 MemberSpecializationInfo(NamedDecl *IF, TemplateSpecializationKind TSK,
618 SourceLocation POI = SourceLocation())
619 : MemberAndTSK(IF, TSK - 1), PointOfInstantiation(POI) {
620 assert(TSK != TSK_Undeclared &&
621 "Cannot encode undeclared template specializations for members");
624 /// \brief Retrieve the member declaration from which this member was
626 NamedDecl *getInstantiatedFrom() const { return MemberAndTSK.getPointer(); }
628 /// \brief Determine what kind of template specialization this is.
629 TemplateSpecializationKind getTemplateSpecializationKind() const {
630 return (TemplateSpecializationKind)(MemberAndTSK.getInt() + 1);
633 bool isExplicitSpecialization() const {
634 return getTemplateSpecializationKind() == TSK_ExplicitSpecialization;
637 /// \brief Set the template specialization kind.
638 void setTemplateSpecializationKind(TemplateSpecializationKind TSK) {
639 assert(TSK != TSK_Undeclared &&
640 "Cannot encode undeclared template specializations for members");
641 MemberAndTSK.setInt(TSK - 1);
644 /// \brief Retrieve the first point of instantiation of this member.
645 /// If the point of instantiation is an invalid location, then this member
646 /// has not yet been instantiated.
647 SourceLocation getPointOfInstantiation() const {
648 return PointOfInstantiation;
651 /// \brief Set the first point of instantiation.
652 void setPointOfInstantiation(SourceLocation POI) {
653 PointOfInstantiation = POI;
657 /// \brief Provides information about a dependent function-template
658 /// specialization declaration.
660 /// Since explicit function template specialization and instantiation
661 /// declarations can only appear in namespace scope, and you can only
662 /// specialize a member of a fully-specialized class, the only way to
663 /// get one of these is in a friend declaration like the following:
666 /// template \<class T> void foo(T);
667 /// template \<class T> class A {
668 /// friend void foo<>(T);
671 class DependentFunctionTemplateSpecializationInfo final
672 : private llvm::TrailingObjects<DependentFunctionTemplateSpecializationInfo,
674 FunctionTemplateDecl *> {
675 /// The number of potential template candidates.
676 unsigned NumTemplates;
678 /// The number of template arguments.
681 /// The locations of the left and right angle brackets.
682 SourceRange AngleLocs;
684 size_t numTrailingObjects(OverloadToken<TemplateArgumentLoc>) const {
687 size_t numTrailingObjects(OverloadToken<FunctionTemplateDecl *>) const {
691 DependentFunctionTemplateSpecializationInfo(
692 const UnresolvedSetImpl &Templates,
693 const TemplateArgumentListInfo &TemplateArgs);
696 friend TrailingObjects;
698 static DependentFunctionTemplateSpecializationInfo *
699 Create(ASTContext &Context, const UnresolvedSetImpl &Templates,
700 const TemplateArgumentListInfo &TemplateArgs);
702 /// \brief Returns the number of function templates that this might
703 /// be a specialization of.
704 unsigned getNumTemplates() const { return NumTemplates; }
706 /// \brief Returns the i'th template candidate.
707 FunctionTemplateDecl *getTemplate(unsigned I) const {
708 assert(I < getNumTemplates() && "template index out of range");
709 return getTrailingObjects<FunctionTemplateDecl *>()[I];
712 /// \brief Returns the explicit template arguments that were given.
713 const TemplateArgumentLoc *getTemplateArgs() const {
714 return getTrailingObjects<TemplateArgumentLoc>();
717 /// \brief Returns the number of explicit template arguments that were given.
718 unsigned getNumTemplateArgs() const { return NumArgs; }
720 /// \brief Returns the nth template argument.
721 const TemplateArgumentLoc &getTemplateArg(unsigned I) const {
722 assert(I < getNumTemplateArgs() && "template arg index out of range");
723 return getTemplateArgs()[I];
726 SourceLocation getLAngleLoc() const {
727 return AngleLocs.getBegin();
730 SourceLocation getRAngleLoc() const {
731 return AngleLocs.getEnd();
735 /// Declaration of a redeclarable template.
736 class RedeclarableTemplateDecl : public TemplateDecl,
737 public Redeclarable<RedeclarableTemplateDecl>
739 using redeclarable_base = Redeclarable<RedeclarableTemplateDecl>;
741 RedeclarableTemplateDecl *getNextRedeclarationImpl() override {
742 return getNextRedeclaration();
745 RedeclarableTemplateDecl *getPreviousDeclImpl() override {
746 return getPreviousDecl();
749 RedeclarableTemplateDecl *getMostRecentDeclImpl() override {
750 return getMostRecentDecl();
754 template <typename EntryType> struct SpecEntryTraits {
755 using DeclType = EntryType;
757 static DeclType *getDecl(EntryType *D) {
761 static ArrayRef<TemplateArgument> getTemplateArgs(EntryType *D) {
762 return D->getTemplateArgs().asArray();
766 template <typename EntryType, typename SETraits = SpecEntryTraits<EntryType>,
767 typename DeclType = typename SETraits::DeclType>
769 : llvm::iterator_adaptor_base<
770 SpecIterator<EntryType, SETraits, DeclType>,
771 typename llvm::FoldingSetVector<EntryType>::iterator,
772 typename std::iterator_traits<typename llvm::FoldingSetVector<
773 EntryType>::iterator>::iterator_category,
774 DeclType *, ptrdiff_t, DeclType *, DeclType *> {
775 SpecIterator() = default;
776 explicit SpecIterator(
777 typename llvm::FoldingSetVector<EntryType>::iterator SetIter)
778 : SpecIterator::iterator_adaptor_base(std::move(SetIter)) {}
780 DeclType *operator*() const {
781 return SETraits::getDecl(&*this->I)->getMostRecentDecl();
784 DeclType *operator->() const { return **this; }
787 template <typename EntryType>
788 static SpecIterator<EntryType>
789 makeSpecIterator(llvm::FoldingSetVector<EntryType> &Specs, bool isEnd) {
790 return SpecIterator<EntryType>(isEnd ? Specs.end() : Specs.begin());
793 void loadLazySpecializationsImpl() const;
795 template <class EntryType> typename SpecEntryTraits<EntryType>::DeclType*
796 findSpecializationImpl(llvm::FoldingSetVector<EntryType> &Specs,
797 ArrayRef<TemplateArgument> Args, void *&InsertPos);
799 template <class Derived, class EntryType>
800 void addSpecializationImpl(llvm::FoldingSetVector<EntryType> &Specs,
801 EntryType *Entry, void *InsertPos);
804 CommonBase() : InstantiatedFromMember(nullptr, false) {}
806 /// \brief The template from which this was most
807 /// directly instantiated (or null).
809 /// The boolean value indicates whether this template
810 /// was explicitly specialized.
811 llvm::PointerIntPair<RedeclarableTemplateDecl*, 1, bool>
812 InstantiatedFromMember;
814 /// \brief If non-null, points to an array of specializations (including
815 /// partial specializations) known only by their external declaration IDs.
817 /// The first value in the array is the number of specializations/partial
818 /// specializations that follow.
819 uint32_t *LazySpecializations = nullptr;
822 /// \brief Pointer to the common data shared by all declarations of this
824 mutable CommonBase *Common = nullptr;
826 /// \brief Retrieves the "common" pointer shared by all (re-)declarations of
827 /// the same template. Calling this routine may implicitly allocate memory
828 /// for the common pointer.
829 CommonBase *getCommonPtr() const;
831 virtual CommonBase *newCommon(ASTContext &C) const = 0;
833 // Construct a template decl with name, parameters, and templated element.
834 RedeclarableTemplateDecl(ConstrainedTemplateDeclInfo *CTDI, Kind DK,
835 ASTContext &C, DeclContext *DC, SourceLocation L,
836 DeclarationName Name, TemplateParameterList *Params,
838 : TemplateDecl(CTDI, DK, DC, L, Name, Params, Decl), redeclarable_base(C)
841 RedeclarableTemplateDecl(Kind DK, ASTContext &C, DeclContext *DC,
842 SourceLocation L, DeclarationName Name,
843 TemplateParameterList *Params, NamedDecl *Decl)
844 : RedeclarableTemplateDecl(nullptr, DK, C, DC, L, Name, Params, Decl) {}
847 friend class ASTDeclReader;
848 friend class ASTDeclWriter;
849 friend class ASTReader;
850 template <class decl_type> friend class RedeclarableTemplate;
852 /// \brief Retrieves the canonical declaration of this template.
853 RedeclarableTemplateDecl *getCanonicalDecl() override {
854 return getFirstDecl();
856 const RedeclarableTemplateDecl *getCanonicalDecl() const {
857 return getFirstDecl();
860 /// \brief Determines whether this template was a specialization of a
863 /// In the following example, the function template \c X<int>::f and the
864 /// member template \c X<int>::Inner are member specializations.
867 /// template<typename T>
869 /// template<typename U> void f(T, U);
870 /// template<typename U> struct Inner;
873 /// template<> template<typename T>
874 /// void X<int>::f(int, T);
875 /// template<> template<typename T>
876 /// struct X<int>::Inner { /* ... */ };
878 bool isMemberSpecialization() const {
879 return getCommonPtr()->InstantiatedFromMember.getInt();
882 /// \brief Note that this member template is a specialization.
883 void setMemberSpecialization() {
884 assert(getCommonPtr()->InstantiatedFromMember.getPointer() &&
885 "Only member templates can be member template specializations");
886 getCommonPtr()->InstantiatedFromMember.setInt(true);
889 /// \brief Retrieve the member template from which this template was
890 /// instantiated, or nullptr if this template was not instantiated from a
893 /// A template is instantiated from a member template when the member
894 /// template itself is part of a class template (or member thereof). For
898 /// template<typename T>
900 /// template<typename U> void f(T, U);
903 /// void test(X<int> x) {
908 /// \c X<int>::f is a FunctionTemplateDecl that describes the function
912 /// template<typename U> void X<int>::f(int, U);
915 /// which was itself created during the instantiation of \c X<int>. Calling
916 /// getInstantiatedFromMemberTemplate() on this FunctionTemplateDecl will
917 /// retrieve the FunctionTemplateDecl for the original template \c f within
918 /// the class template \c X<T>, i.e.,
921 /// template<typename T>
922 /// template<typename U>
923 /// void X<T>::f(T, U);
925 RedeclarableTemplateDecl *getInstantiatedFromMemberTemplate() const {
926 return getCommonPtr()->InstantiatedFromMember.getPointer();
929 void setInstantiatedFromMemberTemplate(RedeclarableTemplateDecl *TD) {
930 assert(!getCommonPtr()->InstantiatedFromMember.getPointer());
931 getCommonPtr()->InstantiatedFromMember.setPointer(TD);
934 using redecl_range = redeclarable_base::redecl_range;
935 using redecl_iterator = redeclarable_base::redecl_iterator;
937 using redeclarable_base::redecls_begin;
938 using redeclarable_base::redecls_end;
939 using redeclarable_base::redecls;
940 using redeclarable_base::getPreviousDecl;
941 using redeclarable_base::getMostRecentDecl;
942 using redeclarable_base::isFirstDecl;
944 // Implement isa/cast/dyncast/etc.
945 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
947 static bool classofKind(Kind K) {
948 return K >= firstRedeclarableTemplate && K <= lastRedeclarableTemplate;
952 template <> struct RedeclarableTemplateDecl::
953 SpecEntryTraits<FunctionTemplateSpecializationInfo> {
954 using DeclType = FunctionDecl;
956 static DeclType *getDecl(FunctionTemplateSpecializationInfo *I) {
960 static ArrayRef<TemplateArgument>
961 getTemplateArgs(FunctionTemplateSpecializationInfo *I) {
962 return I->TemplateArguments->asArray();
966 /// Declaration of a template function.
967 class FunctionTemplateDecl : public RedeclarableTemplateDecl {
969 friend class FunctionDecl;
971 /// \brief Data that is common to all of the declarations of a given
972 /// function template.
973 struct Common : CommonBase {
974 /// \brief The function template specializations for this function
975 /// template, including explicit specializations and instantiations.
976 llvm::FoldingSetVector<FunctionTemplateSpecializationInfo> Specializations;
978 /// \brief The set of "injected" template arguments used within this
979 /// function template.
981 /// This pointer refers to the template arguments (there are as
982 /// many template arguments as template parameaters) for the function
983 /// template, and is allocated lazily, since most function templates do not
984 /// require the use of this information.
985 TemplateArgument *InjectedArgs = nullptr;
990 FunctionTemplateDecl(ASTContext &C, DeclContext *DC, SourceLocation L,
991 DeclarationName Name, TemplateParameterList *Params,
993 : RedeclarableTemplateDecl(FunctionTemplate, C, DC, L, Name, Params,
996 CommonBase *newCommon(ASTContext &C) const override;
998 Common *getCommonPtr() const {
999 return static_cast<Common *>(RedeclarableTemplateDecl::getCommonPtr());
1002 /// \brief Retrieve the set of function template specializations of this
1003 /// function template.
1004 llvm::FoldingSetVector<FunctionTemplateSpecializationInfo> &
1005 getSpecializations() const;
1007 /// \brief Add a specialization of this function template.
1009 /// \param InsertPos Insert position in the FoldingSetVector, must have been
1010 /// retrieved by an earlier call to findSpecialization().
1011 void addSpecialization(FunctionTemplateSpecializationInfo* Info,
1015 friend class ASTDeclReader;
1016 friend class ASTDeclWriter;
1018 /// \brief Load any lazily-loaded specializations from the external source.
1019 void LoadLazySpecializations() const;
1021 /// Get the underlying function declaration of the template.
1022 FunctionDecl *getTemplatedDecl() const {
1023 return static_cast<FunctionDecl *>(TemplatedDecl);
1026 /// Returns whether this template declaration defines the primary
1028 bool isThisDeclarationADefinition() const {
1029 return getTemplatedDecl()->isThisDeclarationADefinition();
1032 /// \brief Return the specialization with the provided arguments if it exists,
1033 /// otherwise return the insertion point.
1034 FunctionDecl *findSpecialization(ArrayRef<TemplateArgument> Args,
1037 FunctionTemplateDecl *getCanonicalDecl() override {
1038 return cast<FunctionTemplateDecl>(
1039 RedeclarableTemplateDecl::getCanonicalDecl());
1041 const FunctionTemplateDecl *getCanonicalDecl() const {
1042 return cast<FunctionTemplateDecl>(
1043 RedeclarableTemplateDecl::getCanonicalDecl());
1046 /// \brief Retrieve the previous declaration of this function template, or
1047 /// nullptr if no such declaration exists.
1048 FunctionTemplateDecl *getPreviousDecl() {
1049 return cast_or_null<FunctionTemplateDecl>(
1050 static_cast<RedeclarableTemplateDecl *>(this)->getPreviousDecl());
1052 const FunctionTemplateDecl *getPreviousDecl() const {
1053 return cast_or_null<FunctionTemplateDecl>(
1054 static_cast<const RedeclarableTemplateDecl *>(this)->getPreviousDecl());
1057 FunctionTemplateDecl *getMostRecentDecl() {
1058 return cast<FunctionTemplateDecl>(
1059 static_cast<RedeclarableTemplateDecl *>(this)
1060 ->getMostRecentDecl());
1062 const FunctionTemplateDecl *getMostRecentDecl() const {
1063 return const_cast<FunctionTemplateDecl*>(this)->getMostRecentDecl();
1066 FunctionTemplateDecl *getInstantiatedFromMemberTemplate() const {
1067 return cast_or_null<FunctionTemplateDecl>(
1068 RedeclarableTemplateDecl::getInstantiatedFromMemberTemplate());
1071 using spec_iterator = SpecIterator<FunctionTemplateSpecializationInfo>;
1072 using spec_range = llvm::iterator_range<spec_iterator>;
1074 spec_range specializations() const {
1075 return spec_range(spec_begin(), spec_end());
1078 spec_iterator spec_begin() const {
1079 return makeSpecIterator(getSpecializations(), false);
1082 spec_iterator spec_end() const {
1083 return makeSpecIterator(getSpecializations(), true);
1086 /// \brief Retrieve the "injected" template arguments that correspond to the
1087 /// template parameters of this function template.
1089 /// Although the C++ standard has no notion of the "injected" template
1090 /// arguments for a function template, the notion is convenient when
1091 /// we need to perform substitutions inside the definition of a function
1093 ArrayRef<TemplateArgument> getInjectedTemplateArgs();
1095 /// \brief Create a function template node.
1096 static FunctionTemplateDecl *Create(ASTContext &C, DeclContext *DC,
1098 DeclarationName Name,
1099 TemplateParameterList *Params,
1102 /// \brief Create an empty function template node.
1103 static FunctionTemplateDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1105 // Implement isa/cast/dyncast support
1106 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1107 static bool classofKind(Kind K) { return K == FunctionTemplate; }
1110 //===----------------------------------------------------------------------===//
1111 // Kinds of Template Parameters
1112 //===----------------------------------------------------------------------===//
1114 /// \brief Defines the position of a template parameter within a template
1117 /// Because template parameter can be listed
1118 /// sequentially for out-of-line template members, each template parameter is
1119 /// given a Depth - the nesting of template parameter scopes - and a Position -
1120 /// the occurrence within the parameter list.
1121 /// This class is inheritedly privately by different kinds of template
1122 /// parameters and is not part of the Decl hierarchy. Just a facility.
1123 class TemplateParmPosition {
1125 // FIXME: These probably don't need to be ints. int:5 for depth, int:8 for
1130 TemplateParmPosition(unsigned D, unsigned P) : Depth(D), Position(P) {}
1133 TemplateParmPosition() = delete;
1135 /// Get the nesting depth of the template parameter.
1136 unsigned getDepth() const { return Depth; }
1137 void setDepth(unsigned D) { Depth = D; }
1139 /// Get the position of the template parameter within its parameter list.
1140 unsigned getPosition() const { return Position; }
1141 void setPosition(unsigned P) { Position = P; }
1143 /// Get the index of the template parameter within its parameter list.
1144 unsigned getIndex() const { return Position; }
1147 /// \brief Declaration of a template type parameter.
1149 /// For example, "T" in
1151 /// template<typename T> class vector;
1153 class TemplateTypeParmDecl : public TypeDecl {
1154 /// Sema creates these on the stack during auto type deduction.
1157 /// \brief Whether this template type parameter was declaration with
1158 /// the 'typename' keyword.
1160 /// If false, it was declared with the 'class' keyword.
1163 /// \brief The default template argument, if any.
1164 using DefArgStorage =
1165 DefaultArgStorage<TemplateTypeParmDecl, TypeSourceInfo *>;
1166 DefArgStorage DefaultArgument;
1168 TemplateTypeParmDecl(DeclContext *DC, SourceLocation KeyLoc,
1169 SourceLocation IdLoc, IdentifierInfo *Id,
1171 : TypeDecl(TemplateTypeParm, DC, IdLoc, Id, KeyLoc), Typename(Typename) {}
1174 static TemplateTypeParmDecl *Create(const ASTContext &C, DeclContext *DC,
1175 SourceLocation KeyLoc,
1176 SourceLocation NameLoc,
1177 unsigned D, unsigned P,
1178 IdentifierInfo *Id, bool Typename,
1179 bool ParameterPack);
1180 static TemplateTypeParmDecl *CreateDeserialized(const ASTContext &C,
1183 /// \brief Whether this template type parameter was declared with
1184 /// the 'typename' keyword.
1186 /// If not, it was declared with the 'class' keyword.
1187 bool wasDeclaredWithTypename() const { return Typename; }
1189 const DefArgStorage &getDefaultArgStorage() const { return DefaultArgument; }
1191 /// \brief Determine whether this template parameter has a default
1193 bool hasDefaultArgument() const { return DefaultArgument.isSet(); }
1195 /// \brief Retrieve the default argument, if any.
1196 QualType getDefaultArgument() const {
1197 return DefaultArgument.get()->getType();
1200 /// \brief Retrieves the default argument's source information, if any.
1201 TypeSourceInfo *getDefaultArgumentInfo() const {
1202 return DefaultArgument.get();
1205 /// \brief Retrieves the location of the default argument declaration.
1206 SourceLocation getDefaultArgumentLoc() const;
1208 /// \brief Determines whether the default argument was inherited
1209 /// from a previous declaration of this template.
1210 bool defaultArgumentWasInherited() const {
1211 return DefaultArgument.isInherited();
1214 /// \brief Set the default argument for this template parameter.
1215 void setDefaultArgument(TypeSourceInfo *DefArg) {
1216 DefaultArgument.set(DefArg);
1219 /// \brief Set that this default argument was inherited from another
1221 void setInheritedDefaultArgument(const ASTContext &C,
1222 TemplateTypeParmDecl *Prev) {
1223 DefaultArgument.setInherited(C, Prev);
1226 /// \brief Removes the default argument of this template parameter.
1227 void removeDefaultArgument() {
1228 DefaultArgument.clear();
1231 /// \brief Set whether this template type parameter was declared with
1232 /// the 'typename' or 'class' keyword.
1233 void setDeclaredWithTypename(bool withTypename) { Typename = withTypename; }
1235 /// \brief Retrieve the depth of the template parameter.
1236 unsigned getDepth() const;
1238 /// \brief Retrieve the index of the template parameter.
1239 unsigned getIndex() const;
1241 /// \brief Returns whether this is a parameter pack.
1242 bool isParameterPack() const;
1244 SourceRange getSourceRange() const override LLVM_READONLY;
1246 // Implement isa/cast/dyncast/etc.
1247 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1248 static bool classofKind(Kind K) { return K == TemplateTypeParm; }
1251 /// NonTypeTemplateParmDecl - Declares a non-type template parameter,
1254 /// template<int Size> class array { };
1256 class NonTypeTemplateParmDecl final
1257 : public DeclaratorDecl,
1258 protected TemplateParmPosition,
1259 private llvm::TrailingObjects<NonTypeTemplateParmDecl,
1260 std::pair<QualType, TypeSourceInfo *>> {
1261 friend class ASTDeclReader;
1262 friend TrailingObjects;
1264 /// \brief The default template argument, if any, and whether or not
1265 /// it was inherited.
1266 using DefArgStorage = DefaultArgStorage<NonTypeTemplateParmDecl, Expr *>;
1267 DefArgStorage DefaultArgument;
1269 // FIXME: Collapse this into TemplateParamPosition; or, just move depth/index
1270 // down here to save memory.
1272 /// \brief Whether this non-type template parameter is a parameter pack.
1275 /// \brief Whether this non-type template parameter is an "expanded"
1276 /// parameter pack, meaning that its type is a pack expansion and we
1277 /// already know the set of types that expansion expands to.
1278 bool ExpandedParameterPack = false;
1280 /// \brief The number of types in an expanded parameter pack.
1281 unsigned NumExpandedTypes = 0;
1283 size_t numTrailingObjects(
1284 OverloadToken<std::pair<QualType, TypeSourceInfo *>>) const {
1285 return NumExpandedTypes;
1288 NonTypeTemplateParmDecl(DeclContext *DC, SourceLocation StartLoc,
1289 SourceLocation IdLoc, unsigned D, unsigned P,
1290 IdentifierInfo *Id, QualType T,
1291 bool ParameterPack, TypeSourceInfo *TInfo)
1292 : DeclaratorDecl(NonTypeTemplateParm, DC, IdLoc, Id, T, TInfo, StartLoc),
1293 TemplateParmPosition(D, P), ParameterPack(ParameterPack) {}
1295 NonTypeTemplateParmDecl(DeclContext *DC, SourceLocation StartLoc,
1296 SourceLocation IdLoc, unsigned D, unsigned P,
1297 IdentifierInfo *Id, QualType T,
1298 TypeSourceInfo *TInfo,
1299 ArrayRef<QualType> ExpandedTypes,
1300 ArrayRef<TypeSourceInfo *> ExpandedTInfos);
1303 static NonTypeTemplateParmDecl *
1304 Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
1305 SourceLocation IdLoc, unsigned D, unsigned P, IdentifierInfo *Id,
1306 QualType T, bool ParameterPack, TypeSourceInfo *TInfo);
1308 static NonTypeTemplateParmDecl *
1309 Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
1310 SourceLocation IdLoc, unsigned D, unsigned P, IdentifierInfo *Id,
1311 QualType T, TypeSourceInfo *TInfo, ArrayRef<QualType> ExpandedTypes,
1312 ArrayRef<TypeSourceInfo *> ExpandedTInfos);
1314 static NonTypeTemplateParmDecl *CreateDeserialized(ASTContext &C,
1316 static NonTypeTemplateParmDecl *CreateDeserialized(ASTContext &C,
1318 unsigned NumExpandedTypes);
1320 using TemplateParmPosition::getDepth;
1321 using TemplateParmPosition::setDepth;
1322 using TemplateParmPosition::getPosition;
1323 using TemplateParmPosition::setPosition;
1324 using TemplateParmPosition::getIndex;
1326 SourceRange getSourceRange() const override LLVM_READONLY;
1328 const DefArgStorage &getDefaultArgStorage() const { return DefaultArgument; }
1330 /// \brief Determine whether this template parameter has a default
1332 bool hasDefaultArgument() const { return DefaultArgument.isSet(); }
1334 /// \brief Retrieve the default argument, if any.
1335 Expr *getDefaultArgument() const { return DefaultArgument.get(); }
1337 /// \brief Retrieve the location of the default argument, if any.
1338 SourceLocation getDefaultArgumentLoc() const;
1340 /// \brief Determines whether the default argument was inherited
1341 /// from a previous declaration of this template.
1342 bool defaultArgumentWasInherited() const {
1343 return DefaultArgument.isInherited();
1346 /// \brief Set the default argument for this template parameter, and
1347 /// whether that default argument was inherited from another
1349 void setDefaultArgument(Expr *DefArg) { DefaultArgument.set(DefArg); }
1350 void setInheritedDefaultArgument(const ASTContext &C,
1351 NonTypeTemplateParmDecl *Parm) {
1352 DefaultArgument.setInherited(C, Parm);
1355 /// \brief Removes the default argument of this template parameter.
1356 void removeDefaultArgument() { DefaultArgument.clear(); }
1358 /// \brief Whether this parameter is a non-type template parameter pack.
1360 /// If the parameter is a parameter pack, the type may be a
1361 /// \c PackExpansionType. In the following example, the \c Dims parameter
1362 /// is a parameter pack (whose type is 'unsigned').
1365 /// template<typename T, unsigned ...Dims> struct multi_array;
1367 bool isParameterPack() const { return ParameterPack; }
1369 /// \brief Whether this parameter pack is a pack expansion.
1371 /// A non-type template parameter pack is a pack expansion if its type
1372 /// contains an unexpanded parameter pack. In this case, we will have
1373 /// built a PackExpansionType wrapping the type.
1374 bool isPackExpansion() const {
1375 return ParameterPack && getType()->getAs<PackExpansionType>();
1378 /// \brief Whether this parameter is a non-type template parameter pack
1379 /// that has a known list of different types at different positions.
1381 /// A parameter pack is an expanded parameter pack when the original
1382 /// parameter pack's type was itself a pack expansion, and that expansion
1383 /// has already been expanded. For example, given:
1386 /// template<typename ...Types>
1388 /// template<Types ...Values>
1389 /// struct Y { /* ... */ };
1393 /// The parameter pack \c Values has a \c PackExpansionType as its type,
1394 /// which expands \c Types. When \c Types is supplied with template arguments
1395 /// by instantiating \c X, the instantiation of \c Values becomes an
1396 /// expanded parameter pack. For example, instantiating
1397 /// \c X<int, unsigned int> results in \c Values being an expanded parameter
1398 /// pack with expansion types \c int and \c unsigned int.
1400 /// The \c getExpansionType() and \c getExpansionTypeSourceInfo() functions
1401 /// return the expansion types.
1402 bool isExpandedParameterPack() const { return ExpandedParameterPack; }
1404 /// \brief Retrieves the number of expansion types in an expanded parameter
1406 unsigned getNumExpansionTypes() const {
1407 assert(ExpandedParameterPack && "Not an expansion parameter pack");
1408 return NumExpandedTypes;
1411 /// \brief Retrieve a particular expansion type within an expanded parameter
1413 QualType getExpansionType(unsigned I) const {
1414 assert(I < NumExpandedTypes && "Out-of-range expansion type index");
1415 auto TypesAndInfos =
1416 getTrailingObjects<std::pair<QualType, TypeSourceInfo *>>();
1417 return TypesAndInfos[I].first;
1420 /// \brief Retrieve a particular expansion type source info within an
1421 /// expanded parameter pack.
1422 TypeSourceInfo *getExpansionTypeSourceInfo(unsigned I) const {
1423 assert(I < NumExpandedTypes && "Out-of-range expansion type index");
1424 auto TypesAndInfos =
1425 getTrailingObjects<std::pair<QualType, TypeSourceInfo *>>();
1426 return TypesAndInfos[I].second;
1429 // Implement isa/cast/dyncast/etc.
1430 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1431 static bool classofKind(Kind K) { return K == NonTypeTemplateParm; }
1434 /// TemplateTemplateParmDecl - Declares a template template parameter,
1437 /// template <template <typename> class T> class container { };
1439 /// A template template parameter is a TemplateDecl because it defines the
1440 /// name of a template and the template parameters allowable for substitution.
1441 class TemplateTemplateParmDecl final
1442 : public TemplateDecl,
1443 protected TemplateParmPosition,
1444 private llvm::TrailingObjects<TemplateTemplateParmDecl,
1445 TemplateParameterList *> {
1446 /// \brief The default template argument, if any.
1447 using DefArgStorage =
1448 DefaultArgStorage<TemplateTemplateParmDecl, TemplateArgumentLoc *>;
1449 DefArgStorage DefaultArgument;
1451 /// \brief Whether this parameter is a parameter pack.
1454 /// \brief Whether this template template parameter is an "expanded"
1455 /// parameter pack, meaning that it is a pack expansion and we
1456 /// already know the set of template parameters that expansion expands to.
1457 bool ExpandedParameterPack = false;
1459 /// \brief The number of parameters in an expanded parameter pack.
1460 unsigned NumExpandedParams = 0;
1462 TemplateTemplateParmDecl(DeclContext *DC, SourceLocation L,
1463 unsigned D, unsigned P, bool ParameterPack,
1464 IdentifierInfo *Id, TemplateParameterList *Params)
1465 : TemplateDecl(TemplateTemplateParm, DC, L, Id, Params),
1466 TemplateParmPosition(D, P), ParameterPack(ParameterPack) {}
1468 TemplateTemplateParmDecl(DeclContext *DC, SourceLocation L,
1469 unsigned D, unsigned P,
1470 IdentifierInfo *Id, TemplateParameterList *Params,
1471 ArrayRef<TemplateParameterList *> Expansions);
1473 void anchor() override;
1476 friend class ASTDeclReader;
1477 friend class ASTDeclWriter;
1478 friend TrailingObjects;
1480 static TemplateTemplateParmDecl *Create(const ASTContext &C, DeclContext *DC,
1481 SourceLocation L, unsigned D,
1482 unsigned P, bool ParameterPack,
1484 TemplateParameterList *Params);
1485 static TemplateTemplateParmDecl *Create(const ASTContext &C, DeclContext *DC,
1486 SourceLocation L, unsigned D,
1489 TemplateParameterList *Params,
1490 ArrayRef<TemplateParameterList *> Expansions);
1492 static TemplateTemplateParmDecl *CreateDeserialized(ASTContext &C,
1494 static TemplateTemplateParmDecl *CreateDeserialized(ASTContext &C,
1496 unsigned NumExpansions);
1498 using TemplateParmPosition::getDepth;
1499 using TemplateParmPosition::setDepth;
1500 using TemplateParmPosition::getPosition;
1501 using TemplateParmPosition::setPosition;
1502 using TemplateParmPosition::getIndex;
1504 /// \brief Whether this template template parameter is a template
1508 /// template<template <class T> ...MetaFunctions> struct Apply;
1510 bool isParameterPack() const { return ParameterPack; }
1512 /// \brief Whether this parameter pack is a pack expansion.
1514 /// A template template parameter pack is a pack expansion if its template
1515 /// parameter list contains an unexpanded parameter pack.
1516 bool isPackExpansion() const {
1517 return ParameterPack &&
1518 getTemplateParameters()->containsUnexpandedParameterPack();
1521 /// \brief Whether this parameter is a template template parameter pack that
1522 /// has a known list of different template parameter lists at different
1525 /// A parameter pack is an expanded parameter pack when the original parameter
1526 /// pack's template parameter list was itself a pack expansion, and that
1527 /// expansion has already been expanded. For exampe, given:
1530 /// template<typename...Types> struct Outer {
1531 /// template<template<Types> class...Templates> struct Inner;
1535 /// The parameter pack \c Templates is a pack expansion, which expands the
1536 /// pack \c Types. When \c Types is supplied with template arguments by
1537 /// instantiating \c Outer, the instantiation of \c Templates is an expanded
1539 bool isExpandedParameterPack() const { return ExpandedParameterPack; }
1541 /// \brief Retrieves the number of expansion template parameters in
1542 /// an expanded parameter pack.
1543 unsigned getNumExpansionTemplateParameters() const {
1544 assert(ExpandedParameterPack && "Not an expansion parameter pack");
1545 return NumExpandedParams;
1548 /// \brief Retrieve a particular expansion type within an expanded parameter
1550 TemplateParameterList *getExpansionTemplateParameters(unsigned I) const {
1551 assert(I < NumExpandedParams && "Out-of-range expansion type index");
1552 return getTrailingObjects<TemplateParameterList *>()[I];
1555 const DefArgStorage &getDefaultArgStorage() const { return DefaultArgument; }
1557 /// \brief Determine whether this template parameter has a default
1559 bool hasDefaultArgument() const { return DefaultArgument.isSet(); }
1561 /// \brief Retrieve the default argument, if any.
1562 const TemplateArgumentLoc &getDefaultArgument() const {
1563 static const TemplateArgumentLoc None;
1564 return DefaultArgument.isSet() ? *DefaultArgument.get() : None;
1567 /// \brief Retrieve the location of the default argument, if any.
1568 SourceLocation getDefaultArgumentLoc() const;
1570 /// \brief Determines whether the default argument was inherited
1571 /// from a previous declaration of this template.
1572 bool defaultArgumentWasInherited() const {
1573 return DefaultArgument.isInherited();
1576 /// \brief Set the default argument for this template parameter, and
1577 /// whether that default argument was inherited from another
1579 void setDefaultArgument(const ASTContext &C,
1580 const TemplateArgumentLoc &DefArg);
1581 void setInheritedDefaultArgument(const ASTContext &C,
1582 TemplateTemplateParmDecl *Prev) {
1583 DefaultArgument.setInherited(C, Prev);
1586 /// \brief Removes the default argument of this template parameter.
1587 void removeDefaultArgument() { DefaultArgument.clear(); }
1589 SourceRange getSourceRange() const override LLVM_READONLY {
1590 SourceLocation End = getLocation();
1591 if (hasDefaultArgument() && !defaultArgumentWasInherited())
1592 End = getDefaultArgument().getSourceRange().getEnd();
1593 return SourceRange(getTemplateParameters()->getTemplateLoc(), End);
1596 // Implement isa/cast/dyncast/etc.
1597 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1598 static bool classofKind(Kind K) { return K == TemplateTemplateParm; }
1601 /// \brief Represents the builtin template declaration which is used to
1602 /// implement __make_integer_seq and other builtin templates. It serves
1603 /// no real purpose beyond existing as a place to hold template parameters.
1604 class BuiltinTemplateDecl : public TemplateDecl {
1605 BuiltinTemplateKind BTK;
1607 BuiltinTemplateDecl(const ASTContext &C, DeclContext *DC,
1608 DeclarationName Name, BuiltinTemplateKind BTK);
1610 void anchor() override;
1613 // Implement isa/cast/dyncast support
1614 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1615 static bool classofKind(Kind K) { return K == BuiltinTemplate; }
1617 static BuiltinTemplateDecl *Create(const ASTContext &C, DeclContext *DC,
1618 DeclarationName Name,
1619 BuiltinTemplateKind BTK) {
1620 return new (C, DC) BuiltinTemplateDecl(C, DC, Name, BTK);
1623 SourceRange getSourceRange() const override LLVM_READONLY {
1624 return SourceRange();
1627 BuiltinTemplateKind getBuiltinTemplateKind() const { return BTK; }
1630 /// \brief Represents a class template specialization, which refers to
1631 /// a class template with a given set of template arguments.
1633 /// Class template specializations represent both explicit
1634 /// specialization of class templates, as in the example below, and
1635 /// implicit instantiations of class templates.
1638 /// template<typename T> class array;
1641 /// class array<bool> { }; // class template specialization array<bool>
1643 class ClassTemplateSpecializationDecl
1644 : public CXXRecordDecl, public llvm::FoldingSetNode {
1645 /// \brief Structure that stores information about a class template
1646 /// specialization that was instantiated from a class template partial
1648 struct SpecializedPartialSpecialization {
1649 /// \brief The class template partial specialization from which this
1650 /// class template specialization was instantiated.
1651 ClassTemplatePartialSpecializationDecl *PartialSpecialization;
1653 /// \brief The template argument list deduced for the class template
1654 /// partial specialization itself.
1655 const TemplateArgumentList *TemplateArgs;
1658 /// \brief The template that this specialization specializes
1659 llvm::PointerUnion<ClassTemplateDecl *, SpecializedPartialSpecialization *>
1660 SpecializedTemplate;
1662 /// \brief Further info for explicit template specialization/instantiation.
1663 struct ExplicitSpecializationInfo {
1664 /// \brief The type-as-written.
1665 TypeSourceInfo *TypeAsWritten = nullptr;
1667 /// \brief The location of the extern keyword.
1668 SourceLocation ExternLoc;
1670 /// \brief The location of the template keyword.
1671 SourceLocation TemplateKeywordLoc;
1673 ExplicitSpecializationInfo() = default;
1676 /// \brief Further info for explicit template specialization/instantiation.
1677 /// Does not apply to implicit specializations.
1678 ExplicitSpecializationInfo *ExplicitInfo = nullptr;
1680 /// \brief The template arguments used to describe this specialization.
1681 const TemplateArgumentList *TemplateArgs;
1683 /// \brief The point where this template was instantiated (if any)
1684 SourceLocation PointOfInstantiation;
1686 /// \brief The kind of specialization this declaration refers to.
1687 /// Really a value of type TemplateSpecializationKind.
1688 unsigned SpecializationKind : 3;
1691 ClassTemplateSpecializationDecl(ASTContext &Context, Kind DK, TagKind TK,
1692 DeclContext *DC, SourceLocation StartLoc,
1693 SourceLocation IdLoc,
1694 ClassTemplateDecl *SpecializedTemplate,
1695 ArrayRef<TemplateArgument> Args,
1696 ClassTemplateSpecializationDecl *PrevDecl);
1698 explicit ClassTemplateSpecializationDecl(ASTContext &C, Kind DK);
1701 friend class ASTDeclReader;
1702 friend class ASTDeclWriter;
1704 static ClassTemplateSpecializationDecl *
1705 Create(ASTContext &Context, TagKind TK, DeclContext *DC,
1706 SourceLocation StartLoc, SourceLocation IdLoc,
1707 ClassTemplateDecl *SpecializedTemplate,
1708 ArrayRef<TemplateArgument> Args,
1709 ClassTemplateSpecializationDecl *PrevDecl);
1710 static ClassTemplateSpecializationDecl *
1711 CreateDeserialized(ASTContext &C, unsigned ID);
1713 void getNameForDiagnostic(raw_ostream &OS, const PrintingPolicy &Policy,
1714 bool Qualified) const override;
1716 // FIXME: This is broken. CXXRecordDecl::getMostRecentDecl() returns a
1717 // different "most recent" declaration from this function for the same
1718 // declaration, because we don't override getMostRecentDeclImpl(). But
1719 // it's not clear that we should override that, because the most recent
1720 // declaration as a CXXRecordDecl sometimes is the injected-class-name.
1721 ClassTemplateSpecializationDecl *getMostRecentDecl() {
1722 CXXRecordDecl *Recent = static_cast<CXXRecordDecl *>(
1723 this)->getMostRecentDecl();
1724 while (!isa<ClassTemplateSpecializationDecl>(Recent)) {
1725 // FIXME: Does injected class name need to be in the redeclarations chain?
1726 assert(Recent->isInjectedClassName() && Recent->getPreviousDecl());
1727 Recent = Recent->getPreviousDecl();
1729 return cast<ClassTemplateSpecializationDecl>(Recent);
1732 /// \brief Retrieve the template that this specialization specializes.
1733 ClassTemplateDecl *getSpecializedTemplate() const;
1735 /// \brief Retrieve the template arguments of the class template
1737 const TemplateArgumentList &getTemplateArgs() const {
1738 return *TemplateArgs;
1741 /// \brief Determine the kind of specialization that this
1742 /// declaration represents.
1743 TemplateSpecializationKind getSpecializationKind() const {
1744 return static_cast<TemplateSpecializationKind>(SpecializationKind);
1747 bool isExplicitSpecialization() const {
1748 return getSpecializationKind() == TSK_ExplicitSpecialization;
1751 /// \brief True if this declaration is an explicit specialization,
1752 /// explicit instantiation declaration, or explicit instantiation
1754 bool isExplicitInstantiationOrSpecialization() const {
1755 return isTemplateExplicitInstantiationOrSpecialization(
1756 getTemplateSpecializationKind());
1759 void setSpecializationKind(TemplateSpecializationKind TSK) {
1760 SpecializationKind = TSK;
1763 /// \brief Get the point of instantiation (if any), or null if none.
1764 SourceLocation getPointOfInstantiation() const {
1765 return PointOfInstantiation;
1768 void setPointOfInstantiation(SourceLocation Loc) {
1769 assert(Loc.isValid() && "point of instantiation must be valid!");
1770 PointOfInstantiation = Loc;
1773 /// \brief If this class template specialization is an instantiation of
1774 /// a template (rather than an explicit specialization), return the
1775 /// class template or class template partial specialization from which it
1776 /// was instantiated.
1777 llvm::PointerUnion<ClassTemplateDecl *,
1778 ClassTemplatePartialSpecializationDecl *>
1779 getInstantiatedFrom() const {
1780 if (!isTemplateInstantiation(getSpecializationKind()))
1781 return llvm::PointerUnion<ClassTemplateDecl *,
1782 ClassTemplatePartialSpecializationDecl *>();
1784 return getSpecializedTemplateOrPartial();
1787 /// \brief Retrieve the class template or class template partial
1788 /// specialization which was specialized by this.
1789 llvm::PointerUnion<ClassTemplateDecl *,
1790 ClassTemplatePartialSpecializationDecl *>
1791 getSpecializedTemplateOrPartial() const {
1792 if (SpecializedPartialSpecialization *PartialSpec
1793 = SpecializedTemplate.dyn_cast<SpecializedPartialSpecialization*>())
1794 return PartialSpec->PartialSpecialization;
1796 return SpecializedTemplate.get<ClassTemplateDecl*>();
1799 /// \brief Retrieve the set of template arguments that should be used
1800 /// to instantiate members of the class template or class template partial
1801 /// specialization from which this class template specialization was
1804 /// \returns For a class template specialization instantiated from the primary
1805 /// template, this function will return the same template arguments as
1806 /// getTemplateArgs(). For a class template specialization instantiated from
1807 /// a class template partial specialization, this function will return the
1808 /// deduced template arguments for the class template partial specialization
1810 const TemplateArgumentList &getTemplateInstantiationArgs() const {
1811 if (SpecializedPartialSpecialization *PartialSpec
1812 = SpecializedTemplate.dyn_cast<SpecializedPartialSpecialization*>())
1813 return *PartialSpec->TemplateArgs;
1815 return getTemplateArgs();
1818 /// \brief Note that this class template specialization is actually an
1819 /// instantiation of the given class template partial specialization whose
1820 /// template arguments have been deduced.
1821 void setInstantiationOf(ClassTemplatePartialSpecializationDecl *PartialSpec,
1822 const TemplateArgumentList *TemplateArgs) {
1823 assert(!SpecializedTemplate.is<SpecializedPartialSpecialization*>() &&
1824 "Already set to a class template partial specialization!");
1825 SpecializedPartialSpecialization *PS
1826 = new (getASTContext()) SpecializedPartialSpecialization();
1827 PS->PartialSpecialization = PartialSpec;
1828 PS->TemplateArgs = TemplateArgs;
1829 SpecializedTemplate = PS;
1832 /// \brief Note that this class template specialization is an instantiation
1833 /// of the given class template.
1834 void setInstantiationOf(ClassTemplateDecl *TemplDecl) {
1835 assert(!SpecializedTemplate.is<SpecializedPartialSpecialization*>() &&
1836 "Previously set to a class template partial specialization!");
1837 SpecializedTemplate = TemplDecl;
1840 /// \brief Sets the type of this specialization as it was written by
1841 /// the user. This will be a class template specialization type.
1842 void setTypeAsWritten(TypeSourceInfo *T) {
1844 ExplicitInfo = new (getASTContext()) ExplicitSpecializationInfo;
1845 ExplicitInfo->TypeAsWritten = T;
1848 /// \brief Gets the type of this specialization as it was written by
1849 /// the user, if it was so written.
1850 TypeSourceInfo *getTypeAsWritten() const {
1851 return ExplicitInfo ? ExplicitInfo->TypeAsWritten : nullptr;
1854 /// \brief Gets the location of the extern keyword, if present.
1855 SourceLocation getExternLoc() const {
1856 return ExplicitInfo ? ExplicitInfo->ExternLoc : SourceLocation();
1859 /// \brief Sets the location of the extern keyword.
1860 void setExternLoc(SourceLocation Loc) {
1862 ExplicitInfo = new (getASTContext()) ExplicitSpecializationInfo;
1863 ExplicitInfo->ExternLoc = Loc;
1866 /// \brief Sets the location of the template keyword.
1867 void setTemplateKeywordLoc(SourceLocation Loc) {
1869 ExplicitInfo = new (getASTContext()) ExplicitSpecializationInfo;
1870 ExplicitInfo->TemplateKeywordLoc = Loc;
1873 /// \brief Gets the location of the template keyword, if present.
1874 SourceLocation getTemplateKeywordLoc() const {
1875 return ExplicitInfo ? ExplicitInfo->TemplateKeywordLoc : SourceLocation();
1878 SourceRange getSourceRange() const override LLVM_READONLY;
1880 void Profile(llvm::FoldingSetNodeID &ID) const {
1881 Profile(ID, TemplateArgs->asArray(), getASTContext());
1885 Profile(llvm::FoldingSetNodeID &ID, ArrayRef<TemplateArgument> TemplateArgs,
1886 ASTContext &Context) {
1887 ID.AddInteger(TemplateArgs.size());
1888 for (const TemplateArgument &TemplateArg : TemplateArgs)
1889 TemplateArg.Profile(ID, Context);
1892 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1894 static bool classofKind(Kind K) {
1895 return K >= firstClassTemplateSpecialization &&
1896 K <= lastClassTemplateSpecialization;
1900 class ClassTemplatePartialSpecializationDecl
1901 : public ClassTemplateSpecializationDecl {
1902 /// \brief The list of template parameters
1903 TemplateParameterList* TemplateParams = nullptr;
1905 /// \brief The source info for the template arguments as written.
1906 /// FIXME: redundant with TypeAsWritten?
1907 const ASTTemplateArgumentListInfo *ArgsAsWritten = nullptr;
1909 /// \brief The class template partial specialization from which this
1910 /// class template partial specialization was instantiated.
1912 /// The boolean value will be true to indicate that this class template
1913 /// partial specialization was specialized at this level.
1914 llvm::PointerIntPair<ClassTemplatePartialSpecializationDecl *, 1, bool>
1915 InstantiatedFromMember;
1917 ClassTemplatePartialSpecializationDecl(ASTContext &Context, TagKind TK,
1919 SourceLocation StartLoc,
1920 SourceLocation IdLoc,
1921 TemplateParameterList *Params,
1922 ClassTemplateDecl *SpecializedTemplate,
1923 ArrayRef<TemplateArgument> Args,
1924 const ASTTemplateArgumentListInfo *ArgsAsWritten,
1925 ClassTemplatePartialSpecializationDecl *PrevDecl);
1927 ClassTemplatePartialSpecializationDecl(ASTContext &C)
1928 : ClassTemplateSpecializationDecl(C, ClassTemplatePartialSpecialization),
1929 InstantiatedFromMember(nullptr, false) {}
1931 void anchor() override;
1934 friend class ASTDeclReader;
1935 friend class ASTDeclWriter;
1937 static ClassTemplatePartialSpecializationDecl *
1938 Create(ASTContext &Context, TagKind TK, DeclContext *DC,
1939 SourceLocation StartLoc, SourceLocation IdLoc,
1940 TemplateParameterList *Params,
1941 ClassTemplateDecl *SpecializedTemplate,
1942 ArrayRef<TemplateArgument> Args,
1943 const TemplateArgumentListInfo &ArgInfos,
1944 QualType CanonInjectedType,
1945 ClassTemplatePartialSpecializationDecl *PrevDecl);
1947 static ClassTemplatePartialSpecializationDecl *
1948 CreateDeserialized(ASTContext &C, unsigned ID);
1950 ClassTemplatePartialSpecializationDecl *getMostRecentDecl() {
1951 return cast<ClassTemplatePartialSpecializationDecl>(
1952 static_cast<ClassTemplateSpecializationDecl *>(
1953 this)->getMostRecentDecl());
1956 /// Get the list of template parameters
1957 TemplateParameterList *getTemplateParameters() const {
1958 return TemplateParams;
1961 /// Get the template arguments as written.
1962 const ASTTemplateArgumentListInfo *getTemplateArgsAsWritten() const {
1963 return ArgsAsWritten;
1966 /// \brief Retrieve the member class template partial specialization from
1967 /// which this particular class template partial specialization was
1971 /// template<typename T>
1973 /// template<typename U> struct Inner;
1974 /// template<typename U> struct Inner<U*> { }; // #1
1977 /// Outer<float>::Inner<int*> ii;
1980 /// In this example, the instantiation of \c Outer<float>::Inner<int*> will
1981 /// end up instantiating the partial specialization
1982 /// \c Outer<float>::Inner<U*>, which itself was instantiated from the class
1983 /// template partial specialization \c Outer<T>::Inner<U*>. Given
1984 /// \c Outer<float>::Inner<U*>, this function would return
1985 /// \c Outer<T>::Inner<U*>.
1986 ClassTemplatePartialSpecializationDecl *getInstantiatedFromMember() const {
1987 const ClassTemplatePartialSpecializationDecl *First =
1988 cast<ClassTemplatePartialSpecializationDecl>(getFirstDecl());
1989 return First->InstantiatedFromMember.getPointer();
1991 ClassTemplatePartialSpecializationDecl *
1992 getInstantiatedFromMemberTemplate() const {
1993 return getInstantiatedFromMember();
1996 void setInstantiatedFromMember(
1997 ClassTemplatePartialSpecializationDecl *PartialSpec) {
1998 ClassTemplatePartialSpecializationDecl *First =
1999 cast<ClassTemplatePartialSpecializationDecl>(getFirstDecl());
2000 First->InstantiatedFromMember.setPointer(PartialSpec);
2003 /// \brief Determines whether this class template partial specialization
2004 /// template was a specialization of a member partial specialization.
2006 /// In the following example, the member template partial specialization
2007 /// \c X<int>::Inner<T*> is a member specialization.
2010 /// template<typename T>
2012 /// template<typename U> struct Inner;
2013 /// template<typename U> struct Inner<U*>;
2016 /// template<> template<typename T>
2017 /// struct X<int>::Inner<T*> { /* ... */ };
2019 bool isMemberSpecialization() {
2020 ClassTemplatePartialSpecializationDecl *First =
2021 cast<ClassTemplatePartialSpecializationDecl>(getFirstDecl());
2022 return First->InstantiatedFromMember.getInt();
2025 /// \brief Note that this member template is a specialization.
2026 void setMemberSpecialization() {
2027 ClassTemplatePartialSpecializationDecl *First =
2028 cast<ClassTemplatePartialSpecializationDecl>(getFirstDecl());
2029 assert(First->InstantiatedFromMember.getPointer() &&
2030 "Only member templates can be member template specializations");
2031 return First->InstantiatedFromMember.setInt(true);
2034 /// Retrieves the injected specialization type for this partial
2035 /// specialization. This is not the same as the type-decl-type for
2036 /// this partial specialization, which is an InjectedClassNameType.
2037 QualType getInjectedSpecializationType() const {
2038 assert(getTypeForDecl() && "partial specialization has no type set!");
2039 return cast<InjectedClassNameType>(getTypeForDecl())
2040 ->getInjectedSpecializationType();
2043 // FIXME: Add Profile support!
2045 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2047 static bool classofKind(Kind K) {
2048 return K == ClassTemplatePartialSpecialization;
2052 /// Declaration of a class template.
2053 class ClassTemplateDecl : public RedeclarableTemplateDecl {
2055 /// \brief Data that is common to all of the declarations of a given
2057 struct Common : CommonBase {
2058 /// \brief The class template specializations for this class
2059 /// template, including explicit specializations and instantiations.
2060 llvm::FoldingSetVector<ClassTemplateSpecializationDecl> Specializations;
2062 /// \brief The class template partial specializations for this class
2064 llvm::FoldingSetVector<ClassTemplatePartialSpecializationDecl>
2065 PartialSpecializations;
2067 /// \brief The injected-class-name type for this class template.
2068 QualType InjectedClassNameType;
2073 /// \brief Retrieve the set of specializations of this class template.
2074 llvm::FoldingSetVector<ClassTemplateSpecializationDecl> &
2075 getSpecializations() const;
2077 /// \brief Retrieve the set of partial specializations of this class
2079 llvm::FoldingSetVector<ClassTemplatePartialSpecializationDecl> &
2080 getPartialSpecializations();
2082 ClassTemplateDecl(ConstrainedTemplateDeclInfo *CTDI, ASTContext &C,
2083 DeclContext *DC, SourceLocation L, DeclarationName Name,
2084 TemplateParameterList *Params, NamedDecl *Decl)
2085 : RedeclarableTemplateDecl(CTDI, ClassTemplate, C, DC, L, Name, Params,
2088 ClassTemplateDecl(ASTContext &C, DeclContext *DC, SourceLocation L,
2089 DeclarationName Name, TemplateParameterList *Params,
2091 : ClassTemplateDecl(nullptr, C, DC, L, Name, Params, Decl) {}
2093 CommonBase *newCommon(ASTContext &C) const override;
2095 Common *getCommonPtr() const {
2096 return static_cast<Common *>(RedeclarableTemplateDecl::getCommonPtr());
2100 friend class ASTDeclReader;
2101 friend class ASTDeclWriter;
2103 /// \brief Load any lazily-loaded specializations from the external source.
2104 void LoadLazySpecializations() const;
2106 /// \brief Get the underlying class declarations of the template.
2107 CXXRecordDecl *getTemplatedDecl() const {
2108 return static_cast<CXXRecordDecl *>(TemplatedDecl);
2111 /// \brief Returns whether this template declaration defines the primary
2113 bool isThisDeclarationADefinition() const {
2114 return getTemplatedDecl()->isThisDeclarationADefinition();
2117 // FIXME: remove default argument for AssociatedConstraints
2118 /// \brief Create a class template node.
2119 static ClassTemplateDecl *Create(ASTContext &C, DeclContext *DC,
2121 DeclarationName Name,
2122 TemplateParameterList *Params,
2124 Expr *AssociatedConstraints = nullptr);
2126 /// \brief Create an empty class template node.
2127 static ClassTemplateDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2129 /// \brief Return the specialization with the provided arguments if it exists,
2130 /// otherwise return the insertion point.
2131 ClassTemplateSpecializationDecl *
2132 findSpecialization(ArrayRef<TemplateArgument> Args, void *&InsertPos);
2134 /// \brief Insert the specified specialization knowing that it is not already
2135 /// in. InsertPos must be obtained from findSpecialization.
2136 void AddSpecialization(ClassTemplateSpecializationDecl *D, void *InsertPos);
2138 ClassTemplateDecl *getCanonicalDecl() override {
2139 return cast<ClassTemplateDecl>(
2140 RedeclarableTemplateDecl::getCanonicalDecl());
2142 const ClassTemplateDecl *getCanonicalDecl() const {
2143 return cast<ClassTemplateDecl>(
2144 RedeclarableTemplateDecl::getCanonicalDecl());
2147 /// \brief Retrieve the previous declaration of this class template, or
2148 /// nullptr if no such declaration exists.
2149 ClassTemplateDecl *getPreviousDecl() {
2150 return cast_or_null<ClassTemplateDecl>(
2151 static_cast<RedeclarableTemplateDecl *>(this)->getPreviousDecl());
2153 const ClassTemplateDecl *getPreviousDecl() const {
2154 return cast_or_null<ClassTemplateDecl>(
2155 static_cast<const RedeclarableTemplateDecl *>(
2156 this)->getPreviousDecl());
2159 ClassTemplateDecl *getMostRecentDecl() {
2160 return cast<ClassTemplateDecl>(
2161 static_cast<RedeclarableTemplateDecl *>(this)->getMostRecentDecl());
2163 const ClassTemplateDecl *getMostRecentDecl() const {
2164 return const_cast<ClassTemplateDecl*>(this)->getMostRecentDecl();
2167 ClassTemplateDecl *getInstantiatedFromMemberTemplate() const {
2168 return cast_or_null<ClassTemplateDecl>(
2169 RedeclarableTemplateDecl::getInstantiatedFromMemberTemplate());
2172 /// \brief Return the partial specialization with the provided arguments if it
2173 /// exists, otherwise return the insertion point.
2174 ClassTemplatePartialSpecializationDecl *
2175 findPartialSpecialization(ArrayRef<TemplateArgument> Args, void *&InsertPos);
2177 /// \brief Insert the specified partial specialization knowing that it is not
2178 /// already in. InsertPos must be obtained from findPartialSpecialization.
2179 void AddPartialSpecialization(ClassTemplatePartialSpecializationDecl *D,
2182 /// \brief Retrieve the partial specializations as an ordered list.
2183 void getPartialSpecializations(
2184 SmallVectorImpl<ClassTemplatePartialSpecializationDecl *> &PS);
2186 /// \brief Find a class template partial specialization with the given
2189 /// \param T a dependent type that names a specialization of this class
2192 /// \returns the class template partial specialization that exactly matches
2193 /// the type \p T, or nullptr if no such partial specialization exists.
2194 ClassTemplatePartialSpecializationDecl *findPartialSpecialization(QualType T);
2196 /// \brief Find a class template partial specialization which was instantiated
2197 /// from the given member partial specialization.
2199 /// \param D a member class template partial specialization.
2201 /// \returns the class template partial specialization which was instantiated
2202 /// from the given member partial specialization, or nullptr if no such
2203 /// partial specialization exists.
2204 ClassTemplatePartialSpecializationDecl *
2205 findPartialSpecInstantiatedFromMember(
2206 ClassTemplatePartialSpecializationDecl *D);
2208 /// \brief Retrieve the template specialization type of the
2209 /// injected-class-name for this class template.
2211 /// The injected-class-name for a class template \c X is \c
2212 /// X<template-args>, where \c template-args is formed from the
2213 /// template arguments that correspond to the template parameters of
2214 /// \c X. For example:
2217 /// template<typename T, int N>
2219 /// typedef array this_type; // "array" is equivalent to "array<T, N>"
2222 QualType getInjectedClassNameSpecialization();
2224 using spec_iterator = SpecIterator<ClassTemplateSpecializationDecl>;
2225 using spec_range = llvm::iterator_range<spec_iterator>;
2227 spec_range specializations() const {
2228 return spec_range(spec_begin(), spec_end());
2231 spec_iterator spec_begin() const {
2232 return makeSpecIterator(getSpecializations(), false);
2235 spec_iterator spec_end() const {
2236 return makeSpecIterator(getSpecializations(), true);
2239 // Implement isa/cast/dyncast support
2240 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2241 static bool classofKind(Kind K) { return K == ClassTemplate; }
2244 /// \brief Declaration of a friend template.
2248 /// template \<typename T> class A {
2249 /// friend class MyVector<T>; // not a friend template
2250 /// template \<typename U> friend class B; // not a friend template
2251 /// template \<typename U> friend class Foo<T>::Nested; // friend template
2255 /// \note This class is not currently in use. All of the above
2256 /// will yield a FriendDecl, not a FriendTemplateDecl.
2257 class FriendTemplateDecl : public Decl {
2258 virtual void anchor();
2261 using FriendUnion = llvm::PointerUnion<NamedDecl *,TypeSourceInfo *>;
2264 // The number of template parameters; always non-zero.
2265 unsigned NumParams = 0;
2267 // The parameter list.
2268 TemplateParameterList **Params = nullptr;
2270 // The declaration that's a friend of this class.
2273 // Location of the 'friend' specifier.
2274 SourceLocation FriendLoc;
2276 FriendTemplateDecl(DeclContext *DC, SourceLocation Loc,
2277 MutableArrayRef<TemplateParameterList *> Params,
2278 FriendUnion Friend, SourceLocation FriendLoc)
2279 : Decl(Decl::FriendTemplate, DC, Loc), NumParams(Params.size()),
2280 Params(Params.data()), Friend(Friend), FriendLoc(FriendLoc) {}
2282 FriendTemplateDecl(EmptyShell Empty) : Decl(Decl::FriendTemplate, Empty) {}
2285 friend class ASTDeclReader;
2287 static FriendTemplateDecl *
2288 Create(ASTContext &Context, DeclContext *DC, SourceLocation Loc,
2289 MutableArrayRef<TemplateParameterList *> Params, FriendUnion Friend,
2290 SourceLocation FriendLoc);
2292 static FriendTemplateDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2294 /// If this friend declaration names a templated type (or
2295 /// a dependent member type of a templated type), return that
2296 /// type; otherwise return null.
2297 TypeSourceInfo *getFriendType() const {
2298 return Friend.dyn_cast<TypeSourceInfo*>();
2301 /// If this friend declaration names a templated function (or
2302 /// a member function of a templated type), return that type;
2303 /// otherwise return null.
2304 NamedDecl *getFriendDecl() const {
2305 return Friend.dyn_cast<NamedDecl*>();
2308 /// \brief Retrieves the location of the 'friend' keyword.
2309 SourceLocation getFriendLoc() const {
2313 TemplateParameterList *getTemplateParameterList(unsigned i) const {
2314 assert(i <= NumParams);
2318 unsigned getNumTemplateParameters() const {
2322 // Implement isa/cast/dyncast/etc.
2323 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2324 static bool classofKind(Kind K) { return K == Decl::FriendTemplate; }
2327 /// \brief Declaration of an alias template.
2331 /// template \<typename T> using V = std::map<T*, int, MyCompare<T>>;
2333 class TypeAliasTemplateDecl : public RedeclarableTemplateDecl {
2335 using Common = CommonBase;
2337 TypeAliasTemplateDecl(ASTContext &C, DeclContext *DC, SourceLocation L,
2338 DeclarationName Name, TemplateParameterList *Params,
2340 : RedeclarableTemplateDecl(TypeAliasTemplate, C, DC, L, Name, Params,
2343 CommonBase *newCommon(ASTContext &C) const override;
2345 Common *getCommonPtr() {
2346 return static_cast<Common *>(RedeclarableTemplateDecl::getCommonPtr());
2350 friend class ASTDeclReader;
2351 friend class ASTDeclWriter;
2353 /// Get the underlying function declaration of the template.
2354 TypeAliasDecl *getTemplatedDecl() const {
2355 return static_cast<TypeAliasDecl *>(TemplatedDecl);
2359 TypeAliasTemplateDecl *getCanonicalDecl() override {
2360 return cast<TypeAliasTemplateDecl>(
2361 RedeclarableTemplateDecl::getCanonicalDecl());
2363 const TypeAliasTemplateDecl *getCanonicalDecl() const {
2364 return cast<TypeAliasTemplateDecl>(
2365 RedeclarableTemplateDecl::getCanonicalDecl());
2368 /// \brief Retrieve the previous declaration of this function template, or
2369 /// nullptr if no such declaration exists.
2370 TypeAliasTemplateDecl *getPreviousDecl() {
2371 return cast_or_null<TypeAliasTemplateDecl>(
2372 static_cast<RedeclarableTemplateDecl *>(this)->getPreviousDecl());
2374 const TypeAliasTemplateDecl *getPreviousDecl() const {
2375 return cast_or_null<TypeAliasTemplateDecl>(
2376 static_cast<const RedeclarableTemplateDecl *>(
2377 this)->getPreviousDecl());
2380 TypeAliasTemplateDecl *getInstantiatedFromMemberTemplate() const {
2381 return cast_or_null<TypeAliasTemplateDecl>(
2382 RedeclarableTemplateDecl::getInstantiatedFromMemberTemplate());
2385 /// \brief Create a function template node.
2386 static TypeAliasTemplateDecl *Create(ASTContext &C, DeclContext *DC,
2388 DeclarationName Name,
2389 TemplateParameterList *Params,
2392 /// \brief Create an empty alias template node.
2393 static TypeAliasTemplateDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2395 // Implement isa/cast/dyncast support
2396 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2397 static bool classofKind(Kind K) { return K == TypeAliasTemplate; }
2400 /// \brief Declaration of a function specialization at template class scope.
2402 /// This is a non-standard extension needed to support MSVC.
2406 /// template <class T>
2408 /// template <class U> void foo(U a) { }
2409 /// template<> void foo(int a) { }
2413 /// "template<> foo(int a)" will be saved in Specialization as a normal
2414 /// CXXMethodDecl. Then during an instantiation of class A, it will be
2415 /// transformed into an actual function specialization.
2416 class ClassScopeFunctionSpecializationDecl : public Decl {
2417 CXXMethodDecl *Specialization;
2418 bool HasExplicitTemplateArgs;
2419 TemplateArgumentListInfo TemplateArgs;
2421 ClassScopeFunctionSpecializationDecl(DeclContext *DC, SourceLocation Loc,
2422 CXXMethodDecl *FD, bool Args,
2423 TemplateArgumentListInfo TemplArgs)
2424 : Decl(Decl::ClassScopeFunctionSpecialization, DC, Loc),
2425 Specialization(FD), HasExplicitTemplateArgs(Args),
2426 TemplateArgs(std::move(TemplArgs)) {}
2428 ClassScopeFunctionSpecializationDecl(EmptyShell Empty)
2429 : Decl(Decl::ClassScopeFunctionSpecialization, Empty) {}
2431 virtual void anchor();
2434 friend class ASTDeclReader;
2435 friend class ASTDeclWriter;
2437 CXXMethodDecl *getSpecialization() const { return Specialization; }
2438 bool hasExplicitTemplateArgs() const { return HasExplicitTemplateArgs; }
2439 const TemplateArgumentListInfo& templateArgs() const { return TemplateArgs; }
2441 static ClassScopeFunctionSpecializationDecl *Create(ASTContext &C,
2445 bool HasExplicitTemplateArgs,
2446 TemplateArgumentListInfo TemplateArgs) {
2447 return new (C, DC) ClassScopeFunctionSpecializationDecl(
2448 DC, Loc, FD, HasExplicitTemplateArgs, std::move(TemplateArgs));
2451 static ClassScopeFunctionSpecializationDecl *
2452 CreateDeserialized(ASTContext &Context, unsigned ID);
2454 // Implement isa/cast/dyncast/etc.
2455 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2457 static bool classofKind(Kind K) {
2458 return K == Decl::ClassScopeFunctionSpecialization;
2462 /// Implementation of inline functions that require the template declarations
2463 inline AnyFunctionDecl::AnyFunctionDecl(FunctionTemplateDecl *FTD)
2466 /// \brief Represents a variable template specialization, which refers to
2467 /// a variable template with a given set of template arguments.
2469 /// Variable template specializations represent both explicit
2470 /// specializations of variable templates, as in the example below, and
2471 /// implicit instantiations of variable templates.
2474 /// template<typename T> constexpr T pi = T(3.1415926535897932385);
2477 /// constexpr float pi<float>; // variable template specialization pi<float>
2479 class VarTemplateSpecializationDecl : public VarDecl,
2480 public llvm::FoldingSetNode {
2482 /// \brief Structure that stores information about a variable template
2483 /// specialization that was instantiated from a variable template partial
2485 struct SpecializedPartialSpecialization {
2486 /// \brief The variable template partial specialization from which this
2487 /// variable template specialization was instantiated.
2488 VarTemplatePartialSpecializationDecl *PartialSpecialization;
2490 /// \brief The template argument list deduced for the variable template
2491 /// partial specialization itself.
2492 const TemplateArgumentList *TemplateArgs;
2495 /// \brief The template that this specialization specializes.
2496 llvm::PointerUnion<VarTemplateDecl *, SpecializedPartialSpecialization *>
2497 SpecializedTemplate;
2499 /// \brief Further info for explicit template specialization/instantiation.
2500 struct ExplicitSpecializationInfo {
2501 /// \brief The type-as-written.
2502 TypeSourceInfo *TypeAsWritten = nullptr;
2504 /// \brief The location of the extern keyword.
2505 SourceLocation ExternLoc;
2507 /// \brief The location of the template keyword.
2508 SourceLocation TemplateKeywordLoc;
2510 ExplicitSpecializationInfo() = default;
2513 /// \brief Further info for explicit template specialization/instantiation.
2514 /// Does not apply to implicit specializations.
2515 ExplicitSpecializationInfo *ExplicitInfo = nullptr;
2517 /// \brief The template arguments used to describe this specialization.
2518 const TemplateArgumentList *TemplateArgs;
2519 TemplateArgumentListInfo TemplateArgsInfo;
2521 /// \brief The point where this template was instantiated (if any).
2522 SourceLocation PointOfInstantiation;
2524 /// \brief The kind of specialization this declaration refers to.
2525 /// Really a value of type TemplateSpecializationKind.
2526 unsigned SpecializationKind : 3;
2528 /// \brief Whether this declaration is a complete definition of the
2529 /// variable template specialization. We can't otherwise tell apart
2530 /// an instantiated declaration from an instantiated definition with
2532 unsigned IsCompleteDefinition : 1;
2535 VarTemplateSpecializationDecl(Kind DK, ASTContext &Context, DeclContext *DC,
2536 SourceLocation StartLoc, SourceLocation IdLoc,
2537 VarTemplateDecl *SpecializedTemplate,
2538 QualType T, TypeSourceInfo *TInfo,
2540 ArrayRef<TemplateArgument> Args);
2542 explicit VarTemplateSpecializationDecl(Kind DK, ASTContext &Context);
2545 friend class ASTDeclReader;
2546 friend class ASTDeclWriter;
2547 friend class VarDecl;
2549 static VarTemplateSpecializationDecl *
2550 Create(ASTContext &Context, DeclContext *DC, SourceLocation StartLoc,
2551 SourceLocation IdLoc, VarTemplateDecl *SpecializedTemplate, QualType T,
2552 TypeSourceInfo *TInfo, StorageClass S,
2553 ArrayRef<TemplateArgument> Args);
2554 static VarTemplateSpecializationDecl *CreateDeserialized(ASTContext &C,
2557 void getNameForDiagnostic(raw_ostream &OS, const PrintingPolicy &Policy,
2558 bool Qualified) const override;
2560 VarTemplateSpecializationDecl *getMostRecentDecl() {
2561 VarDecl *Recent = static_cast<VarDecl *>(this)->getMostRecentDecl();
2562 return cast<VarTemplateSpecializationDecl>(Recent);
2565 /// \brief Retrieve the template that this specialization specializes.
2566 VarTemplateDecl *getSpecializedTemplate() const;
2568 /// \brief Retrieve the template arguments of the variable template
2570 const TemplateArgumentList &getTemplateArgs() const { return *TemplateArgs; }
2572 // TODO: Always set this when creating the new specialization?
2573 void setTemplateArgsInfo(const TemplateArgumentListInfo &ArgsInfo);
2575 const TemplateArgumentListInfo &getTemplateArgsInfo() const {
2576 return TemplateArgsInfo;
2579 /// \brief Determine the kind of specialization that this
2580 /// declaration represents.
2581 TemplateSpecializationKind getSpecializationKind() const {
2582 return static_cast<TemplateSpecializationKind>(SpecializationKind);
2585 bool isExplicitSpecialization() const {
2586 return getSpecializationKind() == TSK_ExplicitSpecialization;
2589 /// \brief True if this declaration is an explicit specialization,
2590 /// explicit instantiation declaration, or explicit instantiation
2592 bool isExplicitInstantiationOrSpecialization() const {
2593 return isTemplateExplicitInstantiationOrSpecialization(
2594 getTemplateSpecializationKind());
2597 void setSpecializationKind(TemplateSpecializationKind TSK) {
2598 SpecializationKind = TSK;
2601 /// \brief Get the point of instantiation (if any), or null if none.
2602 SourceLocation getPointOfInstantiation() const {
2603 return PointOfInstantiation;
2606 void setPointOfInstantiation(SourceLocation Loc) {
2607 assert(Loc.isValid() && "point of instantiation must be valid!");
2608 PointOfInstantiation = Loc;
2611 void setCompleteDefinition() { IsCompleteDefinition = true; }
2613 /// \brief If this variable template specialization is an instantiation of
2614 /// a template (rather than an explicit specialization), return the
2615 /// variable template or variable template partial specialization from which
2616 /// it was instantiated.
2617 llvm::PointerUnion<VarTemplateDecl *, VarTemplatePartialSpecializationDecl *>
2618 getInstantiatedFrom() const {
2619 if (!isTemplateInstantiation(getSpecializationKind()))
2620 return llvm::PointerUnion<VarTemplateDecl *,
2621 VarTemplatePartialSpecializationDecl *>();
2623 return getSpecializedTemplateOrPartial();
2626 /// \brief Retrieve the variable template or variable template partial
2627 /// specialization which was specialized by this.
2628 llvm::PointerUnion<VarTemplateDecl *, VarTemplatePartialSpecializationDecl *>
2629 getSpecializedTemplateOrPartial() const {
2630 if (SpecializedPartialSpecialization *PartialSpec =
2631 SpecializedTemplate.dyn_cast<SpecializedPartialSpecialization *>())
2632 return PartialSpec->PartialSpecialization;
2634 return SpecializedTemplate.get<VarTemplateDecl *>();
2637 /// \brief Retrieve the set of template arguments that should be used
2638 /// to instantiate the initializer of the variable template or variable
2639 /// template partial specialization from which this variable template
2640 /// specialization was instantiated.
2642 /// \returns For a variable template specialization instantiated from the
2643 /// primary template, this function will return the same template arguments
2644 /// as getTemplateArgs(). For a variable template specialization instantiated
2645 /// from a variable template partial specialization, this function will the
2646 /// return deduced template arguments for the variable template partial
2647 /// specialization itself.
2648 const TemplateArgumentList &getTemplateInstantiationArgs() const {
2649 if (SpecializedPartialSpecialization *PartialSpec =
2650 SpecializedTemplate.dyn_cast<SpecializedPartialSpecialization *>())
2651 return *PartialSpec->TemplateArgs;
2653 return getTemplateArgs();
2656 /// \brief Note that this variable template specialization is actually an
2657 /// instantiation of the given variable template partial specialization whose
2658 /// template arguments have been deduced.
2659 void setInstantiationOf(VarTemplatePartialSpecializationDecl *PartialSpec,
2660 const TemplateArgumentList *TemplateArgs) {
2661 assert(!SpecializedTemplate.is<SpecializedPartialSpecialization *>() &&
2662 "Already set to a variable template partial specialization!");
2663 SpecializedPartialSpecialization *PS =
2664 new (getASTContext()) SpecializedPartialSpecialization();
2665 PS->PartialSpecialization = PartialSpec;
2666 PS->TemplateArgs = TemplateArgs;
2667 SpecializedTemplate = PS;
2670 /// \brief Note that this variable template specialization is an instantiation
2671 /// of the given variable template.
2672 void setInstantiationOf(VarTemplateDecl *TemplDecl) {
2673 assert(!SpecializedTemplate.is<SpecializedPartialSpecialization *>() &&
2674 "Previously set to a variable template partial specialization!");
2675 SpecializedTemplate = TemplDecl;
2678 /// \brief Sets the type of this specialization as it was written by
2680 void setTypeAsWritten(TypeSourceInfo *T) {
2682 ExplicitInfo = new (getASTContext()) ExplicitSpecializationInfo;
2683 ExplicitInfo->TypeAsWritten = T;
2686 /// \brief Gets the type of this specialization as it was written by
2687 /// the user, if it was so written.
2688 TypeSourceInfo *getTypeAsWritten() const {
2689 return ExplicitInfo ? ExplicitInfo->TypeAsWritten : nullptr;
2692 /// \brief Gets the location of the extern keyword, if present.
2693 SourceLocation getExternLoc() const {
2694 return ExplicitInfo ? ExplicitInfo->ExternLoc : SourceLocation();
2697 /// \brief Sets the location of the extern keyword.
2698 void setExternLoc(SourceLocation Loc) {
2700 ExplicitInfo = new (getASTContext()) ExplicitSpecializationInfo;
2701 ExplicitInfo->ExternLoc = Loc;
2704 /// \brief Sets the location of the template keyword.
2705 void setTemplateKeywordLoc(SourceLocation Loc) {
2707 ExplicitInfo = new (getASTContext()) ExplicitSpecializationInfo;
2708 ExplicitInfo->TemplateKeywordLoc = Loc;
2711 /// \brief Gets the location of the template keyword, if present.
2712 SourceLocation getTemplateKeywordLoc() const {
2713 return ExplicitInfo ? ExplicitInfo->TemplateKeywordLoc : SourceLocation();
2716 void Profile(llvm::FoldingSetNodeID &ID) const {
2717 Profile(ID, TemplateArgs->asArray(), getASTContext());
2720 static void Profile(llvm::FoldingSetNodeID &ID,
2721 ArrayRef<TemplateArgument> TemplateArgs,
2722 ASTContext &Context) {
2723 ID.AddInteger(TemplateArgs.size());
2724 for (const TemplateArgument &TemplateArg : TemplateArgs)
2725 TemplateArg.Profile(ID, Context);
2728 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2730 static bool classofKind(Kind K) {
2731 return K >= firstVarTemplateSpecialization &&
2732 K <= lastVarTemplateSpecialization;
2736 class VarTemplatePartialSpecializationDecl
2737 : public VarTemplateSpecializationDecl {
2738 /// \brief The list of template parameters
2739 TemplateParameterList *TemplateParams = nullptr;
2741 /// \brief The source info for the template arguments as written.
2742 /// FIXME: redundant with TypeAsWritten?
2743 const ASTTemplateArgumentListInfo *ArgsAsWritten = nullptr;
2745 /// \brief The variable template partial specialization from which this
2746 /// variable template partial specialization was instantiated.
2748 /// The boolean value will be true to indicate that this variable template
2749 /// partial specialization was specialized at this level.
2750 llvm::PointerIntPair<VarTemplatePartialSpecializationDecl *, 1, bool>
2751 InstantiatedFromMember;
2753 VarTemplatePartialSpecializationDecl(
2754 ASTContext &Context, DeclContext *DC, SourceLocation StartLoc,
2755 SourceLocation IdLoc, TemplateParameterList *Params,
2756 VarTemplateDecl *SpecializedTemplate, QualType T, TypeSourceInfo *TInfo,
2757 StorageClass S, ArrayRef<TemplateArgument> Args,
2758 const ASTTemplateArgumentListInfo *ArgInfos);
2760 VarTemplatePartialSpecializationDecl(ASTContext &Context)
2761 : VarTemplateSpecializationDecl(VarTemplatePartialSpecialization,
2763 InstantiatedFromMember(nullptr, false) {}
2765 void anchor() override;
2768 friend class ASTDeclReader;
2769 friend class ASTDeclWriter;
2771 static VarTemplatePartialSpecializationDecl *
2772 Create(ASTContext &Context, DeclContext *DC, SourceLocation StartLoc,
2773 SourceLocation IdLoc, TemplateParameterList *Params,
2774 VarTemplateDecl *SpecializedTemplate, QualType T,
2775 TypeSourceInfo *TInfo, StorageClass S, ArrayRef<TemplateArgument> Args,
2776 const TemplateArgumentListInfo &ArgInfos);
2778 static VarTemplatePartialSpecializationDecl *CreateDeserialized(ASTContext &C,
2781 VarTemplatePartialSpecializationDecl *getMostRecentDecl() {
2782 return cast<VarTemplatePartialSpecializationDecl>(
2783 static_cast<VarTemplateSpecializationDecl *>(
2784 this)->getMostRecentDecl());
2787 /// Get the list of template parameters
2788 TemplateParameterList *getTemplateParameters() const {
2789 return TemplateParams;
2792 /// Get the template arguments as written.
2793 const ASTTemplateArgumentListInfo *getTemplateArgsAsWritten() const {
2794 return ArgsAsWritten;
2797 /// \brief Retrieve the member variable template partial specialization from
2798 /// which this particular variable template partial specialization was
2802 /// template<typename T>
2804 /// template<typename U> U Inner;
2805 /// template<typename U> U* Inner<U*> = (U*)(0); // #1
2808 /// template int* Outer<float>::Inner<int*>;
2811 /// In this example, the instantiation of \c Outer<float>::Inner<int*> will
2812 /// end up instantiating the partial specialization
2813 /// \c Outer<float>::Inner<U*>, which itself was instantiated from the
2814 /// variable template partial specialization \c Outer<T>::Inner<U*>. Given
2815 /// \c Outer<float>::Inner<U*>, this function would return
2816 /// \c Outer<T>::Inner<U*>.
2817 VarTemplatePartialSpecializationDecl *getInstantiatedFromMember() const {
2818 const VarTemplatePartialSpecializationDecl *First =
2819 cast<VarTemplatePartialSpecializationDecl>(getFirstDecl());
2820 return First->InstantiatedFromMember.getPointer();
2824 setInstantiatedFromMember(VarTemplatePartialSpecializationDecl *PartialSpec) {
2825 VarTemplatePartialSpecializationDecl *First =
2826 cast<VarTemplatePartialSpecializationDecl>(getFirstDecl());
2827 First->InstantiatedFromMember.setPointer(PartialSpec);
2830 /// \brief Determines whether this variable template partial specialization
2831 /// was a specialization of a member partial specialization.
2833 /// In the following example, the member template partial specialization
2834 /// \c X<int>::Inner<T*> is a member specialization.
2837 /// template<typename T>
2839 /// template<typename U> U Inner;
2840 /// template<typename U> U* Inner<U*> = (U*)(0);
2843 /// template<> template<typename T>
2844 /// U* X<int>::Inner<T*> = (T*)(0) + 1;
2846 bool isMemberSpecialization() {
2847 VarTemplatePartialSpecializationDecl *First =
2848 cast<VarTemplatePartialSpecializationDecl>(getFirstDecl());
2849 return First->InstantiatedFromMember.getInt();
2852 /// \brief Note that this member template is a specialization.
2853 void setMemberSpecialization() {
2854 VarTemplatePartialSpecializationDecl *First =
2855 cast<VarTemplatePartialSpecializationDecl>(getFirstDecl());
2856 assert(First->InstantiatedFromMember.getPointer() &&
2857 "Only member templates can be member template specializations");
2858 return First->InstantiatedFromMember.setInt(true);
2861 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2863 static bool classofKind(Kind K) {
2864 return K == VarTemplatePartialSpecialization;
2868 /// Declaration of a variable template.
2869 class VarTemplateDecl : public RedeclarableTemplateDecl {
2871 /// \brief Data that is common to all of the declarations of a given
2872 /// variable template.
2873 struct Common : CommonBase {
2874 /// \brief The variable template specializations for this variable
2875 /// template, including explicit specializations and instantiations.
2876 llvm::FoldingSetVector<VarTemplateSpecializationDecl> Specializations;
2878 /// \brief The variable template partial specializations for this variable
2880 llvm::FoldingSetVector<VarTemplatePartialSpecializationDecl>
2881 PartialSpecializations;
2886 /// \brief Retrieve the set of specializations of this variable template.
2887 llvm::FoldingSetVector<VarTemplateSpecializationDecl> &
2888 getSpecializations() const;
2890 /// \brief Retrieve the set of partial specializations of this class
2892 llvm::FoldingSetVector<VarTemplatePartialSpecializationDecl> &
2893 getPartialSpecializations();
2895 VarTemplateDecl(ASTContext &C, DeclContext *DC, SourceLocation L,
2896 DeclarationName Name, TemplateParameterList *Params,
2898 : RedeclarableTemplateDecl(VarTemplate, C, DC, L, Name, Params, Decl) {}
2900 CommonBase *newCommon(ASTContext &C) const override;
2902 Common *getCommonPtr() const {
2903 return static_cast<Common *>(RedeclarableTemplateDecl::getCommonPtr());
2907 friend class ASTDeclReader;
2908 friend class ASTDeclWriter;
2910 /// \brief Load any lazily-loaded specializations from the external source.
2911 void LoadLazySpecializations() const;
2913 /// \brief Get the underlying variable declarations of the template.
2914 VarDecl *getTemplatedDecl() const {
2915 return static_cast<VarDecl *>(TemplatedDecl);
2918 /// \brief Returns whether this template declaration defines the primary
2919 /// variable pattern.
2920 bool isThisDeclarationADefinition() const {
2921 return getTemplatedDecl()->isThisDeclarationADefinition();
2924 VarTemplateDecl *getDefinition();
2926 /// \brief Create a variable template node.
2927 static VarTemplateDecl *Create(ASTContext &C, DeclContext *DC,
2928 SourceLocation L, DeclarationName Name,
2929 TemplateParameterList *Params,
2932 /// \brief Create an empty variable template node.
2933 static VarTemplateDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2935 /// \brief Return the specialization with the provided arguments if it exists,
2936 /// otherwise return the insertion point.
2937 VarTemplateSpecializationDecl *
2938 findSpecialization(ArrayRef<TemplateArgument> Args, void *&InsertPos);
2940 /// \brief Insert the specified specialization knowing that it is not already
2941 /// in. InsertPos must be obtained from findSpecialization.
2942 void AddSpecialization(VarTemplateSpecializationDecl *D, void *InsertPos);
2944 VarTemplateDecl *getCanonicalDecl() override {
2945 return cast<VarTemplateDecl>(RedeclarableTemplateDecl::getCanonicalDecl());
2947 const VarTemplateDecl *getCanonicalDecl() const {
2948 return cast<VarTemplateDecl>(RedeclarableTemplateDecl::getCanonicalDecl());
2951 /// \brief Retrieve the previous declaration of this variable template, or
2952 /// nullptr if no such declaration exists.
2953 VarTemplateDecl *getPreviousDecl() {
2954 return cast_or_null<VarTemplateDecl>(
2955 static_cast<RedeclarableTemplateDecl *>(this)->getPreviousDecl());
2957 const VarTemplateDecl *getPreviousDecl() const {
2958 return cast_or_null<VarTemplateDecl>(
2959 static_cast<const RedeclarableTemplateDecl *>(
2960 this)->getPreviousDecl());
2963 VarTemplateDecl *getMostRecentDecl() {
2964 return cast<VarTemplateDecl>(
2965 static_cast<RedeclarableTemplateDecl *>(this)->getMostRecentDecl());
2967 const VarTemplateDecl *getMostRecentDecl() const {
2968 return const_cast<VarTemplateDecl *>(this)->getMostRecentDecl();
2971 VarTemplateDecl *getInstantiatedFromMemberTemplate() const {
2972 return cast_or_null<VarTemplateDecl>(
2973 RedeclarableTemplateDecl::getInstantiatedFromMemberTemplate());
2976 /// \brief Return the partial specialization with the provided arguments if it
2977 /// exists, otherwise return the insertion point.
2978 VarTemplatePartialSpecializationDecl *
2979 findPartialSpecialization(ArrayRef<TemplateArgument> Args, void *&InsertPos);
2981 /// \brief Insert the specified partial specialization knowing that it is not
2982 /// already in. InsertPos must be obtained from findPartialSpecialization.
2983 void AddPartialSpecialization(VarTemplatePartialSpecializationDecl *D,
2986 /// \brief Retrieve the partial specializations as an ordered list.
2987 void getPartialSpecializations(
2988 SmallVectorImpl<VarTemplatePartialSpecializationDecl *> &PS);
2990 /// \brief Find a variable template partial specialization which was
2992 /// from the given member partial specialization.
2994 /// \param D a member variable template partial specialization.
2996 /// \returns the variable template partial specialization which was
2998 /// from the given member partial specialization, or nullptr if no such
2999 /// partial specialization exists.
3000 VarTemplatePartialSpecializationDecl *findPartialSpecInstantiatedFromMember(
3001 VarTemplatePartialSpecializationDecl *D);
3003 using spec_iterator = SpecIterator<VarTemplateSpecializationDecl>;
3004 using spec_range = llvm::iterator_range<spec_iterator>;
3006 spec_range specializations() const {
3007 return spec_range(spec_begin(), spec_end());
3010 spec_iterator spec_begin() const {
3011 return makeSpecIterator(getSpecializations(), false);
3014 spec_iterator spec_end() const {
3015 return makeSpecIterator(getSpecializations(), true);
3018 // Implement isa/cast/dyncast support
3019 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3020 static bool classofKind(Kind K) { return K == VarTemplate; }
3023 inline NamedDecl *getAsNamedDecl(TemplateParameter P) {
3024 if (auto *PD = P.dyn_cast<TemplateTypeParmDecl*>())
3026 if (auto *PD = P.dyn_cast<NonTypeTemplateParmDecl*>())
3028 return P.get<TemplateTemplateParmDecl*>();
3031 inline TemplateDecl *getAsTypeTemplateDecl(Decl *D) {
3032 auto *TD = dyn_cast<TemplateDecl>(D);
3033 return TD && (isa<ClassTemplateDecl>(TD) ||
3034 isa<ClassTemplatePartialSpecializationDecl>(TD) ||
3035 isa<TypeAliasTemplateDecl>(TD) ||
3036 isa<TemplateTemplateParmDecl>(TD))
3041 } // namespace clang
3043 #endif // LLVM_CLANG_AST_DECLTEMPLATE_H