1 //===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //===----------------------------------------------------------------------===//
8 // This file implements semantic analysis for C++ templates.
9 //===----------------------------------------------------------------------===//
11 #include "TreeTransform.h"
12 #include "clang/AST/ASTConsumer.h"
13 #include "clang/AST/ASTContext.h"
14 #include "clang/AST/DeclFriend.h"
15 #include "clang/AST/DeclTemplate.h"
16 #include "clang/AST/Expr.h"
17 #include "clang/AST/ExprCXX.h"
18 #include "clang/AST/RecursiveASTVisitor.h"
19 #include "clang/AST/TypeVisitor.h"
20 #include "clang/Basic/Builtins.h"
21 #include "clang/Basic/LangOptions.h"
22 #include "clang/Basic/PartialDiagnostic.h"
23 #include "clang/Basic/Stack.h"
24 #include "clang/Basic/TargetInfo.h"
25 #include "clang/Sema/DeclSpec.h"
26 #include "clang/Sema/Lookup.h"
27 #include "clang/Sema/Overload.h"
28 #include "clang/Sema/ParsedTemplate.h"
29 #include "clang/Sema/Scope.h"
30 #include "clang/Sema/SemaInternal.h"
31 #include "clang/Sema/Template.h"
32 #include "clang/Sema/TemplateDeduction.h"
33 #include "llvm/ADT/SmallBitVector.h"
34 #include "llvm/ADT/SmallString.h"
35 #include "llvm/ADT/StringExtras.h"
38 using namespace clang;
41 // Exported for use by Parser.
43 clang::getTemplateParamsRange(TemplateParameterList const * const *Ps,
45 if (!N) return SourceRange();
46 return SourceRange(Ps[0]->getTemplateLoc(), Ps[N-1]->getRAngleLoc());
49 /// \brief Determine whether the declaration found is acceptable as the name
50 /// of a template and, if so, return that template declaration. Otherwise,
53 /// Note that this may return an UnresolvedUsingValueDecl if AllowDependent
54 /// is true. In all other cases it will return a TemplateDecl (or null).
55 NamedDecl *Sema::getAsTemplateNameDecl(NamedDecl *D,
56 bool AllowFunctionTemplates,
57 bool AllowDependent) {
58 D = D->getUnderlyingDecl();
60 if (isa<TemplateDecl>(D)) {
61 if (!AllowFunctionTemplates && isa<FunctionTemplateDecl>(D))
67 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
68 // C++ [temp.local]p1:
69 // Like normal (non-template) classes, class templates have an
70 // injected-class-name (Clause 9). The injected-class-name
71 // can be used with or without a template-argument-list. When
72 // it is used without a template-argument-list, it is
73 // equivalent to the injected-class-name followed by the
74 // template-parameters of the class template enclosed in
75 // <>. When it is used with a template-argument-list, it
76 // refers to the specified class template specialization,
77 // which could be the current specialization or another
79 if (Record->isInjectedClassName()) {
80 Record = cast<CXXRecordDecl>(Record->getDeclContext());
81 if (Record->getDescribedClassTemplate())
82 return Record->getDescribedClassTemplate();
84 if (ClassTemplateSpecializationDecl *Spec
85 = dyn_cast<ClassTemplateSpecializationDecl>(Record))
86 return Spec->getSpecializedTemplate();
92 // 'using Dependent::foo;' can resolve to a template name.
93 // 'using typename Dependent::foo;' cannot (not even if 'foo' is an
94 // injected-class-name).
95 if (AllowDependent && isa<UnresolvedUsingValueDecl>(D))
101 void Sema::FilterAcceptableTemplateNames(LookupResult &R,
102 bool AllowFunctionTemplates,
103 bool AllowDependent) {
104 LookupResult::Filter filter = R.makeFilter();
105 while (filter.hasNext()) {
106 NamedDecl *Orig = filter.next();
107 if (!getAsTemplateNameDecl(Orig, AllowFunctionTemplates, AllowDependent))
113 bool Sema::hasAnyAcceptableTemplateNames(LookupResult &R,
114 bool AllowFunctionTemplates,
116 bool AllowNonTemplateFunctions) {
117 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
118 if (getAsTemplateNameDecl(*I, AllowFunctionTemplates, AllowDependent))
120 if (AllowNonTemplateFunctions &&
121 isa<FunctionDecl>((*I)->getUnderlyingDecl()))
128 TemplateNameKind Sema::isTemplateName(Scope *S,
130 bool hasTemplateKeyword,
131 const UnqualifiedId &Name,
132 ParsedType ObjectTypePtr,
133 bool EnteringContext,
134 TemplateTy &TemplateResult,
135 bool &MemberOfUnknownSpecialization) {
136 assert(getLangOpts().CPlusPlus && "No template names in C!");
138 DeclarationName TName;
139 MemberOfUnknownSpecialization = false;
141 switch (Name.getKind()) {
142 case UnqualifiedIdKind::IK_Identifier:
143 TName = DeclarationName(Name.Identifier);
146 case UnqualifiedIdKind::IK_OperatorFunctionId:
147 TName = Context.DeclarationNames.getCXXOperatorName(
148 Name.OperatorFunctionId.Operator);
151 case UnqualifiedIdKind::IK_LiteralOperatorId:
152 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
156 return TNK_Non_template;
159 QualType ObjectType = ObjectTypePtr.get();
161 AssumedTemplateKind AssumedTemplate;
162 LookupResult R(*this, TName, Name.getBeginLoc(), LookupOrdinaryName);
163 if (LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
164 MemberOfUnknownSpecialization, SourceLocation(),
166 return TNK_Non_template;
168 if (AssumedTemplate != AssumedTemplateKind::None) {
169 TemplateResult = TemplateTy::make(Context.getAssumedTemplateName(TName));
170 // Let the parser know whether we found nothing or found functions; if we
171 // found nothing, we want to more carefully check whether this is actually
172 // a function template name versus some other kind of undeclared identifier.
173 return AssumedTemplate == AssumedTemplateKind::FoundNothing
174 ? TNK_Undeclared_template
175 : TNK_Function_template;
179 return TNK_Non_template;
181 NamedDecl *D = nullptr;
182 if (R.isAmbiguous()) {
183 // If we got an ambiguity involving a non-function template, treat this
184 // as a template name, and pick an arbitrary template for error recovery.
185 bool AnyFunctionTemplates = false;
186 for (NamedDecl *FoundD : R) {
187 if (NamedDecl *FoundTemplate = getAsTemplateNameDecl(FoundD)) {
188 if (isa<FunctionTemplateDecl>(FoundTemplate))
189 AnyFunctionTemplates = true;
197 // If we didn't find any templates at all, this isn't a template name.
198 // Leave the ambiguity for a later lookup to diagnose.
199 if (!D && !AnyFunctionTemplates) {
200 R.suppressDiagnostics();
201 return TNK_Non_template;
204 // If the only templates were function templates, filter out the rest.
205 // We'll diagnose the ambiguity later.
207 FilterAcceptableTemplateNames(R);
210 // At this point, we have either picked a single template name declaration D
211 // or we have a non-empty set of results R containing either one template name
212 // declaration or a set of function templates.
214 TemplateName Template;
215 TemplateNameKind TemplateKind;
217 unsigned ResultCount = R.end() - R.begin();
218 if (!D && ResultCount > 1) {
219 // We assume that we'll preserve the qualifier from a function
220 // template name in other ways.
221 Template = Context.getOverloadedTemplateName(R.begin(), R.end());
222 TemplateKind = TNK_Function_template;
224 // We'll do this lookup again later.
225 R.suppressDiagnostics();
228 D = getAsTemplateNameDecl(*R.begin());
229 assert(D && "unambiguous result is not a template name");
232 if (isa<UnresolvedUsingValueDecl>(D)) {
233 // We don't yet know whether this is a template-name or not.
234 MemberOfUnknownSpecialization = true;
235 return TNK_Non_template;
238 TemplateDecl *TD = cast<TemplateDecl>(D);
240 if (SS.isSet() && !SS.isInvalid()) {
241 NestedNameSpecifier *Qualifier = SS.getScopeRep();
242 Template = Context.getQualifiedTemplateName(Qualifier,
243 hasTemplateKeyword, TD);
245 Template = TemplateName(TD);
248 if (isa<FunctionTemplateDecl>(TD)) {
249 TemplateKind = TNK_Function_template;
251 // We'll do this lookup again later.
252 R.suppressDiagnostics();
254 assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) ||
255 isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD) ||
256 isa<BuiltinTemplateDecl>(TD) || isa<ConceptDecl>(TD));
258 isa<VarTemplateDecl>(TD) ? TNK_Var_template :
259 isa<ConceptDecl>(TD) ? TNK_Concept_template :
264 TemplateResult = TemplateTy::make(Template);
268 bool Sema::isDeductionGuideName(Scope *S, const IdentifierInfo &Name,
269 SourceLocation NameLoc,
270 ParsedTemplateTy *Template) {
272 bool MemberOfUnknownSpecialization = false;
274 // We could use redeclaration lookup here, but we don't need to: the
275 // syntactic form of a deduction guide is enough to identify it even
276 // if we can't look up the template name at all.
277 LookupResult R(*this, DeclarationName(&Name), NameLoc, LookupOrdinaryName);
278 if (LookupTemplateName(R, S, SS, /*ObjectType*/ QualType(),
279 /*EnteringContext*/ false,
280 MemberOfUnknownSpecialization))
283 if (R.empty()) return false;
284 if (R.isAmbiguous()) {
285 // FIXME: Diagnose an ambiguity if we find at least one template.
286 R.suppressDiagnostics();
290 // We only treat template-names that name type templates as valid deduction
292 TemplateDecl *TD = R.getAsSingle<TemplateDecl>();
293 if (!TD || !getAsTypeTemplateDecl(TD))
297 *Template = TemplateTy::make(TemplateName(TD));
301 bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II,
302 SourceLocation IILoc,
304 const CXXScopeSpec *SS,
305 TemplateTy &SuggestedTemplate,
306 TemplateNameKind &SuggestedKind) {
307 // We can't recover unless there's a dependent scope specifier preceding the
309 // FIXME: Typo correction?
310 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
311 computeDeclContext(*SS))
314 // The code is missing a 'template' keyword prior to the dependent template
316 NestedNameSpecifier *Qualifier = (NestedNameSpecifier*)SS->getScopeRep();
317 Diag(IILoc, diag::err_template_kw_missing)
318 << Qualifier << II.getName()
319 << FixItHint::CreateInsertion(IILoc, "template ");
321 = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II));
322 SuggestedKind = TNK_Dependent_template_name;
326 bool Sema::LookupTemplateName(LookupResult &Found,
327 Scope *S, CXXScopeSpec &SS,
329 bool EnteringContext,
330 bool &MemberOfUnknownSpecialization,
331 SourceLocation TemplateKWLoc,
332 AssumedTemplateKind *ATK) {
334 *ATK = AssumedTemplateKind::None;
336 Found.setTemplateNameLookup(true);
338 // Determine where to perform name lookup
339 MemberOfUnknownSpecialization = false;
340 DeclContext *LookupCtx = nullptr;
341 bool IsDependent = false;
342 if (!ObjectType.isNull()) {
343 // This nested-name-specifier occurs in a member access expression, e.g.,
344 // x->B::f, and we are looking into the type of the object.
345 assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
346 LookupCtx = computeDeclContext(ObjectType);
347 IsDependent = !LookupCtx && ObjectType->isDependentType();
348 assert((IsDependent || !ObjectType->isIncompleteType() ||
349 ObjectType->castAs<TagType>()->isBeingDefined()) &&
350 "Caller should have completed object type");
352 // Template names cannot appear inside an Objective-C class or object type
355 // FIXME: This is wrong. For example:
357 // template<typename T> using Vec = T __attribute__((ext_vector_type(4)));
359 // vi.Vec<int>::~Vec<int>();
361 // ... should be accepted but we will not treat 'Vec' as a template name
362 // here. The right thing to do would be to check if the name is a valid
363 // vector component name, and look up a template name if not. And similarly
364 // for lookups into Objective-C class and object types, where the same
365 // problem can arise.
366 if (ObjectType->isObjCObjectOrInterfaceType() ||
367 ObjectType->isVectorType()) {
371 } else if (SS.isSet()) {
372 // This nested-name-specifier occurs after another nested-name-specifier,
373 // so long into the context associated with the prior nested-name-specifier.
374 LookupCtx = computeDeclContext(SS, EnteringContext);
375 IsDependent = !LookupCtx;
377 // The declaration context must be complete.
378 if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
382 bool ObjectTypeSearchedInScope = false;
383 bool AllowFunctionTemplatesInLookup = true;
385 // Perform "qualified" name lookup into the declaration context we
386 // computed, which is either the type of the base of a member access
387 // expression or the declaration context associated with a prior
388 // nested-name-specifier.
389 LookupQualifiedName(Found, LookupCtx);
391 // FIXME: The C++ standard does not clearly specify what happens in the
392 // case where the object type is dependent, and implementations vary. In
393 // Clang, we treat a name after a . or -> as a template-name if lookup
394 // finds a non-dependent member or member of the current instantiation that
395 // is a type template, or finds no such members and lookup in the context
396 // of the postfix-expression finds a type template. In the latter case, the
397 // name is nonetheless dependent, and we may resolve it to a member of an
398 // unknown specialization when we come to instantiate the template.
399 IsDependent |= Found.wasNotFoundInCurrentInstantiation();
402 if (!SS.isSet() && (ObjectType.isNull() || Found.empty())) {
403 // C++ [basic.lookup.classref]p1:
404 // In a class member access expression (5.2.5), if the . or -> token is
405 // immediately followed by an identifier followed by a <, the
406 // identifier must be looked up to determine whether the < is the
407 // beginning of a template argument list (14.2) or a less-than operator.
408 // The identifier is first looked up in the class of the object
409 // expression. If the identifier is not found, it is then looked up in
410 // the context of the entire postfix-expression and shall name a class
413 LookupName(Found, S);
415 if (!ObjectType.isNull()) {
416 // FIXME: We should filter out all non-type templates here, particularly
417 // variable templates and concepts. But the exclusion of alias templates
418 // and template template parameters is a wording defect.
419 AllowFunctionTemplatesInLookup = false;
420 ObjectTypeSearchedInScope = true;
423 IsDependent |= Found.wasNotFoundInCurrentInstantiation();
426 if (Found.isAmbiguous())
429 if (ATK && !SS.isSet() && ObjectType.isNull() && TemplateKWLoc.isInvalid()) {
430 // C++2a [temp.names]p2:
431 // A name is also considered to refer to a template if it is an
432 // unqualified-id followed by a < and name lookup finds either one or more
433 // functions or finds nothing.
435 // To keep our behavior consistent, we apply the "finds nothing" part in
436 // all language modes, and diagnose the empty lookup in ActOnCallExpr if we
437 // successfully form a call to an undeclared template-id.
439 getLangOpts().CPlusPlus2a &&
440 std::all_of(Found.begin(), Found.end(), [](NamedDecl *ND) {
441 return isa<FunctionDecl>(ND->getUnderlyingDecl());
443 if (AllFunctions || (Found.empty() && !IsDependent)) {
444 // If lookup found any functions, or if this is a name that can only be
445 // used for a function, then strongly assume this is a function
447 *ATK = (Found.empty() && Found.getLookupName().isIdentifier())
448 ? AssumedTemplateKind::FoundNothing
449 : AssumedTemplateKind::FoundFunctions;
455 if (Found.empty() && !IsDependent) {
456 // If we did not find any names, attempt to correct any typos.
457 DeclarationName Name = Found.getLookupName();
459 // Simple filter callback that, for keywords, only accepts the C++ *_cast
460 DefaultFilterCCC FilterCCC{};
461 FilterCCC.WantTypeSpecifiers = false;
462 FilterCCC.WantExpressionKeywords = false;
463 FilterCCC.WantRemainingKeywords = false;
464 FilterCCC.WantCXXNamedCasts = true;
465 if (TypoCorrection Corrected =
466 CorrectTypo(Found.getLookupNameInfo(), Found.getLookupKind(), S,
467 &SS, FilterCCC, CTK_ErrorRecovery, LookupCtx)) {
468 if (auto *ND = Corrected.getFoundDecl())
470 FilterAcceptableTemplateNames(Found);
471 if (Found.isAmbiguous()) {
473 } else if (!Found.empty()) {
474 Found.setLookupName(Corrected.getCorrection());
476 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
477 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
478 Name.getAsString() == CorrectedStr;
479 diagnoseTypo(Corrected, PDiag(diag::err_no_member_template_suggest)
480 << Name << LookupCtx << DroppedSpecifier
483 diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest) << Name);
489 NamedDecl *ExampleLookupResult =
490 Found.empty() ? nullptr : Found.getRepresentativeDecl();
491 FilterAcceptableTemplateNames(Found, AllowFunctionTemplatesInLookup);
494 MemberOfUnknownSpecialization = true;
498 // If a 'template' keyword was used, a lookup that finds only non-template
499 // names is an error.
500 if (ExampleLookupResult && TemplateKWLoc.isValid()) {
501 Diag(Found.getNameLoc(), diag::err_template_kw_refers_to_non_template)
502 << Found.getLookupName() << SS.getRange();
503 Diag(ExampleLookupResult->getUnderlyingDecl()->getLocation(),
504 diag::note_template_kw_refers_to_non_template)
505 << Found.getLookupName();
512 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope &&
513 !getLangOpts().CPlusPlus11) {
514 // C++03 [basic.lookup.classref]p1:
515 // [...] If the lookup in the class of the object expression finds a
516 // template, the name is also looked up in the context of the entire
517 // postfix-expression and [...]
519 // Note: C++11 does not perform this second lookup.
520 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
522 FoundOuter.setTemplateNameLookup(true);
523 LookupName(FoundOuter, S);
524 // FIXME: We silently accept an ambiguous lookup here, in violation of
526 FilterAcceptableTemplateNames(FoundOuter, /*AllowFunctionTemplates=*/false);
528 NamedDecl *OuterTemplate;
529 if (FoundOuter.empty()) {
530 // - if the name is not found, the name found in the class of the
531 // object expression is used, otherwise
532 } else if (FoundOuter.isAmbiguous() || !FoundOuter.isSingleResult() ||
534 getAsTemplateNameDecl(FoundOuter.getFoundDecl()))) {
535 // - if the name is found in the context of the entire
536 // postfix-expression and does not name a class template, the name
537 // found in the class of the object expression is used, otherwise
539 } else if (!Found.isSuppressingDiagnostics()) {
540 // - if the name found is a class template, it must refer to the same
541 // entity as the one found in the class of the object expression,
542 // otherwise the program is ill-formed.
543 if (!Found.isSingleResult() ||
544 getAsTemplateNameDecl(Found.getFoundDecl())->getCanonicalDecl() !=
545 OuterTemplate->getCanonicalDecl()) {
546 Diag(Found.getNameLoc(),
547 diag::ext_nested_name_member_ref_lookup_ambiguous)
548 << Found.getLookupName()
550 Diag(Found.getRepresentativeDecl()->getLocation(),
551 diag::note_ambig_member_ref_object_type)
553 Diag(FoundOuter.getFoundDecl()->getLocation(),
554 diag::note_ambig_member_ref_scope);
556 // Recover by taking the template that we found in the object
557 // expression's type.
565 void Sema::diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName,
567 SourceLocation Greater) {
568 if (TemplateName.isInvalid())
571 DeclarationNameInfo NameInfo;
573 LookupNameKind LookupKind;
575 DeclContext *LookupCtx = nullptr;
576 NamedDecl *Found = nullptr;
577 bool MissingTemplateKeyword = false;
579 // Figure out what name we looked up.
580 if (auto *DRE = dyn_cast<DeclRefExpr>(TemplateName.get())) {
581 NameInfo = DRE->getNameInfo();
582 SS.Adopt(DRE->getQualifierLoc());
583 LookupKind = LookupOrdinaryName;
584 Found = DRE->getFoundDecl();
585 } else if (auto *ME = dyn_cast<MemberExpr>(TemplateName.get())) {
586 NameInfo = ME->getMemberNameInfo();
587 SS.Adopt(ME->getQualifierLoc());
588 LookupKind = LookupMemberName;
589 LookupCtx = ME->getBase()->getType()->getAsCXXRecordDecl();
590 Found = ME->getMemberDecl();
591 } else if (auto *DSDRE =
592 dyn_cast<DependentScopeDeclRefExpr>(TemplateName.get())) {
593 NameInfo = DSDRE->getNameInfo();
594 SS.Adopt(DSDRE->getQualifierLoc());
595 MissingTemplateKeyword = true;
596 } else if (auto *DSME =
597 dyn_cast<CXXDependentScopeMemberExpr>(TemplateName.get())) {
598 NameInfo = DSME->getMemberNameInfo();
599 SS.Adopt(DSME->getQualifierLoc());
600 MissingTemplateKeyword = true;
602 llvm_unreachable("unexpected kind of potential template name");
605 // If this is a dependent-scope lookup, diagnose that the 'template' keyword
607 if (MissingTemplateKeyword) {
608 Diag(NameInfo.getBeginLoc(), diag::err_template_kw_missing)
609 << "" << NameInfo.getName().getAsString() << SourceRange(Less, Greater);
613 // Try to correct the name by looking for templates and C++ named casts.
614 struct TemplateCandidateFilter : CorrectionCandidateCallback {
616 TemplateCandidateFilter(Sema &S) : S(S) {
617 WantTypeSpecifiers = false;
618 WantExpressionKeywords = false;
619 WantRemainingKeywords = false;
620 WantCXXNamedCasts = true;
622 bool ValidateCandidate(const TypoCorrection &Candidate) override {
623 if (auto *ND = Candidate.getCorrectionDecl())
624 return S.getAsTemplateNameDecl(ND);
625 return Candidate.isKeyword();
628 std::unique_ptr<CorrectionCandidateCallback> clone() override {
629 return std::make_unique<TemplateCandidateFilter>(*this);
633 DeclarationName Name = NameInfo.getName();
634 TemplateCandidateFilter CCC(*this);
635 if (TypoCorrection Corrected = CorrectTypo(NameInfo, LookupKind, S, &SS, CCC,
636 CTK_ErrorRecovery, LookupCtx)) {
637 auto *ND = Corrected.getFoundDecl();
639 ND = getAsTemplateNameDecl(ND);
640 if (ND || Corrected.isKeyword()) {
642 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
643 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
644 Name.getAsString() == CorrectedStr;
645 diagnoseTypo(Corrected,
646 PDiag(diag::err_non_template_in_member_template_id_suggest)
647 << Name << LookupCtx << DroppedSpecifier
648 << SS.getRange(), false);
650 diagnoseTypo(Corrected,
651 PDiag(diag::err_non_template_in_template_id_suggest)
655 Diag(Found->getLocation(),
656 diag::note_non_template_in_template_id_found);
661 Diag(NameInfo.getLoc(), diag::err_non_template_in_template_id)
662 << Name << SourceRange(Less, Greater);
664 Diag(Found->getLocation(), diag::note_non_template_in_template_id_found);
667 /// ActOnDependentIdExpression - Handle a dependent id-expression that
668 /// was just parsed. This is only possible with an explicit scope
669 /// specifier naming a dependent type.
671 Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
672 SourceLocation TemplateKWLoc,
673 const DeclarationNameInfo &NameInfo,
674 bool isAddressOfOperand,
675 const TemplateArgumentListInfo *TemplateArgs) {
676 DeclContext *DC = getFunctionLevelDeclContext();
678 // C++11 [expr.prim.general]p12:
679 // An id-expression that denotes a non-static data member or non-static
680 // member function of a class can only be used:
682 // - if that id-expression denotes a non-static data member and it
683 // appears in an unevaluated operand.
685 // If this might be the case, form a DependentScopeDeclRefExpr instead of a
686 // CXXDependentScopeMemberExpr. The former can instantiate to either
687 // DeclRefExpr or MemberExpr depending on lookup results, while the latter is
688 // always a MemberExpr.
689 bool MightBeCxx11UnevalField =
690 getLangOpts().CPlusPlus11 && isUnevaluatedContext();
692 // Check if the nested name specifier is an enum type.
694 if (NestedNameSpecifier *NNS = SS.getScopeRep())
695 IsEnum = dyn_cast_or_null<EnumType>(NNS->getAsType());
697 if (!MightBeCxx11UnevalField && !isAddressOfOperand && !IsEnum &&
698 isa<CXXMethodDecl>(DC) && cast<CXXMethodDecl>(DC)->isInstance()) {
699 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType();
701 // Since the 'this' expression is synthesized, we don't need to
702 // perform the double-lookup check.
703 NamedDecl *FirstQualifierInScope = nullptr;
705 return CXXDependentScopeMemberExpr::Create(
706 Context, /*This*/ nullptr, ThisType, /*IsArrow*/ true,
707 /*Op*/ SourceLocation(), SS.getWithLocInContext(Context), TemplateKWLoc,
708 FirstQualifierInScope, NameInfo, TemplateArgs);
711 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
715 Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
716 SourceLocation TemplateKWLoc,
717 const DeclarationNameInfo &NameInfo,
718 const TemplateArgumentListInfo *TemplateArgs) {
719 // DependentScopeDeclRefExpr::Create requires a valid QualifierLoc
720 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
724 return DependentScopeDeclRefExpr::Create(
725 Context, QualifierLoc, TemplateKWLoc, NameInfo, TemplateArgs);
729 /// Determine whether we would be unable to instantiate this template (because
730 /// it either has no definition, or is in the process of being instantiated).
731 bool Sema::DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation,
732 NamedDecl *Instantiation,
733 bool InstantiatedFromMember,
734 const NamedDecl *Pattern,
735 const NamedDecl *PatternDef,
736 TemplateSpecializationKind TSK,
737 bool Complain /*= true*/) {
738 assert(isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) ||
739 isa<VarDecl>(Instantiation));
741 bool IsEntityBeingDefined = false;
742 if (const TagDecl *TD = dyn_cast_or_null<TagDecl>(PatternDef))
743 IsEntityBeingDefined = TD->isBeingDefined();
745 if (PatternDef && !IsEntityBeingDefined) {
746 NamedDecl *SuggestedDef = nullptr;
747 if (!hasVisibleDefinition(const_cast<NamedDecl*>(PatternDef), &SuggestedDef,
748 /*OnlyNeedComplete*/false)) {
749 // If we're allowed to diagnose this and recover, do so.
750 bool Recover = Complain && !isSFINAEContext();
752 diagnoseMissingImport(PointOfInstantiation, SuggestedDef,
753 Sema::MissingImportKind::Definition, Recover);
759 if (!Complain || (PatternDef && PatternDef->isInvalidDecl()))
762 llvm::Optional<unsigned> Note;
763 QualType InstantiationTy;
764 if (TagDecl *TD = dyn_cast<TagDecl>(Instantiation))
765 InstantiationTy = Context.getTypeDeclType(TD);
767 Diag(PointOfInstantiation,
768 diag::err_template_instantiate_within_definition)
769 << /*implicit|explicit*/(TSK != TSK_ImplicitInstantiation)
771 // Not much point in noting the template declaration here, since
772 // we're lexically inside it.
773 Instantiation->setInvalidDecl();
774 } else if (InstantiatedFromMember) {
775 if (isa<FunctionDecl>(Instantiation)) {
776 Diag(PointOfInstantiation,
777 diag::err_explicit_instantiation_undefined_member)
778 << /*member function*/ 1 << Instantiation->getDeclName()
779 << Instantiation->getDeclContext();
780 Note = diag::note_explicit_instantiation_here;
782 assert(isa<TagDecl>(Instantiation) && "Must be a TagDecl!");
783 Diag(PointOfInstantiation,
784 diag::err_implicit_instantiate_member_undefined)
786 Note = diag::note_member_declared_at;
789 if (isa<FunctionDecl>(Instantiation)) {
790 Diag(PointOfInstantiation,
791 diag::err_explicit_instantiation_undefined_func_template)
793 Note = diag::note_explicit_instantiation_here;
794 } else if (isa<TagDecl>(Instantiation)) {
795 Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
796 << (TSK != TSK_ImplicitInstantiation)
798 Note = diag::note_template_decl_here;
800 assert(isa<VarDecl>(Instantiation) && "Must be a VarDecl!");
801 if (isa<VarTemplateSpecializationDecl>(Instantiation)) {
802 Diag(PointOfInstantiation,
803 diag::err_explicit_instantiation_undefined_var_template)
805 Instantiation->setInvalidDecl();
807 Diag(PointOfInstantiation,
808 diag::err_explicit_instantiation_undefined_member)
809 << /*static data member*/ 2 << Instantiation->getDeclName()
810 << Instantiation->getDeclContext();
811 Note = diag::note_explicit_instantiation_here;
814 if (Note) // Diagnostics were emitted.
815 Diag(Pattern->getLocation(), Note.getValue());
817 // In general, Instantiation isn't marked invalid to get more than one
818 // error for multiple undefined instantiations. But the code that does
819 // explicit declaration -> explicit definition conversion can't handle
820 // invalid declarations, so mark as invalid in that case.
821 if (TSK == TSK_ExplicitInstantiationDeclaration)
822 Instantiation->setInvalidDecl();
826 /// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
827 /// that the template parameter 'PrevDecl' is being shadowed by a new
828 /// declaration at location Loc. Returns true to indicate that this is
829 /// an error, and false otherwise.
830 void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
831 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
833 // C++ [temp.local]p4:
834 // A template-parameter shall not be redeclared within its
835 // scope (including nested scopes).
837 // Make this a warning when MSVC compatibility is requested.
838 unsigned DiagId = getLangOpts().MSVCCompat ? diag::ext_template_param_shadow
839 : diag::err_template_param_shadow;
840 Diag(Loc, DiagId) << cast<NamedDecl>(PrevDecl)->getDeclName();
841 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
844 /// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
845 /// the parameter D to reference the templated declaration and return a pointer
846 /// to the template declaration. Otherwise, do nothing to D and return null.
847 TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) {
848 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
849 D = Temp->getTemplatedDecl();
855 ParsedTemplateArgument ParsedTemplateArgument::getTemplatePackExpansion(
856 SourceLocation EllipsisLoc) const {
857 assert(Kind == Template &&
858 "Only template template arguments can be pack expansions here");
859 assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
860 "Template template argument pack expansion without packs");
861 ParsedTemplateArgument Result(*this);
862 Result.EllipsisLoc = EllipsisLoc;
866 static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
867 const ParsedTemplateArgument &Arg) {
869 switch (Arg.getKind()) {
870 case ParsedTemplateArgument::Type: {
872 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
874 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
875 return TemplateArgumentLoc(TemplateArgument(T), DI);
878 case ParsedTemplateArgument::NonType: {
879 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
880 return TemplateArgumentLoc(TemplateArgument(E), E);
883 case ParsedTemplateArgument::Template: {
884 TemplateName Template = Arg.getAsTemplate().get();
885 TemplateArgument TArg;
886 if (Arg.getEllipsisLoc().isValid())
887 TArg = TemplateArgument(Template, Optional<unsigned int>());
890 return TemplateArgumentLoc(TArg,
891 Arg.getScopeSpec().getWithLocInContext(
894 Arg.getEllipsisLoc());
898 llvm_unreachable("Unhandled parsed template argument");
901 /// Translates template arguments as provided by the parser
902 /// into template arguments used by semantic analysis.
903 void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
904 TemplateArgumentListInfo &TemplateArgs) {
905 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
906 TemplateArgs.addArgument(translateTemplateArgument(*this,
910 static void maybeDiagnoseTemplateParameterShadow(Sema &SemaRef, Scope *S,
912 IdentifierInfo *Name) {
913 NamedDecl *PrevDecl = SemaRef.LookupSingleName(
914 S, Name, Loc, Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
915 if (PrevDecl && PrevDecl->isTemplateParameter())
916 SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
919 /// Convert a parsed type into a parsed template argument. This is mostly
920 /// trivial, except that we may have parsed a C++17 deduced class template
921 /// specialization type, in which case we should form a template template
922 /// argument instead of a type template argument.
923 ParsedTemplateArgument Sema::ActOnTemplateTypeArgument(TypeResult ParsedType) {
924 TypeSourceInfo *TInfo;
925 QualType T = GetTypeFromParser(ParsedType.get(), &TInfo);
927 return ParsedTemplateArgument();
928 assert(TInfo && "template argument with no location");
930 // If we might have formed a deduced template specialization type, convert
931 // it to a template template argument.
932 if (getLangOpts().CPlusPlus17) {
933 TypeLoc TL = TInfo->getTypeLoc();
934 SourceLocation EllipsisLoc;
935 if (auto PET = TL.getAs<PackExpansionTypeLoc>()) {
936 EllipsisLoc = PET.getEllipsisLoc();
937 TL = PET.getPatternLoc();
941 if (auto ET = TL.getAs<ElaboratedTypeLoc>()) {
942 SS.Adopt(ET.getQualifierLoc());
943 TL = ET.getNamedTypeLoc();
946 if (auto DTST = TL.getAs<DeducedTemplateSpecializationTypeLoc>()) {
947 TemplateName Name = DTST.getTypePtr()->getTemplateName();
949 Name = Context.getQualifiedTemplateName(SS.getScopeRep(),
950 /*HasTemplateKeyword*/ false,
951 Name.getAsTemplateDecl());
952 ParsedTemplateArgument Result(SS, TemplateTy::make(Name),
953 DTST.getTemplateNameLoc());
954 if (EllipsisLoc.isValid())
955 Result = Result.getTemplatePackExpansion(EllipsisLoc);
960 // This is a normal type template argument. Note, if the type template
961 // argument is an injected-class-name for a template, it has a dual nature
962 // and can be used as either a type or a template. We handle that in
963 // convertTypeTemplateArgumentToTemplate.
964 return ParsedTemplateArgument(ParsedTemplateArgument::Type,
965 ParsedType.get().getAsOpaquePtr(),
966 TInfo->getTypeLoc().getBeginLoc());
969 /// ActOnTypeParameter - Called when a C++ template type parameter
970 /// (e.g., "typename T") has been parsed. Typename specifies whether
971 /// the keyword "typename" was used to declare the type parameter
972 /// (otherwise, "class" was used), and KeyLoc is the location of the
973 /// "class" or "typename" keyword. ParamName is the name of the
974 /// parameter (NULL indicates an unnamed template parameter) and
975 /// ParamNameLoc is the location of the parameter name (if any).
976 /// If the type parameter has a default argument, it will be added
977 /// later via ActOnTypeParameterDefault.
978 NamedDecl *Sema::ActOnTypeParameter(Scope *S, bool Typename,
979 SourceLocation EllipsisLoc,
980 SourceLocation KeyLoc,
981 IdentifierInfo *ParamName,
982 SourceLocation ParamNameLoc,
983 unsigned Depth, unsigned Position,
984 SourceLocation EqualLoc,
985 ParsedType DefaultArg,
986 bool HasTypeConstraint) {
987 assert(S->isTemplateParamScope() &&
988 "Template type parameter not in template parameter scope!");
990 bool IsParameterPack = EllipsisLoc.isValid();
991 TemplateTypeParmDecl *Param
992 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
993 KeyLoc, ParamNameLoc, Depth, Position,
994 ParamName, Typename, IsParameterPack,
996 Param->setAccess(AS_public);
998 if (Param->isParameterPack())
999 if (auto *LSI = getEnclosingLambda())
1000 LSI->LocalPacks.push_back(Param);
1003 maybeDiagnoseTemplateParameterShadow(*this, S, ParamNameLoc, ParamName);
1005 // Add the template parameter into the current scope.
1007 IdResolver.AddDecl(Param);
1010 // C++0x [temp.param]p9:
1011 // A default template-argument may be specified for any kind of
1012 // template-parameter that is not a template parameter pack.
1013 if (DefaultArg && IsParameterPack) {
1014 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1015 DefaultArg = nullptr;
1018 // Handle the default argument, if provided.
1020 TypeSourceInfo *DefaultTInfo;
1021 GetTypeFromParser(DefaultArg, &DefaultTInfo);
1023 assert(DefaultTInfo && "expected source information for type");
1025 // Check for unexpanded parameter packs.
1026 if (DiagnoseUnexpandedParameterPack(ParamNameLoc, DefaultTInfo,
1027 UPPC_DefaultArgument))
1030 // Check the template argument itself.
1031 if (CheckTemplateArgument(Param, DefaultTInfo)) {
1032 Param->setInvalidDecl();
1036 Param->setDefaultArgument(DefaultTInfo);
1042 /// Convert the parser's template argument list representation into our form.
1043 static TemplateArgumentListInfo
1044 makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId) {
1045 TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
1046 TemplateId.RAngleLoc);
1047 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
1048 TemplateId.NumArgs);
1049 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
1050 return TemplateArgs;
1053 bool Sema::ActOnTypeConstraint(TemplateIdAnnotation *TypeConstr,
1054 TemplateTypeParmDecl *ConstrainedParameter,
1055 SourceLocation EllipsisLoc) {
1057 cast<ConceptDecl>(TypeConstr->Template.get().getAsTemplateDecl());
1059 // C++2a [temp.param]p4:
1060 // [...] The concept designated by a type-constraint shall be a type
1061 // concept ([temp.concept]).
1062 if (!CD->isTypeConcept()) {
1063 Diag(TypeConstr->TemplateNameLoc,
1064 diag::err_type_constraint_non_type_concept);
1068 bool WereArgsSpecified = TypeConstr->LAngleLoc.isValid();
1070 if (!WereArgsSpecified &&
1071 CD->getTemplateParameters()->getMinRequiredArguments() > 1) {
1072 Diag(TypeConstr->TemplateNameLoc,
1073 diag::err_type_constraint_missing_arguments) << CD;
1077 TemplateArgumentListInfo TemplateArgs;
1078 if (TypeConstr->LAngleLoc.isValid()) {
1080 makeTemplateArgumentListInfo(*this, *TypeConstr);
1082 return AttachTypeConstraint(
1083 TypeConstr->SS.isSet() ? TypeConstr->SS.getWithLocInContext(Context) :
1084 NestedNameSpecifierLoc(),
1085 DeclarationNameInfo(DeclarationName(TypeConstr->Name),
1086 TypeConstr->TemplateNameLoc), CD,
1087 TypeConstr->LAngleLoc.isValid() ? &TemplateArgs : nullptr,
1088 ConstrainedParameter, EllipsisLoc);
1091 /// Attach a type-constraint to a template parameter.
1092 /// \returns true if an error occured. This can happen if the
1093 /// immediately-declared constraint could not be formed (e.g. incorrect number
1094 /// of arguments for the named concept).
1095 bool Sema::AttachTypeConstraint(NestedNameSpecifierLoc NS,
1096 DeclarationNameInfo NameInfo,
1097 ConceptDecl *NamedConcept,
1098 const TemplateArgumentListInfo *TemplateArgs,
1099 TemplateTypeParmDecl *ConstrainedParameter,
1100 SourceLocation EllipsisLoc) {
1101 // C++2a [temp.param]p4:
1102 // [...] If Q is of the form C<A1, ..., An>, then let E' be
1103 // C<T, A1, ..., An>. Otherwise, let E' be C<T>. [...]
1104 const ASTTemplateArgumentListInfo *ArgsAsWritten =
1105 TemplateArgs ? ASTTemplateArgumentListInfo::Create(Context,
1106 *TemplateArgs) : nullptr;
1108 QualType ParamAsArgument(ConstrainedParameter->getTypeForDecl(), 0);
1109 TemplateArgumentListInfo ConstraintArgs;
1110 ConstraintArgs.addArgument(
1111 TemplateArgumentLoc(
1112 TemplateArgument(ParamAsArgument),
1113 TemplateArgumentLocInfo(
1114 Context.getTrivialTypeSourceInfo(ParamAsArgument,
1115 ConstrainedParameter->getLocation()))));
1117 ConstraintArgs.setRAngleLoc(TemplateArgs->getRAngleLoc());
1118 ConstraintArgs.setLAngleLoc(TemplateArgs->getLAngleLoc());
1119 for (const TemplateArgumentLoc &ArgLoc : TemplateArgs->arguments())
1120 ConstraintArgs.addArgument(ArgLoc);
1123 // C++2a [temp.param]p4:
1124 // [...] This constraint-expression E is called the immediately-declared
1125 // constraint of T. [...]
1128 ExprResult ImmediatelyDeclaredConstraint = CheckConceptTemplateId(SS,
1129 /*TemplateKWLoc=*/SourceLocation(), NameInfo, /*FoundDecl=*/NamedConcept,
1130 NamedConcept, &ConstraintArgs);
1131 if (ImmediatelyDeclaredConstraint.isInvalid())
1134 if (ConstrainedParameter->isParameterPack()) {
1135 // C++2a [temp.param]p4:
1136 // [...] If T is not a pack, then E is E', otherwise E is (E' && ...).
1138 // We have the following case:
1140 // template<typename T> concept C1 = true;
1141 // template<C1... T> struct s1;
1143 // The constraint: (C1<T> && ...)
1144 ImmediatelyDeclaredConstraint =
1145 BuildCXXFoldExpr(/*LParenLoc=*/SourceLocation(),
1146 ImmediatelyDeclaredConstraint.get(), BO_LAnd,
1147 EllipsisLoc, /*RHS=*/nullptr,
1148 /*RParenLoc=*/SourceLocation(),
1149 /*NumExpansions=*/None).get();
1150 if (ImmediatelyDeclaredConstraint.isInvalid())
1154 ConstrainedParameter->setTypeConstraint(NS, NameInfo,
1155 /*FoundDecl=*/NamedConcept,
1156 NamedConcept, ArgsAsWritten,
1157 ImmediatelyDeclaredConstraint.get());
1161 /// Check that the type of a non-type template parameter is
1164 /// \returns the (possibly-promoted) parameter type if valid;
1165 /// otherwise, produces a diagnostic and returns a NULL type.
1166 QualType Sema::CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI,
1167 SourceLocation Loc) {
1168 if (TSI->getType()->isUndeducedType()) {
1169 // C++17 [temp.dep.expr]p3:
1170 // An id-expression is type-dependent if it contains
1171 // - an identifier associated by name lookup with a non-type
1172 // template-parameter declared with a type that contains a
1173 // placeholder type (7.1.7.4),
1174 TSI = SubstAutoTypeSourceInfo(TSI, Context.DependentTy);
1177 return CheckNonTypeTemplateParameterType(TSI->getType(), Loc);
1180 QualType Sema::CheckNonTypeTemplateParameterType(QualType T,
1181 SourceLocation Loc) {
1182 // We don't allow variably-modified types as the type of non-type template
1184 if (T->isVariablyModifiedType()) {
1185 Diag(Loc, diag::err_variably_modified_nontype_template_param)
1190 // C++ [temp.param]p4:
1192 // A non-type template-parameter shall have one of the following
1193 // (optionally cv-qualified) types:
1195 // -- integral or enumeration type,
1196 if (T->isIntegralOrEnumerationType() ||
1197 // -- pointer to object or pointer to function,
1198 T->isPointerType() ||
1199 // -- reference to object or reference to function,
1200 T->isReferenceType() ||
1201 // -- pointer to member,
1202 T->isMemberPointerType() ||
1203 // -- std::nullptr_t.
1204 T->isNullPtrType() ||
1205 // Allow use of auto in template parameter declarations.
1206 T->isUndeducedType()) {
1207 // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
1208 // are ignored when determining its type.
1209 return T.getUnqualifiedType();
1212 // C++ [temp.param]p8:
1214 // A non-type template-parameter of type "array of T" or
1215 // "function returning T" is adjusted to be of type "pointer to
1216 // T" or "pointer to function returning T", respectively.
1217 if (T->isArrayType() || T->isFunctionType())
1218 return Context.getDecayedType(T);
1220 // If T is a dependent type, we can't do the check now, so we
1221 // assume that it is well-formed. Note that stripping off the
1222 // qualifiers here is not really correct if T turns out to be
1223 // an array type, but we'll recompute the type everywhere it's
1224 // used during instantiation, so that should be OK. (Using the
1225 // qualified type is equally wrong.)
1226 if (T->isDependentType())
1227 return T.getUnqualifiedType();
1229 Diag(Loc, diag::err_template_nontype_parm_bad_type)
1235 NamedDecl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
1238 SourceLocation EqualLoc,
1240 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
1242 // Check that we have valid decl-specifiers specified.
1243 auto CheckValidDeclSpecifiers = [this, &D] {
1246 // template-parameter:
1248 // parameter-declaration
1250 // ... A storage class shall not be specified in a template-parameter
1253 // The typedef specifier [...] shall not be used in the decl-specifier-seq
1254 // of a parameter-declaration
1255 const DeclSpec &DS = D.getDeclSpec();
1256 auto EmitDiag = [this](SourceLocation Loc) {
1257 Diag(Loc, diag::err_invalid_decl_specifier_in_nontype_parm)
1258 << FixItHint::CreateRemoval(Loc);
1260 if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified)
1261 EmitDiag(DS.getStorageClassSpecLoc());
1263 if (DS.getThreadStorageClassSpec() != TSCS_unspecified)
1264 EmitDiag(DS.getThreadStorageClassSpecLoc());
1267 // The inline specifier can be applied only to the declaration or
1268 // definition of a variable or function.
1270 if (DS.isInlineSpecified())
1271 EmitDiag(DS.getInlineSpecLoc());
1273 // [dcl.constexpr]p1:
1274 // The constexpr specifier shall be applied only to the definition of a
1275 // variable or variable template or the declaration of a function or
1276 // function template.
1278 if (DS.hasConstexprSpecifier())
1279 EmitDiag(DS.getConstexprSpecLoc());
1281 // [dcl.fct.spec]p1:
1282 // Function-specifiers can be used only in function declarations.
1284 if (DS.isVirtualSpecified())
1285 EmitDiag(DS.getVirtualSpecLoc());
1287 if (DS.hasExplicitSpecifier())
1288 EmitDiag(DS.getExplicitSpecLoc());
1290 if (DS.isNoreturnSpecified())
1291 EmitDiag(DS.getNoreturnSpecLoc());
1294 CheckValidDeclSpecifiers();
1296 if (TInfo->getType()->isUndeducedType()) {
1297 Diag(D.getIdentifierLoc(),
1298 diag::warn_cxx14_compat_template_nontype_parm_auto_type)
1299 << QualType(TInfo->getType()->getContainedAutoType(), 0);
1302 assert(S->isTemplateParamScope() &&
1303 "Non-type template parameter not in template parameter scope!");
1304 bool Invalid = false;
1306 QualType T = CheckNonTypeTemplateParameterType(TInfo, D.getIdentifierLoc());
1308 T = Context.IntTy; // Recover with an 'int' type.
1312 CheckFunctionOrTemplateParamDeclarator(S, D);
1314 IdentifierInfo *ParamName = D.getIdentifier();
1315 bool IsParameterPack = D.hasEllipsis();
1316 NonTypeTemplateParmDecl *Param = NonTypeTemplateParmDecl::Create(
1317 Context, Context.getTranslationUnitDecl(), D.getBeginLoc(),
1318 D.getIdentifierLoc(), Depth, Position, ParamName, T, IsParameterPack,
1320 Param->setAccess(AS_public);
1323 Param->setInvalidDecl();
1325 if (Param->isParameterPack())
1326 if (auto *LSI = getEnclosingLambda())
1327 LSI->LocalPacks.push_back(Param);
1330 maybeDiagnoseTemplateParameterShadow(*this, S, D.getIdentifierLoc(),
1333 // Add the template parameter into the current scope.
1335 IdResolver.AddDecl(Param);
1338 // C++0x [temp.param]p9:
1339 // A default template-argument may be specified for any kind of
1340 // template-parameter that is not a template parameter pack.
1341 if (Default && IsParameterPack) {
1342 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1346 // Check the well-formedness of the default template argument, if provided.
1348 // Check for unexpanded parameter packs.
1349 if (DiagnoseUnexpandedParameterPack(Default, UPPC_DefaultArgument))
1352 TemplateArgument Converted;
1353 ExprResult DefaultRes =
1354 CheckTemplateArgument(Param, Param->getType(), Default, Converted);
1355 if (DefaultRes.isInvalid()) {
1356 Param->setInvalidDecl();
1359 Default = DefaultRes.get();
1361 Param->setDefaultArgument(Default);
1367 /// ActOnTemplateTemplateParameter - Called when a C++ template template
1368 /// parameter (e.g. T in template <template \<typename> class T> class array)
1369 /// has been parsed. S is the current scope.
1370 NamedDecl *Sema::ActOnTemplateTemplateParameter(Scope* S,
1371 SourceLocation TmpLoc,
1372 TemplateParameterList *Params,
1373 SourceLocation EllipsisLoc,
1374 IdentifierInfo *Name,
1375 SourceLocation NameLoc,
1378 SourceLocation EqualLoc,
1379 ParsedTemplateArgument Default) {
1380 assert(S->isTemplateParamScope() &&
1381 "Template template parameter not in template parameter scope!");
1383 // Construct the parameter object.
1384 bool IsParameterPack = EllipsisLoc.isValid();
1385 TemplateTemplateParmDecl *Param =
1386 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
1387 NameLoc.isInvalid()? TmpLoc : NameLoc,
1388 Depth, Position, IsParameterPack,
1390 Param->setAccess(AS_public);
1392 if (Param->isParameterPack())
1393 if (auto *LSI = getEnclosingLambda())
1394 LSI->LocalPacks.push_back(Param);
1396 // If the template template parameter has a name, then link the identifier
1397 // into the scope and lookup mechanisms.
1399 maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name);
1402 IdResolver.AddDecl(Param);
1405 if (Params->size() == 0) {
1406 Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
1407 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
1408 Param->setInvalidDecl();
1411 // C++0x [temp.param]p9:
1412 // A default template-argument may be specified for any kind of
1413 // template-parameter that is not a template parameter pack.
1414 if (IsParameterPack && !Default.isInvalid()) {
1415 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1416 Default = ParsedTemplateArgument();
1419 if (!Default.isInvalid()) {
1420 // Check only that we have a template template argument. We don't want to
1421 // try to check well-formedness now, because our template template parameter
1422 // might have dependent types in its template parameters, which we wouldn't
1423 // be able to match now.
1425 // If none of the template template parameter's template arguments mention
1426 // other template parameters, we could actually perform more checking here.
1427 // However, it isn't worth doing.
1428 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
1429 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
1430 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_valid_template)
1431 << DefaultArg.getSourceRange();
1435 // Check for unexpanded parameter packs.
1436 if (DiagnoseUnexpandedParameterPack(DefaultArg.getLocation(),
1437 DefaultArg.getArgument().getAsTemplate(),
1438 UPPC_DefaultArgument))
1441 Param->setDefaultArgument(Context, DefaultArg);
1447 /// ActOnTemplateParameterList - Builds a TemplateParameterList, optionally
1448 /// constrained by RequiresClause, that contains the template parameters in
1450 TemplateParameterList *
1451 Sema::ActOnTemplateParameterList(unsigned Depth,
1452 SourceLocation ExportLoc,
1453 SourceLocation TemplateLoc,
1454 SourceLocation LAngleLoc,
1455 ArrayRef<NamedDecl *> Params,
1456 SourceLocation RAngleLoc,
1457 Expr *RequiresClause) {
1458 if (ExportLoc.isValid())
1459 Diag(ExportLoc, diag::warn_template_export_unsupported);
1461 return TemplateParameterList::Create(
1462 Context, TemplateLoc, LAngleLoc,
1463 llvm::makeArrayRef(Params.data(), Params.size()),
1464 RAngleLoc, RequiresClause);
1467 static void SetNestedNameSpecifier(Sema &S, TagDecl *T,
1468 const CXXScopeSpec &SS) {
1470 T->setQualifierInfo(SS.getWithLocInContext(S.Context));
1473 DeclResult Sema::CheckClassTemplate(
1474 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
1475 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
1476 const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams,
1477 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
1478 SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists,
1479 TemplateParameterList **OuterTemplateParamLists, SkipBodyInfo *SkipBody) {
1480 assert(TemplateParams && TemplateParams->size() > 0 &&
1481 "No template parameters");
1482 assert(TUK != TUK_Reference && "Can only declare or define class templates");
1483 bool Invalid = false;
1485 // Check that we can declare a template here.
1486 if (CheckTemplateDeclScope(S, TemplateParams))
1489 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
1490 assert(Kind != TTK_Enum && "can't build template of enumerated type");
1492 // There is no such thing as an unnamed class template.
1494 Diag(KWLoc, diag::err_template_unnamed_class);
1498 // Find any previous declaration with this name. For a friend with no
1499 // scope explicitly specified, we only look for tag declarations (per
1500 // C++11 [basic.lookup.elab]p2).
1501 DeclContext *SemanticContext;
1502 LookupResult Previous(*this, Name, NameLoc,
1503 (SS.isEmpty() && TUK == TUK_Friend)
1504 ? LookupTagName : LookupOrdinaryName,
1505 forRedeclarationInCurContext());
1506 if (SS.isNotEmpty() && !SS.isInvalid()) {
1507 SemanticContext = computeDeclContext(SS, true);
1508 if (!SemanticContext) {
1509 // FIXME: Horrible, horrible hack! We can't currently represent this
1510 // in the AST, and historically we have just ignored such friend
1511 // class templates, so don't complain here.
1512 Diag(NameLoc, TUK == TUK_Friend
1513 ? diag::warn_template_qualified_friend_ignored
1514 : diag::err_template_qualified_declarator_no_match)
1515 << SS.getScopeRep() << SS.getRange();
1516 return TUK != TUK_Friend;
1519 if (RequireCompleteDeclContext(SS, SemanticContext))
1522 // If we're adding a template to a dependent context, we may need to
1523 // rebuilding some of the types used within the template parameter list,
1524 // now that we know what the current instantiation is.
1525 if (SemanticContext->isDependentContext()) {
1526 ContextRAII SavedContext(*this, SemanticContext);
1527 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
1529 } else if (TUK != TUK_Friend && TUK != TUK_Reference)
1530 diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc, false);
1532 LookupQualifiedName(Previous, SemanticContext);
1534 SemanticContext = CurContext;
1536 // C++14 [class.mem]p14:
1537 // If T is the name of a class, then each of the following shall have a
1538 // name different from T:
1539 // -- every member template of class T
1540 if (TUK != TUK_Friend &&
1541 DiagnoseClassNameShadow(SemanticContext,
1542 DeclarationNameInfo(Name, NameLoc)))
1545 LookupName(Previous, S);
1548 if (Previous.isAmbiguous())
1551 NamedDecl *PrevDecl = nullptr;
1552 if (Previous.begin() != Previous.end())
1553 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
1555 if (PrevDecl && PrevDecl->isTemplateParameter()) {
1556 // Maybe we will complain about the shadowed template parameter.
1557 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
1558 // Just pretend that we didn't see the previous declaration.
1562 // If there is a previous declaration with the same name, check
1563 // whether this is a valid redeclaration.
1564 ClassTemplateDecl *PrevClassTemplate =
1565 dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
1567 // We may have found the injected-class-name of a class template,
1568 // class template partial specialization, or class template specialization.
1569 // In these cases, grab the template that is being defined or specialized.
1570 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
1571 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
1572 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
1574 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
1575 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
1577 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
1578 ->getSpecializedTemplate();
1582 if (TUK == TUK_Friend) {
1583 // C++ [namespace.memdef]p3:
1584 // [...] When looking for a prior declaration of a class or a function
1585 // declared as a friend, and when the name of the friend class or
1586 // function is neither a qualified name nor a template-id, scopes outside
1587 // the innermost enclosing namespace scope are not considered.
1589 DeclContext *OutermostContext = CurContext;
1590 while (!OutermostContext->isFileContext())
1591 OutermostContext = OutermostContext->getLookupParent();
1594 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
1595 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
1596 SemanticContext = PrevDecl->getDeclContext();
1598 // Declarations in outer scopes don't matter. However, the outermost
1599 // context we computed is the semantic context for our new
1601 PrevDecl = PrevClassTemplate = nullptr;
1602 SemanticContext = OutermostContext;
1604 // Check that the chosen semantic context doesn't already contain a
1605 // declaration of this name as a non-tag type.
1606 Previous.clear(LookupOrdinaryName);
1607 DeclContext *LookupContext = SemanticContext;
1608 while (LookupContext->isTransparentContext())
1609 LookupContext = LookupContext->getLookupParent();
1610 LookupQualifiedName(Previous, LookupContext);
1612 if (Previous.isAmbiguous())
1615 if (Previous.begin() != Previous.end())
1616 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
1619 } else if (PrevDecl &&
1620 !isDeclInScope(Previous.getRepresentativeDecl(), SemanticContext,
1622 PrevDecl = PrevClassTemplate = nullptr;
1624 if (auto *Shadow = dyn_cast_or_null<UsingShadowDecl>(
1625 PrevDecl ? Previous.getRepresentativeDecl() : nullptr)) {
1627 !(PrevClassTemplate &&
1628 PrevClassTemplate->getDeclContext()->getRedeclContext()->Equals(
1629 SemanticContext->getRedeclContext()))) {
1630 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
1631 Diag(Shadow->getTargetDecl()->getLocation(),
1632 diag::note_using_decl_target);
1633 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
1634 // Recover by ignoring the old declaration.
1635 PrevDecl = PrevClassTemplate = nullptr;
1639 if (PrevClassTemplate) {
1640 // Ensure that the template parameter lists are compatible. Skip this check
1641 // for a friend in a dependent context: the template parameter list itself
1642 // could be dependent.
1643 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
1644 !TemplateParameterListsAreEqual(TemplateParams,
1645 PrevClassTemplate->getTemplateParameters(),
1650 // C++ [temp.class]p4:
1651 // In a redeclaration, partial specialization, explicit
1652 // specialization or explicit instantiation of a class template,
1653 // the class-key shall agree in kind with the original class
1654 // template declaration (7.1.5.3).
1655 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
1656 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind,
1657 TUK == TUK_Definition, KWLoc, Name)) {
1658 Diag(KWLoc, diag::err_use_with_wrong_tag)
1660 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
1661 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
1662 Kind = PrevRecordDecl->getTagKind();
1665 // Check for redefinition of this class template.
1666 if (TUK == TUK_Definition) {
1667 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
1668 // If we have a prior definition that is not visible, treat this as
1669 // simply making that previous definition visible.
1670 NamedDecl *Hidden = nullptr;
1671 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
1672 SkipBody->ShouldSkip = true;
1673 SkipBody->Previous = Def;
1674 auto *Tmpl = cast<CXXRecordDecl>(Hidden)->getDescribedClassTemplate();
1675 assert(Tmpl && "original definition of a class template is not a "
1677 makeMergedDefinitionVisible(Hidden);
1678 makeMergedDefinitionVisible(Tmpl);
1680 Diag(NameLoc, diag::err_redefinition) << Name;
1681 Diag(Def->getLocation(), diag::note_previous_definition);
1682 // FIXME: Would it make sense to try to "forget" the previous
1683 // definition, as part of error recovery?
1688 } else if (PrevDecl) {
1690 // A class template shall not have the same name as any other
1691 // template, class, function, object, enumeration, enumerator,
1692 // namespace, or type in the same scope (3.3), except as specified
1694 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
1695 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1699 // Check the template parameter list of this declaration, possibly
1700 // merging in the template parameter list from the previous class
1701 // template declaration. Skip this check for a friend in a dependent
1702 // context, because the template parameter list might be dependent.
1703 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
1704 CheckTemplateParameterList(
1707 ? PrevClassTemplate->getMostRecentDecl()->getTemplateParameters()
1709 (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
1710 SemanticContext->isDependentContext())
1711 ? TPC_ClassTemplateMember
1712 : TUK == TUK_Friend ? TPC_FriendClassTemplate : TPC_ClassTemplate,
1717 // If the name of the template was qualified, we must be defining the
1718 // template out-of-line.
1719 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
1720 Diag(NameLoc, TUK == TUK_Friend ? diag::err_friend_decl_does_not_match
1721 : diag::err_member_decl_does_not_match)
1722 << Name << SemanticContext << /*IsDefinition*/true << SS.getRange();
1727 // If this is a templated friend in a dependent context we should not put it
1728 // on the redecl chain. In some cases, the templated friend can be the most
1729 // recent declaration tricking the template instantiator to make substitutions
1731 // FIXME: Figure out how to combine with shouldLinkDependentDeclWithPrevious
1732 bool ShouldAddRedecl
1733 = !(TUK == TUK_Friend && CurContext->isDependentContext());
1735 CXXRecordDecl *NewClass =
1736 CXXRecordDecl::Create(Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
1737 PrevClassTemplate && ShouldAddRedecl ?
1738 PrevClassTemplate->getTemplatedDecl() : nullptr,
1739 /*DelayTypeCreation=*/true);
1740 SetNestedNameSpecifier(*this, NewClass, SS);
1741 if (NumOuterTemplateParamLists > 0)
1742 NewClass->setTemplateParameterListsInfo(
1743 Context, llvm::makeArrayRef(OuterTemplateParamLists,
1744 NumOuterTemplateParamLists));
1746 // Add alignment attributes if necessary; these attributes are checked when
1747 // the ASTContext lays out the structure.
1748 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
1749 AddAlignmentAttributesForRecord(NewClass);
1750 AddMsStructLayoutForRecord(NewClass);
1753 ClassTemplateDecl *NewTemplate
1754 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
1755 DeclarationName(Name), TemplateParams,
1758 if (ShouldAddRedecl)
1759 NewTemplate->setPreviousDecl(PrevClassTemplate);
1761 NewClass->setDescribedClassTemplate(NewTemplate);
1763 if (ModulePrivateLoc.isValid())
1764 NewTemplate->setModulePrivate();
1766 // Build the type for the class template declaration now.
1767 QualType T = NewTemplate->getInjectedClassNameSpecialization();
1768 T = Context.getInjectedClassNameType(NewClass, T);
1769 assert(T->isDependentType() && "Class template type is not dependent?");
1772 // If we are providing an explicit specialization of a member that is a
1773 // class template, make a note of that.
1774 if (PrevClassTemplate &&
1775 PrevClassTemplate->getInstantiatedFromMemberTemplate())
1776 PrevClassTemplate->setMemberSpecialization();
1778 // Set the access specifier.
1779 if (!Invalid && TUK != TUK_Friend && NewTemplate->getDeclContext()->isRecord())
1780 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
1782 // Set the lexical context of these templates
1783 NewClass->setLexicalDeclContext(CurContext);
1784 NewTemplate->setLexicalDeclContext(CurContext);
1786 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
1787 NewClass->startDefinition();
1789 ProcessDeclAttributeList(S, NewClass, Attr);
1791 if (PrevClassTemplate)
1792 mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
1794 AddPushedVisibilityAttribute(NewClass);
1795 inferGslOwnerPointerAttribute(NewClass);
1797 if (TUK != TUK_Friend) {
1798 // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
1800 while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
1801 Outer = Outer->getParent();
1802 PushOnScopeChains(NewTemplate, Outer);
1804 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
1805 NewTemplate->setAccess(PrevClassTemplate->getAccess());
1806 NewClass->setAccess(PrevClassTemplate->getAccess());
1809 NewTemplate->setObjectOfFriendDecl();
1811 // Friend templates are visible in fairly strange ways.
1812 if (!CurContext->isDependentContext()) {
1813 DeclContext *DC = SemanticContext->getRedeclContext();
1814 DC->makeDeclVisibleInContext(NewTemplate);
1815 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
1816 PushOnScopeChains(NewTemplate, EnclosingScope,
1817 /* AddToContext = */ false);
1820 FriendDecl *Friend = FriendDecl::Create(
1821 Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc);
1822 Friend->setAccess(AS_public);
1823 CurContext->addDecl(Friend);
1826 if (PrevClassTemplate)
1827 CheckRedeclarationModuleOwnership(NewTemplate, PrevClassTemplate);
1830 NewTemplate->setInvalidDecl();
1831 NewClass->setInvalidDecl();
1834 ActOnDocumentableDecl(NewTemplate);
1836 if (SkipBody && SkipBody->ShouldSkip)
1837 return SkipBody->Previous;
1843 /// Tree transform to "extract" a transformed type from a class template's
1844 /// constructor to a deduction guide.
1845 class ExtractTypeForDeductionGuide
1846 : public TreeTransform<ExtractTypeForDeductionGuide> {
1848 typedef TreeTransform<ExtractTypeForDeductionGuide> Base;
1849 ExtractTypeForDeductionGuide(Sema &SemaRef) : Base(SemaRef) {}
1851 TypeSourceInfo *transform(TypeSourceInfo *TSI) { return TransformType(TSI); }
1853 QualType TransformTypedefType(TypeLocBuilder &TLB, TypedefTypeLoc TL) {
1854 return TransformType(
1856 TL.getTypedefNameDecl()->getTypeSourceInfo()->getTypeLoc());
1860 /// Transform to convert portions of a constructor declaration into the
1861 /// corresponding deduction guide, per C++1z [over.match.class.deduct]p1.
1862 struct ConvertConstructorToDeductionGuideTransform {
1863 ConvertConstructorToDeductionGuideTransform(Sema &S,
1864 ClassTemplateDecl *Template)
1865 : SemaRef(S), Template(Template) {}
1868 ClassTemplateDecl *Template;
1870 DeclContext *DC = Template->getDeclContext();
1871 CXXRecordDecl *Primary = Template->getTemplatedDecl();
1872 DeclarationName DeductionGuideName =
1873 SemaRef.Context.DeclarationNames.getCXXDeductionGuideName(Template);
1875 QualType DeducedType = SemaRef.Context.getTypeDeclType(Primary);
1877 // Index adjustment to apply to convert depth-1 template parameters into
1878 // depth-0 template parameters.
1879 unsigned Depth1IndexAdjustment = Template->getTemplateParameters()->size();
1881 /// Transform a constructor declaration into a deduction guide.
1882 NamedDecl *transformConstructor(FunctionTemplateDecl *FTD,
1883 CXXConstructorDecl *CD) {
1884 SmallVector<TemplateArgument, 16> SubstArgs;
1886 LocalInstantiationScope Scope(SemaRef);
1888 // C++ [over.match.class.deduct]p1:
1889 // -- For each constructor of the class template designated by the
1890 // template-name, a function template with the following properties:
1892 // -- The template parameters are the template parameters of the class
1893 // template followed by the template parameters (including default
1894 // template arguments) of the constructor, if any.
1895 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
1897 TemplateParameterList *InnerParams = FTD->getTemplateParameters();
1898 SmallVector<NamedDecl *, 16> AllParams;
1899 AllParams.reserve(TemplateParams->size() + InnerParams->size());
1900 AllParams.insert(AllParams.begin(),
1901 TemplateParams->begin(), TemplateParams->end());
1902 SubstArgs.reserve(InnerParams->size());
1904 // Later template parameters could refer to earlier ones, so build up
1905 // a list of substituted template arguments as we go.
1906 for (NamedDecl *Param : *InnerParams) {
1907 MultiLevelTemplateArgumentList Args;
1908 Args.addOuterTemplateArguments(SubstArgs);
1909 Args.addOuterRetainedLevel();
1910 NamedDecl *NewParam = transformTemplateParameter(Param, Args);
1913 AllParams.push_back(NewParam);
1914 SubstArgs.push_back(SemaRef.Context.getCanonicalTemplateArgument(
1915 SemaRef.Context.getInjectedTemplateArg(NewParam)));
1917 TemplateParams = TemplateParameterList::Create(
1918 SemaRef.Context, InnerParams->getTemplateLoc(),
1919 InnerParams->getLAngleLoc(), AllParams, InnerParams->getRAngleLoc(),
1920 /*FIXME: RequiresClause*/ nullptr);
1923 // If we built a new template-parameter-list, track that we need to
1924 // substitute references to the old parameters into references to the
1926 MultiLevelTemplateArgumentList Args;
1928 Args.addOuterTemplateArguments(SubstArgs);
1929 Args.addOuterRetainedLevel();
1932 FunctionProtoTypeLoc FPTL = CD->getTypeSourceInfo()->getTypeLoc()
1933 .getAsAdjusted<FunctionProtoTypeLoc>();
1934 assert(FPTL && "no prototype for constructor declaration");
1936 // Transform the type of the function, adjusting the return type and
1937 // replacing references to the old parameters with references to the
1940 SmallVector<ParmVarDecl*, 8> Params;
1941 QualType NewType = transformFunctionProtoType(TLB, FPTL, Params, Args);
1942 if (NewType.isNull())
1944 TypeSourceInfo *NewTInfo = TLB.getTypeSourceInfo(SemaRef.Context, NewType);
1946 return buildDeductionGuide(TemplateParams, CD->getExplicitSpecifier(),
1947 NewTInfo, CD->getBeginLoc(), CD->getLocation(),
1951 /// Build a deduction guide with the specified parameter types.
1952 NamedDecl *buildSimpleDeductionGuide(MutableArrayRef<QualType> ParamTypes) {
1953 SourceLocation Loc = Template->getLocation();
1955 // Build the requested type.
1956 FunctionProtoType::ExtProtoInfo EPI;
1957 EPI.HasTrailingReturn = true;
1958 QualType Result = SemaRef.BuildFunctionType(DeducedType, ParamTypes, Loc,
1959 DeductionGuideName, EPI);
1960 TypeSourceInfo *TSI = SemaRef.Context.getTrivialTypeSourceInfo(Result, Loc);
1962 FunctionProtoTypeLoc FPTL =
1963 TSI->getTypeLoc().castAs<FunctionProtoTypeLoc>();
1965 // Build the parameters, needed during deduction / substitution.
1966 SmallVector<ParmVarDecl*, 4> Params;
1967 for (auto T : ParamTypes) {
1968 ParmVarDecl *NewParam = ParmVarDecl::Create(
1969 SemaRef.Context, DC, Loc, Loc, nullptr, T,
1970 SemaRef.Context.getTrivialTypeSourceInfo(T, Loc), SC_None, nullptr);
1971 NewParam->setScopeInfo(0, Params.size());
1972 FPTL.setParam(Params.size(), NewParam);
1973 Params.push_back(NewParam);
1976 return buildDeductionGuide(Template->getTemplateParameters(),
1977 ExplicitSpecifier(), TSI, Loc, Loc, Loc);
1981 /// Transform a constructor template parameter into a deduction guide template
1982 /// parameter, rebuilding any internal references to earlier parameters and
1983 /// renumbering as we go.
1984 NamedDecl *transformTemplateParameter(NamedDecl *TemplateParam,
1985 MultiLevelTemplateArgumentList &Args) {
1986 if (auto *TTP = dyn_cast<TemplateTypeParmDecl>(TemplateParam)) {
1987 // TemplateTypeParmDecl's index cannot be changed after creation, so
1988 // substitute it directly.
1989 auto *NewTTP = TemplateTypeParmDecl::Create(
1990 SemaRef.Context, DC, TTP->getBeginLoc(), TTP->getLocation(),
1991 /*Depth*/ 0, Depth1IndexAdjustment + TTP->getIndex(),
1992 TTP->getIdentifier(), TTP->wasDeclaredWithTypename(),
1993 TTP->isParameterPack(), TTP->hasTypeConstraint(),
1994 TTP->isExpandedParameterPack() ?
1995 llvm::Optional<unsigned>(TTP->getNumExpansionParameters()) : None);
1996 if (const auto *TC = TTP->getTypeConstraint()) {
1997 TemplateArgumentListInfo TransformedArgs;
1998 const auto *ArgsAsWritten = TC->getTemplateArgsAsWritten();
1999 if (SemaRef.Subst(ArgsAsWritten->getTemplateArgs(),
2000 ArgsAsWritten->NumTemplateArgs, TransformedArgs,
2002 SemaRef.AttachTypeConstraint(
2003 TC->getNestedNameSpecifierLoc(), TC->getConceptNameInfo(),
2004 TC->getNamedConcept(), &TransformedArgs, NewTTP,
2005 NewTTP->isParameterPack()
2006 ? cast<CXXFoldExpr>(TC->getImmediatelyDeclaredConstraint())
2008 : SourceLocation());
2010 if (TTP->hasDefaultArgument()) {
2011 TypeSourceInfo *InstantiatedDefaultArg =
2012 SemaRef.SubstType(TTP->getDefaultArgumentInfo(), Args,
2013 TTP->getDefaultArgumentLoc(), TTP->getDeclName());
2014 if (InstantiatedDefaultArg)
2015 NewTTP->setDefaultArgument(InstantiatedDefaultArg);
2017 SemaRef.CurrentInstantiationScope->InstantiatedLocal(TemplateParam,
2022 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(TemplateParam))
2023 return transformTemplateParameterImpl(TTP, Args);
2025 return transformTemplateParameterImpl(
2026 cast<NonTypeTemplateParmDecl>(TemplateParam), Args);
2028 template<typename TemplateParmDecl>
2030 transformTemplateParameterImpl(TemplateParmDecl *OldParam,
2031 MultiLevelTemplateArgumentList &Args) {
2032 // Ask the template instantiator to do the heavy lifting for us, then adjust
2033 // the index of the parameter once it's done.
2035 cast<TemplateParmDecl>(SemaRef.SubstDecl(OldParam, DC, Args));
2036 assert(NewParam->getDepth() == 0 && "unexpected template param depth");
2037 NewParam->setPosition(NewParam->getPosition() + Depth1IndexAdjustment);
2041 QualType transformFunctionProtoType(TypeLocBuilder &TLB,
2042 FunctionProtoTypeLoc TL,
2043 SmallVectorImpl<ParmVarDecl*> &Params,
2044 MultiLevelTemplateArgumentList &Args) {
2045 SmallVector<QualType, 4> ParamTypes;
2046 const FunctionProtoType *T = TL.getTypePtr();
2048 // -- The types of the function parameters are those of the constructor.
2049 for (auto *OldParam : TL.getParams()) {
2050 ParmVarDecl *NewParam = transformFunctionTypeParam(OldParam, Args);
2053 ParamTypes.push_back(NewParam->getType());
2054 Params.push_back(NewParam);
2057 // -- The return type is the class template specialization designated by
2058 // the template-name and template arguments corresponding to the
2059 // template parameters obtained from the class template.
2061 // We use the injected-class-name type of the primary template instead.
2062 // This has the convenient property that it is different from any type that
2063 // the user can write in a deduction-guide (because they cannot enter the
2064 // context of the template), so implicit deduction guides can never collide
2065 // with explicit ones.
2066 QualType ReturnType = DeducedType;
2067 TLB.pushTypeSpec(ReturnType).setNameLoc(Primary->getLocation());
2069 // Resolving a wording defect, we also inherit the variadicness of the
2071 FunctionProtoType::ExtProtoInfo EPI;
2072 EPI.Variadic = T->isVariadic();
2073 EPI.HasTrailingReturn = true;
2075 QualType Result = SemaRef.BuildFunctionType(
2076 ReturnType, ParamTypes, TL.getBeginLoc(), DeductionGuideName, EPI);
2077 if (Result.isNull())
2080 FunctionProtoTypeLoc NewTL = TLB.push<FunctionProtoTypeLoc>(Result);
2081 NewTL.setLocalRangeBegin(TL.getLocalRangeBegin());
2082 NewTL.setLParenLoc(TL.getLParenLoc());
2083 NewTL.setRParenLoc(TL.getRParenLoc());
2084 NewTL.setExceptionSpecRange(SourceRange());
2085 NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
2086 for (unsigned I = 0, E = NewTL.getNumParams(); I != E; ++I)
2087 NewTL.setParam(I, Params[I]);
2093 transformFunctionTypeParam(ParmVarDecl *OldParam,
2094 MultiLevelTemplateArgumentList &Args) {
2095 TypeSourceInfo *OldDI = OldParam->getTypeSourceInfo();
2096 TypeSourceInfo *NewDI;
2097 if (auto PackTL = OldDI->getTypeLoc().getAs<PackExpansionTypeLoc>()) {
2098 // Expand out the one and only element in each inner pack.
2099 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, 0);
2101 SemaRef.SubstType(PackTL.getPatternLoc(), Args,
2102 OldParam->getLocation(), OldParam->getDeclName());
2103 if (!NewDI) return nullptr;
2105 SemaRef.CheckPackExpansion(NewDI, PackTL.getEllipsisLoc(),
2106 PackTL.getTypePtr()->getNumExpansions());
2108 NewDI = SemaRef.SubstType(OldDI, Args, OldParam->getLocation(),
2109 OldParam->getDeclName());
2113 // Extract the type. This (for instance) replaces references to typedef
2114 // members of the current instantiations with the definitions of those
2115 // typedefs, avoiding triggering instantiation of the deduced type during
2117 NewDI = ExtractTypeForDeductionGuide(SemaRef).transform(NewDI);
2119 // Resolving a wording defect, we also inherit default arguments from the
2121 ExprResult NewDefArg;
2122 if (OldParam->hasDefaultArg()) {
2123 NewDefArg = SemaRef.SubstExpr(OldParam->getDefaultArg(), Args);
2124 if (NewDefArg.isInvalid())
2128 ParmVarDecl *NewParam = ParmVarDecl::Create(SemaRef.Context, DC,
2129 OldParam->getInnerLocStart(),
2130 OldParam->getLocation(),
2131 OldParam->getIdentifier(),
2134 OldParam->getStorageClass(),
2136 NewParam->setScopeInfo(OldParam->getFunctionScopeDepth(),
2137 OldParam->getFunctionScopeIndex());
2138 SemaRef.CurrentInstantiationScope->InstantiatedLocal(OldParam, NewParam);
2142 NamedDecl *buildDeductionGuide(TemplateParameterList *TemplateParams,
2143 ExplicitSpecifier ES, TypeSourceInfo *TInfo,
2144 SourceLocation LocStart, SourceLocation Loc,
2145 SourceLocation LocEnd) {
2146 DeclarationNameInfo Name(DeductionGuideName, Loc);
2147 ArrayRef<ParmVarDecl *> Params =
2148 TInfo->getTypeLoc().castAs<FunctionProtoTypeLoc>().getParams();
2150 // Build the implicit deduction guide template.
2152 CXXDeductionGuideDecl::Create(SemaRef.Context, DC, LocStart, ES, Name,
2153 TInfo->getType(), TInfo, LocEnd);
2154 Guide->setImplicit();
2155 Guide->setParams(Params);
2157 for (auto *Param : Params)
2158 Param->setDeclContext(Guide);
2160 auto *GuideTemplate = FunctionTemplateDecl::Create(
2161 SemaRef.Context, DC, Loc, DeductionGuideName, TemplateParams, Guide);
2162 GuideTemplate->setImplicit();
2163 Guide->setDescribedFunctionTemplate(GuideTemplate);
2165 if (isa<CXXRecordDecl>(DC)) {
2166 Guide->setAccess(AS_public);
2167 GuideTemplate->setAccess(AS_public);
2170 DC->addDecl(GuideTemplate);
2171 return GuideTemplate;
2176 void Sema::DeclareImplicitDeductionGuides(TemplateDecl *Template,
2177 SourceLocation Loc) {
2178 if (CXXRecordDecl *DefRecord =
2179 cast<CXXRecordDecl>(Template->getTemplatedDecl())->getDefinition()) {
2180 TemplateDecl *DescribedTemplate = DefRecord->getDescribedClassTemplate();
2181 Template = DescribedTemplate ? DescribedTemplate : Template;
2184 DeclContext *DC = Template->getDeclContext();
2185 if (DC->isDependentContext())
2188 ConvertConstructorToDeductionGuideTransform Transform(
2189 *this, cast<ClassTemplateDecl>(Template));
2190 if (!isCompleteType(Loc, Transform.DeducedType))
2193 // Check whether we've already declared deduction guides for this template.
2194 // FIXME: Consider storing a flag on the template to indicate this.
2195 auto Existing = DC->lookup(Transform.DeductionGuideName);
2196 for (auto *D : Existing)
2197 if (D->isImplicit())
2200 // In case we were expanding a pack when we attempted to declare deduction
2201 // guides, turn off pack expansion for everything we're about to do.
2202 ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
2203 // Create a template instantiation record to track the "instantiation" of
2204 // constructors into deduction guides.
2205 // FIXME: Add a kind for this to give more meaningful diagnostics. But can
2206 // this substitution process actually fail?
2207 InstantiatingTemplate BuildingDeductionGuides(*this, Loc, Template);
2208 if (BuildingDeductionGuides.isInvalid())
2211 // Convert declared constructors into deduction guide templates.
2212 // FIXME: Skip constructors for which deduction must necessarily fail (those
2213 // for which some class template parameter without a default argument never
2214 // appears in a deduced context).
2215 bool AddedAny = false;
2216 for (NamedDecl *D : LookupConstructors(Transform.Primary)) {
2217 D = D->getUnderlyingDecl();
2218 if (D->isInvalidDecl() || D->isImplicit())
2220 D = cast<NamedDecl>(D->getCanonicalDecl());
2222 auto *FTD = dyn_cast<FunctionTemplateDecl>(D);
2224 dyn_cast_or_null<CXXConstructorDecl>(FTD ? FTD->getTemplatedDecl() : D);
2225 // Class-scope explicit specializations (MS extension) do not result in
2226 // deduction guides.
2227 if (!CD || (!FTD && CD->isFunctionTemplateSpecialization()))
2230 Transform.transformConstructor(FTD, CD);
2234 // C++17 [over.match.class.deduct]
2235 // -- If C is not defined or does not declare any constructors, an
2236 // additional function template derived as above from a hypothetical
2239 Transform.buildSimpleDeductionGuide(None);
2241 // -- An additional function template derived as above from a hypothetical
2242 // constructor C(C), called the copy deduction candidate.
2243 cast<CXXDeductionGuideDecl>(
2244 cast<FunctionTemplateDecl>(
2245 Transform.buildSimpleDeductionGuide(Transform.DeducedType))
2246 ->getTemplatedDecl())
2247 ->setIsCopyDeductionCandidate();
2250 /// Diagnose the presence of a default template argument on a
2251 /// template parameter, which is ill-formed in certain contexts.
2253 /// \returns true if the default template argument should be dropped.
2254 static bool DiagnoseDefaultTemplateArgument(Sema &S,
2255 Sema::TemplateParamListContext TPC,
2256 SourceLocation ParamLoc,
2257 SourceRange DefArgRange) {
2259 case Sema::TPC_ClassTemplate:
2260 case Sema::TPC_VarTemplate:
2261 case Sema::TPC_TypeAliasTemplate:
2264 case Sema::TPC_FunctionTemplate:
2265 case Sema::TPC_FriendFunctionTemplateDefinition:
2266 // C++ [temp.param]p9:
2267 // A default template-argument shall not be specified in a
2268 // function template declaration or a function template
2270 // If a friend function template declaration specifies a default
2271 // template-argument, that declaration shall be a definition and shall be
2272 // the only declaration of the function template in the translation unit.
2273 // (C++98/03 doesn't have this wording; see DR226).
2274 S.Diag(ParamLoc, S.getLangOpts().CPlusPlus11 ?
2275 diag::warn_cxx98_compat_template_parameter_default_in_function_template
2276 : diag::ext_template_parameter_default_in_function_template)
2280 case Sema::TPC_ClassTemplateMember:
2281 // C++0x [temp.param]p9:
2282 // A default template-argument shall not be specified in the
2283 // template-parameter-lists of the definition of a member of a
2284 // class template that appears outside of the member's class.
2285 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
2289 case Sema::TPC_FriendClassTemplate:
2290 case Sema::TPC_FriendFunctionTemplate:
2291 // C++ [temp.param]p9:
2292 // A default template-argument shall not be specified in a
2293 // friend template declaration.
2294 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
2298 // FIXME: C++0x [temp.param]p9 allows default template-arguments
2299 // for friend function templates if there is only a single
2300 // declaration (and it is a definition). Strange!
2303 llvm_unreachable("Invalid TemplateParamListContext!");
2306 /// Check for unexpanded parameter packs within the template parameters
2307 /// of a template template parameter, recursively.
2308 static bool DiagnoseUnexpandedParameterPacks(Sema &S,
2309 TemplateTemplateParmDecl *TTP) {
2310 // A template template parameter which is a parameter pack is also a pack
2312 if (TTP->isParameterPack())
2315 TemplateParameterList *Params = TTP->getTemplateParameters();
2316 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2317 NamedDecl *P = Params->getParam(I);
2318 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(P)) {
2319 if (!TTP->isParameterPack())
2320 if (const TypeConstraint *TC = TTP->getTypeConstraint())
2321 if (TC->hasExplicitTemplateArgs())
2322 for (auto &ArgLoc : TC->getTemplateArgsAsWritten()->arguments())
2323 if (S.DiagnoseUnexpandedParameterPack(ArgLoc,
2324 Sema::UPPC_TypeConstraint))
2329 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
2330 if (!NTTP->isParameterPack() &&
2331 S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
2332 NTTP->getTypeSourceInfo(),
2333 Sema::UPPC_NonTypeTemplateParameterType))
2339 if (TemplateTemplateParmDecl *InnerTTP
2340 = dyn_cast<TemplateTemplateParmDecl>(P))
2341 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
2348 /// Checks the validity of a template parameter list, possibly
2349 /// considering the template parameter list from a previous
2352 /// If an "old" template parameter list is provided, it must be
2353 /// equivalent (per TemplateParameterListsAreEqual) to the "new"
2354 /// template parameter list.
2356 /// \param NewParams Template parameter list for a new template
2357 /// declaration. This template parameter list will be updated with any
2358 /// default arguments that are carried through from the previous
2359 /// template parameter list.
2361 /// \param OldParams If provided, template parameter list from a
2362 /// previous declaration of the same template. Default template
2363 /// arguments will be merged from the old template parameter list to
2364 /// the new template parameter list.
2366 /// \param TPC Describes the context in which we are checking the given
2367 /// template parameter list.
2369 /// \param SkipBody If we might have already made a prior merged definition
2370 /// of this template visible, the corresponding body-skipping information.
2371 /// Default argument redefinition is not an error when skipping such a body,
2372 /// because (under the ODR) we can assume the default arguments are the same
2373 /// as the prior merged definition.
2375 /// \returns true if an error occurred, false otherwise.
2376 bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
2377 TemplateParameterList *OldParams,
2378 TemplateParamListContext TPC,
2379 SkipBodyInfo *SkipBody) {
2380 bool Invalid = false;
2382 // C++ [temp.param]p10:
2383 // The set of default template-arguments available for use with a
2384 // template declaration or definition is obtained by merging the
2385 // default arguments from the definition (if in scope) and all
2386 // declarations in scope in the same way default function
2387 // arguments are (8.3.6).
2388 bool SawDefaultArgument = false;
2389 SourceLocation PreviousDefaultArgLoc;
2391 // Dummy initialization to avoid warnings.
2392 TemplateParameterList::iterator OldParam = NewParams->end();
2394 OldParam = OldParams->begin();
2396 bool RemoveDefaultArguments = false;
2397 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2398 NewParamEnd = NewParams->end();
2399 NewParam != NewParamEnd; ++NewParam) {
2400 // Variables used to diagnose redundant default arguments
2401 bool RedundantDefaultArg = false;
2402 SourceLocation OldDefaultLoc;
2403 SourceLocation NewDefaultLoc;
2405 // Variable used to diagnose missing default arguments
2406 bool MissingDefaultArg = false;
2408 // Variable used to diagnose non-final parameter packs
2409 bool SawParameterPack = false;
2411 if (TemplateTypeParmDecl *NewTypeParm
2412 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
2413 // Check the presence of a default argument here.
2414 if (NewTypeParm->hasDefaultArgument() &&
2415 DiagnoseDefaultTemplateArgument(*this, TPC,
2416 NewTypeParm->getLocation(),
2417 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
2419 NewTypeParm->removeDefaultArgument();
2421 // Merge default arguments for template type parameters.
2422 TemplateTypeParmDecl *OldTypeParm
2423 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr;
2424 if (NewTypeParm->isParameterPack()) {
2425 assert(!NewTypeParm->hasDefaultArgument() &&
2426 "Parameter packs can't have a default argument!");
2427 SawParameterPack = true;
2428 } else if (OldTypeParm && hasVisibleDefaultArgument(OldTypeParm) &&
2429 NewTypeParm->hasDefaultArgument() &&
2430 (!SkipBody || !SkipBody->ShouldSkip)) {
2431 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
2432 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
2433 SawDefaultArgument = true;
2434 RedundantDefaultArg = true;
2435 PreviousDefaultArgLoc = NewDefaultLoc;
2436 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
2437 // Merge the default argument from the old declaration to the
2439 NewTypeParm->setInheritedDefaultArgument(Context, OldTypeParm);
2440 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
2441 } else if (NewTypeParm->hasDefaultArgument()) {
2442 SawDefaultArgument = true;
2443 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
2444 } else if (SawDefaultArgument)
2445 MissingDefaultArg = true;
2446 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
2447 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
2448 // Check for unexpanded parameter packs.
2449 if (!NewNonTypeParm->isParameterPack() &&
2450 DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
2451 NewNonTypeParm->getTypeSourceInfo(),
2452 UPPC_NonTypeTemplateParameterType)) {
2457 // Check the presence of a default argument here.
2458 if (NewNonTypeParm->hasDefaultArgument() &&
2459 DiagnoseDefaultTemplateArgument(*this, TPC,
2460 NewNonTypeParm->getLocation(),
2461 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
2462 NewNonTypeParm->removeDefaultArgument();
2465 // Merge default arguments for non-type template parameters
2466 NonTypeTemplateParmDecl *OldNonTypeParm
2467 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr;
2468 if (NewNonTypeParm->isParameterPack()) {
2469 assert(!NewNonTypeParm->hasDefaultArgument() &&
2470 "Parameter packs can't have a default argument!");
2471 if (!NewNonTypeParm->isPackExpansion())
2472 SawParameterPack = true;
2473 } else if (OldNonTypeParm && hasVisibleDefaultArgument(OldNonTypeParm) &&
2474 NewNonTypeParm->hasDefaultArgument() &&
2475 (!SkipBody || !SkipBody->ShouldSkip)) {
2476 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
2477 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
2478 SawDefaultArgument = true;
2479 RedundantDefaultArg = true;
2480 PreviousDefaultArgLoc = NewDefaultLoc;
2481 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
2482 // Merge the default argument from the old declaration to the
2484 NewNonTypeParm->setInheritedDefaultArgument(Context, OldNonTypeParm);
2485 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
2486 } else if (NewNonTypeParm->hasDefaultArgument()) {
2487 SawDefaultArgument = true;
2488 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
2489 } else if (SawDefaultArgument)
2490 MissingDefaultArg = true;
2492 TemplateTemplateParmDecl *NewTemplateParm
2493 = cast<TemplateTemplateParmDecl>(*NewParam);
2495 // Check for unexpanded parameter packs, recursively.
2496 if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
2501 // Check the presence of a default argument here.
2502 if (NewTemplateParm->hasDefaultArgument() &&
2503 DiagnoseDefaultTemplateArgument(*this, TPC,
2504 NewTemplateParm->getLocation(),
2505 NewTemplateParm->getDefaultArgument().getSourceRange()))
2506 NewTemplateParm->removeDefaultArgument();
2508 // Merge default arguments for template template parameters
2509 TemplateTemplateParmDecl *OldTemplateParm
2510 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr;
2511 if (NewTemplateParm->isParameterPack()) {
2512 assert(!NewTemplateParm->hasDefaultArgument() &&
2513 "Parameter packs can't have a default argument!");
2514 if (!NewTemplateParm->isPackExpansion())
2515 SawParameterPack = true;
2516 } else if (OldTemplateParm &&
2517 hasVisibleDefaultArgument(OldTemplateParm) &&
2518 NewTemplateParm->hasDefaultArgument() &&
2519 (!SkipBody || !SkipBody->ShouldSkip)) {
2520 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
2521 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
2522 SawDefaultArgument = true;
2523 RedundantDefaultArg = true;
2524 PreviousDefaultArgLoc = NewDefaultLoc;
2525 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
2526 // Merge the default argument from the old declaration to the
2528 NewTemplateParm->setInheritedDefaultArgument(Context, OldTemplateParm);
2529 PreviousDefaultArgLoc
2530 = OldTemplateParm->getDefaultArgument().getLocation();
2531 } else if (NewTemplateParm->hasDefaultArgument()) {
2532 SawDefaultArgument = true;
2533 PreviousDefaultArgLoc
2534 = NewTemplateParm->getDefaultArgument().getLocation();
2535 } else if (SawDefaultArgument)
2536 MissingDefaultArg = true;
2539 // C++11 [temp.param]p11:
2540 // If a template parameter of a primary class template or alias template
2541 // is a template parameter pack, it shall be the last template parameter.
2542 if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
2543 (TPC == TPC_ClassTemplate || TPC == TPC_VarTemplate ||
2544 TPC == TPC_TypeAliasTemplate)) {
2545 Diag((*NewParam)->getLocation(),
2546 diag::err_template_param_pack_must_be_last_template_parameter);
2550 if (RedundantDefaultArg) {
2551 // C++ [temp.param]p12:
2552 // A template-parameter shall not be given default arguments
2553 // by two different declarations in the same scope.
2554 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
2555 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
2557 } else if (MissingDefaultArg && TPC != TPC_FunctionTemplate) {
2558 // C++ [temp.param]p11:
2559 // If a template-parameter of a class template has a default
2560 // template-argument, each subsequent template-parameter shall either
2561 // have a default template-argument supplied or be a template parameter
2563 Diag((*NewParam)->getLocation(),
2564 diag::err_template_param_default_arg_missing);
2565 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
2567 RemoveDefaultArguments = true;
2570 // If we have an old template parameter list that we're merging
2571 // in, move on to the next parameter.
2576 // We were missing some default arguments at the end of the list, so remove
2577 // all of the default arguments.
2578 if (RemoveDefaultArguments) {
2579 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2580 NewParamEnd = NewParams->end();
2581 NewParam != NewParamEnd; ++NewParam) {
2582 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
2583 TTP->removeDefaultArgument();
2584 else if (NonTypeTemplateParmDecl *NTTP
2585 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
2586 NTTP->removeDefaultArgument();
2588 cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
2597 /// A class which looks for a use of a certain level of template
2599 struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
2600 typedef RecursiveASTVisitor<DependencyChecker> super;
2604 // Whether we're looking for a use of a template parameter that makes the
2605 // overall construct type-dependent / a dependent type. This is strictly
2606 // best-effort for now; we may fail to match at all for a dependent type
2607 // in some cases if this is set.
2608 bool IgnoreNonTypeDependent;
2611 SourceLocation MatchLoc;
2613 DependencyChecker(unsigned Depth, bool IgnoreNonTypeDependent)
2614 : Depth(Depth), IgnoreNonTypeDependent(IgnoreNonTypeDependent),
2617 DependencyChecker(TemplateParameterList *Params, bool IgnoreNonTypeDependent)
2618 : IgnoreNonTypeDependent(IgnoreNonTypeDependent), Match(false) {
2619 NamedDecl *ND = Params->getParam(0);
2620 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
2621 Depth = PD->getDepth();
2622 } else if (NonTypeTemplateParmDecl *PD =
2623 dyn_cast<NonTypeTemplateParmDecl>(ND)) {
2624 Depth = PD->getDepth();
2626 Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
2630 bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
2631 if (ParmDepth >= Depth) {
2639 bool TraverseStmt(Stmt *S, DataRecursionQueue *Q = nullptr) {
2640 // Prune out non-type-dependent expressions if requested. This can
2641 // sometimes result in us failing to find a template parameter reference
2642 // (if a value-dependent expression creates a dependent type), but this
2643 // mode is best-effort only.
2644 if (auto *E = dyn_cast_or_null<Expr>(S))
2645 if (IgnoreNonTypeDependent && !E->isTypeDependent())
2647 return super::TraverseStmt(S, Q);
2650 bool TraverseTypeLoc(TypeLoc TL) {
2651 if (IgnoreNonTypeDependent && !TL.isNull() &&
2652 !TL.getType()->isDependentType())
2654 return super::TraverseTypeLoc(TL);
2657 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
2658 return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());
2661 bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
2662 // For a best-effort search, keep looking until we find a location.
2663 return IgnoreNonTypeDependent || !Matches(T->getDepth());
2666 bool TraverseTemplateName(TemplateName N) {
2667 if (TemplateTemplateParmDecl *PD =
2668 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
2669 if (Matches(PD->getDepth()))
2671 return super::TraverseTemplateName(N);
2674 bool VisitDeclRefExpr(DeclRefExpr *E) {
2675 if (NonTypeTemplateParmDecl *PD =
2676 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
2677 if (Matches(PD->getDepth(), E->getExprLoc()))
2679 return super::VisitDeclRefExpr(E);
2682 bool VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
2683 return TraverseType(T->getReplacementType());
2687 VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *T) {
2688 return TraverseTemplateArgument(T->getArgumentPack());
2691 bool TraverseInjectedClassNameType(const InjectedClassNameType *T) {
2692 return TraverseType(T->getInjectedSpecializationType());
2695 } // end anonymous namespace
2697 /// Determines whether a given type depends on the given parameter
2700 DependsOnTemplateParameters(QualType T, TemplateParameterList *Params) {
2701 if (!Params->size())
2704 DependencyChecker Checker(Params, /*IgnoreNonTypeDependent*/false);
2705 Checker.TraverseType(T);
2706 return Checker.Match;
2709 // Find the source range corresponding to the named type in the given
2710 // nested-name-specifier, if any.
2711 static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context,
2713 const CXXScopeSpec &SS) {
2714 NestedNameSpecifierLoc NNSLoc(SS.getScopeRep(), SS.location_data());
2715 while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) {
2716 if (const Type *CurType = NNS->getAsType()) {
2717 if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0)))
2718 return NNSLoc.getTypeLoc().getSourceRange();
2722 NNSLoc = NNSLoc.getPrefix();
2725 return SourceRange();
2728 /// Match the given template parameter lists to the given scope
2729 /// specifier, returning the template parameter list that applies to the
2732 /// \param DeclStartLoc the start of the declaration that has a scope
2733 /// specifier or a template parameter list.
2735 /// \param DeclLoc The location of the declaration itself.
2737 /// \param SS the scope specifier that will be matched to the given template
2738 /// parameter lists. This scope specifier precedes a qualified name that is
2741 /// \param TemplateId The template-id following the scope specifier, if there
2742 /// is one. Used to check for a missing 'template<>'.
2744 /// \param ParamLists the template parameter lists, from the outermost to the
2745 /// innermost template parameter lists.
2747 /// \param IsFriend Whether to apply the slightly different rules for
2748 /// matching template parameters to scope specifiers in friend
2751 /// \param IsMemberSpecialization will be set true if the scope specifier
2752 /// denotes a fully-specialized type, and therefore this is a declaration of
2753 /// a member specialization.
2755 /// \returns the template parameter list, if any, that corresponds to the
2756 /// name that is preceded by the scope specifier @p SS. This template
2757 /// parameter list may have template parameters (if we're declaring a
2758 /// template) or may have no template parameters (if we're declaring a
2759 /// template specialization), or may be NULL (if what we're declaring isn't
2760 /// itself a template).
2761 TemplateParameterList *Sema::MatchTemplateParametersToScopeSpecifier(
2762 SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
2763 TemplateIdAnnotation *TemplateId,
2764 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
2765 bool &IsMemberSpecialization, bool &Invalid) {
2766 IsMemberSpecialization = false;
2769 // The sequence of nested types to which we will match up the template
2770 // parameter lists. We first build this list by starting with the type named
2771 // by the nested-name-specifier and walking out until we run out of types.
2772 SmallVector<QualType, 4> NestedTypes;
2774 if (SS.getScopeRep()) {
2775 if (CXXRecordDecl *Record
2776 = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
2777 T = Context.getTypeDeclType(Record);
2779 T = QualType(SS.getScopeRep()->getAsType(), 0);
2782 // If we found an explicit specialization that prevents us from needing
2783 // 'template<>' headers, this will be set to the location of that
2784 // explicit specialization.
2785 SourceLocation ExplicitSpecLoc;
2787 while (!T.isNull()) {
2788 NestedTypes.push_back(T);
2790 // Retrieve the parent of a record type.
2791 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
2792 // If this type is an explicit specialization, we're done.
2793 if (ClassTemplateSpecializationDecl *Spec
2794 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
2795 if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) &&
2796 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
2797 ExplicitSpecLoc = Spec->getLocation();
2800 } else if (Record->getTemplateSpecializationKind()
2801 == TSK_ExplicitSpecialization) {
2802 ExplicitSpecLoc = Record->getLocation();
2806 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
2807 T = Context.getTypeDeclType(Parent);
2813 if (const TemplateSpecializationType *TST
2814 = T->getAs<TemplateSpecializationType>()) {
2815 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
2816 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
2817 T = Context.getTypeDeclType(Parent);
2824 // Look one step prior in a dependent template specialization type.
2825 if (const DependentTemplateSpecializationType *DependentTST
2826 = T->getAs<DependentTemplateSpecializationType>()) {
2827 if (NestedNameSpecifier *NNS = DependentTST->getQualifier())
2828 T = QualType(NNS->getAsType(), 0);
2834 // Look one step prior in a dependent name type.
2835 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
2836 if (NestedNameSpecifier *NNS = DependentName->getQualifier())
2837 T = QualType(NNS->getAsType(), 0);
2843 // Retrieve the parent of an enumeration type.
2844 if (const EnumType *EnumT = T->getAs<EnumType>()) {
2845 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
2847 EnumDecl *Enum = EnumT->getDecl();
2849 // Get to the parent type.
2850 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
2851 T = Context.getTypeDeclType(Parent);
2859 // Reverse the nested types list, since we want to traverse from the outermost
2860 // to the innermost while checking template-parameter-lists.
2861 std::reverse(NestedTypes.begin(), NestedTypes.end());
2863 // C++0x [temp.expl.spec]p17:
2864 // A member or a member template may be nested within many
2865 // enclosing class templates. In an explicit specialization for
2866 // such a member, the member declaration shall be preceded by a
2867 // template<> for each enclosing class template that is
2868 // explicitly specialized.
2869 bool SawNonEmptyTemplateParameterList = false;
2871 auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
2872 if (SawNonEmptyTemplateParameterList) {
2873 Diag(DeclLoc, diag::err_specialize_member_of_template)
2874 << !Recovery << Range;
2876 IsMemberSpecialization = false;
2883 auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
2884 // Check that we can have an explicit specialization here.
2885 if (CheckExplicitSpecialization(Range, true))
2888 // We don't have a template header, but we should.
2889 SourceLocation ExpectedTemplateLoc;
2890 if (!ParamLists.empty())
2891 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
2893 ExpectedTemplateLoc = DeclStartLoc;
2895 Diag(DeclLoc, diag::err_template_spec_needs_header)
2897 << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
2901 unsigned ParamIdx = 0;
2902 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
2904 T = NestedTypes[TypeIdx];
2906 // Whether we expect a 'template<>' header.
2907 bool NeedEmptyTemplateHeader = false;
2909 // Whether we expect a template header with parameters.
2910 bool NeedNonemptyTemplateHeader = false;
2912 // For a dependent type, the set of template parameters that we
2914 TemplateParameterList *ExpectedTemplateParams = nullptr;
2916 // C++0x [temp.expl.spec]p15:
2917 // A member or a member template may be nested within many enclosing
2918 // class templates. In an explicit specialization for such a member, the
2919 // member declaration shall be preceded by a template<> for each
2920 // enclosing class template that is explicitly specialized.
2921 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
2922 if (ClassTemplatePartialSpecializationDecl *Partial
2923 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
2924 ExpectedTemplateParams = Partial->getTemplateParameters();
2925 NeedNonemptyTemplateHeader = true;
2926 } else if (Record->isDependentType()) {
2927 if (Record->getDescribedClassTemplate()) {
2928 ExpectedTemplateParams = Record->getDescribedClassTemplate()
2929 ->getTemplateParameters();
2930 NeedNonemptyTemplateHeader = true;
2932 } else if (ClassTemplateSpecializationDecl *Spec
2933 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
2934 // C++0x [temp.expl.spec]p4:
2935 // Members of an explicitly specialized class template are defined
2936 // in the same manner as members of normal classes, and not using
2937 // the template<> syntax.
2938 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
2939 NeedEmptyTemplateHeader = true;
2942 } else if (Record->getTemplateSpecializationKind()) {
2943 if (Record->getTemplateSpecializationKind()
2944 != TSK_ExplicitSpecialization &&
2945 TypeIdx == NumTypes - 1)
2946 IsMemberSpecialization = true;
2950 } else if (const TemplateSpecializationType *TST
2951 = T->getAs<TemplateSpecializationType>()) {
2952 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
2953 ExpectedTemplateParams = Template->getTemplateParameters();
2954 NeedNonemptyTemplateHeader = true;
2956 } else if (T->getAs<DependentTemplateSpecializationType>()) {
2957 // FIXME: We actually could/should check the template arguments here
2958 // against the corresponding template parameter list.
2959 NeedNonemptyTemplateHeader = false;
2962 // C++ [temp.expl.spec]p16:
2963 // In an explicit specialization declaration for a member of a class
2964 // template or a member template that ap- pears in namespace scope, the
2965 // member template and some of its enclosing class templates may remain
2966 // unspecialized, except that the declaration shall not explicitly
2967 // specialize a class member template if its en- closing class templates
2968 // are not explicitly specialized as well.
2969 if (ParamIdx < ParamLists.size()) {
2970 if (ParamLists[ParamIdx]->size() == 0) {
2971 if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
2975 SawNonEmptyTemplateParameterList = true;
2978 if (NeedEmptyTemplateHeader) {
2979 // If we're on the last of the types, and we need a 'template<>' header
2980 // here, then it's a member specialization.
2981 if (TypeIdx == NumTypes - 1)
2982 IsMemberSpecialization = true;
2984 if (ParamIdx < ParamLists.size()) {
2985 if (ParamLists[ParamIdx]->size() > 0) {
2986 // The header has template parameters when it shouldn't. Complain.
2987 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
2988 diag::err_template_param_list_matches_nontemplate)
2990 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
2991 ParamLists[ParamIdx]->getRAngleLoc())
2992 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
2997 // Consume this template header.
3003 if (DiagnoseMissingExplicitSpecialization(
3004 getRangeOfTypeInNestedNameSpecifier(Context, T, SS)))
3010 if (NeedNonemptyTemplateHeader) {
3011 // In friend declarations we can have template-ids which don't
3012 // depend on the corresponding template parameter lists. But
3013 // assume that empty parameter lists are supposed to match this
3015 if (IsFriend && T->isDependentType()) {
3016 if (ParamIdx < ParamLists.size() &&
3017 DependsOnTemplateParameters(T, ParamLists[ParamIdx]))
3018 ExpectedTemplateParams = nullptr;
3023 if (ParamIdx < ParamLists.size()) {
3024 // Check the template parameter list, if we can.
3025 if (ExpectedTemplateParams &&
3026 !TemplateParameterListsAreEqual(ParamLists[ParamIdx],
3027 ExpectedTemplateParams,
3028 true, TPL_TemplateMatch))
3032 CheckTemplateParameterList(ParamLists[ParamIdx], nullptr,
3033 TPC_ClassTemplateMember))
3040 Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
3042 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
3048 // If there were at least as many template-ids as there were template
3049 // parameter lists, then there are no template parameter lists remaining for
3050 // the declaration itself.
3051 if (ParamIdx >= ParamLists.size()) {
3052 if (TemplateId && !IsFriend) {
3053 // We don't have a template header for the declaration itself, but we
3055 DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
3056 TemplateId->RAngleLoc));
3058 // Fabricate an empty template parameter list for the invented header.
3059 return TemplateParameterList::Create(Context, SourceLocation(),
3060 SourceLocation(), None,
3061 SourceLocation(), nullptr);
3067 // If there were too many template parameter lists, complain about that now.
3068 if (ParamIdx < ParamLists.size() - 1) {
3069 bool HasAnyExplicitSpecHeader = false;
3070 bool AllExplicitSpecHeaders = true;
3071 for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
3072 if (ParamLists[I]->size() == 0)
3073 HasAnyExplicitSpecHeader = true;
3075 AllExplicitSpecHeaders = false;
3078 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
3079 AllExplicitSpecHeaders ? diag::warn_template_spec_extra_headers
3080 : diag::err_template_spec_extra_headers)
3081 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
3082 ParamLists[ParamLists.size() - 2]->getRAngleLoc());
3084 // If there was a specialization somewhere, such that 'template<>' is
3085 // not required, and there were any 'template<>' headers, note where the
3086 // specialization occurred.
3087 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader)
3088 Diag(ExplicitSpecLoc,
3089 diag::note_explicit_template_spec_does_not_need_header)
3090 << NestedTypes.back();
3092 // We have a template parameter list with no corresponding scope, which
3093 // means that the resulting template declaration can't be instantiated
3094 // properly (we'll end up with dependent nodes when we shouldn't).
3095 if (!AllExplicitSpecHeaders)
3099 // C++ [temp.expl.spec]p16:
3100 // In an explicit specialization declaration for a member of a class
3101 // template or a member template that ap- pears in namespace scope, the
3102 // member template and some of its enclosing class templates may remain
3103 // unspecialized, except that the declaration shall not explicitly
3104 // specialize a class member template if its en- closing class templates
3105 // are not explicitly specialized as well.
3106 if (ParamLists.back()->size() == 0 &&
3107 CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
3111 // Return the last template parameter list, which corresponds to the
3112 // entity being declared.
3113 return ParamLists.back();
3116 void Sema::NoteAllFoundTemplates(TemplateName Name) {
3117 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3118 Diag(Template->getLocation(), diag::note_template_declared_here)
3119 << (isa<FunctionTemplateDecl>(Template)
3121 : isa<ClassTemplateDecl>(Template)
3123 : isa<VarTemplateDecl>(Template)
3125 : isa<TypeAliasTemplateDecl>(Template) ? 3 : 4)
3126 << Template->getDeclName();
3130 if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
3131 for (OverloadedTemplateStorage::iterator I = OST->begin(),
3134 Diag((*I)->getLocation(), diag::note_template_declared_here)
3135 << 0 << (*I)->getDeclName();
3142 checkBuiltinTemplateIdType(Sema &SemaRef, BuiltinTemplateDecl *BTD,
3143 const SmallVectorImpl<TemplateArgument> &Converted,
3144 SourceLocation TemplateLoc,
3145 TemplateArgumentListInfo &TemplateArgs) {
3146 ASTContext &Context = SemaRef.getASTContext();
3147 switch (BTD->getBuiltinTemplateKind()) {
3148 case BTK__make_integer_seq: {
3149 // Specializations of __make_integer_seq<S, T, N> are treated like
3150 // S<T, 0, ..., N-1>.
3152 // C++14 [inteseq.intseq]p1:
3153 // T shall be an integer type.
3154 if (!Converted[1].getAsType()->isIntegralType(Context)) {
3155 SemaRef.Diag(TemplateArgs[1].getLocation(),
3156 diag::err_integer_sequence_integral_element_type);
3160 // C++14 [inteseq.make]p1:
3161 // If N is negative the program is ill-formed.
3162 TemplateArgument NumArgsArg = Converted[2];
3163 llvm::APSInt NumArgs = NumArgsArg.getAsIntegral();
3165 SemaRef.Diag(TemplateArgs[2].getLocation(),
3166 diag::err_integer_sequence_negative_length);
3170 QualType ArgTy = NumArgsArg.getIntegralType();
3171 TemplateArgumentListInfo SyntheticTemplateArgs;
3172 // The type argument gets reused as the first template argument in the
3173 // synthetic template argument list.
3174 SyntheticTemplateArgs.addArgument(TemplateArgs[1]);
3175 // Expand N into 0 ... N-1.
3176 for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned());
3178 TemplateArgument TA(Context, I, ArgTy);
3179 SyntheticTemplateArgs.addArgument(SemaRef.getTrivialTemplateArgumentLoc(
3180 TA, ArgTy, TemplateArgs[2].getLocation()));
3182 // The first template argument will be reused as the template decl that
3183 // our synthetic template arguments will be applied to.
3184 return SemaRef.CheckTemplateIdType(Converted[0].getAsTemplate(),
3185 TemplateLoc, SyntheticTemplateArgs);
3188 case BTK__type_pack_element:
3189 // Specializations of
3190 // __type_pack_element<Index, T_1, ..., T_N>
3191 // are treated like T_Index.
3192 assert(Converted.size() == 2 &&
3193 "__type_pack_element should be given an index and a parameter pack");
3195 // If the Index is out of bounds, the program is ill-formed.
3196 TemplateArgument IndexArg = Converted[0], Ts = Converted[1];
3197 llvm::APSInt Index = IndexArg.getAsIntegral();
3198 assert(Index >= 0 && "the index used with __type_pack_element should be of "
3199 "type std::size_t, and hence be non-negative");
3200 if (Index >= Ts.pack_size()) {
3201 SemaRef.Diag(TemplateArgs[0].getLocation(),
3202 diag::err_type_pack_element_out_of_bounds);
3206 // We simply return the type at index `Index`.
3207 auto Nth = std::next(Ts.pack_begin(), Index.getExtValue());
3208 return Nth->getAsType();
3210 llvm_unreachable("unexpected BuiltinTemplateDecl!");
3213 /// Determine whether this alias template is "enable_if_t".
3214 static bool isEnableIfAliasTemplate(TypeAliasTemplateDecl *AliasTemplate) {
3215 return AliasTemplate->getName().equals("enable_if_t");
3218 /// Collect all of the separable terms in the given condition, which
3219 /// might be a conjunction.
3221 /// FIXME: The right answer is to convert the logical expression into
3222 /// disjunctive normal form, so we can find the first failed term
3223 /// within each possible clause.
3224 static void collectConjunctionTerms(Expr *Clause,
3225 SmallVectorImpl<Expr *> &Terms) {
3226 if (auto BinOp = dyn_cast<BinaryOperator>(Clause->IgnoreParenImpCasts())) {
3227 if (BinOp->getOpcode() == BO_LAnd) {
3228 collectConjunctionTerms(BinOp->getLHS(), Terms);
3229 collectConjunctionTerms(BinOp->getRHS(), Terms);
3235 Terms.push_back(Clause);
3238 // The ranges-v3 library uses an odd pattern of a top-level "||" with
3239 // a left-hand side that is value-dependent but never true. Identify
3240 // the idiom and ignore that term.
3241 static Expr *lookThroughRangesV3Condition(Preprocessor &PP, Expr *Cond) {
3243 auto *BinOp = dyn_cast<BinaryOperator>(Cond->IgnoreParenImpCasts());
3244 if (!BinOp) return Cond;
3246 if (BinOp->getOpcode() != BO_LOr) return Cond;
3248 // With an inner '==' that has a literal on the right-hand side.
3249 Expr *LHS = BinOp->getLHS();
3250 auto *InnerBinOp = dyn_cast<BinaryOperator>(LHS->IgnoreParenImpCasts());
3251 if (!InnerBinOp) return Cond;
3253 if (InnerBinOp->getOpcode() != BO_EQ ||
3254 !isa<IntegerLiteral>(InnerBinOp->getRHS()))
3257 // If the inner binary operation came from a macro expansion named
3258 // CONCEPT_REQUIRES or CONCEPT_REQUIRES_, return the right-hand side
3259 // of the '||', which is the real, user-provided condition.
3260 SourceLocation Loc = InnerBinOp->getExprLoc();
3261 if (!Loc.isMacroID()) return Cond;
3263 StringRef MacroName = PP.getImmediateMacroName(Loc);
3264 if (MacroName == "CONCEPT_REQUIRES" || MacroName == "CONCEPT_REQUIRES_")
3265 return BinOp->getRHS();
3272 // A PrinterHelper that prints more helpful diagnostics for some sub-expressions
3273 // within failing boolean expression, such as substituting template parameters
3274 // for actual types.
3275 class FailedBooleanConditionPrinterHelper : public PrinterHelper {
3277 explicit FailedBooleanConditionPrinterHelper(const PrintingPolicy &P)
3280 bool handledStmt(Stmt *E, raw_ostream &OS) override {
3281 const auto *DR = dyn_cast<DeclRefExpr>(E);
3282 if (DR && DR->getQualifier()) {
3283 // If this is a qualified name, expand the template arguments in nested
3285 DR->getQualifier()->print(OS, Policy, true);
3286 // Then print the decl itself.
3287 const ValueDecl *VD = DR->getDecl();
3288 OS << VD->getName();
3289 if (const auto *IV = dyn_cast<VarTemplateSpecializationDecl>(VD)) {
3290 // This is a template variable, print the expanded template arguments.
3291 printTemplateArgumentList(OS, IV->getTemplateArgs().asArray(), Policy);
3299 const PrintingPolicy Policy;
3302 } // end anonymous namespace
3304 std::pair<Expr *, std::string>
3305 Sema::findFailedBooleanCondition(Expr *Cond) {
3306 Cond = lookThroughRangesV3Condition(PP, Cond);
3308 // Separate out all of the terms in a conjunction.
3309 SmallVector<Expr *, 4> Terms;
3310 collectConjunctionTerms(Cond, Terms);
3312 // Determine which term failed.
3313 Expr *FailedCond = nullptr;
3314 for (Expr *Term : Terms) {
3315 Expr *TermAsWritten = Term->IgnoreParenImpCasts();
3317 // Literals are uninteresting.
3318 if (isa<CXXBoolLiteralExpr>(TermAsWritten) ||
3319 isa<IntegerLiteral>(TermAsWritten))
3322 // The initialization of the parameter from the argument is
3323 // a constant-evaluated context.
3324 EnterExpressionEvaluationContext ConstantEvaluated(
3325 *this, Sema::ExpressionEvaluationContext::ConstantEvaluated);
3328 if (Term->EvaluateAsBooleanCondition(Succeeded, Context) &&
3330 FailedCond = TermAsWritten;
3335 FailedCond = Cond->IgnoreParenImpCasts();
3337 std::string Description;
3339 llvm::raw_string_ostream Out(Description);
3340 PrintingPolicy Policy = getPrintingPolicy();
3341 Policy.PrintCanonicalTypes = true;
3342 FailedBooleanConditionPrinterHelper Helper(Policy);
3343 FailedCond->printPretty(Out, &Helper, Policy, 0, "\n", nullptr);
3345 return { FailedCond, Description };
3348 QualType Sema::CheckTemplateIdType(TemplateName Name,
3349 SourceLocation TemplateLoc,
3350 TemplateArgumentListInfo &TemplateArgs) {
3351 DependentTemplateName *DTN
3352 = Name.getUnderlying().getAsDependentTemplateName();
3353 if (DTN && DTN->isIdentifier())
3354 // When building a template-id where the template-name is dependent,
3355 // assume the template is a type template. Either our assumption is
3356 // correct, or the code is ill-formed and will be diagnosed when the
3357 // dependent name is substituted.
3358 return Context.getDependentTemplateSpecializationType(ETK_None,
3359 DTN->getQualifier(),
3360 DTN->getIdentifier(),
3363 TemplateDecl *Template = Name.getAsTemplateDecl();
3364 if (!Template || isa<FunctionTemplateDecl>(Template) ||
3365 isa<VarTemplateDecl>(Template) || isa<ConceptDecl>(Template)) {
3366 // We might have a substituted template template parameter pack. If so,
3367 // build a template specialization type for it.
3368 if (Name.getAsSubstTemplateTemplateParmPack())
3369 return Context.getTemplateSpecializationType(Name, TemplateArgs);
3371 Diag(TemplateLoc, diag::err_template_id_not_a_type)
3373 NoteAllFoundTemplates(Name);
3377 // Check that the template argument list is well-formed for this
3379 SmallVector<TemplateArgument, 4> Converted;
3380 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
3382 /*UpdateArgsWithConversion=*/true))
3387 bool InstantiationDependent = false;
3388 if (TypeAliasTemplateDecl *AliasTemplate =
3389 dyn_cast<TypeAliasTemplateDecl>(Template)) {
3391 // Find the canonical type for this type alias template specialization.
3392 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
3393 if (Pattern->isInvalidDecl())
3396 TemplateArgumentList StackTemplateArgs(TemplateArgumentList::OnStack,
3399 // Only substitute for the innermost template argument list.
3400 MultiLevelTemplateArgumentList TemplateArgLists;
3401 TemplateArgLists.addOuterTemplateArguments(&StackTemplateArgs);
3402 unsigned Depth = AliasTemplate->getTemplateParameters()->getDepth();
3403 for (unsigned I = 0; I < Depth; ++I)
3404 TemplateArgLists.addOuterTemplateArguments(None);
3406 LocalInstantiationScope Scope(*this);
3407 InstantiatingTemplate Inst(*this, TemplateLoc, Template);
3408 if (Inst.isInvalid())
3411 CanonType = SubstType(Pattern->getUnderlyingType(),
3412 TemplateArgLists, AliasTemplate->getLocation(),
3413 AliasTemplate->getDeclName());
3414 if (CanonType.isNull()) {
3415 // If this was enable_if and we failed to find the nested type
3416 // within enable_if in a SFINAE context, dig out the specific
3417 // enable_if condition that failed and present that instead.
3418 if (isEnableIfAliasTemplate(AliasTemplate)) {
3419 if (auto DeductionInfo = isSFINAEContext()) {
3420 if (*DeductionInfo &&
3421 (*DeductionInfo)->hasSFINAEDiagnostic() &&
3422 (*DeductionInfo)->peekSFINAEDiagnostic().second.getDiagID() ==
3423 diag::err_typename_nested_not_found_enable_if &&
3424 TemplateArgs[0].getArgument().getKind()
3425 == TemplateArgument::Expression) {
3427 std::string FailedDescription;
3428 std::tie(FailedCond, FailedDescription) =
3429 findFailedBooleanCondition(TemplateArgs[0].getSourceExpression());
3431 // Remove the old SFINAE diagnostic.
3432 PartialDiagnosticAt OldDiag =
3433 {SourceLocation(), PartialDiagnostic::NullDiagnostic()};
3434 (*DeductionInfo)->takeSFINAEDiagnostic(OldDiag);
3436 // Add a new SFINAE diagnostic specifying which condition
3438 (*DeductionInfo)->addSFINAEDiagnostic(
3440 PDiag(diag::err_typename_nested_not_found_requirement)
3441 << FailedDescription
3442 << FailedCond->getSourceRange());
3449 } else if (Name.isDependent() ||
3450 TemplateSpecializationType::anyDependentTemplateArguments(
3451 TemplateArgs, InstantiationDependent)) {
3452 // This class template specialization is a dependent
3453 // type. Therefore, its canonical type is another class template
3454 // specialization type that contains all of the converted
3455 // arguments in canonical form. This ensures that, e.g., A<T> and
3456 // A<T, T> have identical types when A is declared as:
3458 // template<typename T, typename U = T> struct A;
3459 CanonType = Context.getCanonicalTemplateSpecializationType(Name, Converted);
3461 // This might work out to be a current instantiation, in which
3462 // case the canonical type needs to be the InjectedClassNameType.
3464 // TODO: in theory this could be a simple hashtable lookup; most
3465 // changes to CurContext don't change the set of current
3467 if (isa<ClassTemplateDecl>(Template)) {
3468 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
3469 // If we get out to a namespace, we're done.
3470 if (Ctx->isFileContext()) break;
3472 // If this isn't a record, keep looking.
3473 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
3474 if (!Record) continue;
3476 // Look for one of the two cases with InjectedClassNameTypes
3477 // and check whether it's the same template.
3478 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
3479 !Record->getDescribedClassTemplate())
3482 // Fetch the injected class name type and check whether its
3483 // injected type is equal to the type we just built.
3484 QualType ICNT = Context.getTypeDeclType(Record);
3485 QualType Injected = cast<InjectedClassNameType>(ICNT)
3486 ->getInjectedSpecializationType();
3488 if (CanonType != Injected->getCanonicalTypeInternal())
3491 // If so, the canonical type of this TST is the injected
3492 // class name type of the record we just found.
3493 assert(ICNT.isCanonical());
3498 } else if (ClassTemplateDecl *ClassTemplate
3499 = dyn_cast<ClassTemplateDecl>(Template)) {
3500 // Find the class template specialization declaration that
3501 // corresponds to these arguments.
3502 void *InsertPos = nullptr;
3503 ClassTemplateSpecializationDecl *Decl
3504 = ClassTemplate->findSpecialization(Converted, InsertPos);
3506 // This is the first time we have referenced this class template
3507 // specialization. Create the canonical declaration and add it to
3508 // the set of specializations.
3509 Decl = ClassTemplateSpecializationDecl::Create(
3510 Context, ClassTemplate->getTemplatedDecl()->getTagKind(),
3511 ClassTemplate->getDeclContext(),
3512 ClassTemplate->getTemplatedDecl()->getBeginLoc(),
3513 ClassTemplate->getLocation(), ClassTemplate, Converted, nullptr);
3514 ClassTemplate->AddSpecialization(Decl, InsertPos);
3515 if (ClassTemplate->isOutOfLine())
3516 Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
3519 if (Decl->getSpecializationKind() == TSK_Undeclared) {
3520 MultiLevelTemplateArgumentList TemplateArgLists;
3521 TemplateArgLists.addOuterTemplateArguments(Converted);
3522 InstantiateAttrsForDecl(TemplateArgLists, ClassTemplate->getTemplatedDecl(),
3526 // Diagnose uses of this specialization.
3527 (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
3529 CanonType = Context.getTypeDeclType(Decl);
3530 assert(isa<RecordType>(CanonType) &&
3531 "type of non-dependent specialization is not a RecordType");
3532 } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Template)) {
3533 CanonType = checkBuiltinTemplateIdType(*this, BTD, Converted, TemplateLoc,
3537 // Build the fully-sugared type for this class template
3538 // specialization, which refers back to the class template
3539 // specialization we created or found.
3540 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
3543 void Sema::ActOnUndeclaredTypeTemplateName(Scope *S, TemplateTy &ParsedName,
3544 TemplateNameKind &TNK,
3545 SourceLocation NameLoc,
3546 IdentifierInfo *&II) {
3547 assert(TNK == TNK_Undeclared_template && "not an undeclared template name");
3549 TemplateName Name = ParsedName.get();
3550 auto *ATN = Name.getAsAssumedTemplateName();
3551 assert(ATN && "not an assumed template name");
3552 II = ATN->getDeclName().getAsIdentifierInfo();
3554 if (!resolveAssumedTemplateNameAsType(S, Name, NameLoc, /*Diagnose*/false)) {
3555 // Resolved to a type template name.
3556 ParsedName = TemplateTy::make(Name);
3557 TNK = TNK_Type_template;
3561 bool Sema::resolveAssumedTemplateNameAsType(Scope *S, TemplateName &Name,
3562 SourceLocation NameLoc,
3564 // We assumed this undeclared identifier to be an (ADL-only) function
3565 // template name, but it was used in a context where a type was required.
3566 // Try to typo-correct it now.
3567 AssumedTemplateStorage *ATN = Name.getAsAssumedTemplateName();
3568 assert(ATN && "not an assumed template name");
3570 LookupResult R(*this, ATN->getDeclName(), NameLoc, LookupOrdinaryName);
3571 struct CandidateCallback : CorrectionCandidateCallback {
3572 bool ValidateCandidate(const TypoCorrection &TC) override {
3573 return TC.getCorrectionDecl() &&
3574 getAsTypeTemplateDecl(TC.getCorrectionDecl());
3576 std::unique_ptr<CorrectionCandidateCallback> clone() override {
3577 return std::make_unique<CandidateCallback>(*this);
3581 TypoCorrection Corrected =
3582 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, nullptr,
3583 FilterCCC, CTK_ErrorRecovery);
3584 if (Corrected && Corrected.getFoundDecl()) {
3585 diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest)
3586 << ATN->getDeclName());
3587 Name = TemplateName(Corrected.getCorrectionDeclAs<TemplateDecl>());
3592 Diag(R.getNameLoc(), diag::err_no_template) << R.getLookupName();
3596 TypeResult Sema::ActOnTemplateIdType(
3597 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
3598 TemplateTy TemplateD, IdentifierInfo *TemplateII,
3599 SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
3600 ASTTemplateArgsPtr TemplateArgsIn, SourceLocation RAngleLoc,
3601 bool IsCtorOrDtorName, bool IsClassName) {
3605 if (!IsCtorOrDtorName && !IsClassName && SS.isSet()) {
3606 DeclContext *LookupCtx = computeDeclContext(SS, /*EnteringContext*/false);
3608 // C++ [temp.res]p3:
3609 // A qualified-id that refers to a type and in which the
3610 // nested-name-specifier depends on a template-parameter (14.6.2)
3611 // shall be prefixed by the keyword typename to indicate that the
3612 // qualified-id denotes a type, forming an
3613 // elaborated-type-specifier (7.1.5.3).
3614 if (!LookupCtx && isDependentScopeSpecifier(SS)) {
3615 Diag(SS.getBeginLoc(), diag::err_typename_missing_template)
3616 << SS.getScopeRep() << TemplateII->getName();
3617 // Recover as if 'typename' were specified.
3618 // FIXME: This is not quite correct recovery as we don't transform SS
3619 // into the corresponding dependent form (and we don't diagnose missing
3620 // 'template' keywords within SS as a result).
3621 return ActOnTypenameType(nullptr, SourceLocation(), SS, TemplateKWLoc,
3622 TemplateD, TemplateII, TemplateIILoc, LAngleLoc,
3623 TemplateArgsIn, RAngleLoc);
3626 // Per C++ [class.qual]p2, if the template-id was an injected-class-name,
3627 // it's not actually allowed to be used as a type in most cases. Because
3628 // we annotate it before we know whether it's valid, we have to check for
3630 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
3631 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
3633 TemplateKWLoc.isInvalid()
3634 ? diag::err_out_of_line_qualified_id_type_names_constructor
3635 : diag::ext_out_of_line_qualified_id_type_names_constructor)
3636 << TemplateII << 0 /*injected-class-name used as template name*/
3637 << 1 /*if any keyword was present, it was 'template'*/;
3641 TemplateName Template = TemplateD.get();
3642 if (Template.getAsAssumedTemplateName() &&
3643 resolveAssumedTemplateNameAsType(S, Template, TemplateIILoc))
3646 // Translate the parser's template argument list in our AST format.
3647 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
3648 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
3650 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
3652 = Context.getDependentTemplateSpecializationType(ETK_None,
3653 DTN->getQualifier(),
3654 DTN->getIdentifier(),
3656 // Build type-source information.
3658 DependentTemplateSpecializationTypeLoc SpecTL
3659 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
3660 SpecTL.setElaboratedKeywordLoc(SourceLocation());
3661 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
3662 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3663 SpecTL.setTemplateNameLoc(TemplateIILoc);
3664 SpecTL.setLAngleLoc(LAngleLoc);
3665 SpecTL.setRAngleLoc(RAngleLoc);
3666 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
3667 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
3668 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
3671 QualType Result = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
3672 if (Result.isNull())
3675 // Build type-source information.
3677 TemplateSpecializationTypeLoc SpecTL
3678 = TLB.push<TemplateSpecializationTypeLoc>(Result);
3679 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3680 SpecTL.setTemplateNameLoc(TemplateIILoc);
3681 SpecTL.setLAngleLoc(LAngleLoc);
3682 SpecTL.setRAngleLoc(RAngleLoc);
3683 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
3684 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
3686 // NOTE: avoid constructing an ElaboratedTypeLoc if this is a
3687 // constructor or destructor name (in such a case, the scope specifier
3688 // will be attached to the enclosing Decl or Expr node).
3689 if (SS.isNotEmpty() && !IsCtorOrDtorName) {
3690 // Create an elaborated-type-specifier containing the nested-name-specifier.
3691 Result = Context.getElaboratedType(ETK_None, SS.getScopeRep(), Result);
3692 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
3693 ElabTL.setElaboratedKeywordLoc(SourceLocation());
3694 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
3697 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
3700 TypeResult Sema::ActOnTagTemplateIdType(TagUseKind TUK,
3701 TypeSpecifierType TagSpec,
3702 SourceLocation TagLoc,
3704 SourceLocation TemplateKWLoc,
3705 TemplateTy TemplateD,
3706 SourceLocation TemplateLoc,
3707 SourceLocation LAngleLoc,
3708 ASTTemplateArgsPtr TemplateArgsIn,
3709 SourceLocation RAngleLoc) {
3710 TemplateName Template = TemplateD.get();
3712 // Translate the parser's template argument list in our AST format.
3713 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
3714 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
3716 // Determine the tag kind
3717 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
3718 ElaboratedTypeKeyword Keyword
3719 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
3721 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
3722 QualType T = Context.getDependentTemplateSpecializationType(Keyword,
3723 DTN->getQualifier(),
3724 DTN->getIdentifier(),
3727 // Build type-source information.
3729 DependentTemplateSpecializationTypeLoc SpecTL
3730 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
3731 SpecTL.setElaboratedKeywordLoc(TagLoc);
3732 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
3733 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3734 SpecTL.setTemplateNameLoc(TemplateLoc);
3735 SpecTL.setLAngleLoc(LAngleLoc);
3736 SpecTL.setRAngleLoc(RAngleLoc);
3737 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
3738 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
3739 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
3742 if (TypeAliasTemplateDecl *TAT =
3743 dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) {
3744 // C++0x [dcl.type.elab]p2:
3745 // If the identifier resolves to a typedef-name or the simple-template-id
3746 // resolves to an alias template specialization, the
3747 // elaborated-type-specifier is ill-formed.
3748 Diag(TemplateLoc, diag::err_tag_reference_non_tag)
3749 << TAT << NTK_TypeAliasTemplate << TagKind;
3750 Diag(TAT->getLocation(), diag::note_declared_at);
3753 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
3754 if (Result.isNull())
3755 return TypeResult(true);
3757 // Check the tag kind
3758 if (const RecordType *RT = Result->getAs<RecordType>()) {
3759 RecordDecl *D = RT->getDecl();
3761 IdentifierInfo *Id = D->getIdentifier();
3762 assert(Id && "templated class must have an identifier");
3764 if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TUK_Definition,
3766 Diag(TagLoc, diag::err_use_with_wrong_tag)
3768 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
3769 Diag(D->getLocation(), diag::note_previous_use);
3773 // Provide source-location information for the template specialization.
3775 TemplateSpecializationTypeLoc SpecTL
3776 = TLB.push<TemplateSpecializationTypeLoc>(Result);
3777 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3778 SpecTL.setTemplateNameLoc(TemplateLoc);
3779 SpecTL.setLAngleLoc(LAngleLoc);
3780 SpecTL.setRAngleLoc(RAngleLoc);
3781 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
3782 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
3784 // Construct an elaborated type containing the nested-name-specifier (if any)
3786 Result = Context.getElaboratedType(Keyword, SS.getScopeRep(), Result);
3787 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
3788 ElabTL.setElaboratedKeywordLoc(TagLoc);
3789 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
3790 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
3793 static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
3794 NamedDecl *PrevDecl,
3796 bool IsPartialSpecialization);
3798 static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D);
3800 static bool isTemplateArgumentTemplateParameter(
3801 const TemplateArgument &Arg, unsigned Depth, unsigned Index) {
3802 switch (Arg.getKind()) {
3803 case TemplateArgument::Null:
3804 case TemplateArgument::NullPtr:
3805 case TemplateArgument::Integral:
3806 case TemplateArgument::Declaration:
3807 case TemplateArgument::Pack:
3808 case TemplateArgument::TemplateExpansion:
3811 case TemplateArgument::Type: {
3812 QualType Type = Arg.getAsType();
3813 const TemplateTypeParmType *TPT =
3814 Arg.getAsType()->getAs<TemplateTypeParmType>();
3815 return TPT && !Type.hasQualifiers() &&
3816 TPT->getDepth() == Depth && TPT->getIndex() == Index;
3819 case TemplateArgument::Expression: {
3820 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
3821 if (!DRE || !DRE->getDecl())
3823 const NonTypeTemplateParmDecl *NTTP =
3824 dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
3825 return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
3828 case TemplateArgument::Template:
3829 const TemplateTemplateParmDecl *TTP =
3830 dyn_cast_or_null<TemplateTemplateParmDecl>(
3831 Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl());
3832 return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
3834 llvm_unreachable("unexpected kind of template argument");
3837 static bool isSameAsPrimaryTemplate(TemplateParameterList *Params,
3838 ArrayRef<TemplateArgument> Args) {
3839 if (Params->size() != Args.size())
3842 unsigned Depth = Params->getDepth();
3844 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
3845 TemplateArgument Arg = Args[I];
3847 // If the parameter is a pack expansion, the argument must be a pack
3848 // whose only element is a pack expansion.
3849 if (Params->getParam(I)->isParameterPack()) {
3850 if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
3851 !Arg.pack_begin()->isPackExpansion())
3853 Arg = Arg.pack_begin()->getPackExpansionPattern();
3856 if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))
3863 template<typename PartialSpecDecl>
3864 static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial) {
3865 if (Partial->getDeclContext()->isDependentContext())
3868 // FIXME: Get the TDK from deduction in order to provide better diagnostics
3869 // for non-substitution-failure issues?
3870 TemplateDeductionInfo Info(Partial->getLocation());
3871 if (S.isMoreSpecializedThanPrimary(Partial, Info))
3874 auto *Template = Partial->getSpecializedTemplate();
3875 S.Diag(Partial->getLocation(),
3876 diag::ext_partial_spec_not_more_specialized_than_primary)
3877 << isa<VarTemplateDecl>(Template);
3879 if (Info.hasSFINAEDiagnostic()) {
3880 PartialDiagnosticAt Diag = {SourceLocation(),
3881 PartialDiagnostic::NullDiagnostic()};
3882 Info.takeSFINAEDiagnostic(Diag);
3883 SmallString<128> SFINAEArgString;
3884 Diag.second.EmitToString(S.getDiagnostics(), SFINAEArgString);
3886 diag::note_partial_spec_not_more_specialized_than_primary)
3890 S.Diag(Template->getLocation(), diag::note_template_decl_here);
3891 SmallVector<const Expr *, 3> PartialAC, TemplateAC;
3892 Template->getAssociatedConstraints(TemplateAC);
3893 Partial->getAssociatedConstraints(PartialAC);
3894 S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(Partial, PartialAC, Template,
3899 noteNonDeducibleParameters(Sema &S, TemplateParameterList *TemplateParams,
3900 const llvm::SmallBitVector &DeducibleParams) {
3901 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
3902 if (!DeducibleParams[I]) {
3903 NamedDecl *Param = TemplateParams->getParam(I);
3904 if (Param->getDeclName())
3905 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
3906 << Param->getDeclName();
3908 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
3915 template<typename PartialSpecDecl>
3916 static void checkTemplatePartialSpecialization(Sema &S,
3917 PartialSpecDecl *Partial) {
3918 // C++1z [temp.class.spec]p8: (DR1495)
3919 // - The specialization shall be more specialized than the primary
3920 // template (14.5.5.2).
3921 checkMoreSpecializedThanPrimary(S, Partial);
3923 // C++ [temp.class.spec]p8: (DR1315)
3924 // - Each template-parameter shall appear at least once in the
3925 // template-id outside a non-deduced context.
3926 // C++1z [temp.class.spec.match]p3 (P0127R2)
3927 // If the template arguments of a partial specialization cannot be
3928 // deduced because of the structure of its template-parameter-list
3929 // and the template-id, the program is ill-formed.
3930 auto *TemplateParams = Partial->getTemplateParameters();
3931 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
3932 S.MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
3933 TemplateParams->getDepth(), DeducibleParams);
3935 if (!DeducibleParams.all()) {
3936 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
3937 S.Diag(Partial->getLocation(), diag::ext_partial_specs_not_deducible)
3938 << isa<VarTemplatePartialSpecializationDecl>(Partial)
3939 << (NumNonDeducible > 1)
3940 << SourceRange(Partial->getLocation(),
3941 Partial->getTemplateArgsAsWritten()->RAngleLoc);
3942 noteNonDeducibleParameters(S, TemplateParams, DeducibleParams);
3946 void Sema::CheckTemplatePartialSpecialization(
3947 ClassTemplatePartialSpecializationDecl *Partial) {
3948 checkTemplatePartialSpecialization(*this, Partial);
3951 void Sema::CheckTemplatePartialSpecialization(
3952 VarTemplatePartialSpecializationDecl *Partial) {
3953 checkTemplatePartialSpecialization(*this, Partial);
3956 void Sema::CheckDeductionGuideTemplate(FunctionTemplateDecl *TD) {
3957 // C++1z [temp.param]p11:
3958 // A template parameter of a deduction guide template that does not have a
3959 // default-argument shall be deducible from the parameter-type-list of the
3960 // deduction guide template.
3961 auto *TemplateParams = TD->getTemplateParameters();
3962 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
3963 MarkDeducedTemplateParameters(TD, DeducibleParams);
3964 for (unsigned I = 0; I != TemplateParams->size(); ++I) {
3965 // A parameter pack is deducible (to an empty pack).
3966 auto *Param = TemplateParams->getParam(I);
3967 if (Param->isParameterPack() || hasVisibleDefaultArgument(Param))
3968 DeducibleParams[I] = true;
3971 if (!DeducibleParams.all()) {
3972 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
3973 Diag(TD->getLocation(), diag::err_deduction_guide_template_not_deducible)
3974 << (NumNonDeducible > 1);
3975 noteNonDeducibleParameters(*this, TemplateParams, DeducibleParams);
3979 DeclResult Sema::ActOnVarTemplateSpecialization(
3980 Scope *S, Declarator &D, TypeSourceInfo *DI, SourceLocation TemplateKWLoc,
3981 TemplateParameterList *TemplateParams, StorageClass SC,
3982 bool IsPartialSpecialization) {
3983 // D must be variable template id.
3984 assert(D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId &&
3985 "Variable template specialization is declared with a template it.");
3987 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
3988 TemplateArgumentListInfo TemplateArgs =
3989 makeTemplateArgumentListInfo(*this, *TemplateId);
3990 SourceLocation TemplateNameLoc = D.getIdentifierLoc();
3991 SourceLocation LAngleLoc = TemplateId->LAngleLoc;
3992 SourceLocation RAngleLoc = TemplateId->RAngleLoc;
3994 TemplateName Name = TemplateId->Template.get();
3996 // The template-id must name a variable template.
3997 VarTemplateDecl *VarTemplate =
3998 dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
4000 NamedDecl *FnTemplate;
4001 if (auto *OTS = Name.getAsOverloadedTemplate())
4002 FnTemplate = *OTS->begin();
4004 FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
4006 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
4007 << FnTemplate->getDeclName();
4008 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
4009 << IsPartialSpecialization;
4012 // Check for unexpanded parameter packs in any of the template arguments.
4013 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
4014 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
4015 UPPC_PartialSpecialization))
4018 // Check that the template argument list is well-formed for this
4020 SmallVector<TemplateArgument, 4> Converted;
4021 if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
4023 /*UpdateArgsWithConversion=*/true))
4026 // Find the variable template (partial) specialization declaration that
4027 // corresponds to these arguments.
4028 if (IsPartialSpecialization) {
4029 if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, VarTemplate,
4030 TemplateArgs.size(), Converted))
4033 // FIXME: Move these checks to CheckTemplatePartialSpecializationArgs so we
4034 // also do them during instantiation.
4035 bool InstantiationDependent;
4036 if (!Name.isDependent() &&
4037 !TemplateSpecializationType::anyDependentTemplateArguments(
4038 TemplateArgs.arguments(),
4039 InstantiationDependent)) {
4040 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
4041 << VarTemplate->getDeclName();
4042 IsPartialSpecialization = false;
4045 if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(),
4047 (!Context.getLangOpts().ConceptsTS ||
4048 !TemplateParams->hasAssociatedConstraints())) {
4049 // C++ [temp.class.spec]p9b3:
4051 // -- The argument list of the specialization shall not be identical
4052 // to the implicit argument list of the primary template.
4053 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
4054 << /*variable template*/ 1
4055 << /*is definition*/(SC != SC_Extern && !CurContext->isRecord())
4056 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
4057 // FIXME: Recover from this by treating the declaration as a redeclaration
4058 // of the primary template.
4063 void *InsertPos = nullptr;
4064 VarTemplateSpecializationDecl *PrevDecl = nullptr;
4066 if (IsPartialSpecialization)
4067 PrevDecl = VarTemplate->findPartialSpecialization(Converted, TemplateParams,
4070 PrevDecl = VarTemplate->findSpecialization(Converted, InsertPos);
4072 VarTemplateSpecializationDecl *Specialization = nullptr;
4074 // Check whether we can declare a variable template specialization in
4075 // the current scope.
4076 if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
4078 IsPartialSpecialization))
4081 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
4082 // Since the only prior variable template specialization with these
4083 // arguments was referenced but not declared, reuse that
4084 // declaration node as our own, updating its source location and
4085 // the list of outer template parameters to reflect our new declaration.
4086 Specialization = PrevDecl;
4087 Specialization->setLocation(TemplateNameLoc);
4089 } else if (IsPartialSpecialization) {
4090 // Create a new class template partial specialization declaration node.
4091 VarTemplatePartialSpecializationDecl *PrevPartial =
4092 cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
4093 VarTemplatePartialSpecializationDecl *Partial =
4094 VarTemplatePartialSpecializationDecl::Create(
4095 Context, VarTemplate->getDeclContext(), TemplateKWLoc,
4096 TemplateNameLoc, TemplateParams, VarTemplate, DI->getType(), DI, SC,
4097 Converted, TemplateArgs);
4100 VarTemplate->AddPartialSpecialization(Partial, InsertPos);
4101 Specialization = Partial;
4103 // If we are providing an explicit specialization of a member variable
4104 // template specialization, make a note of that.
4105 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
4106 PrevPartial->setMemberSpecialization();
4108 CheckTemplatePartialSpecialization(Partial);
4110 // Create a new class template specialization declaration node for
4111 // this explicit specialization or friend declaration.
4112 Specialization = VarTemplateSpecializationDecl::Create(
4113 Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
4114 VarTemplate, DI->getType(), DI, SC, Converted);
4115 Specialization->setTemplateArgsInfo(TemplateArgs);
4118 VarTemplate->AddSpecialization(Specialization, InsertPos);
4121 // C++ [temp.expl.spec]p6:
4122 // If a template, a member template or the member of a class template is
4123 // explicitly specialized then that specialization shall be declared
4124 // before the first use of that specialization that would cause an implicit
4125 // instantiation to take place, in every translation unit in which such a
4126 // use occurs; no diagnostic is required.
4127 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
4129 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
4130 // Is there any previous explicit specialization declaration?
4131 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
4138 SourceRange Range(TemplateNameLoc, RAngleLoc);
4139 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
4142 Diag(PrevDecl->getPointOfInstantiation(),
4143 diag::note_instantiation_required_here)
4144 << (PrevDecl->getTemplateSpecializationKind() !=
4145 TSK_ImplicitInstantiation);
4150 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
4151 Specialization->setLexicalDeclContext(CurContext);
4153 // Add the specialization into its lexical context, so that it can
4154 // be seen when iterating through the list of declarations in that
4155 // context. However, specializations are not found by name lookup.
4156 CurContext->addDecl(Specialization);
4158 // Note that this is an explicit specialization.
4159 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
4162 // Check that this isn't a redefinition of this specialization,
4163 // merging with previous declarations.
4164 LookupResult PrevSpec(*this, GetNameForDeclarator(D), LookupOrdinaryName,
4165 forRedeclarationInCurContext());
4166 PrevSpec.addDecl(PrevDecl);
4167 D.setRedeclaration(CheckVariableDeclaration(Specialization, PrevSpec));
4168 } else if (Specialization->isStaticDataMember() &&
4169 Specialization->isOutOfLine()) {
4170 Specialization->setAccess(VarTemplate->getAccess());
4173 return Specialization;
4177 /// A partial specialization whose template arguments have matched
4178 /// a given template-id.
4179 struct PartialSpecMatchResult {
4180 VarTemplatePartialSpecializationDecl *Partial;
4181 TemplateArgumentList *Args;
4183 } // end anonymous namespace
4186 Sema::CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc,
4187 SourceLocation TemplateNameLoc,
4188 const TemplateArgumentListInfo &TemplateArgs) {
4189 assert(Template && "A variable template id without template?");
4191 // Check that the template argument list is well-formed for this template.
4192 SmallVector<TemplateArgument, 4> Converted;
4193 if (CheckTemplateArgumentList(
4194 Template, TemplateNameLoc,
4195 const_cast<TemplateArgumentListInfo &>(TemplateArgs), false,
4196 Converted, /*UpdateArgsWithConversion=*/true))
4199 // Find the variable template specialization declaration that
4200 // corresponds to these arguments.
4201 void *InsertPos = nullptr;
4202 if (VarTemplateSpecializationDecl *Spec = Template->findSpecialization(
4203 Converted, InsertPos)) {
4204 checkSpecializationVisibility(TemplateNameLoc, Spec);
4205 // If we already have a variable template specialization, return it.
4209 // This is the first time we have referenced this variable template
4210 // specialization. Create the canonical declaration and add it to
4211 // the set of specializations, based on the closest partial specialization
4212 // that it represents. That is,
4213 VarDecl *InstantiationPattern = Template->getTemplatedDecl();
4214 TemplateArgumentList TemplateArgList(TemplateArgumentList::OnStack,
4216 TemplateArgumentList *InstantiationArgs = &TemplateArgList;
4217 bool AmbiguousPartialSpec = false;
4218 typedef PartialSpecMatchResult MatchResult;
4219 SmallVector<MatchResult, 4> Matched;
4220 SourceLocation PointOfInstantiation = TemplateNameLoc;
4221 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation,
4222 /*ForTakingAddress=*/false);
4224 // 1. Attempt to find the closest partial specialization that this
4225 // specializes, if any.
4226 // If any of the template arguments is dependent, then this is probably
4227 // a placeholder for an incomplete declarative context; which must be
4228 // complete by instantiation time. Thus, do not search through the partial
4229 // specializations yet.
4230 // TODO: Unify with InstantiateClassTemplateSpecialization()?
4231 // Perhaps better after unification of DeduceTemplateArguments() and
4232 // getMoreSpecializedPartialSpecialization().
4233 bool InstantiationDependent = false;
4234 if (!TemplateSpecializationType::anyDependentTemplateArguments(
4235 TemplateArgs, InstantiationDependent)) {
4237 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
4238 Template->getPartialSpecializations(PartialSpecs);
4240 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
4241 VarTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
4242 TemplateDeductionInfo Info(FailedCandidates.getLocation());
4244 if (TemplateDeductionResult Result =
4245 DeduceTemplateArguments(Partial, TemplateArgList, Info)) {
4246 // Store the failed-deduction information for use in diagnostics, later.
4247 // TODO: Actually use the failed-deduction info?
4248 FailedCandidates.addCandidate().set(
4249 DeclAccessPair::make(Template, AS_public), Partial,
4250 MakeDeductionFailureInfo(Context, Result, Info));
4253 Matched.push_back(PartialSpecMatchResult());
4254 Matched.back().Partial = Partial;
4255 Matched.back().Args = Info.take();
4259 if (Matched.size() >= 1) {
4260 SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
4261 if (Matched.size() == 1) {
4262 // -- If exactly one matching specialization is found, the
4263 // instantiation is generated from that specialization.
4264 // We don't need to do anything for this.
4266 // -- If more than one matching specialization is found, the
4267 // partial order rules (14.5.4.2) are used to determine
4268 // whether one of the specializations is more specialized
4269 // than the others. If none of the specializations is more
4270 // specialized than all of the other matching
4271 // specializations, then the use of the variable template is
4272 // ambiguous and the program is ill-formed.
4273 for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
4274 PEnd = Matched.end();
4276 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
4277 PointOfInstantiation) ==
4282 // Determine if the best partial specialization is more specialized than
4284 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
4285 PEnd = Matched.end();
4287 if (P != Best && getMoreSpecializedPartialSpecialization(
4288 P->Partial, Best->Partial,
4289 PointOfInstantiation) != Best->Partial) {
4290 AmbiguousPartialSpec = true;
4296 // Instantiate using the best variable template partial specialization.
4297 InstantiationPattern = Best->Partial;
4298 InstantiationArgs = Best->Args;
4300 // -- If no match is found, the instantiation is generated
4301 // from the primary template.
4302 // InstantiationPattern = Template->getTemplatedDecl();
4306 // 2. Create the canonical declaration.
4307 // Note that we do not instantiate a definition until we see an odr-use
4308 // in DoMarkVarDeclReferenced().
4309 // FIXME: LateAttrs et al.?
4310 VarTemplateSpecializationDecl *Decl = BuildVarTemplateInstantiation(
4311 Template, InstantiationPattern, *InstantiationArgs, TemplateArgs,
4312 Converted, TemplateNameLoc, InsertPos /*, LateAttrs, StartingScope*/);
4316 if (AmbiguousPartialSpec) {
4317 // Partial ordering did not produce a clear winner. Complain.
4318 Decl->setInvalidDecl();
4319 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
4322 // Print the matching partial specializations.
4323 for (MatchResult P : Matched)
4324 Diag(P.Partial->getLocation(), diag::note_partial_spec_match)
4325 << getTemplateArgumentBindingsText(P.Partial->getTemplateParameters(),
4330 if (VarTemplatePartialSpecializationDecl *D =
4331 dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
4332 Decl->setInstantiationOf(D, InstantiationArgs);
4334 checkSpecializationVisibility(TemplateNameLoc, Decl);
4336 assert(Decl && "No variable template specialization?");
4341 Sema::CheckVarTemplateId(const CXXScopeSpec &SS,
4342 const DeclarationNameInfo &NameInfo,
4343 VarTemplateDecl *Template, SourceLocation TemplateLoc,
4344 const TemplateArgumentListInfo *TemplateArgs) {
4346 DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
4348 if (Decl.isInvalid())
4351 VarDecl *Var = cast<VarDecl>(Decl.get());
4352 if (!Var->getTemplateSpecializationKind())
4353 Var->setTemplateSpecializationKind(TSK_ImplicitInstantiation,
4356 // Build an ordinary singleton decl ref.
4357 return BuildDeclarationNameExpr(SS, NameInfo, Var,
4358 /*FoundD=*/nullptr, TemplateArgs);
4361 void Sema::diagnoseMissingTemplateArguments(TemplateName Name,
4362 SourceLocation Loc) {
4363 Diag(Loc, diag::err_template_missing_args)
4364 << (int)getTemplateNameKindForDiagnostics(Name) << Name;
4365 if (TemplateDecl *TD = Name.getAsTemplateDecl()) {
4366 Diag(TD->getLocation(), diag::note_template_decl_here)
4367 << TD->getTemplateParameters()->getSourceRange();
4372 Sema::CheckConceptTemplateId(const CXXScopeSpec &SS,
4373 SourceLocation TemplateKWLoc,
4374 const DeclarationNameInfo &ConceptNameInfo,
4375 NamedDecl *FoundDecl,
4376 ConceptDecl *NamedConcept,
4377 const TemplateArgumentListInfo *TemplateArgs) {
4378 assert(NamedConcept && "A concept template id without a template?");
4380 llvm::SmallVector<TemplateArgument, 4> Converted;
4381 if (CheckTemplateArgumentList(NamedConcept, ConceptNameInfo.getLoc(),
4382 const_cast<TemplateArgumentListInfo&>(*TemplateArgs),
4383 /*PartialTemplateArgs=*/false, Converted,
4384 /*UpdateArgsWithConversion=*/false))
4387 ConstraintSatisfaction Satisfaction;
4388 bool AreArgsDependent = false;
4389 for (TemplateArgument &Arg : Converted) {
4390 if (Arg.isDependent()) {
4391 AreArgsDependent = true;
4395 if (!AreArgsDependent &&
4396 CheckConstraintSatisfaction(NamedConcept,
4397 {NamedConcept->getConstraintExpr()},
4399 SourceRange(SS.isSet() ? SS.getBeginLoc() :
4400 ConceptNameInfo.getLoc(),
4401 TemplateArgs->getRAngleLoc()),
4405 return ConceptSpecializationExpr::Create(Context,
4406 SS.isSet() ? SS.getWithLocInContext(Context) : NestedNameSpecifierLoc{},
4407 TemplateKWLoc, ConceptNameInfo, FoundDecl, NamedConcept,
4408 ASTTemplateArgumentListInfo::Create(Context, *TemplateArgs), Converted,
4409 AreArgsDependent ? nullptr : &Satisfaction);
4412 ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
4413 SourceLocation TemplateKWLoc,
4416 const TemplateArgumentListInfo *TemplateArgs) {
4417 // FIXME: Can we do any checking at this point? I guess we could check the
4418 // template arguments that we have against the template name, if the template
4419 // name refers to a single template. That's not a terribly common case,
4421 // foo<int> could identify a single function unambiguously
4422 // This approach does NOT work, since f<int>(1);
4423 // gets resolved prior to resorting to overload resolution
4424 // i.e., template<class T> void f(double);
4425 // vs template<class T, class U> void f(U);
4427 // These should be filtered out by our callers.
4428 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
4430 // Non-function templates require a template argument list.
4431 if (auto *TD = R.getAsSingle<TemplateDecl>()) {
4432 if (!TemplateArgs && !isa<FunctionTemplateDecl>(TD)) {
4433 diagnoseMissingTemplateArguments(TemplateName(TD), R.getNameLoc());
4438 auto AnyDependentArguments = [&]() -> bool {
4439 bool InstantiationDependent;
4440 return TemplateArgs &&
4441 TemplateSpecializationType::anyDependentTemplateArguments(
4442 *TemplateArgs, InstantiationDependent);
4445 // In C++1y, check variable template ids.
4446 if (R.getAsSingle<VarTemplateDecl>() && !AnyDependentArguments()) {
4447 return CheckVarTemplateId(SS, R.getLookupNameInfo(),
4448 R.getAsSingle<VarTemplateDecl>(),
4449 TemplateKWLoc, TemplateArgs);
4452 if (R.getAsSingle<ConceptDecl>()) {
4453 return CheckConceptTemplateId(SS, TemplateKWLoc, R.getLookupNameInfo(),
4455 R.getAsSingle<ConceptDecl>(), TemplateArgs);
4458 // We don't want lookup warnings at this point.
4459 R.suppressDiagnostics();
4461 UnresolvedLookupExpr *ULE
4462 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
4463 SS.getWithLocInContext(Context),
4465 R.getLookupNameInfo(),
4466 RequiresADL, TemplateArgs,
4467 R.begin(), R.end());
4472 // We actually only call this from template instantiation.
4474 Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
4475 SourceLocation TemplateKWLoc,
4476 const DeclarationNameInfo &NameInfo,
4477 const TemplateArgumentListInfo *TemplateArgs) {
4479 assert(TemplateArgs || TemplateKWLoc.isValid());
4481 if (!(DC = computeDeclContext(SS, false)) ||
4482 DC->isDependentContext() ||
4483 RequireCompleteDeclContext(SS, DC))
4484 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
4486 bool MemberOfUnknownSpecialization;
4487 LookupResult R(*this, NameInfo, LookupOrdinaryName);
4488 if (LookupTemplateName(R, (Scope *)nullptr, SS, QualType(),
4489 /*Entering*/false, MemberOfUnknownSpecialization,
4493 if (R.isAmbiguous())
4497 Diag(NameInfo.getLoc(), diag::err_no_member)
4498 << NameInfo.getName() << DC << SS.getRange();
4502 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
4503 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
4505 << NameInfo.getName().getAsString() << SS.getRange();
4506 Diag(Temp->getLocation(), diag::note_referenced_class_template);
4510 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL*/ false, TemplateArgs);
4513 /// Form a dependent template name.
4515 /// This action forms a dependent template name given the template
4516 /// name and its (presumably dependent) scope specifier. For
4517 /// example, given "MetaFun::template apply", the scope specifier \p
4518 /// SS will be "MetaFun::", \p TemplateKWLoc contains the location
4519 /// of the "template" keyword, and "apply" is the \p Name.
4520 TemplateNameKind Sema::ActOnDependentTemplateName(Scope *S,
4522 SourceLocation TemplateKWLoc,
4523 const UnqualifiedId &Name,
4524 ParsedType ObjectType,
4525 bool EnteringContext,
4527 bool AllowInjectedClassName) {
4528 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
4530 getLangOpts().CPlusPlus11 ?
4531 diag::warn_cxx98_compat_template_outside_of_template :
4532 diag::ext_template_outside_of_template)
4533 << FixItHint::CreateRemoval(TemplateKWLoc);
4535 DeclContext *LookupCtx = nullptr;
4537 LookupCtx = computeDeclContext(SS, EnteringContext);
4538 if (!LookupCtx && ObjectType)
4539 LookupCtx = computeDeclContext(ObjectType.get());
4541 // C++0x [temp.names]p5:
4542 // If a name prefixed by the keyword template is not the name of
4543 // a template, the program is ill-formed. [Note: the keyword
4544 // template may not be applied to non-template members of class
4545 // templates. -end note ] [ Note: as is the case with the
4546 // typename prefix, the template prefix is allowed in cases
4547 // where it is not strictly necessary; i.e., when the
4548 // nested-name-specifier or the expression on the left of the ->
4549 // or . is not dependent on a template-parameter, or the use
4550 // does not appear in the scope of a template. -end note]
4552 // Note: C++03 was more strict here, because it banned the use of
4553 // the "template" keyword prior to a template-name that was not a
4554 // dependent name. C++ DR468 relaxed this requirement (the
4555 // "template" keyword is now permitted). We follow the C++0x
4556 // rules, even in C++03 mode with a warning, retroactively applying the DR.
4557 bool MemberOfUnknownSpecialization;
4558 TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
4559 ObjectType, EnteringContext, Result,
4560 MemberOfUnknownSpecialization);
4561 if (TNK == TNK_Non_template && MemberOfUnknownSpecialization) {
4562 // This is a dependent template. Handle it below.
4563 } else if (TNK == TNK_Non_template) {
4564 // Do the lookup again to determine if this is a "nothing found" case or
4565 // a "not a template" case. FIXME: Refactor isTemplateName so we don't
4567 DeclarationNameInfo DNI = GetNameFromUnqualifiedId(Name);
4568 LookupResult R(*this, DNI.getName(), Name.getBeginLoc(),
4569 LookupOrdinaryName);
4571 if (!LookupTemplateName(R, S, SS, ObjectType.get(), EnteringContext,
4572 MOUS, TemplateKWLoc) && !R.isAmbiguous())
4573 Diag(Name.getBeginLoc(), diag::err_no_member)
4574 << DNI.getName() << LookupCtx << SS.getRange();
4575 return TNK_Non_template;
4577 // We found something; return it.
4578 auto *LookupRD = dyn_cast<CXXRecordDecl>(LookupCtx);
4579 if (!AllowInjectedClassName && SS.isSet() && LookupRD &&
4580 Name.getKind() == UnqualifiedIdKind::IK_Identifier &&
4581 Name.Identifier && LookupRD->getIdentifier() == Name.Identifier) {
4582 // C++14 [class.qual]p2:
4583 // In a lookup in which function names are not ignored and the
4584 // nested-name-specifier nominates a class C, if the name specified
4585 // [...] is the injected-class-name of C, [...] the name is instead
4586 // considered to name the constructor
4588 // We don't get here if naming the constructor would be valid, so we
4589 // just reject immediately and recover by treating the
4590 // injected-class-name as naming the template.
4591 Diag(Name.getBeginLoc(),
4592 diag::ext_out_of_line_qualified_id_type_names_constructor)
4594 << 0 /*injected-class-name used as template name*/
4595 << 1 /*'template' keyword was used*/;
4601 NestedNameSpecifier *Qualifier = SS.getScopeRep();
4603 switch (Name.getKind()) {
4604 case UnqualifiedIdKind::IK_Identifier:
4605 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
4607 return TNK_Dependent_template_name;
4609 case UnqualifiedIdKind::IK_OperatorFunctionId:
4610 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
4611 Name.OperatorFunctionId.Operator));
4612 return TNK_Function_template;
4614 case UnqualifiedIdKind::IK_LiteralOperatorId:
4615 llvm_unreachable("literal operator id cannot have a dependent scope");
4621 Diag(Name.getBeginLoc(), diag::err_template_kw_refers_to_non_template)
4622 << GetNameFromUnqualifiedId(Name).getName() << Name.getSourceRange()
4624 return TNK_Non_template;
4627 bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
4628 TemplateArgumentLoc &AL,
4629 SmallVectorImpl<TemplateArgument> &Converted) {
4630 const TemplateArgument &Arg = AL.getArgument();
4632 TypeSourceInfo *TSI = nullptr;
4634 // Check template type parameter.
4635 switch(Arg.getKind()) {
4636 case TemplateArgument::Type:
4637 // C++ [temp.arg.type]p1:
4638 // A template-argument for a template-parameter which is a
4639 // type shall be a type-id.
4640 ArgType = Arg.getAsType();
4641 TSI = AL.getTypeSourceInfo();
4643 case TemplateArgument::Template:
4644 case TemplateArgument::TemplateExpansion: {
4645 // We have a template type parameter but the template argument
4646 // is a template without any arguments.
4647 SourceRange SR = AL.getSourceRange();
4648 TemplateName Name = Arg.getAsTemplateOrTemplatePattern();
4649 diagnoseMissingTemplateArguments(Name, SR.getEnd());
4652 case TemplateArgument::Expression: {
4653 // We have a template type parameter but the template argument is an
4654 // expression; see if maybe it is missing the "typename" keyword.
4656 DeclarationNameInfo NameInfo;
4658 if (DeclRefExpr *ArgExpr = dyn_cast<DeclRefExpr>(Arg.getAsExpr())) {
4659 SS.Adopt(ArgExpr->getQualifierLoc());
4660 NameInfo = ArgExpr->getNameInfo();
4661 } else if (DependentScopeDeclRefExpr *ArgExpr =
4662 dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
4663 SS.Adopt(ArgExpr->getQualifierLoc());
4664 NameInfo = ArgExpr->getNameInfo();
4665 } else if (CXXDependentScopeMemberExpr *ArgExpr =
4666 dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
4667 if (ArgExpr->isImplicitAccess()) {
4668 SS.Adopt(ArgExpr->getQualifierLoc());
4669 NameInfo = ArgExpr->getMemberNameInfo();
4673 if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
4674 LookupResult Result(*this, NameInfo, LookupOrdinaryName);
4675 LookupParsedName(Result, CurScope, &SS);
4677 if (Result.getAsSingle<TypeDecl>() ||
4678 Result.getResultKind() ==
4679 LookupResult::NotFoundInCurrentInstantiation) {
4680 // Suggest that the user add 'typename' before the NNS.
4681 SourceLocation Loc = AL.getSourceRange().getBegin();
4682 Diag(Loc, getLangOpts().MSVCCompat
4683 ? diag::ext_ms_template_type_arg_missing_typename
4684 : diag::err_template_arg_must_be_type_suggest)
4685 << FixItHint::CreateInsertion(Loc, "typename ");
4686 Diag(Param->getLocation(), diag::note_template_param_here);
4688 // Recover by synthesizing a type using the location information that we
4691 Context.getDependentNameType(ETK_Typename, SS.getScopeRep(), II);
4693 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(ArgType);
4694 TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
4695 TL.setQualifierLoc(SS.getWithLocInContext(Context));
4696 TL.setNameLoc(NameInfo.getLoc());
4697 TSI = TLB.getTypeSourceInfo(Context, ArgType);
4699 // Overwrite our input TemplateArgumentLoc so that we can recover
4701 AL = TemplateArgumentLoc(TemplateArgument(ArgType),
4702 TemplateArgumentLocInfo(TSI));
4711 // We have a template type parameter but the template argument
4713 SourceRange SR = AL.getSourceRange();
4714 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
4715 Diag(Param->getLocation(), diag::note_template_param_here);
4721 if (CheckTemplateArgument(Param, TSI))
4724 // Add the converted template type argument.
4725 ArgType = Context.getCanonicalType(ArgType);
4728 // If an explicitly-specified template argument type is a lifetime type
4729 // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
4730 if (getLangOpts().ObjCAutoRefCount &&
4731 ArgType->isObjCLifetimeType() &&
4732 !ArgType.getObjCLifetime()) {
4734 Qs.setObjCLifetime(Qualifiers::OCL_Strong);
4735 ArgType = Context.getQualifiedType(ArgType, Qs);
4738 Converted.push_back(TemplateArgument(ArgType));
4742 /// Substitute template arguments into the default template argument for
4743 /// the given template type parameter.
4745 /// \param SemaRef the semantic analysis object for which we are performing
4746 /// the substitution.
4748 /// \param Template the template that we are synthesizing template arguments
4751 /// \param TemplateLoc the location of the template name that started the
4752 /// template-id we are checking.
4754 /// \param RAngleLoc the location of the right angle bracket ('>') that
4755 /// terminates the template-id.
4757 /// \param Param the template template parameter whose default we are
4758 /// substituting into.
4760 /// \param Converted the list of template arguments provided for template
4761 /// parameters that precede \p Param in the template parameter list.
4762 /// \returns the substituted template argument, or NULL if an error occurred.
4763 static TypeSourceInfo *
4764 SubstDefaultTemplateArgument(Sema &SemaRef,
4765 TemplateDecl *Template,
4766 SourceLocation TemplateLoc,
4767 SourceLocation RAngleLoc,
4768 TemplateTypeParmDecl *Param,
4769 SmallVectorImpl<TemplateArgument> &Converted) {
4770 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
4772 // If the argument type is dependent, instantiate it now based
4773 // on the previously-computed template arguments.
4774 if (ArgType->getType()->isInstantiationDependentType()) {
4775 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
4776 Param, Template, Converted,
4777 SourceRange(TemplateLoc, RAngleLoc));
4778 if (Inst.isInvalid())
4781 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
4783 // Only substitute for the innermost template argument list.
4784 MultiLevelTemplateArgumentList TemplateArgLists;
4785 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
4786 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4787 TemplateArgLists.addOuterTemplateArguments(None);
4789 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
4791 SemaRef.SubstType(ArgType, TemplateArgLists,
4792 Param->getDefaultArgumentLoc(), Param->getDeclName());
4798 /// Substitute template arguments into the default template argument for
4799 /// the given non-type template parameter.
4801 /// \param SemaRef the semantic analysis object for which we are performing
4802 /// the substitution.
4804 /// \param Template the template that we are synthesizing template arguments
4807 /// \param TemplateLoc the location of the template name that started the
4808 /// template-id we are checking.
4810 /// \param RAngleLoc the location of the right angle bracket ('>') that
4811 /// terminates the template-id.
4813 /// \param Param the non-type template parameter whose default we are
4814 /// substituting into.
4816 /// \param Converted the list of template arguments provided for template
4817 /// parameters that precede \p Param in the template parameter list.
4819 /// \returns the substituted template argument, or NULL if an error occurred.
4821 SubstDefaultTemplateArgument(Sema &SemaRef,
4822 TemplateDecl *Template,
4823 SourceLocation TemplateLoc,
4824 SourceLocation RAngleLoc,
4825 NonTypeTemplateParmDecl *Param,
4826 SmallVectorImpl<TemplateArgument> &Converted) {
4827 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
4828 Param, Template, Converted,
4829 SourceRange(TemplateLoc, RAngleLoc));
4830 if (Inst.isInvalid())
4833 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
4835 // Only substitute for the innermost template argument list.
4836 MultiLevelTemplateArgumentList TemplateArgLists;
4837 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
4838 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4839 TemplateArgLists.addOuterTemplateArguments(None);
4841 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
4842 EnterExpressionEvaluationContext ConstantEvaluated(
4843 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
4844 return SemaRef.SubstExpr(Param->getDefaultArgument(), TemplateArgLists);
4847 /// Substitute template arguments into the default template argument for
4848 /// the given template template parameter.
4850 /// \param SemaRef the semantic analysis object for which we are performing
4851 /// the substitution.
4853 /// \param Template the template that we are synthesizing template arguments
4856 /// \param TemplateLoc the location of the template name that started the
4857 /// template-id we are checking.
4859 /// \param RAngleLoc the location of the right angle bracket ('>') that
4860 /// terminates the template-id.
4862 /// \param Param the template template parameter whose default we are
4863 /// substituting into.
4865 /// \param Converted the list of template arguments provided for template
4866 /// parameters that precede \p Param in the template parameter list.
4868 /// \param QualifierLoc Will be set to the nested-name-specifier (with
4869 /// source-location information) that precedes the template name.
4871 /// \returns the substituted template argument, or NULL if an error occurred.
4873 SubstDefaultTemplateArgument(Sema &SemaRef,
4874 TemplateDecl *Template,
4875 SourceLocation TemplateLoc,
4876 SourceLocation RAngleLoc,
4877 TemplateTemplateParmDecl *Param,
4878 SmallVectorImpl<TemplateArgument> &Converted,
4879 NestedNameSpecifierLoc &QualifierLoc) {
4880 Sema::InstantiatingTemplate Inst(
4881 SemaRef, TemplateLoc, TemplateParameter(Param), Template, Converted,
4882 SourceRange(TemplateLoc, RAngleLoc));
4883 if (Inst.isInvalid())
4884 return TemplateName();
4886 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
4888 // Only substitute for the innermost template argument list.
4889 MultiLevelTemplateArgumentList TemplateArgLists;
4890 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
4891 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4892 TemplateArgLists.addOuterTemplateArguments(None);
4894 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
4895 // Substitute into the nested-name-specifier first,
4896 QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc();
4899 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgLists);
4901 return TemplateName();
4904 return SemaRef.SubstTemplateName(
4906 Param->getDefaultArgument().getArgument().getAsTemplate(),
4907 Param->getDefaultArgument().getTemplateNameLoc(),
4911 /// If the given template parameter has a default template
4912 /// argument, substitute into that default template argument and
4913 /// return the corresponding template argument.
4915 Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
4916 SourceLocation TemplateLoc,
4917 SourceLocation RAngleLoc,
4919 SmallVectorImpl<TemplateArgument>
4921 bool &HasDefaultArg) {
4922 HasDefaultArg = false;
4924 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
4925 if (!hasVisibleDefaultArgument(TypeParm))
4926 return TemplateArgumentLoc();
4928 HasDefaultArg = true;
4929 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
4935 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
4937 return TemplateArgumentLoc();
4940 if (NonTypeTemplateParmDecl *NonTypeParm
4941 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
4942 if (!hasVisibleDefaultArgument(NonTypeParm))
4943 return TemplateArgumentLoc();
4945 HasDefaultArg = true;
4946 ExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
4951 if (Arg.isInvalid())
4952 return TemplateArgumentLoc();
4954 Expr *ArgE = Arg.getAs<Expr>();
4955 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
4958 TemplateTemplateParmDecl *TempTempParm
4959 = cast<TemplateTemplateParmDecl>(Param);
4960 if (!hasVisibleDefaultArgument(TempTempParm))
4961 return TemplateArgumentLoc();
4963 HasDefaultArg = true;
4964 NestedNameSpecifierLoc QualifierLoc;
4965 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
4972 return TemplateArgumentLoc();
4974 return TemplateArgumentLoc(TemplateArgument(TName),
4975 TempTempParm->getDefaultArgument().getTemplateQualifierLoc(),
4976 TempTempParm->getDefaultArgument().getTemplateNameLoc());
4979 /// Convert a template-argument that we parsed as a type into a template, if
4980 /// possible. C++ permits injected-class-names to perform dual service as
4981 /// template template arguments and as template type arguments.
4982 static TemplateArgumentLoc convertTypeTemplateArgumentToTemplate(TypeLoc TLoc) {
4983 // Extract and step over any surrounding nested-name-specifier.
4984 NestedNameSpecifierLoc QualLoc;
4985 if (auto ETLoc = TLoc.getAs<ElaboratedTypeLoc>()) {
4986 if (ETLoc.getTypePtr()->getKeyword() != ETK_None)
4987 return TemplateArgumentLoc();
4989 QualLoc = ETLoc.getQualifierLoc();
4990 TLoc = ETLoc.getNamedTypeLoc();
4993 // If this type was written as an injected-class-name, it can be used as a
4994 // template template argument.
4995 if (auto InjLoc = TLoc.getAs<InjectedClassNameTypeLoc>())
4996 return TemplateArgumentLoc(InjLoc.getTypePtr()->getTemplateName(),
4997 QualLoc, InjLoc.getNameLoc());
4999 // If this type was written as an injected-class-name, it may have been
5000 // converted to a RecordType during instantiation. If the RecordType is
5001 // *not* wrapped in a TemplateSpecializationType and denotes a class
5002 // template specialization, it must have come from an injected-class-name.
5003 if (auto RecLoc = TLoc.getAs<RecordTypeLoc>())
5005 dyn_cast<ClassTemplateSpecializationDecl>(RecLoc.getDecl()))
5006 return TemplateArgumentLoc(TemplateName(CTSD->getSpecializedTemplate()),
5007 QualLoc, RecLoc.getNameLoc());
5009 return TemplateArgumentLoc();
5012 /// Check that the given template argument corresponds to the given
5013 /// template parameter.
5015 /// \param Param The template parameter against which the argument will be
5018 /// \param Arg The template argument, which may be updated due to conversions.
5020 /// \param Template The template in which the template argument resides.
5022 /// \param TemplateLoc The location of the template name for the template
5023 /// whose argument list we're matching.
5025 /// \param RAngleLoc The location of the right angle bracket ('>') that closes
5026 /// the template argument list.
5028 /// \param ArgumentPackIndex The index into the argument pack where this
5029 /// argument will be placed. Only valid if the parameter is a parameter pack.
5031 /// \param Converted The checked, converted argument will be added to the
5032 /// end of this small vector.
5034 /// \param CTAK Describes how we arrived at this particular template argument:
5035 /// explicitly written, deduced, etc.
5037 /// \returns true on error, false otherwise.
5038 bool Sema::CheckTemplateArgument(NamedDecl *Param,
5039 TemplateArgumentLoc &Arg,
5040 NamedDecl *Template,
5041 SourceLocation TemplateLoc,
5042 SourceLocation RAngleLoc,
5043 unsigned ArgumentPackIndex,
5044 SmallVectorImpl<TemplateArgument> &Converted,
5045 CheckTemplateArgumentKind CTAK) {
5046 // Check template type parameters.
5047 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
5048 return CheckTemplateTypeArgument(TTP, Arg, Converted);
5050 // Check non-type template parameters.
5051 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
5052 // Do substitution on the type of the non-type template parameter
5053 // with the template arguments we've seen thus far. But if the
5054 // template has a dependent context then we cannot substitute yet.
5055 QualType NTTPType = NTTP->getType();
5056 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
5057 NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
5059 if (NTTPType->isInstantiationDependentType() &&
5060 !isa<TemplateTemplateParmDecl>(Template) &&
5061 !Template->getDeclContext()->isDependentContext()) {
5062 // Do substitution on the type of the non-type template parameter.
5063 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
5065 SourceRange(TemplateLoc, RAngleLoc));
5066 if (Inst.isInvalid())
5069 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
5072 // If the parameter is a pack expansion, expand this slice of the pack.
5073 if (auto *PET = NTTPType->getAs<PackExpansionType>()) {
5074 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this,
5076 NTTPType = SubstType(PET->getPattern(),
5077 MultiLevelTemplateArgumentList(TemplateArgs),
5078 NTTP->getLocation(),
5079 NTTP->getDeclName());
5081 NTTPType = SubstType(NTTPType,
5082 MultiLevelTemplateArgumentList(TemplateArgs),
5083 NTTP->getLocation(),
5084 NTTP->getDeclName());
5087 // If that worked, check the non-type template parameter type
5089 if (!NTTPType.isNull())
5090 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
5091 NTTP->getLocation());
5092 if (NTTPType.isNull())
5096 switch (Arg.getArgument().getKind()) {
5097 case TemplateArgument::Null:
5098 llvm_unreachable("Should never see a NULL template argument here");
5100 case TemplateArgument::Expression: {
5101 TemplateArgument Result;
5102 unsigned CurSFINAEErrors = NumSFINAEErrors;
5104 CheckTemplateArgument(NTTP, NTTPType, Arg.getArgument().getAsExpr(),
5106 if (Res.isInvalid())
5108 // If the current template argument causes an error, give up now.
5109 if (CurSFINAEErrors < NumSFINAEErrors)
5112 // If the resulting expression is new, then use it in place of the
5113 // old expression in the template argument.
5114 if (Res.get() != Arg.getArgument().getAsExpr()) {
5115 TemplateArgument TA(Res.get());
5116 Arg = TemplateArgumentLoc(TA, Res.get());
5119 Converted.push_back(Result);
5123 case TemplateArgument::Declaration:
5124 case TemplateArgument::Integral:
5125 case TemplateArgument::NullPtr:
5126 // We've already checked this template argument, so just copy
5127 // it to the list of converted arguments.
5128 Converted.push_back(Arg.getArgument());
5131 case TemplateArgument::Template:
5132 case TemplateArgument::TemplateExpansion:
5133 // We were given a template template argument. It may not be ill-formed;
5135 if (DependentTemplateName *DTN
5136 = Arg.getArgument().getAsTemplateOrTemplatePattern()
5137 .getAsDependentTemplateName()) {
5138 // We have a template argument such as \c T::template X, which we
5139 // parsed as a template template argument. However, since we now
5140 // know that we need a non-type template argument, convert this
5141 // template name into an expression.
5143 DeclarationNameInfo NameInfo(DTN->getIdentifier(),
5144 Arg.getTemplateNameLoc());
5147 SS.Adopt(Arg.getTemplateQualifierLoc());
5148 // FIXME: the template-template arg was a DependentTemplateName,
5149 // so it was provided with a template keyword. However, its source
5150 // location is not stored in the template argument structure.
5151 SourceLocation TemplateKWLoc;
5152 ExprResult E = DependentScopeDeclRefExpr::Create(
5153 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
5156 // If we parsed the template argument as a pack expansion, create a
5157 // pack expansion expression.
5158 if (Arg.getArgument().getKind() == TemplateArgument::TemplateExpansion){
5159 E = ActOnPackExpansion(E.get(), Arg.getTemplateEllipsisLoc());
5164 TemplateArgument Result;
5165 E = CheckTemplateArgument(NTTP, NTTPType, E.get(), Result);
5169 Converted.push_back(Result);
5173 // We have a template argument that actually does refer to a class
5174 // template, alias template, or template template parameter, and
5175 // therefore cannot be a non-type template argument.
5176 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
5177 << Arg.getSourceRange();
5179 Diag(Param->getLocation(), diag::note_template_param_here);
5182 case TemplateArgument::Type: {
5183 // We have a non-type template parameter but the template
5184 // argument is a type.
5186 // C++ [temp.arg]p2:
5187 // In a template-argument, an ambiguity between a type-id and
5188 // an expression is resolved to a type-id, regardless of the
5189 // form of the corresponding template-parameter.
5191 // We warn specifically about this case, since it can be rather
5192 // confusing for users.
5193 QualType T = Arg.getArgument().getAsType();
5194 SourceRange SR = Arg.getSourceRange();
5195 if (T->isFunctionType())
5196 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
5198 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
5199 Diag(Param->getLocation(), diag::note_template_param_here);
5203 case TemplateArgument::Pack:
5204 llvm_unreachable("Caller must expand template argument packs");
5211 // Check template template parameters.
5212 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
5214 TemplateParameterList *Params = TempParm->getTemplateParameters();
5215 if (TempParm->isExpandedParameterPack())
5216 Params = TempParm->getExpansionTemplateParameters(ArgumentPackIndex);
5218 // Substitute into the template parameter list of the template
5219 // template parameter, since previously-supplied template arguments
5220 // may appear within the template template parameter.
5222 // FIXME: Skip this if the parameters aren't instantiation-dependent.
5224 // Set up a template instantiation context.
5225 LocalInstantiationScope Scope(*this);
5226 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
5227 TempParm, Converted,
5228 SourceRange(TemplateLoc, RAngleLoc));
5229 if (Inst.isInvalid())
5232 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
5233 Params = SubstTemplateParams(Params, CurContext,
5234 MultiLevelTemplateArgumentList(TemplateArgs));
5239 // C++1z [temp.local]p1: (DR1004)
5240 // When [the injected-class-name] is used [...] as a template-argument for
5241 // a template template-parameter [...] it refers to the class template
5243 if (Arg.getArgument().getKind() == TemplateArgument::Type) {
5244 TemplateArgumentLoc ConvertedArg = convertTypeTemplateArgumentToTemplate(
5245 Arg.getTypeSourceInfo()->getTypeLoc());
5246 if (!ConvertedArg.getArgument().isNull())
5250 switch (Arg.getArgument().getKind()) {
5251 case TemplateArgument::Null:
5252 llvm_unreachable("Should never see a NULL template argument here");
5254 case TemplateArgument::Template:
5255 case TemplateArgument::TemplateExpansion:
5256 if (CheckTemplateTemplateArgument(TempParm, Params, Arg))
5259 Converted.push_back(Arg.getArgument());
5262 case TemplateArgument::Expression:
5263 case TemplateArgument::Type:
5264 // We have a template template parameter but the template
5265 // argument does not refer to a template.
5266 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template)
5267 << getLangOpts().CPlusPlus11;
5270 case TemplateArgument::Declaration:
5271 llvm_unreachable("Declaration argument with template template parameter");
5272 case TemplateArgument::Integral:
5273 llvm_unreachable("Integral argument with template template parameter");
5274 case TemplateArgument::NullPtr:
5275 llvm_unreachable("Null pointer argument with template template parameter");
5277 case TemplateArgument::Pack:
5278 llvm_unreachable("Caller must expand template argument packs");
5284 /// Check whether the template parameter is a pack expansion, and if so,
5285 /// determine the number of parameters produced by that expansion. For instance:
5288 /// template<typename ...Ts> struct A {
5289 /// template<Ts ...NTs, template<Ts> class ...TTs, typename ...Us> struct B;
5293 /// In \c A<int,int>::B, \c NTs and \c TTs have expanded pack size 2, and \c Us
5294 /// is not a pack expansion, so returns an empty Optional.
5295 static Optional<unsigned> getExpandedPackSize(NamedDecl *Param) {
5296 if (TemplateTypeParmDecl *TTP
5297 = dyn_cast<TemplateTypeParmDecl>(Param)) {
5298 if (TTP->isExpandedParameterPack())
5299 return TTP->getNumExpansionParameters();
5302 if (NonTypeTemplateParmDecl *NTTP
5303 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
5304 if (NTTP->isExpandedParameterPack())
5305 return NTTP->getNumExpansionTypes();
5308 if (TemplateTemplateParmDecl *TTP
5309 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
5310 if (TTP->isExpandedParameterPack())
5311 return TTP->getNumExpansionTemplateParameters();
5317 /// Diagnose a missing template argument.
5318 template<typename TemplateParmDecl>
5319 static bool diagnoseMissingArgument(Sema &S, SourceLocation Loc,
5321 const TemplateParmDecl *D,
5322 TemplateArgumentListInfo &Args) {
5323 // Dig out the most recent declaration of the template parameter; there may be
5324 // declarations of the template that are more recent than TD.
5325 D = cast<TemplateParmDecl>(cast<TemplateDecl>(TD->getMostRecentDecl())
5326 ->getTemplateParameters()
5327 ->getParam(D->getIndex()));
5329 // If there's a default argument that's not visible, diagnose that we're
5330 // missing a module import.
5331 llvm::SmallVector<Module*, 8> Modules;
5332 if (D->hasDefaultArgument() && !S.hasVisibleDefaultArgument(D, &Modules)) {
5333 S.diagnoseMissingImport(Loc, cast<NamedDecl>(TD),
5334 D->getDefaultArgumentLoc(), Modules,
5335 Sema::MissingImportKind::DefaultArgument,
5340 // FIXME: If there's a more recent default argument that *is* visible,
5341 // diagnose that it was declared too late.
5343 TemplateParameterList *Params = TD->getTemplateParameters();
5345 S.Diag(Loc, diag::err_template_arg_list_different_arity)
5346 << /*not enough args*/0
5347 << (int)S.getTemplateNameKindForDiagnostics(TemplateName(TD))
5349 S.Diag(TD->getLocation(), diag::note_template_decl_here)
5350 << Params->getSourceRange();
5354 /// Check that the given template argument list is well-formed
5355 /// for specializing the given template.
5356 bool Sema::CheckTemplateArgumentList(
5357 TemplateDecl *Template, SourceLocation TemplateLoc,
5358 TemplateArgumentListInfo &TemplateArgs, bool PartialTemplateArgs,
5359 SmallVectorImpl<TemplateArgument> &Converted,
5360 bool UpdateArgsWithConversions, bool *ConstraintsNotSatisfied) {
5362 if (ConstraintsNotSatisfied)
5363 *ConstraintsNotSatisfied = false;
5365 // Make a copy of the template arguments for processing. Only make the
5366 // changes at the end when successful in matching the arguments to the
5368 TemplateArgumentListInfo NewArgs = TemplateArgs;
5370 // Make sure we get the template parameter list from the most
5371 // recentdeclaration, since that is the only one that has is guaranteed to
5372 // have all the default template argument information.
5373 TemplateParameterList *Params =
5374 cast<TemplateDecl>(Template->getMostRecentDecl())
5375 ->getTemplateParameters();
5377 SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
5379 // C++ [temp.arg]p1:
5380 // [...] The type and form of each template-argument specified in
5381 // a template-id shall match the type and form specified for the
5382 // corresponding parameter declared by the template in its
5383 // template-parameter-list.
5384 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
5385 SmallVector<TemplateArgument, 2> ArgumentPack;
5386 unsigned ArgIdx = 0, NumArgs = NewArgs.size();
5387 LocalInstantiationScope InstScope(*this, true);
5388 for (TemplateParameterList::iterator Param = Params->begin(),
5389 ParamEnd = Params->end();
5390 Param != ParamEnd; /* increment in loop */) {
5391 // If we have an expanded parameter pack, make sure we don't have too
5393 if (Optional<unsigned> Expansions = getExpandedPackSize(*Param)) {
5394 if (*Expansions == ArgumentPack.size()) {
5395 // We're done with this parameter pack. Pack up its arguments and add
5396 // them to the list.
5397 Converted.push_back(
5398 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
5399 ArgumentPack.clear();
5401 // This argument is assigned to the next parameter.
5404 } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
5405 // Not enough arguments for this parameter pack.
5406 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
5407 << /*not enough args*/0
5408 << (int)getTemplateNameKindForDiagnostics(TemplateName(Template))
5410 Diag(Template->getLocation(), diag::note_template_decl_here)
5411 << Params->getSourceRange();
5416 if (ArgIdx < NumArgs) {
5417 // Check the template argument we were given.
5418 if (CheckTemplateArgument(*Param, NewArgs[ArgIdx], Template,
5419 TemplateLoc, RAngleLoc,
5420 ArgumentPack.size(), Converted))
5423 bool PackExpansionIntoNonPack =
5424 NewArgs[ArgIdx].getArgument().isPackExpansion() &&
5425 (!(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param));
5426 if (PackExpansionIntoNonPack && (isa<TypeAliasTemplateDecl>(Template) ||
5427 isa<ConceptDecl>(Template))) {
5428 // Core issue 1430: we have a pack expansion as an argument to an
5429 // alias template, and it's not part of a parameter pack. This
5430 // can't be canonicalized, so reject it now.
5431 // As for concepts - we cannot normalize constraints where this
5432 // situation exists.
5433 Diag(NewArgs[ArgIdx].getLocation(),
5434 diag::err_template_expansion_into_fixed_list)
5435 << (isa<ConceptDecl>(Template) ? 1 : 0)
5436 << NewArgs[ArgIdx].getSourceRange();
5437 Diag((*Param)->getLocation(), diag::note_template_param_here);
5441 // We're now done with this argument.
5444 if ((*Param)->isTemplateParameterPack()) {
5445 // The template parameter was a template parameter pack, so take the
5446 // deduced argument and place it on the argument pack. Note that we
5447 // stay on the same template parameter so that we can deduce more
5449 ArgumentPack.push_back(Converted.pop_back_val());
5451 // Move to the next template parameter.
5455 // If we just saw a pack expansion into a non-pack, then directly convert
5456 // the remaining arguments, because we don't know what parameters they'll
5458 if (PackExpansionIntoNonPack) {
5459 if (!ArgumentPack.empty()) {
5460 // If we were part way through filling in an expanded parameter pack,
5461 // fall back to just producing individual arguments.
5462 Converted.insert(Converted.end(),
5463 ArgumentPack.begin(), ArgumentPack.end());
5464 ArgumentPack.clear();
5467 while (ArgIdx < NumArgs) {
5468 Converted.push_back(NewArgs[ArgIdx].getArgument());
5478 // If we're checking a partial template argument list, we're done.
5479 if (PartialTemplateArgs) {
5480 if ((*Param)->isTemplateParameterPack() && !ArgumentPack.empty())
5481 Converted.push_back(
5482 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
5486 // If we have a template parameter pack with no more corresponding
5487 // arguments, just break out now and we'll fill in the argument pack below.
5488 if ((*Param)->isTemplateParameterPack()) {
5489 assert(!getExpandedPackSize(*Param) &&
5490 "Should have dealt with this already");
5492 // A non-expanded parameter pack before the end of the parameter list
5493 // only occurs for an ill-formed template parameter list, unless we've
5494 // got a partial argument list for a function template, so just bail out.
5495 if (Param + 1 != ParamEnd)
5498 Converted.push_back(
5499 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
5500 ArgumentPack.clear();
5506 // Check whether we have a default argument.
5507 TemplateArgumentLoc Arg;
5509 // Retrieve the default template argument from the template
5510 // parameter. For each kind of template parameter, we substitute the
5511 // template arguments provided thus far and any "outer" template arguments
5512 // (when the template parameter was part of a nested template) into
5513 // the default argument.
5514 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
5515 if (!hasVisibleDefaultArgument(TTP))
5516 return diagnoseMissingArgument(*this, TemplateLoc, Template, TTP,
5519 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
5528 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
5530 } else if (NonTypeTemplateParmDecl *NTTP
5531 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
5532 if (!hasVisibleDefaultArgument(NTTP))
5533 return diagnoseMissingArgument(*this, TemplateLoc, Template, NTTP,
5536 ExprResult E = SubstDefaultTemplateArgument(*this, Template,
5544 Expr *Ex = E.getAs<Expr>();
5545 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
5547 TemplateTemplateParmDecl *TempParm
5548 = cast<TemplateTemplateParmDecl>(*Param);
5550 if (!hasVisibleDefaultArgument(TempParm))
5551 return diagnoseMissingArgument(*this, TemplateLoc, Template, TempParm,
5554 NestedNameSpecifierLoc QualifierLoc;
5555 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
5564 Arg = TemplateArgumentLoc(TemplateArgument(Name), QualifierLoc,
5565 TempParm->getDefaultArgument().getTemplateNameLoc());
5568 // Introduce an instantiation record that describes where we are using
5569 // the default template argument. We're not actually instantiating a
5570 // template here, we just create this object to put a note into the
5572 InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param, Converted,
5573 SourceRange(TemplateLoc, RAngleLoc));
5574 if (Inst.isInvalid())
5577 // Check the default template argument.
5578 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
5579 RAngleLoc, 0, Converted))
5582 // Core issue 150 (assumed resolution): if this is a template template
5583 // parameter, keep track of the default template arguments from the
5584 // template definition.
5585 if (isTemplateTemplateParameter)
5586 NewArgs.addArgument(Arg);
5588 // Move to the next template parameter and argument.
5593 // If we're performing a partial argument substitution, allow any trailing
5594 // pack expansions; they might be empty. This can happen even if
5595 // PartialTemplateArgs is false (the list of arguments is complete but
5596 // still dependent).
5597 if (ArgIdx < NumArgs && CurrentInstantiationScope &&
5598 CurrentInstantiationScope->getPartiallySubstitutedPack()) {
5599 while (ArgIdx < NumArgs && NewArgs[ArgIdx].getArgument().isPackExpansion())
5600 Converted.push_back(NewArgs[ArgIdx++].getArgument());
5603 // If we have any leftover arguments, then there were too many arguments.
5604 // Complain and fail.
5605 if (ArgIdx < NumArgs) {
5606 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
5607 << /*too many args*/1
5608 << (int)getTemplateNameKindForDiagnostics(TemplateName(Template))
5610 << SourceRange(NewArgs[ArgIdx].getLocation(), NewArgs.getRAngleLoc());
5611 Diag(Template->getLocation(), diag::note_template_decl_here)
5612 << Params->getSourceRange();
5616 // No problems found with the new argument list, propagate changes back
5618 if (UpdateArgsWithConversions)
5619 TemplateArgs = std::move(NewArgs);
5621 if (!PartialTemplateArgs &&
5622 EnsureTemplateArgumentListConstraints(
5623 Template, Converted, SourceRange(TemplateLoc,
5624 TemplateArgs.getRAngleLoc()))) {
5625 if (ConstraintsNotSatisfied)
5626 *ConstraintsNotSatisfied = true;
5634 class UnnamedLocalNoLinkageFinder
5635 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
5640 typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
5643 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
5645 bool Visit(QualType T) {
5646 return T.isNull() ? false : inherited::Visit(T.getTypePtr());
5649 #define TYPE(Class, Parent) \
5650 bool Visit##Class##Type(const Class##Type *);
5651 #define ABSTRACT_TYPE(Class, Parent) \
5652 bool Visit##Class##Type(const Class##Type *) { return false; }
5653 #define NON_CANONICAL_TYPE(Class, Parent) \
5654 bool Visit##Class##Type(const Class##Type *) { return false; }
5655 #include "clang/AST/TypeNodes.inc"
5657 bool VisitTagDecl(const TagDecl *Tag);
5658 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
5660 } // end anonymous namespace
5662 bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
5666 bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
5667 return Visit(T->getElementType());
5670 bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
5671 return Visit(T->getPointeeType());
5674 bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
5675 const BlockPointerType* T) {
5676 return Visit(T->getPointeeType());
5679 bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
5680 const LValueReferenceType* T) {
5681 return Visit(T->getPointeeType());
5684 bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
5685 const RValueReferenceType* T) {
5686 return Visit(T->getPointeeType());
5689 bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
5690 const MemberPointerType* T) {
5691 return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
5694 bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
5695 const ConstantArrayType* T) {
5696 return Visit(T->getElementType());
5699 bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
5700 const IncompleteArrayType* T) {
5701 return Visit(T->getElementType());
5704 bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
5705 const VariableArrayType* T) {
5706 return Visit(T->getElementType());
5709 bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
5710 const DependentSizedArrayType* T) {
5711 return Visit(T->getElementType());
5714 bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
5715 const DependentSizedExtVectorType* T) {
5716 return Visit(T->getElementType());
5719 bool UnnamedLocalNoLinkageFinder::VisitDependentAddressSpaceType(
5720 const DependentAddressSpaceType *T) {
5721 return Visit(T->getPointeeType());
5724 bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
5725 return Visit(T->getElementType());
5728 bool UnnamedLocalNoLinkageFinder::VisitDependentVectorType(
5729 const DependentVectorType *T) {
5730 return Visit(T->getElementType());
5733 bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
5734 return Visit(T->getElementType());
5737 bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
5738 const FunctionProtoType* T) {
5739 for (const auto &A : T->param_types()) {
5744 return Visit(T->getReturnType());
5747 bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
5748 const FunctionNoProtoType* T) {
5749 return Visit(T->getReturnType());
5752 bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
5753 const UnresolvedUsingType*) {
5757 bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
5761 bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
5762 return Visit(T->getUnderlyingType());
5765 bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
5769 bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
5770 const UnaryTransformType*) {
5774 bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
5775 return Visit(T->getDeducedType());
5778 bool UnnamedLocalNoLinkageFinder::VisitDeducedTemplateSpecializationType(
5779 const DeducedTemplateSpecializationType *T) {
5780 return Visit(T->getDeducedType());
5783 bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
5784 return VisitTagDecl(T->getDecl());
5787 bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
5788 return VisitTagDecl(T->getDecl());
5791 bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
5792 const TemplateTypeParmType*) {
5796 bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
5797 const SubstTemplateTypeParmPackType *) {
5801 bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
5802 const TemplateSpecializationType*) {
5806 bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
5807 const InjectedClassNameType* T) {
5808 return VisitTagDecl(T->getDecl());
5811 bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
5812 const DependentNameType* T) {
5813 return VisitNestedNameSpecifier(T->getQualifier());
5816 bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
5817 const DependentTemplateSpecializationType* T) {
5818 return VisitNestedNameSpecifier(T->getQualifier());
5821 bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
5822 const PackExpansionType* T) {
5823 return Visit(T->getPattern());
5826 bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
5830 bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
5831 const ObjCInterfaceType *) {
5835 bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
5836 const ObjCObjectPointerType *) {
5840 bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
5841 return Visit(T->getValueType());
5844 bool UnnamedLocalNoLinkageFinder::VisitPipeType(const PipeType* T) {
5848 bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
5849 if (Tag->getDeclContext()->isFunctionOrMethod()) {
5850 S.Diag(SR.getBegin(),
5851 S.getLangOpts().CPlusPlus11 ?
5852 diag::warn_cxx98_compat_template_arg_local_type :
5853 diag::ext_template_arg_local_type)
5854 << S.Context.getTypeDeclType(Tag) << SR;
5858 if (!Tag->hasNameForLinkage()) {
5859 S.Diag(SR.getBegin(),
5860 S.getLangOpts().CPlusPlus11 ?
5861 diag::warn_cxx98_compat_template_arg_unnamed_type :
5862 diag::ext_template_arg_unnamed_type) << SR;
5863 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
5870 bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
5871 NestedNameSpecifier *NNS) {
5872 if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
5875 switch (NNS->getKind()) {
5876 case NestedNameSpecifier::Identifier:
5877 case NestedNameSpecifier::Namespace:
5878 case NestedNameSpecifier::NamespaceAlias:
5879 case NestedNameSpecifier::Global:
5880 case NestedNameSpecifier::Super:
5883 case NestedNameSpecifier::TypeSpec:
5884 case NestedNameSpecifier::TypeSpecWithTemplate:
5885 return Visit(QualType(NNS->getAsType(), 0));
5887 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
5890 /// Check a template argument against its corresponding
5891 /// template type parameter.
5893 /// This routine implements the semantics of C++ [temp.arg.type]. It
5894 /// returns true if an error occurred, and false otherwise.
5895 bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
5896 TypeSourceInfo *ArgInfo) {
5897 assert(ArgInfo && "invalid TypeSourceInfo");
5898 QualType Arg = ArgInfo->getType();
5899 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
5901 if (Arg->isVariablyModifiedType()) {
5902 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
5903 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
5904 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
5907 // C++03 [temp.arg.type]p2:
5908 // A local type, a type with no linkage, an unnamed type or a type
5909 // compounded from any of these types shall not be used as a
5910 // template-argument for a template type-parameter.
5912 // C++11 allows these, and even in C++03 we allow them as an extension with
5914 if (LangOpts.CPlusPlus11 || Arg->hasUnnamedOrLocalType()) {
5915 UnnamedLocalNoLinkageFinder Finder(*this, SR);
5916 (void)Finder.Visit(Context.getCanonicalType(Arg));
5922 enum NullPointerValueKind {
5928 /// Determine whether the given template argument is a null pointer
5929 /// value of the appropriate type.
5930 static NullPointerValueKind
5931 isNullPointerValueTemplateArgument(Sema &S, NonTypeTemplateParmDecl *Param,
5932 QualType ParamType, Expr *Arg,
5933 Decl *Entity = nullptr) {
5934 if (Arg->isValueDependent() || Arg->isTypeDependent())
5935 return NPV_NotNullPointer;
5937 // dllimport'd entities aren't constant but are available inside of template
5939 if (Entity && Entity->hasAttr<DLLImportAttr>())
5940 return NPV_NotNullPointer;
5942 if (!S.isCompleteType(Arg->getExprLoc(), ParamType))
5944 "Incomplete parameter type in isNullPointerValueTemplateArgument!");
5946 if (!S.getLangOpts().CPlusPlus11)
5947 return NPV_NotNullPointer;
5949 // Determine whether we have a constant expression.
5950 ExprResult ArgRV = S.DefaultFunctionArrayConversion(Arg);
5951 if (ArgRV.isInvalid())
5955 Expr::EvalResult EvalResult;
5956 SmallVector<PartialDiagnosticAt, 8> Notes;
5957 EvalResult.Diag = &Notes;
5958 if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
5959 EvalResult.HasSideEffects) {
5960 SourceLocation DiagLoc = Arg->getExprLoc();
5962 // If our only note is the usual "invalid subexpression" note, just point
5963 // the caret at its location rather than producing an essentially
5965 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
5966 diag::note_invalid_subexpr_in_const_expr) {
5967 DiagLoc = Notes[0].first;
5971 S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
5972 << Arg->getType() << Arg->getSourceRange();
5973 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
5974 S.Diag(Notes[I].first, Notes[I].second);
5976 S.Diag(Param->getLocation(), diag::note_template_param_here);
5980 // C++11 [temp.arg.nontype]p1:
5981 // - an address constant expression of type std::nullptr_t
5982 if (Arg->getType()->isNullPtrType())
5983 return NPV_NullPointer;
5985 // - a constant expression that evaluates to a null pointer value (4.10); or
5986 // - a constant expression that evaluates to a null member pointer value
5988 if ((EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) ||
5989 (EvalResult.Val.isMemberPointer() &&
5990 !EvalResult.Val.getMemberPointerDecl())) {
5991 // If our expression has an appropriate type, we've succeeded.
5992 bool ObjCLifetimeConversion;
5993 if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
5994 S.IsQualificationConversion(Arg->getType(), ParamType, false,
5995 ObjCLifetimeConversion))
5996 return NPV_NullPointer;
5998 // The types didn't match, but we know we got a null pointer; complain,
5999 // then recover as if the types were correct.
6000 S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
6001 << Arg->getType() << ParamType << Arg->getSourceRange();
6002 S.Diag(Param->getLocation(), diag::note_template_param_here);
6003 return NPV_NullPointer;
6006 // If we don't have a null pointer value, but we do have a NULL pointer
6007 // constant, suggest a cast to the appropriate type.
6008 if (Arg->isNullPointerConstant(S.Context, Expr::NPC_NeverValueDependent)) {
6009 std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
6010 S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
6011 << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), Code)
6012 << FixItHint::CreateInsertion(S.getLocForEndOfToken(Arg->getEndLoc()),
6014 S.Diag(Param->getLocation(), diag::note_template_param_here);
6015 return NPV_NullPointer;
6018 // FIXME: If we ever want to support general, address-constant expressions
6019 // as non-type template arguments, we should return the ExprResult here to
6020 // be interpreted by the caller.
6021 return NPV_NotNullPointer;
6024 /// Checks whether the given template argument is compatible with its
6025 /// template parameter.
6026 static bool CheckTemplateArgumentIsCompatibleWithParameter(
6027 Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
6028 Expr *Arg, QualType ArgType) {
6029 bool ObjCLifetimeConversion;
6030 if (ParamType->isPointerType() &&
6031 !ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType() &&
6032 S.IsQualificationConversion(ArgType, ParamType, false,
6033 ObjCLifetimeConversion)) {
6034 // For pointer-to-object types, qualification conversions are
6037 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
6038 if (!ParamRef->getPointeeType()->isFunctionType()) {
6039 // C++ [temp.arg.nontype]p5b3:
6040 // For a non-type template-parameter of type reference to
6041 // object, no conversions apply. The type referred to by the
6042 // reference may be more cv-qualified than the (otherwise
6043 // identical) type of the template- argument. The
6044 // template-parameter is bound directly to the
6045 // template-argument, which shall be an lvalue.
6047 // FIXME: Other qualifiers?
6048 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
6049 unsigned ArgQuals = ArgType.getCVRQualifiers();
6051 if ((ParamQuals | ArgQuals) != ParamQuals) {
6052 S.Diag(Arg->getBeginLoc(),
6053 diag::err_template_arg_ref_bind_ignores_quals)
6054 << ParamType << Arg->getType() << Arg->getSourceRange();
6055 S.Diag(Param->getLocation(), diag::note_template_param_here);
6061 // At this point, the template argument refers to an object or
6062 // function with external linkage. We now need to check whether the
6063 // argument and parameter types are compatible.
6064 if (!S.Context.hasSameUnqualifiedType(ArgType,
6065 ParamType.getNonReferenceType())) {
6066 // We can't perform this conversion or binding.
6067 if (ParamType->isReferenceType())
6068 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_no_ref_bind)
6069 << ParamType << ArgIn->getType() << Arg->getSourceRange();
6071 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_convertible)
6072 << ArgIn->getType() << ParamType << Arg->getSourceRange();
6073 S.Diag(Param->getLocation(), diag::note_template_param_here);
6081 /// Checks whether the given template argument is the address
6082 /// of an object or function according to C++ [temp.arg.nontype]p1.
6084 CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
6085 NonTypeTemplateParmDecl *Param,
6088 TemplateArgument &Converted) {
6089 bool Invalid = false;
6091 QualType ArgType = Arg->getType();
6093 bool AddressTaken = false;
6094 SourceLocation AddrOpLoc;
6095 if (S.getLangOpts().MicrosoftExt) {
6096 // Microsoft Visual C++ strips all casts, allows an arbitrary number of
6097 // dereference and address-of operators.
6098 Arg = Arg->IgnoreParenCasts();
6100 bool ExtWarnMSTemplateArg = false;
6101 UnaryOperatorKind FirstOpKind;
6102 SourceLocation FirstOpLoc;
6103 while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
6104 UnaryOperatorKind UnOpKind = UnOp->getOpcode();
6105 if (UnOpKind == UO_Deref)
6106 ExtWarnMSTemplateArg = true;
6107 if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
6108 Arg = UnOp->getSubExpr()->IgnoreParenCasts();
6109 if (!AddrOpLoc.isValid()) {
6110 FirstOpKind = UnOpKind;
6111 FirstOpLoc = UnOp->getOperatorLoc();
6116 if (FirstOpLoc.isValid()) {
6117 if (ExtWarnMSTemplateArg)
6118 S.Diag(ArgIn->getBeginLoc(), diag::ext_ms_deref_template_argument)
6119 << ArgIn->getSourceRange();
6121 if (FirstOpKind == UO_AddrOf)
6122 AddressTaken = true;
6123 else if (Arg->getType()->isPointerType()) {
6124 // We cannot let pointers get dereferenced here, that is obviously not a
6125 // constant expression.
6126 assert(FirstOpKind == UO_Deref);
6127 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
6128 << Arg->getSourceRange();
6132 // See through any implicit casts we added to fix the type.
6133 Arg = Arg->IgnoreImpCasts();
6135 // C++ [temp.arg.nontype]p1:
6137 // A template-argument for a non-type, non-template
6138 // template-parameter shall be one of: [...]
6140 // -- the address of an object or function with external
6141 // linkage, including function templates and function
6142 // template-ids but excluding non-static class members,
6143 // expressed as & id-expression where the & is optional if
6144 // the name refers to a function or array, or if the
6145 // corresponding template-parameter is a reference; or
6147 // In C++98/03 mode, give an extension warning on any extra parentheses.
6148 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
6149 bool ExtraParens = false;
6150 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
6151 if (!Invalid && !ExtraParens) {
6152 S.Diag(Arg->getBeginLoc(),
6153 S.getLangOpts().CPlusPlus11
6154 ? diag::warn_cxx98_compat_template_arg_extra_parens
6155 : diag::ext_template_arg_extra_parens)
6156 << Arg->getSourceRange();
6160 Arg = Parens->getSubExpr();
6163 while (SubstNonTypeTemplateParmExpr *subst =
6164 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
6165 Arg = subst->getReplacement()->IgnoreImpCasts();
6167 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
6168 if (UnOp->getOpcode() == UO_AddrOf) {
6169 Arg = UnOp->getSubExpr();
6170 AddressTaken = true;
6171 AddrOpLoc = UnOp->getOperatorLoc();
6175 while (SubstNonTypeTemplateParmExpr *subst =
6176 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
6177 Arg = subst->getReplacement()->IgnoreImpCasts();
6180 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg);
6181 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
6183 // If our parameter has pointer type, check for a null template value.
6184 if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
6185 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn,
6187 case NPV_NullPointer:
6188 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
6189 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
6190 /*isNullPtr=*/true);
6196 case NPV_NotNullPointer:
6201 // Stop checking the precise nature of the argument if it is value dependent,
6202 // it should be checked when instantiated.
6203 if (Arg->isValueDependent()) {
6204 Converted = TemplateArgument(ArgIn);
6208 if (isa<CXXUuidofExpr>(Arg)) {
6209 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType,
6210 ArgIn, Arg, ArgType))
6213 Converted = TemplateArgument(ArgIn);
6218 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
6219 << Arg->getSourceRange();
6220 S.Diag(Param->getLocation(), diag::note_template_param_here);
6224 // Cannot refer to non-static data members
6225 if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) {
6226 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_field)
6227 << Entity << Arg->getSourceRange();
6228 S.Diag(Param->getLocation(), diag::note_template_param_here);
6232 // Cannot refer to non-static member functions
6233 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
6234 if (!Method->isStatic()) {
6235 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_method)
6236 << Method << Arg->getSourceRange();
6237 S.Diag(Param->getLocation(), diag::note_template_param_here);
6242 FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
6243 VarDecl *Var = dyn_cast<VarDecl>(Entity);
6245 // A non-type template argument must refer to an object or function.
6246 if (!Func && !Var) {
6247 // We found something, but we don't know specifically what it is.
6248 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_object_or_func)
6249 << Arg->getSourceRange();
6250 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
6254 // Address / reference template args must have external linkage in C++98.
6255 if (Entity->getFormalLinkage() == InternalLinkage) {
6256 S.Diag(Arg->getBeginLoc(),
6257 S.getLangOpts().CPlusPlus11
6258 ? diag::warn_cxx98_compat_template_arg_object_internal
6259 : diag::ext_template_arg_object_internal)
6260 << !Func << Entity << Arg->getSourceRange();
6261 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
6263 } else if (!Entity->hasLinkage()) {
6264 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_object_no_linkage)
6265 << !Func << Entity << Arg->getSourceRange();
6266 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
6272 // If the template parameter has pointer type, the function decays.
6273 if (ParamType->isPointerType() && !AddressTaken)
6274 ArgType = S.Context.getPointerType(Func->getType());
6275 else if (AddressTaken && ParamType->isReferenceType()) {
6276 // If we originally had an address-of operator, but the
6277 // parameter has reference type, complain and (if things look
6278 // like they will work) drop the address-of operator.
6279 if (!S.Context.hasSameUnqualifiedType(Func->getType(),
6280 ParamType.getNonReferenceType())) {
6281 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
6283 S.Diag(Param->getLocation(), diag::note_template_param_here);
6287 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
6289 << FixItHint::CreateRemoval(AddrOpLoc);
6290 S.Diag(Param->getLocation(), diag::note_template_param_here);
6292 ArgType = Func->getType();
6295 // A value of reference type is not an object.
6296 if (Var->getType()->isReferenceType()) {
6297 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_reference_var)
6298 << Var->getType() << Arg->getSourceRange();
6299 S.Diag(Param->getLocation(), diag::note_template_param_here);
6303 // A template argument must have static storage duration.
6304 if (Var->getTLSKind()) {
6305 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_thread_local)
6306 << Arg->getSourceRange();
6307 S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
6311 // If the template parameter has pointer type, we must have taken
6312 // the address of this object.
6313 if (ParamType->isReferenceType()) {
6315 // If we originally had an address-of operator, but the
6316 // parameter has reference type, complain and (if things look
6317 // like they will work) drop the address-of operator.
6318 if (!S.Context.hasSameUnqualifiedType(Var->getType(),
6319 ParamType.getNonReferenceType())) {
6320 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
6322 S.Diag(Param->getLocation(), diag::note_template_param_here);
6326 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
6328 << FixItHint::CreateRemoval(AddrOpLoc);
6329 S.Diag(Param->getLocation(), diag::note_template_param_here);
6331 ArgType = Var->getType();
6333 } else if (!AddressTaken && ParamType->isPointerType()) {
6334 if (Var->getType()->isArrayType()) {
6335 // Array-to-pointer decay.
6336 ArgType = S.Context.getArrayDecayedType(Var->getType());
6338 // If the template parameter has pointer type but the address of
6339 // this object was not taken, complain and (possibly) recover by
6340 // taking the address of the entity.
6341 ArgType = S.Context.getPointerType(Var->getType());
6342 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
6343 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of)
6345 S.Diag(Param->getLocation(), diag::note_template_param_here);
6349 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of)
6350 << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), "&");
6352 S.Diag(Param->getLocation(), diag::note_template_param_here);
6357 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
6361 // Create the template argument.
6363 TemplateArgument(cast<ValueDecl>(Entity->getCanonicalDecl()), ParamType);
6364 S.MarkAnyDeclReferenced(Arg->getBeginLoc(), Entity, false);
6368 /// Checks whether the given template argument is a pointer to
6369 /// member constant according to C++ [temp.arg.nontype]p1.
6370 static bool CheckTemplateArgumentPointerToMember(Sema &S,
6371 NonTypeTemplateParmDecl *Param,
6374 TemplateArgument &Converted) {
6375 bool Invalid = false;
6377 Expr *Arg = ResultArg;
6378 bool ObjCLifetimeConversion;
6380 // C++ [temp.arg.nontype]p1:
6382 // A template-argument for a non-type, non-template
6383 // template-parameter shall be one of: [...]
6385 // -- a pointer to member expressed as described in 5.3.1.
6386 DeclRefExpr *DRE = nullptr;
6388 // In C++98/03 mode, give an extension warning on any extra parentheses.
6389 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
6390 bool ExtraParens = false;
6391 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
6392 if (!Invalid && !ExtraParens) {
6393 S.Diag(Arg->getBeginLoc(),
6394 S.getLangOpts().CPlusPlus11
6395 ? diag::warn_cxx98_compat_template_arg_extra_parens
6396 : diag::ext_template_arg_extra_parens)
6397 << Arg->getSourceRange();
6401 Arg = Parens->getSubExpr();
6404 while (SubstNonTypeTemplateParmExpr *subst =
6405 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
6406 Arg = subst->getReplacement()->IgnoreImpCasts();
6408 // A pointer-to-member constant written &Class::member.
6409 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
6410 if (UnOp->getOpcode() == UO_AddrOf) {
6411 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
6412 if (DRE && !DRE->getQualifier())
6416 // A constant of pointer-to-member type.
6417 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
6418 ValueDecl *VD = DRE->getDecl();
6419 if (VD->getType()->isMemberPointerType()) {
6420 if (isa<NonTypeTemplateParmDecl>(VD)) {
6421 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
6422 Converted = TemplateArgument(Arg);
6424 VD = cast<ValueDecl>(VD->getCanonicalDecl());
6425 Converted = TemplateArgument(VD, ParamType);
6434 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
6436 // Check for a null pointer value.
6437 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ResultArg,
6441 case NPV_NullPointer:
6442 S.Diag(ResultArg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
6443 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
6446 case NPV_NotNullPointer:
6450 if (S.IsQualificationConversion(ResultArg->getType(),
6451 ParamType.getNonReferenceType(), false,
6452 ObjCLifetimeConversion)) {
6453 ResultArg = S.ImpCastExprToType(ResultArg, ParamType, CK_NoOp,
6454 ResultArg->getValueKind())
6456 } else if (!S.Context.hasSameUnqualifiedType(
6457 ResultArg->getType(), ParamType.getNonReferenceType())) {
6458 // We can't perform this conversion.
6459 S.Diag(ResultArg->getBeginLoc(), diag::err_template_arg_not_convertible)
6460 << ResultArg->getType() << ParamType << ResultArg->getSourceRange();
6461 S.Diag(Param->getLocation(), diag::note_template_param_here);
6466 return S.Diag(Arg->getBeginLoc(),
6467 diag::err_template_arg_not_pointer_to_member_form)
6468 << Arg->getSourceRange();
6470 if (isa<FieldDecl>(DRE->getDecl()) ||
6471 isa<IndirectFieldDecl>(DRE->getDecl()) ||
6472 isa<CXXMethodDecl>(DRE->getDecl())) {
6473 assert((isa<FieldDecl>(DRE->getDecl()) ||
6474 isa<IndirectFieldDecl>(DRE->getDecl()) ||
6475 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
6476 "Only non-static member pointers can make it here");
6478 // Okay: this is the address of a non-static member, and therefore
6479 // a member pointer constant.
6480 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
6481 Converted = TemplateArgument(Arg);
6483 ValueDecl *D = cast<ValueDecl>(DRE->getDecl()->getCanonicalDecl());
6484 Converted = TemplateArgument(D, ParamType);
6489 // We found something else, but we don't know specifically what it is.
6490 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_pointer_to_member_form)
6491 << Arg->getSourceRange();
6492 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
6496 /// Check a template argument against its corresponding
6497 /// non-type template parameter.
6499 /// This routine implements the semantics of C++ [temp.arg.nontype].
6500 /// If an error occurred, it returns ExprError(); otherwise, it
6501 /// returns the converted template argument. \p ParamType is the
6502 /// type of the non-type template parameter after it has been instantiated.
6503 ExprResult Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
6504 QualType ParamType, Expr *Arg,
6505 TemplateArgument &Converted,
6506 CheckTemplateArgumentKind CTAK) {
6507 SourceLocation StartLoc = Arg->getBeginLoc();
6509 // If the parameter type somehow involves auto, deduce the type now.
6510 if (getLangOpts().CPlusPlus17 && ParamType->isUndeducedType()) {
6511 // During template argument deduction, we allow 'decltype(auto)' to
6512 // match an arbitrary dependent argument.
6513 // FIXME: The language rules don't say what happens in this case.
6514 // FIXME: We get an opaque dependent type out of decltype(auto) if the
6515 // expression is merely instantiation-dependent; is this enough?
6516 if (CTAK == CTAK_Deduced && Arg->isTypeDependent()) {
6517 auto *AT = dyn_cast<AutoType>(ParamType);
6518 if (AT && AT->isDecltypeAuto()) {
6519 Converted = TemplateArgument(Arg);
6524 // When checking a deduced template argument, deduce from its type even if
6525 // the type is dependent, in order to check the types of non-type template
6526 // arguments line up properly in partial ordering.
6527 Optional<unsigned> Depth = Param->getDepth() + 1;
6528 Expr *DeductionArg = Arg;
6529 if (auto *PE = dyn_cast<PackExpansionExpr>(DeductionArg))
6530 DeductionArg = PE->getPattern();
6532 Context.getTrivialTypeSourceInfo(ParamType, Param->getLocation()),
6533 DeductionArg, ParamType, Depth) == DAR_Failed) {
6534 Diag(Arg->getExprLoc(),
6535 diag::err_non_type_template_parm_type_deduction_failure)
6536 << Param->getDeclName() << Param->getType() << Arg->getType()
6537 << Arg->getSourceRange();
6538 Diag(Param->getLocation(), diag::note_template_param_here);
6541 // CheckNonTypeTemplateParameterType will produce a diagnostic if there's
6542 // an error. The error message normally references the parameter
6543 // declaration, but here we'll pass the argument location because that's
6544 // where the parameter type is deduced.
6545 ParamType = CheckNonTypeTemplateParameterType(ParamType, Arg->getExprLoc());
6546 if (ParamType.isNull()) {
6547 Diag(Param->getLocation(), diag::note_template_param_here);
6552 // We should have already dropped all cv-qualifiers by now.
6553 assert(!ParamType.hasQualifiers() &&
6554 "non-type template parameter type cannot be qualified");
6556 if (CTAK == CTAK_Deduced &&
6557 !Context.hasSameType(ParamType.getNonLValueExprType(Context),
6559 // FIXME: If either type is dependent, we skip the check. This isn't
6560 // correct, since during deduction we're supposed to have replaced each
6561 // template parameter with some unique (non-dependent) placeholder.
6562 // FIXME: If the argument type contains 'auto', we carry on and fail the
6563 // type check in order to force specific types to be more specialized than
6564 // 'auto'. It's not clear how partial ordering with 'auto' is supposed to
6566 if ((ParamType->isDependentType() || Arg->isTypeDependent()) &&
6567 !Arg->getType()->getContainedAutoType()) {
6568 Converted = TemplateArgument(Arg);
6571 // FIXME: This attempts to implement C++ [temp.deduct.type]p17. Per DR1770,
6572 // we should actually be checking the type of the template argument in P,
6573 // not the type of the template argument deduced from A, against the
6574 // template parameter type.
6575 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
6577 << ParamType.getUnqualifiedType();
6578 Diag(Param->getLocation(), diag::note_template_param_here);
6582 // If either the parameter has a dependent type or the argument is
6583 // type-dependent, there's nothing we can check now. The argument only
6584 // contains an unexpanded pack during partial ordering, and there's
6585 // nothing more we can check in that case.
6586 if (ParamType->isDependentType() || Arg->isTypeDependent() ||
6587 Arg->containsUnexpandedParameterPack()) {
6588 // Force the argument to the type of the parameter to maintain invariants.
6589 auto *PE = dyn_cast<PackExpansionExpr>(Arg);
6591 Arg = PE->getPattern();
6592 ExprResult E = ImpCastExprToType(
6593 Arg, ParamType.getNonLValueExprType(Context), CK_Dependent,
6594 ParamType->isLValueReferenceType() ? VK_LValue :
6595 ParamType->isRValueReferenceType() ? VK_XValue : VK_RValue);
6599 // Recreate a pack expansion if we unwrapped one.
6601 PackExpansionExpr(E.get()->getType(), E.get(), PE->getEllipsisLoc(),
6602 PE->getNumExpansions());
6604 Converted = TemplateArgument(E.get());
6608 // The initialization of the parameter from the argument is
6609 // a constant-evaluated context.
6610 EnterExpressionEvaluationContext ConstantEvaluated(
6611 *this, Sema::ExpressionEvaluationContext::ConstantEvaluated);
6613 if (getLangOpts().CPlusPlus17) {
6614 // C++17 [temp.arg.nontype]p1:
6615 // A template-argument for a non-type template parameter shall be
6616 // a converted constant expression of the type of the template-parameter.
6618 ExprResult ArgResult = CheckConvertedConstantExpression(
6619 Arg, ParamType, Value, CCEK_TemplateArg);
6620 if (ArgResult.isInvalid())
6623 // For a value-dependent argument, CheckConvertedConstantExpression is
6624 // permitted (and expected) to be unable to determine a value.
6625 if (ArgResult.get()->isValueDependent()) {
6626 Converted = TemplateArgument(ArgResult.get());
6630 QualType CanonParamType = Context.getCanonicalType(ParamType);
6632 // Convert the APValue to a TemplateArgument.
6633 switch (Value.getKind()) {
6635 assert(ParamType->isNullPtrType());
6636 Converted = TemplateArgument(CanonParamType, /*isNullPtr*/true);
6638 case APValue::Indeterminate:
6639 llvm_unreachable("result of constant evaluation should be initialized");
6642 assert(ParamType->isIntegralOrEnumerationType());
6643 Converted = TemplateArgument(Context, Value.getInt(), CanonParamType);
6645 case APValue::MemberPointer: {
6646 assert(ParamType->isMemberPointerType());
6648 // FIXME: We need TemplateArgument representation and mangling for these.
6649 if (!Value.getMemberPointerPath().empty()) {
6650 Diag(Arg->getBeginLoc(),
6651 diag::err_template_arg_member_ptr_base_derived_not_supported)
6652 << Value.getMemberPointerDecl() << ParamType
6653 << Arg->getSourceRange();
6657 auto *VD = const_cast<ValueDecl*>(Value.getMemberPointerDecl());
6658 Converted = VD ? TemplateArgument(VD, CanonParamType)
6659 : TemplateArgument(CanonParamType, /*isNullPtr*/true);
6662 case APValue::LValue: {
6663 // For a non-type template-parameter of pointer or reference type,
6664 // the value of the constant expression shall not refer to
6665 assert(ParamType->isPointerType() || ParamType->isReferenceType() ||
6666 ParamType->isNullPtrType());
6667 // -- a temporary object
6668 // -- a string literal
6669 // -- the result of a typeid expression, or
6670 // -- a predefined __func__ variable
6671 APValue::LValueBase Base = Value.getLValueBase();
6672 auto *VD = const_cast<ValueDecl *>(Base.dyn_cast<const ValueDecl *>());
6674 auto *E = Base.dyn_cast<const Expr *>();
6675 if (E && isa<CXXUuidofExpr>(E)) {
6676 Converted = TemplateArgument(ArgResult.get()->IgnoreImpCasts());
6679 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
6680 << Arg->getSourceRange();
6684 if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 &&
6685 VD && VD->getType()->isArrayType() &&
6686 Value.getLValuePath()[0].getAsArrayIndex() == 0 &&
6687 !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
6688 // Per defect report (no number yet):
6689 // ... other than a pointer to the first element of a complete array
6691 } else if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
6692 Value.isLValueOnePastTheEnd()) {
6693 Diag(StartLoc, diag::err_non_type_template_arg_subobject)
6694 << Value.getAsString(Context, ParamType);
6697 assert((VD || !ParamType->isReferenceType()) &&
6698 "null reference should not be a constant expression");
6699 assert((!VD || !ParamType->isNullPtrType()) &&
6700 "non-null value of type nullptr_t?");
6701 Converted = VD ? TemplateArgument(VD, CanonParamType)
6702 : TemplateArgument(CanonParamType, /*isNullPtr*/true);
6705 case APValue::AddrLabelDiff:
6706 return Diag(StartLoc, diag::err_non_type_template_arg_addr_label_diff);
6707 case APValue::FixedPoint:
6708 case APValue::Float:
6709 case APValue::ComplexInt:
6710 case APValue::ComplexFloat:
6711 case APValue::Vector:
6712 case APValue::Array:
6713 case APValue::Struct:
6714 case APValue::Union:
6715 llvm_unreachable("invalid kind for template argument");
6718 return ArgResult.get();
6721 // C++ [temp.arg.nontype]p5:
6722 // The following conversions are performed on each expression used
6723 // as a non-type template-argument. If a non-type
6724 // template-argument cannot be converted to the type of the
6725 // corresponding template-parameter then the program is
6727 if (ParamType->isIntegralOrEnumerationType()) {
6729 // -- for a non-type template-parameter of integral or
6730 // enumeration type, conversions permitted in a converted
6731 // constant expression are applied.
6734 // -- for a non-type template-parameter of integral or
6735 // enumeration type, integral promotions (4.5) and integral
6736 // conversions (4.7) are applied.
6738 if (getLangOpts().CPlusPlus11) {
6739 // C++ [temp.arg.nontype]p1:
6740 // A template-argument for a non-type, non-template template-parameter
6743 // -- for a non-type template-parameter of integral or enumeration
6744 // type, a converted constant expression of the type of the
6745 // template-parameter; or
6747 ExprResult ArgResult =
6748 CheckConvertedConstantExpression(Arg, ParamType, Value,
6750 if (ArgResult.isInvalid())
6753 // We can't check arbitrary value-dependent arguments.
6754 if (ArgResult.get()->isValueDependent()) {
6755 Converted = TemplateArgument(ArgResult.get());
6759 // Widen the argument value to sizeof(parameter type). This is almost
6760 // always a no-op, except when the parameter type is bool. In
6761 // that case, this may extend the argument from 1 bit to 8 bits.
6762 QualType IntegerType = ParamType;
6763 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
6764 IntegerType = Enum->getDecl()->getIntegerType();
6765 Value = Value.extOrTrunc(Context.getTypeSize(IntegerType));
6767 Converted = TemplateArgument(Context, Value,
6768 Context.getCanonicalType(ParamType));
6772 ExprResult ArgResult = DefaultLvalueConversion(Arg);
6773 if (ArgResult.isInvalid())
6775 Arg = ArgResult.get();
6777 QualType ArgType = Arg->getType();
6779 // C++ [temp.arg.nontype]p1:
6780 // A template-argument for a non-type, non-template
6781 // template-parameter shall be one of:
6783 // -- an integral constant-expression of integral or enumeration
6785 // -- the name of a non-type template-parameter; or
6787 if (!ArgType->isIntegralOrEnumerationType()) {
6788 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_integral_or_enumeral)
6789 << ArgType << Arg->getSourceRange();
6790 Diag(Param->getLocation(), diag::note_template_param_here);
6792 } else if (!Arg->isValueDependent()) {
6793 class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
6797 TmplArgICEDiagnoser(QualType T) : T(T) { }
6799 void diagnoseNotICE(Sema &S, SourceLocation Loc,
6800 SourceRange SR) override {
6801 S.Diag(Loc, diag::err_template_arg_not_ice) << T << SR;
6803 } Diagnoser(ArgType);
6805 Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser,
6811 // From here on out, all we care about is the unqualified form
6812 // of the argument type.
6813 ArgType = ArgType.getUnqualifiedType();
6815 // Try to convert the argument to the parameter's type.
6816 if (Context.hasSameType(ParamType, ArgType)) {
6817 // Okay: no conversion necessary
6818 } else if (ParamType->isBooleanType()) {
6819 // This is an integral-to-boolean conversion.
6820 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).get();
6821 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
6822 !ParamType->isEnumeralType()) {
6823 // This is an integral promotion or conversion.
6824 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).get();
6826 // We can't perform this conversion.
6827 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_convertible)
6828 << Arg->getType() << ParamType << Arg->getSourceRange();
6829 Diag(Param->getLocation(), diag::note_template_param_here);
6833 // Add the value of this argument to the list of converted
6834 // arguments. We use the bitwidth and signedness of the template
6836 if (Arg->isValueDependent()) {
6837 // The argument is value-dependent. Create a new
6838 // TemplateArgument with the converted expression.
6839 Converted = TemplateArgument(Arg);
6843 QualType IntegerType = Context.getCanonicalType(ParamType);
6844 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
6845 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
6847 if (ParamType->isBooleanType()) {
6848 // Value must be zero or one.
6850 unsigned AllowedBits = Context.getTypeSize(IntegerType);
6851 if (Value.getBitWidth() != AllowedBits)
6852 Value = Value.extOrTrunc(AllowedBits);
6853 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
6855 llvm::APSInt OldValue = Value;
6857 // Coerce the template argument's value to the value it will have
6858 // based on the template parameter's type.
6859 unsigned AllowedBits = Context.getTypeSize(IntegerType);
6860 if (Value.getBitWidth() != AllowedBits)
6861 Value = Value.extOrTrunc(AllowedBits);
6862 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
6864 // Complain if an unsigned parameter received a negative value.
6865 if (IntegerType->isUnsignedIntegerOrEnumerationType()
6866 && (OldValue.isSigned() && OldValue.isNegative())) {
6867 Diag(Arg->getBeginLoc(), diag::warn_template_arg_negative)
6868 << OldValue.toString(10) << Value.toString(10) << Param->getType()
6869 << Arg->getSourceRange();
6870 Diag(Param->getLocation(), diag::note_template_param_here);
6873 // Complain if we overflowed the template parameter's type.
6874 unsigned RequiredBits;
6875 if (IntegerType->isUnsignedIntegerOrEnumerationType())
6876 RequiredBits = OldValue.getActiveBits();
6877 else if (OldValue.isUnsigned())
6878 RequiredBits = OldValue.getActiveBits() + 1;
6880 RequiredBits = OldValue.getMinSignedBits();
6881 if (RequiredBits > AllowedBits) {
6882 Diag(Arg->getBeginLoc(), diag::warn_template_arg_too_large)
6883 << OldValue.toString(10) << Value.toString(10) << Param->getType()
6884 << Arg->getSourceRange();
6885 Diag(Param->getLocation(), diag::note_template_param_here);
6889 Converted = TemplateArgument(Context, Value,
6890 ParamType->isEnumeralType()
6891 ? Context.getCanonicalType(ParamType)
6896 QualType ArgType = Arg->getType();
6897 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
6899 // Handle pointer-to-function, reference-to-function, and
6900 // pointer-to-member-function all in (roughly) the same way.
6901 if (// -- For a non-type template-parameter of type pointer to
6902 // function, only the function-to-pointer conversion (4.3) is
6903 // applied. If the template-argument represents a set of
6904 // overloaded functions (or a pointer to such), the matching
6905 // function is selected from the set (13.4).
6906 (ParamType->isPointerType() &&
6907 ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType()) ||
6908 // -- For a non-type template-parameter of type reference to
6909 // function, no conversions apply. If the template-argument
6910 // represents a set of overloaded functions, the matching
6911 // function is selected from the set (13.4).
6912 (ParamType->isReferenceType() &&
6913 ParamType->castAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
6914 // -- For a non-type template-parameter of type pointer to
6915 // member function, no conversions apply. If the
6916 // template-argument represents a set of overloaded member
6917 // functions, the matching member function is selected from
6919 (ParamType->isMemberPointerType() &&
6920 ParamType->castAs<MemberPointerType>()->getPointeeType()
6921 ->isFunctionType())) {
6923 if (Arg->getType() == Context.OverloadTy) {
6924 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
6927 if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc()))
6930 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
6931 ArgType = Arg->getType();
6936 if (!ParamType->isMemberPointerType()) {
6937 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
6944 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
6950 if (ParamType->isPointerType()) {
6951 // -- for a non-type template-parameter of type pointer to
6952 // object, qualification conversions (4.4) and the
6953 // array-to-pointer conversion (4.2) are applied.
6954 // C++0x also allows a value of std::nullptr_t.
6955 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
6956 "Only object pointers allowed here");
6958 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
6965 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
6966 // -- For a non-type template-parameter of type reference to
6967 // object, no conversions apply. The type referred to by the
6968 // reference may be more cv-qualified than the (otherwise
6969 // identical) type of the template-argument. The
6970 // template-parameter is bound directly to the
6971 // template-argument, which must be an lvalue.
6972 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
6973 "Only object references allowed here");
6975 if (Arg->getType() == Context.OverloadTy) {
6976 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
6977 ParamRefType->getPointeeType(),
6980 if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc()))
6983 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
6984 ArgType = Arg->getType();
6989 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
6996 // Deal with parameters of type std::nullptr_t.
6997 if (ParamType->isNullPtrType()) {
6998 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
6999 Converted = TemplateArgument(Arg);
7003 switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) {
7004 case NPV_NotNullPointer:
7005 Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
7006 << Arg->getType() << ParamType;
7007 Diag(Param->getLocation(), diag::note_template_param_here);
7013 case NPV_NullPointer:
7014 Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
7015 Converted = TemplateArgument(Context.getCanonicalType(ParamType),
7021 // -- For a non-type template-parameter of type pointer to data
7022 // member, qualification conversions (4.4) are applied.
7023 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
7025 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
7031 static void DiagnoseTemplateParameterListArityMismatch(
7032 Sema &S, TemplateParameterList *New, TemplateParameterList *Old,
7033 Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc);
7035 /// Check a template argument against its corresponding
7036 /// template template parameter.
7038 /// This routine implements the semantics of C++ [temp.arg.template].
7039 /// It returns true if an error occurred, and false otherwise.
7040 bool Sema::CheckTemplateTemplateArgument(TemplateTemplateParmDecl *Param,
7041 TemplateParameterList *Params,
7042 TemplateArgumentLoc &Arg) {
7043 TemplateName Name = Arg.getArgument().getAsTemplateOrTemplatePattern();
7044 TemplateDecl *Template = Name.getAsTemplateDecl();
7046 // Any dependent template name is fine.
7047 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
7051 if (Template->isInvalidDecl())
7054 // C++0x [temp.arg.template]p1:
7055 // A template-argument for a template template-parameter shall be
7056 // the name of a class template or an alias template, expressed as an
7057 // id-expression. When the template-argument names a class template, only
7058 // primary class templates are considered when matching the
7059 // template template argument with the corresponding parameter;
7060 // partial specializations are not considered even if their
7061 // parameter lists match that of the template template parameter.
7063 // Note that we also allow template template parameters here, which
7064 // will happen when we are dealing with, e.g., class template
7065 // partial specializations.
7066 if (!isa<ClassTemplateDecl>(Template) &&
7067 !isa<TemplateTemplateParmDecl>(Template) &&
7068 !isa<TypeAliasTemplateDecl>(Template) &&
7069 !isa<BuiltinTemplateDecl>(Template)) {
7070 assert(isa<FunctionTemplateDecl>(Template) &&
7071 "Only function templates are possible here");
7072 Diag(Arg.getLocation(), diag::err_template_arg_not_valid_template);
7073 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
7077 // C++1z [temp.arg.template]p3: (DR 150)
7078 // A template-argument matches a template template-parameter P when P
7079 // is at least as specialized as the template-argument A.
7080 // FIXME: We should enable RelaxedTemplateTemplateArgs by default as it is a
7081 // defect report resolution from C++17 and shouldn't be introduced by
7083 if (getLangOpts().RelaxedTemplateTemplateArgs) {
7084 // Quick check for the common case:
7085 // If P contains a parameter pack, then A [...] matches P if each of A's
7086 // template parameters matches the corresponding template parameter in
7087 // the template-parameter-list of P.
7088 if (TemplateParameterListsAreEqual(
7089 Template->getTemplateParameters(), Params, false,
7090 TPL_TemplateTemplateArgumentMatch, Arg.getLocation()) &&
7091 // If the argument has no associated constraints, then the parameter is
7092 // definitely at least as specialized as the argument.
7093 // Otherwise - we need a more thorough check.
7094 !Template->hasAssociatedConstraints())
7097 if (isTemplateTemplateParameterAtLeastAsSpecializedAs(Params, Template,
7098 Arg.getLocation())) {
7099 // C++2a[temp.func.order]p2
7100 // [...] If both deductions succeed, the partial ordering selects the
7101 // more constrained template as described by the rules in
7102 // [temp.constr.order].
7103 SmallVector<const Expr *, 3> ParamsAC, TemplateAC;
7104 Params->getAssociatedConstraints(ParamsAC);
7105 Template->getAssociatedConstraints(TemplateAC);
7106 bool IsParamAtLeastAsConstrained;
7107 if (IsAtLeastAsConstrained(Param, ParamsAC, Template, TemplateAC,
7108 IsParamAtLeastAsConstrained))
7110 if (!IsParamAtLeastAsConstrained) {
7111 Diag(Arg.getLocation(),
7112 diag::err_template_template_parameter_not_at_least_as_constrained)
7113 << Template << Param << Arg.getSourceRange();
7114 Diag(Param->getLocation(), diag::note_entity_declared_at) << Param;
7115 Diag(Template->getLocation(), diag::note_entity_declared_at)
7117 MaybeEmitAmbiguousAtomicConstraintsDiagnostic(Param, ParamsAC, Template,
7123 // FIXME: Produce better diagnostics for deduction failures.
7126 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
7129 TPL_TemplateTemplateArgumentMatch,
7133 /// Given a non-type template argument that refers to a
7134 /// declaration and the type of its corresponding non-type template
7135 /// parameter, produce an expression that properly refers to that
7138 Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
7140 SourceLocation Loc) {
7141 // C++ [temp.param]p8:
7143 // A non-type template-parameter of type "array of T" or
7144 // "function returning T" is adjusted to be of type "pointer to
7145 // T" or "pointer to function returning T", respectively.
7146 if (ParamType->isArrayType())
7147 ParamType = Context.getArrayDecayedType(ParamType);
7148 else if (ParamType->isFunctionType())
7149 ParamType = Context.getPointerType(ParamType);
7151 // For a NULL non-type template argument, return nullptr casted to the
7152 // parameter's type.
7153 if (Arg.getKind() == TemplateArgument::NullPtr) {
7154 return ImpCastExprToType(
7155 new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),
7157 ParamType->getAs<MemberPointerType>()
7158 ? CK_NullToMemberPointer
7159 : CK_NullToPointer);
7161 assert(Arg.getKind() == TemplateArgument::Declaration &&
7162 "Only declaration template arguments permitted here");
7164 ValueDecl *VD = Arg.getAsDecl();
7167 if (ParamType->isMemberPointerType()) {
7168 // If this is a pointer to member, we need to use a qualified name to
7169 // form a suitable pointer-to-member constant.
7170 assert(VD->getDeclContext()->isRecord() &&
7171 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
7172 isa<IndirectFieldDecl>(VD)));
7174 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
7175 NestedNameSpecifier *Qualifier
7176 = NestedNameSpecifier::Create(Context, nullptr, false,
7177 ClassType.getTypePtr());
7178 SS.MakeTrivial(Context, Qualifier, Loc);
7181 ExprResult RefExpr = BuildDeclarationNameExpr(
7182 SS, DeclarationNameInfo(VD->getDeclName(), Loc), VD);
7183 if (RefExpr.isInvalid())
7186 // For a pointer, the argument declaration is the pointee. Take its address.
7187 QualType ElemT(RefExpr.get()->getType()->getArrayElementTypeNoTypeQual(), 0);
7188 if (ParamType->isPointerType() && !ElemT.isNull() &&
7189 Context.hasSimilarType(ElemT, ParamType->getPointeeType())) {
7190 // Decay an array argument if we want a pointer to its first element.
7191 RefExpr = DefaultFunctionArrayConversion(RefExpr.get());
7192 if (RefExpr.isInvalid())
7194 } else if (ParamType->isPointerType() || ParamType->isMemberPointerType()) {
7195 // For any other pointer, take the address (or form a pointer-to-member).
7196 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
7197 if (RefExpr.isInvalid())
7200 assert(ParamType->isReferenceType() &&
7201 "unexpected type for decl template argument");
7204 // At this point we should have the right value category.
7205 assert(ParamType->isReferenceType() == RefExpr.get()->isLValue() &&
7206 "value kind mismatch for non-type template argument");
7208 // The type of the template parameter can differ from the type of the
7209 // argument in various ways; convert it now if necessary.
7210 QualType DestExprType = ParamType.getNonLValueExprType(Context);
7211 if (!Context.hasSameType(RefExpr.get()->getType(), DestExprType)) {
7214 if (Context.hasSimilarType(RefExpr.get()->getType(), DestExprType) ||
7215 IsFunctionConversion(RefExpr.get()->getType(), DestExprType, Ignored)) {
7217 } else if (ParamType->isVoidPointerType() &&
7218 RefExpr.get()->getType()->isPointerType()) {
7221 // FIXME: Pointers to members can need conversion derived-to-base or
7222 // base-to-derived conversions. We currently don't retain enough
7223 // information to convert properly (we need to track a cast path or
7224 // subobject number in the template argument).
7226 "unexpected conversion required for non-type template argument");
7228 RefExpr = ImpCastExprToType(RefExpr.get(), DestExprType, CK,
7229 RefExpr.get()->getValueKind());
7235 /// Construct a new expression that refers to the given
7236 /// integral template argument with the given source-location
7239 /// This routine takes care of the mapping from an integral template
7240 /// argument (which may have any integral type) to the appropriate
7243 Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
7244 SourceLocation Loc) {
7245 assert(Arg.getKind() == TemplateArgument::Integral &&
7246 "Operation is only valid for integral template arguments");
7247 QualType OrigT = Arg.getIntegralType();
7249 // If this is an enum type that we're instantiating, we need to use an integer
7250 // type the same size as the enumerator. We don't want to build an
7251 // IntegerLiteral with enum type. The integer type of an enum type can be of
7252 // any integral type with C++11 enum classes, make sure we create the right
7253 // type of literal for it.
7255 if (const EnumType *ET = OrigT->getAs<EnumType>())
7256 T = ET->getDecl()->getIntegerType();
7259 if (T->isAnyCharacterType()) {
7260 CharacterLiteral::CharacterKind Kind;
7261 if (T->isWideCharType())
7262 Kind = CharacterLiteral::Wide;
7263 else if (T->isChar8Type() && getLangOpts().Char8)
7264 Kind = CharacterLiteral::UTF8;
7265 else if (T->isChar16Type())
7266 Kind = CharacterLiteral::UTF16;
7267 else if (T->isChar32Type())
7268 Kind = CharacterLiteral::UTF32;
7270 Kind = CharacterLiteral::Ascii;
7272 E = new (Context) CharacterLiteral(Arg.getAsIntegral().getZExtValue(),
7274 } else if (T->isBooleanType()) {
7275 E = new (Context) CXXBoolLiteralExpr(Arg.getAsIntegral().getBoolValue(),
7277 } else if (T->isNullPtrType()) {
7278 E = new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
7280 E = IntegerLiteral::Create(Context, Arg.getAsIntegral(), T, Loc);
7283 if (OrigT->isEnumeralType()) {
7284 // FIXME: This is a hack. We need a better way to handle substituted
7285 // non-type template parameters.
7286 E = CStyleCastExpr::Create(Context, OrigT, VK_RValue, CK_IntegralCast, E,
7288 Context.getTrivialTypeSourceInfo(OrigT, Loc),
7295 /// Match two template parameters within template parameter lists.
7296 static bool MatchTemplateParameterKind(Sema &S, NamedDecl *New, NamedDecl *Old,
7298 Sema::TemplateParameterListEqualKind Kind,
7299 SourceLocation TemplateArgLoc) {
7300 // Check the actual kind (type, non-type, template).
7301 if (Old->getKind() != New->getKind()) {
7303 unsigned NextDiag = diag::err_template_param_different_kind;
7304 if (TemplateArgLoc.isValid()) {
7305 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
7306 NextDiag = diag::note_template_param_different_kind;
7308 S.Diag(New->getLocation(), NextDiag)
7309 << (Kind != Sema::TPL_TemplateMatch);
7310 S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
7311 << (Kind != Sema::TPL_TemplateMatch);
7317 // Check that both are parameter packs or neither are parameter packs.
7318 // However, if we are matching a template template argument to a
7319 // template template parameter, the template template parameter can have
7320 // a parameter pack where the template template argument does not.
7321 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack() &&
7322 !(Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
7323 Old->isTemplateParameterPack())) {
7325 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
7326 if (TemplateArgLoc.isValid()) {
7327 S.Diag(TemplateArgLoc,
7328 diag::err_template_arg_template_params_mismatch);
7329 NextDiag = diag::note_template_parameter_pack_non_pack;
7332 unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
7333 : isa<NonTypeTemplateParmDecl>(New)? 1
7335 S.Diag(New->getLocation(), NextDiag)
7336 << ParamKind << New->isParameterPack();
7337 S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
7338 << ParamKind << Old->isParameterPack();
7344 // For non-type template parameters, check the type of the parameter.
7345 if (NonTypeTemplateParmDecl *OldNTTP
7346 = dyn_cast<NonTypeTemplateParmDecl>(Old)) {
7347 NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(New);
7349 // If we are matching a template template argument to a template
7350 // template parameter and one of the non-type template parameter types
7351 // is dependent, then we must wait until template instantiation time
7352 // to actually compare the arguments.
7353 if (Kind != Sema::TPL_TemplateTemplateArgumentMatch ||
7354 (!OldNTTP->getType()->isDependentType() &&
7355 !NewNTTP->getType()->isDependentType()))
7356 if (!S.Context.hasSameType(OldNTTP->getType(), NewNTTP->getType())) {
7358 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
7359 if (TemplateArgLoc.isValid()) {
7360 S.Diag(TemplateArgLoc,
7361 diag::err_template_arg_template_params_mismatch);
7362 NextDiag = diag::note_template_nontype_parm_different_type;
7364 S.Diag(NewNTTP->getLocation(), NextDiag)
7365 << NewNTTP->getType()
7366 << (Kind != Sema::TPL_TemplateMatch);
7367 S.Diag(OldNTTP->getLocation(),
7368 diag::note_template_nontype_parm_prev_declaration)
7369 << OldNTTP->getType();
7375 // For template template parameters, check the template parameter types.
7376 // The template parameter lists of template template
7377 // parameters must agree.
7378 else if (TemplateTemplateParmDecl *OldTTP
7379 = dyn_cast<TemplateTemplateParmDecl>(Old)) {
7380 TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(New);
7381 if (!S.TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
7382 OldTTP->getTemplateParameters(),
7384 (Kind == Sema::TPL_TemplateMatch
7385 ? Sema::TPL_TemplateTemplateParmMatch
7389 } else if (Kind != Sema::TPL_TemplateTemplateArgumentMatch) {
7390 const Expr *NewC = nullptr, *OldC = nullptr;
7391 if (const auto *TC = cast<TemplateTypeParmDecl>(New)->getTypeConstraint())
7392 NewC = TC->getImmediatelyDeclaredConstraint();
7393 if (const auto *TC = cast<TemplateTypeParmDecl>(Old)->getTypeConstraint())
7394 OldC = TC->getImmediatelyDeclaredConstraint();
7396 auto Diagnose = [&] {
7397 S.Diag(NewC ? NewC->getBeginLoc() : New->getBeginLoc(),
7398 diag::err_template_different_type_constraint);
7399 S.Diag(OldC ? OldC->getBeginLoc() : Old->getBeginLoc(),
7400 diag::note_template_prev_declaration) << /*declaration*/0;
7403 if (!NewC != !OldC) {
7410 llvm::FoldingSetNodeID OldCID, NewCID;
7411 OldC->Profile(OldCID, S.Context, /*Canonical=*/true);
7412 NewC->Profile(NewCID, S.Context, /*Canonical=*/true);
7413 if (OldCID != NewCID) {
7424 /// Diagnose a known arity mismatch when comparing template argument
7427 void DiagnoseTemplateParameterListArityMismatch(Sema &S,
7428 TemplateParameterList *New,
7429 TemplateParameterList *Old,
7430 Sema::TemplateParameterListEqualKind Kind,
7431 SourceLocation TemplateArgLoc) {
7432 unsigned NextDiag = diag::err_template_param_list_different_arity;
7433 if (TemplateArgLoc.isValid()) {
7434 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
7435 NextDiag = diag::note_template_param_list_different_arity;
7437 S.Diag(New->getTemplateLoc(), NextDiag)
7438 << (New->size() > Old->size())
7439 << (Kind != Sema::TPL_TemplateMatch)
7440 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
7441 S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
7442 << (Kind != Sema::TPL_TemplateMatch)
7443 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
7446 /// Determine whether the given template parameter lists are
7449 /// \param New The new template parameter list, typically written in the
7450 /// source code as part of a new template declaration.
7452 /// \param Old The old template parameter list, typically found via
7453 /// name lookup of the template declared with this template parameter
7456 /// \param Complain If true, this routine will produce a diagnostic if
7457 /// the template parameter lists are not equivalent.
7459 /// \param Kind describes how we are to match the template parameter lists.
7461 /// \param TemplateArgLoc If this source location is valid, then we
7462 /// are actually checking the template parameter list of a template
7463 /// argument (New) against the template parameter list of its
7464 /// corresponding template template parameter (Old). We produce
7465 /// slightly different diagnostics in this scenario.
7467 /// \returns True if the template parameter lists are equal, false
7470 Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
7471 TemplateParameterList *Old,
7473 TemplateParameterListEqualKind Kind,
7474 SourceLocation TemplateArgLoc) {
7475 if (Old->size() != New->size() && Kind != TPL_TemplateTemplateArgumentMatch) {
7477 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
7483 // C++0x [temp.arg.template]p3:
7484 // A template-argument matches a template template-parameter (call it P)
7485 // when each of the template parameters in the template-parameter-list of
7486 // the template-argument's corresponding class template or alias template
7487 // (call it A) matches the corresponding template parameter in the
7488 // template-parameter-list of P. [...]
7489 TemplateParameterList::iterator NewParm = New->begin();
7490 TemplateParameterList::iterator NewParmEnd = New->end();
7491 for (TemplateParameterList::iterator OldParm = Old->begin(),
7492 OldParmEnd = Old->end();
7493 OldParm != OldParmEnd; ++OldParm) {
7494 if (Kind != TPL_TemplateTemplateArgumentMatch ||
7495 !(*OldParm)->isTemplateParameterPack()) {
7496 if (NewParm == NewParmEnd) {
7498 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
7504 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
7505 Kind, TemplateArgLoc))
7512 // C++0x [temp.arg.template]p3:
7513 // [...] When P's template- parameter-list contains a template parameter
7514 // pack (14.5.3), the template parameter pack will match zero or more
7515 // template parameters or template parameter packs in the
7516 // template-parameter-list of A with the same type and form as the
7517 // template parameter pack in P (ignoring whether those template
7518 // parameters are template parameter packs).
7519 for (; NewParm != NewParmEnd; ++NewParm) {
7520 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
7521 Kind, TemplateArgLoc))
7526 // Make sure we exhausted all of the arguments.
7527 if (NewParm != NewParmEnd) {
7529 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
7535 if (Kind != TPL_TemplateTemplateArgumentMatch) {
7536 const Expr *NewRC = New->getRequiresClause();
7537 const Expr *OldRC = Old->getRequiresClause();
7539 auto Diagnose = [&] {
7540 Diag(NewRC ? NewRC->getBeginLoc() : New->getTemplateLoc(),
7541 diag::err_template_different_requires_clause);
7542 Diag(OldRC ? OldRC->getBeginLoc() : Old->getTemplateLoc(),
7543 diag::note_template_prev_declaration) << /*declaration*/0;
7546 if (!NewRC != !OldRC) {
7553 llvm::FoldingSetNodeID OldRCID, NewRCID;
7554 OldRC->Profile(OldRCID, Context, /*Canonical=*/true);
7555 NewRC->Profile(NewRCID, Context, /*Canonical=*/true);
7556 if (OldRCID != NewRCID) {
7567 /// Check whether a template can be declared within this scope.
7569 /// If the template declaration is valid in this scope, returns
7570 /// false. Otherwise, issues a diagnostic and returns true.
7572 Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
7576 // Find the nearest enclosing declaration scope.
7577 while ((S->getFlags() & Scope::DeclScope) == 0 ||
7578 (S->getFlags() & Scope::TemplateParamScope) != 0)
7582 // A template [...] shall not have C linkage.
7583 DeclContext *Ctx = S->getEntity();
7584 assert(Ctx && "Unknown context");
7585 if (Ctx->isExternCContext()) {
7586 Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
7587 << TemplateParams->getSourceRange();
7588 if (const LinkageSpecDecl *LSD = Ctx->getExternCContext())
7589 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
7592 Ctx = Ctx->getRedeclContext();
7595 // A template-declaration can appear only as a namespace scope or
7596 // class scope declaration.
7598 if (Ctx->isFileContext())
7600 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Ctx)) {
7601 // C++ [temp.mem]p2:
7602 // A local class shall not have member templates.
7603 if (RD->isLocalClass())
7604 return Diag(TemplateParams->getTemplateLoc(),
7605 diag::err_template_inside_local_class)
7606 << TemplateParams->getSourceRange();
7612 return Diag(TemplateParams->getTemplateLoc(),
7613 diag::err_template_outside_namespace_or_class_scope)
7614 << TemplateParams->getSourceRange();
7617 /// Determine what kind of template specialization the given declaration
7619 static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D) {
7621 return TSK_Undeclared;
7623 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
7624 return Record->getTemplateSpecializationKind();
7625 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
7626 return Function->getTemplateSpecializationKind();
7627 if (VarDecl *Var = dyn_cast<VarDecl>(D))
7628 return Var->getTemplateSpecializationKind();
7630 return TSK_Undeclared;
7633 /// Check whether a specialization is well-formed in the current
7636 /// This routine determines whether a template specialization can be declared
7637 /// in the current context (C++ [temp.expl.spec]p2).
7639 /// \param S the semantic analysis object for which this check is being
7642 /// \param Specialized the entity being specialized or instantiated, which
7643 /// may be a kind of template (class template, function template, etc.) or
7644 /// a member of a class template (member function, static data member,
7647 /// \param PrevDecl the previous declaration of this entity, if any.
7649 /// \param Loc the location of the explicit specialization or instantiation of
7652 /// \param IsPartialSpecialization whether this is a partial specialization of
7653 /// a class template.
7655 /// \returns true if there was an error that we cannot recover from, false
7657 static bool CheckTemplateSpecializationScope(Sema &S,
7658 NamedDecl *Specialized,
7659 NamedDecl *PrevDecl,
7661 bool IsPartialSpecialization) {
7662 // Keep these "kind" numbers in sync with the %select statements in the
7663 // various diagnostics emitted by this routine.
7665 if (isa<ClassTemplateDecl>(Specialized))
7666 EntityKind = IsPartialSpecialization? 1 : 0;
7667 else if (isa<VarTemplateDecl>(Specialized))
7668 EntityKind = IsPartialSpecialization ? 3 : 2;
7669 else if (isa<FunctionTemplateDecl>(Specialized))
7671 else if (isa<CXXMethodDecl>(Specialized))
7673 else if (isa<VarDecl>(Specialized))
7675 else if (isa<RecordDecl>(Specialized))
7677 else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11)
7680 S.Diag(Loc, diag::err_template_spec_unknown_kind)
7681 << S.getLangOpts().CPlusPlus11;
7682 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
7686 // C++ [temp.expl.spec]p2:
7687 // An explicit specialization may be declared in any scope in which
7688 // the corresponding primary template may be defined.
7689 if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
7690 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
7695 // C++ [temp.class.spec]p6:
7696 // A class template partial specialization may be declared in any
7697 // scope in which the primary template may be defined.
7698 DeclContext *SpecializedContext =
7699 Specialized->getDeclContext()->getRedeclContext();
7700 DeclContext *DC = S.CurContext->getRedeclContext();
7702 // Make sure that this redeclaration (or definition) occurs in the same
7703 // scope or an enclosing namespace.
7704 if (!(DC->isFileContext() ? DC->Encloses(SpecializedContext)
7705 : DC->Equals(SpecializedContext))) {
7706 if (isa<TranslationUnitDecl>(SpecializedContext))
7707 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
7708 << EntityKind << Specialized;
7710 auto *ND = cast<NamedDecl>(SpecializedContext);
7711 int Diag = diag::err_template_spec_redecl_out_of_scope;
7712 if (S.getLangOpts().MicrosoftExt && !DC->isRecord())
7713 Diag = diag::ext_ms_template_spec_redecl_out_of_scope;
7714 S.Diag(Loc, Diag) << EntityKind << Specialized
7715 << ND << isa<CXXRecordDecl>(ND);
7718 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
7720 // Don't allow specializing in the wrong class during error recovery.
7721 // Otherwise, things can go horribly wrong.
7729 static SourceRange findTemplateParameterInType(unsigned Depth, Expr *E) {
7730 if (!E->isTypeDependent())
7731 return SourceLocation();
7732 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
7733 Checker.TraverseStmt(E);
7734 if (Checker.MatchLoc.isInvalid())
7735 return E->getSourceRange();
7736 return Checker.MatchLoc;
7739 static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
7740 if (!TL.getType()->isDependentType())
7741 return SourceLocation();
7742 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
7743 Checker.TraverseTypeLoc(TL);
7744 if (Checker.MatchLoc.isInvalid())
7745 return TL.getSourceRange();
7746 return Checker.MatchLoc;
7749 /// Subroutine of Sema::CheckTemplatePartialSpecializationArgs
7750 /// that checks non-type template partial specialization arguments.
7751 static bool CheckNonTypeTemplatePartialSpecializationArgs(
7752 Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
7753 const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
7754 for (unsigned I = 0; I != NumArgs; ++I) {
7755 if (Args[I].getKind() == TemplateArgument::Pack) {
7756 if (CheckNonTypeTemplatePartialSpecializationArgs(
7757 S, TemplateNameLoc, Param, Args[I].pack_begin(),
7758 Args[I].pack_size(), IsDefaultArgument))
7764 if (Args[I].getKind() != TemplateArgument::Expression)
7767 Expr *ArgExpr = Args[I].getAsExpr();
7769 // We can have a pack expansion of any of the bullets below.
7770 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
7771 ArgExpr = Expansion->getPattern();
7773 // Strip off any implicit casts we added as part of type checking.
7774 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
7775 ArgExpr = ICE->getSubExpr();
7777 // C++ [temp.class.spec]p8:
7778 // A non-type argument is non-specialized if it is the name of a
7779 // non-type parameter. All other non-type arguments are
7782 // Below, we check the two conditions that only apply to
7783 // specialized non-type arguments, so skip any non-specialized
7785 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
7786 if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
7789 // C++ [temp.class.spec]p9:
7790 // Within the argument list of a class template partial
7791 // specialization, the following restrictions apply:
7792 // -- A partially specialized non-type argument expression
7793 // shall not involve a template parameter of the partial
7794 // specialization except when the argument expression is a
7795 // simple identifier.
7796 // -- The type of a template parameter corresponding to a
7797 // specialized non-type argument shall not be dependent on a
7798 // parameter of the specialization.
7799 // DR1315 removes the first bullet, leaving an incoherent set of rules.
7800 // We implement a compromise between the original rules and DR1315:
7801 // -- A specialized non-type template argument shall not be
7802 // type-dependent and the corresponding template parameter
7803 // shall have a non-dependent type.
7804 SourceRange ParamUseRange =
7805 findTemplateParameterInType(Param->getDepth(), ArgExpr);
7806 if (ParamUseRange.isValid()) {
7807 if (IsDefaultArgument) {
7808 S.Diag(TemplateNameLoc,
7809 diag::err_dependent_non_type_arg_in_partial_spec);
7810 S.Diag(ParamUseRange.getBegin(),
7811 diag::note_dependent_non_type_default_arg_in_partial_spec)
7814 S.Diag(ParamUseRange.getBegin(),
7815 diag::err_dependent_non_type_arg_in_partial_spec)
7821 ParamUseRange = findTemplateParameter(
7822 Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc());
7823 if (ParamUseRange.isValid()) {
7824 S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getBeginLoc(),
7825 diag::err_dependent_typed_non_type_arg_in_partial_spec)
7826 << Param->getType();
7827 S.Diag(Param->getLocation(), diag::note_template_param_here)
7828 << (IsDefaultArgument ? ParamUseRange : SourceRange())
7837 /// Check the non-type template arguments of a class template
7838 /// partial specialization according to C++ [temp.class.spec]p9.
7840 /// \param TemplateNameLoc the location of the template name.
7841 /// \param PrimaryTemplate the template parameters of the primary class
7843 /// \param NumExplicit the number of explicitly-specified template arguments.
7844 /// \param TemplateArgs the template arguments of the class template
7845 /// partial specialization.
7847 /// \returns \c true if there was an error, \c false otherwise.
7848 bool Sema::CheckTemplatePartialSpecializationArgs(
7849 SourceLocation TemplateNameLoc, TemplateDecl *PrimaryTemplate,
7850 unsigned NumExplicit, ArrayRef<TemplateArgument> TemplateArgs) {
7851 // We have to be conservative when checking a template in a dependent
7853 if (PrimaryTemplate->getDeclContext()->isDependentContext())
7856 TemplateParameterList *TemplateParams =
7857 PrimaryTemplate->getTemplateParameters();
7858 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
7859 NonTypeTemplateParmDecl *Param
7860 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
7864 if (CheckNonTypeTemplatePartialSpecializationArgs(*this, TemplateNameLoc,
7865 Param, &TemplateArgs[I],
7866 1, I >= NumExplicit))
7873 DeclResult Sema::ActOnClassTemplateSpecialization(
7874 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
7875 SourceLocation ModulePrivateLoc, TemplateIdAnnotation &TemplateId,
7876 const ParsedAttributesView &Attr,
7877 MultiTemplateParamsArg TemplateParameterLists, SkipBodyInfo *SkipBody) {
7878 assert(TUK != TUK_Reference && "References are not specializations");
7880 CXXScopeSpec &SS = TemplateId.SS;
7882 // NOTE: KWLoc is the location of the tag keyword. This will instead
7883 // store the location of the outermost template keyword in the declaration.
7884 SourceLocation TemplateKWLoc = TemplateParameterLists.size() > 0
7885 ? TemplateParameterLists[0]->getTemplateLoc() : KWLoc;
7886 SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
7887 SourceLocation LAngleLoc = TemplateId.LAngleLoc;
7888 SourceLocation RAngleLoc = TemplateId.RAngleLoc;
7890 // Find the class template we're specializing
7891 TemplateName Name = TemplateId.Template.get();
7892 ClassTemplateDecl *ClassTemplate
7893 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
7895 if (!ClassTemplate) {
7896 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
7897 << (Name.getAsTemplateDecl() &&
7898 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
7902 bool isMemberSpecialization = false;
7903 bool isPartialSpecialization = false;
7905 // Check the validity of the template headers that introduce this
7907 // FIXME: We probably shouldn't complain about these headers for
7908 // friend declarations.
7909 bool Invalid = false;
7910 TemplateParameterList *TemplateParams =
7911 MatchTemplateParametersToScopeSpecifier(
7912 KWLoc, TemplateNameLoc, SS, &TemplateId,
7913 TemplateParameterLists, TUK == TUK_Friend, isMemberSpecialization,
7918 if (TemplateParams && TemplateParams->size() > 0) {
7919 isPartialSpecialization = true;
7921 if (TUK == TUK_Friend) {
7922 Diag(KWLoc, diag::err_partial_specialization_friend)
7923 << SourceRange(LAngleLoc, RAngleLoc);
7927 // C++ [temp.class.spec]p10:
7928 // The template parameter list of a specialization shall not
7929 // contain default template argument values.
7930 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
7931 Decl *Param = TemplateParams->getParam(I);
7932 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
7933 if (TTP->hasDefaultArgument()) {
7934 Diag(TTP->getDefaultArgumentLoc(),
7935 diag::err_default_arg_in_partial_spec);
7936 TTP->removeDefaultArgument();
7938 } else if (NonTypeTemplateParmDecl *NTTP
7939 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
7940 if (Expr *DefArg = NTTP->getDefaultArgument()) {
7941 Diag(NTTP->getDefaultArgumentLoc(),
7942 diag::err_default_arg_in_partial_spec)
7943 << DefArg->getSourceRange();
7944 NTTP->removeDefaultArgument();
7947 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
7948 if (TTP->hasDefaultArgument()) {
7949 Diag(TTP->getDefaultArgument().getLocation(),
7950 diag::err_default_arg_in_partial_spec)
7951 << TTP->getDefaultArgument().getSourceRange();
7952 TTP->removeDefaultArgument();
7956 } else if (TemplateParams) {
7957 if (TUK == TUK_Friend)
7958 Diag(KWLoc, diag::err_template_spec_friend)
7959 << FixItHint::CreateRemoval(
7960 SourceRange(TemplateParams->getTemplateLoc(),
7961 TemplateParams->getRAngleLoc()))
7962 << SourceRange(LAngleLoc, RAngleLoc);
7964 assert(TUK == TUK_Friend && "should have a 'template<>' for this decl");
7967 // Check that the specialization uses the same tag kind as the
7968 // original template.
7969 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
7970 assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
7971 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
7972 Kind, TUK == TUK_Definition, KWLoc,
7973 ClassTemplate->getIdentifier())) {
7974 Diag(KWLoc, diag::err_use_with_wrong_tag)
7976 << FixItHint::CreateReplacement(KWLoc,
7977 ClassTemplate->getTemplatedDecl()->getKindName());
7978 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
7979 diag::note_previous_use);
7980 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
7983 // Translate the parser's template argument list in our AST format.
7984 TemplateArgumentListInfo TemplateArgs =
7985 makeTemplateArgumentListInfo(*this, TemplateId);
7987 // Check for unexpanded parameter packs in any of the template arguments.
7988 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
7989 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
7990 UPPC_PartialSpecialization))
7993 // Check that the template argument list is well-formed for this
7995 SmallVector<TemplateArgument, 4> Converted;
7996 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
7997 TemplateArgs, false, Converted,
7998 /*UpdateArgsWithConversion=*/true))
8001 // Find the class template (partial) specialization declaration that
8002 // corresponds to these arguments.
8003 if (isPartialSpecialization) {
8004 if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, ClassTemplate,
8005 TemplateArgs.size(), Converted))
8008 // FIXME: Move this to CheckTemplatePartialSpecializationArgs so we
8009 // also do it during instantiation.
8010 bool InstantiationDependent;
8011 if (!Name.isDependent() &&
8012 !TemplateSpecializationType::anyDependentTemplateArguments(
8013 TemplateArgs.arguments(), InstantiationDependent)) {
8014 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
8015 << ClassTemplate->getDeclName();
8016 isPartialSpecialization = false;
8020 void *InsertPos = nullptr;
8021 ClassTemplateSpecializationDecl *PrevDecl = nullptr;
8023 if (isPartialSpecialization)
8024 PrevDecl = ClassTemplate->findPartialSpecialization(Converted,
8028 PrevDecl = ClassTemplate->findSpecialization(Converted, InsertPos);
8030 ClassTemplateSpecializationDecl *Specialization = nullptr;
8032 // Check whether we can declare a class template specialization in
8033 // the current scope.
8034 if (TUK != TUK_Friend &&
8035 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
8037 isPartialSpecialization))
8040 // The canonical type
8042 if (isPartialSpecialization) {
8043 // Build the canonical type that describes the converted template
8044 // arguments of the class template partial specialization.
8045 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
8046 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
8049 if (Context.hasSameType(CanonType,
8050 ClassTemplate->getInjectedClassNameSpecialization()) &&
8051 (!Context.getLangOpts().ConceptsTS ||
8052 !TemplateParams->hasAssociatedConstraints())) {
8053 // C++ [temp.class.spec]p9b3:
8055 // -- The argument list of the specialization shall not be identical
8056 // to the implicit argument list of the primary template.
8058 // This rule has since been removed, because it's redundant given DR1495,
8059 // but we keep it because it produces better diagnostics and recovery.
8060 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
8061 << /*class template*/0 << (TUK == TUK_Definition)
8062 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
8063 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
8064 ClassTemplate->getIdentifier(),
8068 AS_none, /*ModulePrivateLoc=*/SourceLocation(),
8069 /*FriendLoc*/SourceLocation(),
8070 TemplateParameterLists.size() - 1,
8071 TemplateParameterLists.data());
8074 // Create a new class template partial specialization declaration node.
8075 ClassTemplatePartialSpecializationDecl *PrevPartial
8076 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
8077 ClassTemplatePartialSpecializationDecl *Partial
8078 = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
8079 ClassTemplate->getDeclContext(),
8080 KWLoc, TemplateNameLoc,
8087 SetNestedNameSpecifier(*this, Partial, SS);
8088 if (TemplateParameterLists.size() > 1 && SS.isSet()) {
8089 Partial->setTemplateParameterListsInfo(
8090 Context, TemplateParameterLists.drop_back(1));
8094 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
8095 Specialization = Partial;
8097 // If we are providing an explicit specialization of a member class
8098 // template specialization, make a note of that.
8099 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
8100 PrevPartial->setMemberSpecialization();
8102 CheckTemplatePartialSpecialization(Partial);
8104 // Create a new class template specialization declaration node for
8105 // this explicit specialization or friend declaration.
8107 = ClassTemplateSpecializationDecl::Create(Context, Kind,
8108 ClassTemplate->getDeclContext(),
8109 KWLoc, TemplateNameLoc,
8113 SetNestedNameSpecifier(*this, Specialization, SS);
8114 if (TemplateParameterLists.size() > 0) {
8115 Specialization->setTemplateParameterListsInfo(Context,
8116 TemplateParameterLists);
8120 ClassTemplate->AddSpecialization(Specialization, InsertPos);
8122 if (CurContext->isDependentContext()) {
8123 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
8124 CanonType = Context.getTemplateSpecializationType(
8125 CanonTemplate, Converted);
8127 CanonType = Context.getTypeDeclType(Specialization);
8131 // C++ [temp.expl.spec]p6:
8132 // If a template, a member template or the member of a class template is
8133 // explicitly specialized then that specialization shall be declared
8134 // before the first use of that specialization that would cause an implicit
8135 // instantiation to take place, in every translation unit in which such a
8136 // use occurs; no diagnostic is required.
8137 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
8139 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
8140 // Is there any previous explicit specialization declaration?
8141 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
8148 SourceRange Range(TemplateNameLoc, RAngleLoc);
8149 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
8150 << Context.getTypeDeclType(Specialization) << Range;
8152 Diag(PrevDecl->getPointOfInstantiation(),
8153 diag::note_instantiation_required_here)
8154 << (PrevDecl->getTemplateSpecializationKind()
8155 != TSK_ImplicitInstantiation);
8160 // If this is not a friend, note that this is an explicit specialization.
8161 if (TUK != TUK_Friend)
8162 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
8164 // Check that this isn't a redefinition of this specialization.
8165 if (TUK == TUK_Definition) {
8166 RecordDecl *Def = Specialization->getDefinition();
8167 NamedDecl *Hidden = nullptr;
8168 if (Def && SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
8169 SkipBody->ShouldSkip = true;
8170 SkipBody->Previous = Def;
8171 makeMergedDefinitionVisible(Hidden);
8173 SourceRange Range(TemplateNameLoc, RAngleLoc);
8174 Diag(TemplateNameLoc, diag::err_redefinition) << Specialization << Range;
8175 Diag(Def->getLocation(), diag::note_previous_definition);
8176 Specialization->setInvalidDecl();
8181 ProcessDeclAttributeList(S, Specialization, Attr);
8183 // Add alignment attributes if necessary; these attributes are checked when
8184 // the ASTContext lays out the structure.
8185 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
8186 AddAlignmentAttributesForRecord(Specialization);
8187 AddMsStructLayoutForRecord(Specialization);
8190 if (ModulePrivateLoc.isValid())
8191 Diag(Specialization->getLocation(), diag::err_module_private_specialization)
8192 << (isPartialSpecialization? 1 : 0)
8193 << FixItHint::CreateRemoval(ModulePrivateLoc);
8195 // Build the fully-sugared type for this class template
8196 // specialization as the user wrote in the specialization
8197 // itself. This means that we'll pretty-print the type retrieved
8198 // from the specialization's declaration the way that the user
8199 // actually wrote the specialization, rather than formatting the
8200 // name based on the "canonical" representation used to store the
8201 // template arguments in the specialization.
8202 TypeSourceInfo *WrittenTy
8203 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
8204 TemplateArgs, CanonType);
8205 if (TUK != TUK_Friend) {
8206 Specialization->setTypeAsWritten(WrittenTy);
8207 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
8210 // C++ [temp.expl.spec]p9:
8211 // A template explicit specialization is in the scope of the
8212 // namespace in which the template was defined.
8214 // We actually implement this paragraph where we set the semantic
8215 // context (in the creation of the ClassTemplateSpecializationDecl),
8216 // but we also maintain the lexical context where the actual
8217 // definition occurs.
8218 Specialization->setLexicalDeclContext(CurContext);
8220 // We may be starting the definition of this specialization.
8221 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
8222 Specialization->startDefinition();
8224 if (TUK == TUK_Friend) {
8225 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
8229 Friend->setAccess(AS_public);
8230 CurContext->addDecl(Friend);
8232 // Add the specialization into its lexical context, so that it can
8233 // be seen when iterating through the list of declarations in that
8234 // context. However, specializations are not found by name lookup.
8235 CurContext->addDecl(Specialization);
8238 if (SkipBody && SkipBody->ShouldSkip)
8239 return SkipBody->Previous;
8241 return Specialization;
8244 Decl *Sema::ActOnTemplateDeclarator(Scope *S,
8245 MultiTemplateParamsArg TemplateParameterLists,
8247 Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
8248 ActOnDocumentableDecl(NewDecl);
8252 Decl *Sema::ActOnConceptDefinition(Scope *S,
8253 MultiTemplateParamsArg TemplateParameterLists,
8254 IdentifierInfo *Name, SourceLocation NameLoc,
8255 Expr *ConstraintExpr) {
8256 DeclContext *DC = CurContext;
8258 if (!DC->getRedeclContext()->isFileContext()) {
8260 diag::err_concept_decls_may_only_appear_in_global_namespace_scope);
8264 if (TemplateParameterLists.size() > 1) {
8265 Diag(NameLoc, diag::err_concept_extra_headers);
8269 if (TemplateParameterLists.front()->size() == 0) {
8270 Diag(NameLoc, diag::err_concept_no_parameters);
8274 ConceptDecl *NewDecl = ConceptDecl::Create(Context, DC, NameLoc, Name,
8275 TemplateParameterLists.front(),
8278 if (NewDecl->hasAssociatedConstraints()) {
8279 // C++2a [temp.concept]p4:
8280 // A concept shall not have associated constraints.
8281 Diag(NameLoc, diag::err_concept_no_associated_constraints);
8282 NewDecl->setInvalidDecl();
8285 // Check for conflicting previous declaration.
8286 DeclarationNameInfo NameInfo(NewDecl->getDeclName(), NameLoc);
8287 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
8288 ForVisibleRedeclaration);
8289 LookupName(Previous, S);
8291 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage=*/false,
8292 /*AllowInlineNamespace*/false);
8293 if (!Previous.empty()) {
8294 auto *Old = Previous.getRepresentativeDecl();
8295 Diag(NameLoc, isa<ConceptDecl>(Old) ? diag::err_redefinition :
8296 diag::err_redefinition_different_kind) << NewDecl->getDeclName();
8297 Diag(Old->getLocation(), diag::note_previous_definition);
8300 ActOnDocumentableDecl(NewDecl);
8301 PushOnScopeChains(NewDecl, S);
8305 /// \brief Strips various properties off an implicit instantiation
8306 /// that has just been explicitly specialized.
8307 static void StripImplicitInstantiation(NamedDecl *D) {
8308 D->dropAttr<DLLImportAttr>();
8309 D->dropAttr<DLLExportAttr>();
8311 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
8312 FD->setInlineSpecified(false);
8315 /// Compute the diagnostic location for an explicit instantiation
8316 // declaration or definition.
8317 static SourceLocation DiagLocForExplicitInstantiation(
8318 NamedDecl* D, SourceLocation PointOfInstantiation) {
8319 // Explicit instantiations following a specialization have no effect and
8320 // hence no PointOfInstantiation. In that case, walk decl backwards
8321 // until a valid name loc is found.
8322 SourceLocation PrevDiagLoc = PointOfInstantiation;
8323 for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
8324 Prev = Prev->getPreviousDecl()) {
8325 PrevDiagLoc = Prev->getLocation();
8327 assert(PrevDiagLoc.isValid() &&
8328 "Explicit instantiation without point of instantiation?");
8332 /// Diagnose cases where we have an explicit template specialization
8333 /// before/after an explicit template instantiation, producing diagnostics
8334 /// for those cases where they are required and determining whether the
8335 /// new specialization/instantiation will have any effect.
8337 /// \param NewLoc the location of the new explicit specialization or
8340 /// \param NewTSK the kind of the new explicit specialization or instantiation.
8342 /// \param PrevDecl the previous declaration of the entity.
8344 /// \param PrevTSK the kind of the old explicit specialization or instantiatin.
8346 /// \param PrevPointOfInstantiation if valid, indicates where the previus
8347 /// declaration was instantiated (either implicitly or explicitly).
8349 /// \param HasNoEffect will be set to true to indicate that the new
8350 /// specialization or instantiation has no effect and should be ignored.
8352 /// \returns true if there was an error that should prevent the introduction of
8353 /// the new declaration into the AST, false otherwise.
8355 Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
8356 TemplateSpecializationKind NewTSK,
8357 NamedDecl *PrevDecl,
8358 TemplateSpecializationKind PrevTSK,
8359 SourceLocation PrevPointOfInstantiation,
8360 bool &HasNoEffect) {
8361 HasNoEffect = false;
8364 case TSK_Undeclared:
8365 case TSK_ImplicitInstantiation:
8367 (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
8368 "previous declaration must be implicit!");
8371 case TSK_ExplicitSpecialization:
8373 case TSK_Undeclared:
8374 case TSK_ExplicitSpecialization:
8375 // Okay, we're just specializing something that is either already
8376 // explicitly specialized or has merely been mentioned without any
8380 case TSK_ImplicitInstantiation:
8381 if (PrevPointOfInstantiation.isInvalid()) {
8382 // The declaration itself has not actually been instantiated, so it is
8383 // still okay to specialize it.
8384 StripImplicitInstantiation(PrevDecl);
8390 case TSK_ExplicitInstantiationDeclaration:
8391 case TSK_ExplicitInstantiationDefinition:
8392 assert((PrevTSK == TSK_ImplicitInstantiation ||
8393 PrevPointOfInstantiation.isValid()) &&
8394 "Explicit instantiation without point of instantiation?");
8396 // C++ [temp.expl.spec]p6:
8397 // If a template, a member template or the member of a class template
8398 // is explicitly specialized then that specialization shall be declared
8399 // before the first use of that specialization that would cause an
8400 // implicit instantiation to take place, in every translation unit in
8401 // which such a use occurs; no diagnostic is required.
8402 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
8403 // Is there any previous explicit specialization declaration?
8404 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
8408 Diag(NewLoc, diag::err_specialization_after_instantiation)
8410 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
8411 << (PrevTSK != TSK_ImplicitInstantiation);
8415 llvm_unreachable("The switch over PrevTSK must be exhaustive.");
8417 case TSK_ExplicitInstantiationDeclaration:
8419 case TSK_ExplicitInstantiationDeclaration:
8420 // This explicit instantiation declaration is redundant (that's okay).
8424 case TSK_Undeclared:
8425 case TSK_ImplicitInstantiation:
8426 // We're explicitly instantiating something that may have already been
8427 // implicitly instantiated; that's fine.
8430 case TSK_ExplicitSpecialization:
8431 // C++0x [temp.explicit]p4:
8432 // For a given set of template parameters, if an explicit instantiation
8433 // of a template appears after a declaration of an explicit
8434 // specialization for that template, the explicit instantiation has no
8439 case TSK_ExplicitInstantiationDefinition:
8440 // C++0x [temp.explicit]p10:
8441 // If an entity is the subject of both an explicit instantiation
8442 // declaration and an explicit instantiation definition in the same
8443 // translation unit, the definition shall follow the declaration.
8445 diag::err_explicit_instantiation_declaration_after_definition);
8447 // Explicit instantiations following a specialization have no effect and
8448 // hence no PrevPointOfInstantiation. In that case, walk decl backwards
8449 // until a valid name loc is found.
8450 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
8451 diag::note_explicit_instantiation_definition_here);
8455 llvm_unreachable("Unexpected TemplateSpecializationKind!");
8457 case TSK_ExplicitInstantiationDefinition:
8459 case TSK_Undeclared:
8460 case TSK_ImplicitInstantiation:
8461 // We're explicitly instantiating something that may have already been
8462 // implicitly instantiated; that's fine.
8465 case TSK_ExplicitSpecialization:
8466 // C++ DR 259, C++0x [temp.explicit]p4:
8467 // For a given set of template parameters, if an explicit
8468 // instantiation of a template appears after a declaration of
8469 // an explicit specialization for that template, the explicit
8470 // instantiation has no effect.
8471 Diag(NewLoc, diag::warn_explicit_instantiation_after_specialization)
8473 Diag(PrevDecl->getLocation(),
8474 diag::note_previous_template_specialization);
8478 case TSK_ExplicitInstantiationDeclaration:
8479 // We're explicitly instantiating a definition for something for which we
8480 // were previously asked to suppress instantiations. That's fine.
8482 // C++0x [temp.explicit]p4:
8483 // For a given set of template parameters, if an explicit instantiation
8484 // of a template appears after a declaration of an explicit
8485 // specialization for that template, the explicit instantiation has no
8487 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
8488 // Is there any previous explicit specialization declaration?
8489 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
8497 case TSK_ExplicitInstantiationDefinition:
8498 // C++0x [temp.spec]p5:
8499 // For a given template and a given set of template-arguments,
8500 // - an explicit instantiation definition shall appear at most once
8503 // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
8504 Diag(NewLoc, (getLangOpts().MSVCCompat)
8505 ? diag::ext_explicit_instantiation_duplicate
8506 : diag::err_explicit_instantiation_duplicate)
8508 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
8509 diag::note_previous_explicit_instantiation);
8515 llvm_unreachable("Missing specialization/instantiation case?");
8518 /// Perform semantic analysis for the given dependent function
8519 /// template specialization.
8521 /// The only possible way to get a dependent function template specialization
8522 /// is with a friend declaration, like so:
8525 /// template \<class T> void foo(T);
8526 /// template \<class T> class A {
8527 /// friend void foo<>(T);
8531 /// There really isn't any useful analysis we can do here, so we
8532 /// just store the information.
8534 Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
8535 const TemplateArgumentListInfo &ExplicitTemplateArgs,
8536 LookupResult &Previous) {
8537 // Remove anything from Previous that isn't a function template in
8538 // the correct context.
8539 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
8540 LookupResult::Filter F = Previous.makeFilter();
8541 enum DiscardReason { NotAFunctionTemplate, NotAMemberOfEnclosing };
8542 SmallVector<std::pair<DiscardReason, Decl *>, 8> DiscardedCandidates;
8543 while (F.hasNext()) {
8544 NamedDecl *D = F.next()->getUnderlyingDecl();
8545 if (!isa<FunctionTemplateDecl>(D)) {
8547 DiscardedCandidates.push_back(std::make_pair(NotAFunctionTemplate, D));
8551 if (!FDLookupContext->InEnclosingNamespaceSetOf(
8552 D->getDeclContext()->getRedeclContext())) {
8554 DiscardedCandidates.push_back(std::make_pair(NotAMemberOfEnclosing, D));
8560 if (Previous.empty()) {
8561 Diag(FD->getLocation(),
8562 diag::err_dependent_function_template_spec_no_match);
8563 for (auto &P : DiscardedCandidates)
8564 Diag(P.second->getLocation(),
8565 diag::note_dependent_function_template_spec_discard_reason)
8570 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
8571 ExplicitTemplateArgs);
8575 /// Perform semantic analysis for the given function template
8578 /// This routine performs all of the semantic analysis required for an
8579 /// explicit function template specialization. On successful completion,
8580 /// the function declaration \p FD will become a function template
8583 /// \param FD the function declaration, which will be updated to become a
8584 /// function template specialization.
8586 /// \param ExplicitTemplateArgs the explicitly-provided template arguments,
8587 /// if any. Note that this may be valid info even when 0 arguments are
8588 /// explicitly provided as in, e.g., \c void sort<>(char*, char*);
8589 /// as it anyway contains info on the angle brackets locations.
8591 /// \param Previous the set of declarations that may be specialized by
8592 /// this function specialization.
8594 /// \param QualifiedFriend whether this is a lookup for a qualified friend
8595 /// declaration with no explicit template argument list that might be
8596 /// befriending a function template specialization.
8597 bool Sema::CheckFunctionTemplateSpecialization(
8598 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
8599 LookupResult &Previous, bool QualifiedFriend) {
8600 // The set of function template specializations that could match this
8601 // explicit function template specialization.
8602 UnresolvedSet<8> Candidates;
8603 TemplateSpecCandidateSet FailedCandidates(FD->getLocation(),
8604 /*ForTakingAddress=*/false);
8606 llvm::SmallDenseMap<FunctionDecl *, TemplateArgumentListInfo, 8>
8607 ConvertedTemplateArgs;
8609 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
8610 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8612 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
8613 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
8614 // Only consider templates found within the same semantic lookup scope as
8616 if (!FDLookupContext->InEnclosingNamespaceSetOf(
8617 Ovl->getDeclContext()->getRedeclContext()))
8620 // When matching a constexpr member function template specialization
8621 // against the primary template, we don't yet know whether the
8622 // specialization has an implicit 'const' (because we don't know whether
8623 // it will be a static member function until we know which template it
8624 // specializes), so adjust it now assuming it specializes this template.
8625 QualType FT = FD->getType();
8626 if (FD->isConstexpr()) {
8627 CXXMethodDecl *OldMD =
8628 dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
8629 if (OldMD && OldMD->isConst()) {
8630 const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
8631 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8632 EPI.TypeQuals.addConst();
8633 FT = Context.getFunctionType(FPT->getReturnType(),
8634 FPT->getParamTypes(), EPI);
8638 TemplateArgumentListInfo Args;
8639 if (ExplicitTemplateArgs)
8640 Args = *ExplicitTemplateArgs;
8642 // C++ [temp.expl.spec]p11:
8643 // A trailing template-argument can be left unspecified in the
8644 // template-id naming an explicit function template specialization
8645 // provided it can be deduced from the function argument type.
8646 // Perform template argument deduction to determine whether we may be
8647 // specializing this template.
8648 // FIXME: It is somewhat wasteful to build
8649 TemplateDeductionInfo Info(FailedCandidates.getLocation());
8650 FunctionDecl *Specialization = nullptr;
8651 if (TemplateDeductionResult TDK = DeduceTemplateArguments(
8652 cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()),
8653 ExplicitTemplateArgs ? &Args : nullptr, FT, Specialization,
8655 // Template argument deduction failed; record why it failed, so
8656 // that we can provide nifty diagnostics.
8657 FailedCandidates.addCandidate().set(
8658 I.getPair(), FunTmpl->getTemplatedDecl(),
8659 MakeDeductionFailureInfo(Context, TDK, Info));
8664 // Target attributes are part of the cuda function signature, so
8665 // the deduced template's cuda target must match that of the
8666 // specialization. Given that C++ template deduction does not
8667 // take target attributes into account, we reject candidates
8668 // here that have a different target.
8669 if (LangOpts.CUDA &&
8670 IdentifyCUDATarget(Specialization,
8671 /* IgnoreImplicitHDAttr = */ true) !=
8672 IdentifyCUDATarget(FD, /* IgnoreImplicitHDAttr = */ true)) {
8673 FailedCandidates.addCandidate().set(
8674 I.getPair(), FunTmpl->getTemplatedDecl(),
8675 MakeDeductionFailureInfo(Context, TDK_CUDATargetMismatch, Info));
8679 // Record this candidate.
8680 if (ExplicitTemplateArgs)
8681 ConvertedTemplateArgs[Specialization] = std::move(Args);
8682 Candidates.addDecl(Specialization, I.getAccess());
8686 // For a qualified friend declaration (with no explicit marker to indicate
8687 // that a template specialization was intended), note all (template and
8688 // non-template) candidates.
8689 if (QualifiedFriend && Candidates.empty()) {
8690 Diag(FD->getLocation(), diag::err_qualified_friend_no_match)
8691 << FD->getDeclName() << FDLookupContext;
8692 // FIXME: We should form a single candidate list and diagnose all
8693 // candidates at once, to get proper sorting and limiting.
8694 for (auto *OldND : Previous) {
8695 if (auto *OldFD = dyn_cast<FunctionDecl>(OldND->getUnderlyingDecl()))
8696 NoteOverloadCandidate(OldND, OldFD, CRK_None, FD->getType(), false);
8698 FailedCandidates.NoteCandidates(*this, FD->getLocation());
8702 // Find the most specialized function template.
8703 UnresolvedSetIterator Result = getMostSpecialized(
8704 Candidates.begin(), Candidates.end(), FailedCandidates, FD->getLocation(),
8705 PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(),
8706 PDiag(diag::err_function_template_spec_ambiguous)
8707 << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
8708 PDiag(diag::note_function_template_spec_matched));
8710 if (Result == Candidates.end())
8713 // Ignore access information; it doesn't figure into redeclaration checking.
8714 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
8716 FunctionTemplateSpecializationInfo *SpecInfo
8717 = Specialization->getTemplateSpecializationInfo();
8718 assert(SpecInfo && "Function template specialization info missing?");
8720 // Note: do not overwrite location info if previous template
8721 // specialization kind was explicit.
8722 TemplateSpecializationKind TSK = SpecInfo->getTemplateSpecializationKind();
8723 if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
8724 Specialization->setLocation(FD->getLocation());
8725 Specialization->setLexicalDeclContext(FD->getLexicalDeclContext());
8726 // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
8727 // function can differ from the template declaration with respect to
8728 // the constexpr specifier.
8729 // FIXME: We need an update record for this AST mutation.
8730 // FIXME: What if there are multiple such prior declarations (for instance,
8731 // from different modules)?
8732 Specialization->setConstexprKind(FD->getConstexprKind());
8735 // FIXME: Check if the prior specialization has a point of instantiation.
8736 // If so, we have run afoul of .
8738 // If this is a friend declaration, then we're not really declaring
8739 // an explicit specialization.
8740 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
8742 // Check the scope of this explicit specialization.
8744 CheckTemplateSpecializationScope(*this,
8745 Specialization->getPrimaryTemplate(),
8746 Specialization, FD->getLocation(),
8750 // C++ [temp.expl.spec]p6:
8751 // If a template, a member template or the member of a class template is
8752 // explicitly specialized then that specialization shall be declared
8753 // before the first use of that specialization that would cause an implicit
8754 // instantiation to take place, in every translation unit in which such a
8755 // use occurs; no diagnostic is required.
8756 bool HasNoEffect = false;
8758 CheckSpecializationInstantiationRedecl(FD->getLocation(),
8759 TSK_ExplicitSpecialization,
8761 SpecInfo->getTemplateSpecializationKind(),
8762 SpecInfo->getPointOfInstantiation(),
8766 // Mark the prior declaration as an explicit specialization, so that later
8767 // clients know that this is an explicit specialization.
8769 // Since explicit specializations do not inherit '=delete' from their
8770 // primary function template - check if the 'specialization' that was
8771 // implicitly generated (during template argument deduction for partial
8772 // ordering) from the most specialized of all the function templates that
8773 // 'FD' could have been specializing, has a 'deleted' definition. If so,
8774 // first check that it was implicitly generated during template argument
8775 // deduction by making sure it wasn't referenced, and then reset the deleted
8776 // flag to not-deleted, so that we can inherit that information from 'FD'.
8777 if (Specialization->isDeleted() && !SpecInfo->isExplicitSpecialization() &&
8778 !Specialization->getCanonicalDecl()->isReferenced()) {
8779 // FIXME: This assert will not hold in the presence of modules.
8781 Specialization->getCanonicalDecl() == Specialization &&
8782 "This must be the only existing declaration of this specialization");
8783 // FIXME: We need an update record for this AST mutation.
8784 Specialization->setDeletedAsWritten(false);
8786 // FIXME: We need an update record for this AST mutation.
8787 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
8788 MarkUnusedFileScopedDecl(Specialization);
8791 // Turn the given function declaration into a function template
8792 // specialization, with the template arguments from the previous
8794 // Take copies of (semantic and syntactic) template argument lists.
8795 const TemplateArgumentList* TemplArgs = new (Context)
8796 TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
8797 FD->setFunctionTemplateSpecialization(
8798 Specialization->getPrimaryTemplate(), TemplArgs, /*InsertPos=*/nullptr,
8799 SpecInfo->getTemplateSpecializationKind(),
8800 ExplicitTemplateArgs ? &ConvertedTemplateArgs[Specialization] : nullptr);
8802 // A function template specialization inherits the target attributes
8803 // of its template. (We require the attributes explicitly in the
8804 // code to match, but a template may have implicit attributes by
8805 // virtue e.g. of being constexpr, and it passes these implicit
8806 // attributes on to its specializations.)
8808 inheritCUDATargetAttrs(FD, *Specialization->getPrimaryTemplate());
8810 // The "previous declaration" for this function template specialization is
8811 // the prior function template specialization.
8813 Previous.addDecl(Specialization);
8817 /// Perform semantic analysis for the given non-template member
8820 /// This routine performs all of the semantic analysis required for an
8821 /// explicit member function specialization. On successful completion,
8822 /// the function declaration \p FD will become a member function
8825 /// \param Member the member declaration, which will be updated to become a
8828 /// \param Previous the set of declarations, one of which may be specialized
8829 /// by this function specialization; the set will be modified to contain the
8830 /// redeclared member.
8832 Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
8833 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
8835 // Try to find the member we are instantiating.
8836 NamedDecl *FoundInstantiation = nullptr;
8837 NamedDecl *Instantiation = nullptr;
8838 NamedDecl *InstantiatedFrom = nullptr;
8839 MemberSpecializationInfo *MSInfo = nullptr;
8841 if (Previous.empty()) {
8842 // Nowhere to look anyway.
8843 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
8844 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8846 NamedDecl *D = (*I)->getUnderlyingDecl();
8847 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
8848 QualType Adjusted = Function->getType();
8849 if (!hasExplicitCallingConv(Adjusted))
8850 Adjusted = adjustCCAndNoReturn(Adjusted, Method->getType());
8851 // This doesn't handle deduced return types, but both function
8852 // declarations should be undeduced at this point.
8853 if (Context.hasSameType(Adjusted, Method->getType())) {
8854 FoundInstantiation = *I;
8855 Instantiation = Method;
8856 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
8857 MSInfo = Method->getMemberSpecializationInfo();
8862 } else if (isa<VarDecl>(Member)) {
8864 if (Previous.isSingleResult() &&
8865 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
8866 if (PrevVar->isStaticDataMember()) {
8867 FoundInstantiation = Previous.getRepresentativeDecl();
8868 Instantiation = PrevVar;
8869 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
8870 MSInfo = PrevVar->getMemberSpecializationInfo();
8872 } else if (isa<RecordDecl>(Member)) {
8873 CXXRecordDecl *PrevRecord;
8874 if (Previous.isSingleResult() &&
8875 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
8876 FoundInstantiation = Previous.getRepresentativeDecl();
8877 Instantiation = PrevRecord;
8878 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
8879 MSInfo = PrevRecord->getMemberSpecializationInfo();
8881 } else if (isa<EnumDecl>(Member)) {
8883 if (Previous.isSingleResult() &&
8884 (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) {
8885 FoundInstantiation = Previous.getRepresentativeDecl();
8886 Instantiation = PrevEnum;
8887 InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
8888 MSInfo = PrevEnum->getMemberSpecializationInfo();
8892 if (!Instantiation) {
8893 // There is no previous declaration that matches. Since member
8894 // specializations are always out-of-line, the caller will complain about
8895 // this mismatch later.
8899 // A member specialization in a friend declaration isn't really declaring
8900 // an explicit specialization, just identifying a specific (possibly implicit)
8901 // specialization. Don't change the template specialization kind.
8903 // FIXME: Is this really valid? Other compilers reject.
8904 if (Member->getFriendObjectKind() != Decl::FOK_None) {
8905 // Preserve instantiation information.
8906 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
8907 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
8908 cast<CXXMethodDecl>(InstantiatedFrom),
8909 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
8910 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
8911 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
8912 cast<CXXRecordDecl>(InstantiatedFrom),
8913 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
8917 Previous.addDecl(FoundInstantiation);
8921 // Make sure that this is a specialization of a member.
8922 if (!InstantiatedFrom) {
8923 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
8925 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
8929 // C++ [temp.expl.spec]p6:
8930 // If a template, a member template or the member of a class template is
8931 // explicitly specialized then that specialization shall be declared
8932 // before the first use of that specialization that would cause an implicit
8933 // instantiation to take place, in every translation unit in which such a
8934 // use occurs; no diagnostic is required.
8935 assert(MSInfo && "Member specialization info missing?");
8937 bool HasNoEffect = false;
8938 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
8939 TSK_ExplicitSpecialization,
8941 MSInfo->getTemplateSpecializationKind(),
8942 MSInfo->getPointOfInstantiation(),
8946 // Check the scope of this explicit specialization.
8947 if (CheckTemplateSpecializationScope(*this,
8949 Instantiation, Member->getLocation(),
8953 // Note that this member specialization is an "instantiation of" the
8954 // corresponding member of the original template.
8955 if (auto *MemberFunction = dyn_cast<FunctionDecl>(Member)) {
8956 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
8957 if (InstantiationFunction->getTemplateSpecializationKind() ==
8958 TSK_ImplicitInstantiation) {
8959 // Explicit specializations of member functions of class templates do not
8960 // inherit '=delete' from the member function they are specializing.
8961 if (InstantiationFunction->isDeleted()) {
8962 // FIXME: This assert will not hold in the presence of modules.
8963 assert(InstantiationFunction->getCanonicalDecl() ==
8964 InstantiationFunction);
8965 // FIXME: We need an update record for this AST mutation.
8966 InstantiationFunction->setDeletedAsWritten(false);
8970 MemberFunction->setInstantiationOfMemberFunction(
8971 cast<CXXMethodDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
8972 } else if (auto *MemberVar = dyn_cast<VarDecl>(Member)) {
8973 MemberVar->setInstantiationOfStaticDataMember(
8974 cast<VarDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
8975 } else if (auto *MemberClass = dyn_cast<CXXRecordDecl>(Member)) {
8976 MemberClass->setInstantiationOfMemberClass(
8977 cast<CXXRecordDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
8978 } else if (auto *MemberEnum = dyn_cast<EnumDecl>(Member)) {
8979 MemberEnum->setInstantiationOfMemberEnum(
8980 cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
8982 llvm_unreachable("unknown member specialization kind");
8985 // Save the caller the trouble of having to figure out which declaration
8986 // this specialization matches.
8988 Previous.addDecl(FoundInstantiation);
8992 /// Complete the explicit specialization of a member of a class template by
8993 /// updating the instantiated member to be marked as an explicit specialization.
8995 /// \param OrigD The member declaration instantiated from the template.
8996 /// \param Loc The location of the explicit specialization of the member.
8997 template<typename DeclT>
8998 static void completeMemberSpecializationImpl(Sema &S, DeclT *OrigD,
8999 SourceLocation Loc) {
9000 if (OrigD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
9003 // FIXME: Inform AST mutation listeners of this AST mutation.
9004 // FIXME: If there are multiple in-class declarations of the member (from
9005 // multiple modules, or a declaration and later definition of a member type),
9006 // should we update all of them?
9007 OrigD->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
9008 OrigD->setLocation(Loc);
9011 void Sema::CompleteMemberSpecialization(NamedDecl *Member,
9012 LookupResult &Previous) {
9013 NamedDecl *Instantiation = cast<NamedDecl>(Member->getCanonicalDecl());
9014 if (Instantiation == Member)
9017 if (auto *Function = dyn_cast<CXXMethodDecl>(Instantiation))
9018 completeMemberSpecializationImpl(*this, Function, Member->getLocation());
9019 else if (auto *Var = dyn_cast<VarDecl>(Instantiation))
9020 completeMemberSpecializationImpl(*this, Var, Member->getLocation());
9021 else if (auto *Record = dyn_cast<CXXRecordDecl>(Instantiation))
9022 completeMemberSpecializationImpl(*this, Record, Member->getLocation());
9023 else if (auto *Enum = dyn_cast<EnumDecl>(Instantiation))
9024 completeMemberSpecializationImpl(*this, Enum, Member->getLocation());
9026 llvm_unreachable("unknown member specialization kind");
9029 /// Check the scope of an explicit instantiation.
9031 /// \returns true if a serious error occurs, false otherwise.
9032 static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
9033 SourceLocation InstLoc,
9034 bool WasQualifiedName) {
9035 DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
9036 DeclContext *CurContext = S.CurContext->getRedeclContext();
9038 if (CurContext->isRecord()) {
9039 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
9044 // C++11 [temp.explicit]p3:
9045 // An explicit instantiation shall appear in an enclosing namespace of its
9046 // template. If the name declared in the explicit instantiation is an
9047 // unqualified name, the explicit instantiation shall appear in the
9048 // namespace where its template is declared or, if that namespace is inline
9049 // (7.3.1), any namespace from its enclosing namespace set.
9051 // This is DR275, which we do not retroactively apply to C++98/03.
9052 if (WasQualifiedName) {
9053 if (CurContext->Encloses(OrigContext))
9056 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
9060 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
9061 if (WasQualifiedName)
9063 S.getLangOpts().CPlusPlus11?
9064 diag::err_explicit_instantiation_out_of_scope :
9065 diag::warn_explicit_instantiation_out_of_scope_0x)
9069 S.getLangOpts().CPlusPlus11?
9070 diag::err_explicit_instantiation_unqualified_wrong_namespace :
9071 diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
9075 S.getLangOpts().CPlusPlus11?
9076 diag::err_explicit_instantiation_must_be_global :
9077 diag::warn_explicit_instantiation_must_be_global_0x)
9079 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
9083 /// Common checks for whether an explicit instantiation of \p D is valid.
9084 static bool CheckExplicitInstantiation(Sema &S, NamedDecl *D,
9085 SourceLocation InstLoc,
9086 bool WasQualifiedName,
9087 TemplateSpecializationKind TSK) {
9088 // C++ [temp.explicit]p13:
9089 // An explicit instantiation declaration shall not name a specialization of
9090 // a template with internal linkage.
9091 if (TSK == TSK_ExplicitInstantiationDeclaration &&
9092 D->getFormalLinkage() == InternalLinkage) {
9093 S.Diag(InstLoc, diag::err_explicit_instantiation_internal_linkage) << D;
9097 // C++11 [temp.explicit]p3: [DR 275]
9098 // An explicit instantiation shall appear in an enclosing namespace of its
9100 if (CheckExplicitInstantiationScope(S, D, InstLoc, WasQualifiedName))
9106 /// Determine whether the given scope specifier has a template-id in it.
9107 static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
9111 // C++11 [temp.explicit]p3:
9112 // If the explicit instantiation is for a member function, a member class
9113 // or a static data member of a class template specialization, the name of
9114 // the class template specialization in the qualified-id for the member
9115 // name shall be a simple-template-id.
9117 // C++98 has the same restriction, just worded differently.
9118 for (NestedNameSpecifier *NNS = SS.getScopeRep(); NNS;
9119 NNS = NNS->getPrefix())
9120 if (const Type *T = NNS->getAsType())
9121 if (isa<TemplateSpecializationType>(T))
9127 /// Make a dllexport or dllimport attr on a class template specialization take
9129 static void dllExportImportClassTemplateSpecialization(
9130 Sema &S, ClassTemplateSpecializationDecl *Def) {
9131 auto *A = cast_or_null<InheritableAttr>(getDLLAttr(Def));
9132 assert(A && "dllExportImportClassTemplateSpecialization called "
9133 "on Def without dllexport or dllimport");
9135 // We reject explicit instantiations in class scope, so there should
9136 // never be any delayed exported classes to worry about.
9137 assert(S.DelayedDllExportClasses.empty() &&
9138 "delayed exports present at explicit instantiation");
9139 S.checkClassLevelDLLAttribute(Def);
9141 // Propagate attribute to base class templates.
9142 for (auto &B : Def->bases()) {
9143 if (auto *BT = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
9144 B.getType()->getAsCXXRecordDecl()))
9145 S.propagateDLLAttrToBaseClassTemplate(Def, A, BT, B.getBeginLoc());
9148 S.referenceDLLExportedClassMethods();
9151 // Explicit instantiation of a class template specialization
9152 DeclResult Sema::ActOnExplicitInstantiation(
9153 Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc,
9154 unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS,
9155 TemplateTy TemplateD, SourceLocation TemplateNameLoc,
9156 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn,
9157 SourceLocation RAngleLoc, const ParsedAttributesView &Attr) {
9158 // Find the class template we're specializing
9159 TemplateName Name = TemplateD.get();
9160 TemplateDecl *TD = Name.getAsTemplateDecl();
9161 // Check that the specialization uses the same tag kind as the
9162 // original template.
9163 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
9164 assert(Kind != TTK_Enum &&
9165 "Invalid enum tag in class template explicit instantiation!");
9167 ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(TD);
9169 if (!ClassTemplate) {
9170 NonTagKind NTK = getNonTagTypeDeclKind(TD, Kind);
9171 Diag(TemplateNameLoc, diag::err_tag_reference_non_tag) << TD << NTK << Kind;
9172 Diag(TD->getLocation(), diag::note_previous_use);
9176 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
9177 Kind, /*isDefinition*/false, KWLoc,
9178 ClassTemplate->getIdentifier())) {
9179 Diag(KWLoc, diag::err_use_with_wrong_tag)
9181 << FixItHint::CreateReplacement(KWLoc,
9182 ClassTemplate->getTemplatedDecl()->getKindName());
9183 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
9184 diag::note_previous_use);
9185 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
9188 // C++0x [temp.explicit]p2:
9189 // There are two forms of explicit instantiation: an explicit instantiation
9190 // definition and an explicit instantiation declaration. An explicit
9191 // instantiation declaration begins with the extern keyword. [...]
9192 TemplateSpecializationKind TSK = ExternLoc.isInvalid()
9193 ? TSK_ExplicitInstantiationDefinition
9194 : TSK_ExplicitInstantiationDeclaration;
9196 if (TSK == TSK_ExplicitInstantiationDeclaration &&
9197 !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
9198 // Check for dllexport class template instantiation declarations,
9199 // except for MinGW mode.
9200 for (const ParsedAttr &AL : Attr) {
9201 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
9203 diag::warn_attribute_dllexport_explicit_instantiation_decl);
9204 Diag(AL.getLoc(), diag::note_attribute);
9209 if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) {
9211 diag::warn_attribute_dllexport_explicit_instantiation_decl);
9212 Diag(A->getLocation(), diag::note_attribute);
9216 // In MSVC mode, dllimported explicit instantiation definitions are treated as
9217 // instantiation declarations for most purposes.
9218 bool DLLImportExplicitInstantiationDef = false;
9219 if (TSK == TSK_ExplicitInstantiationDefinition &&
9220 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
9221 // Check for dllimport class template instantiation definitions.
9223 ClassTemplate->getTemplatedDecl()->getAttr<DLLImportAttr>();
9224 for (const ParsedAttr &AL : Attr) {
9225 if (AL.getKind() == ParsedAttr::AT_DLLImport)
9227 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
9228 // dllexport trumps dllimport here.
9234 TSK = TSK_ExplicitInstantiationDeclaration;
9235 DLLImportExplicitInstantiationDef = true;
9239 // Translate the parser's template argument list in our AST format.
9240 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
9241 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
9243 // Check that the template argument list is well-formed for this
9245 SmallVector<TemplateArgument, 4> Converted;
9246 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
9247 TemplateArgs, false, Converted,
9248 /*UpdateArgsWithConversion=*/true))
9251 // Find the class template specialization declaration that
9252 // corresponds to these arguments.
9253 void *InsertPos = nullptr;
9254 ClassTemplateSpecializationDecl *PrevDecl
9255 = ClassTemplate->findSpecialization(Converted, InsertPos);
9257 TemplateSpecializationKind PrevDecl_TSK
9258 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
9260 if (TSK == TSK_ExplicitInstantiationDefinition && PrevDecl != nullptr &&
9261 Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
9262 // Check for dllexport class template instantiation definitions in MinGW
9263 // mode, if a previous declaration of the instantiation was seen.
9264 for (const ParsedAttr &AL : Attr) {
9265 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
9267 diag::warn_attribute_dllexport_explicit_instantiation_def);
9273 if (CheckExplicitInstantiation(*this, ClassTemplate, TemplateNameLoc,
9277 ClassTemplateSpecializationDecl *Specialization = nullptr;
9279 bool HasNoEffect = false;
9281 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
9282 PrevDecl, PrevDecl_TSK,
9283 PrevDecl->getPointOfInstantiation(),
9287 // Even though HasNoEffect == true means that this explicit instantiation
9288 // has no effect on semantics, we go on to put its syntax in the AST.
9290 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
9291 PrevDecl_TSK == TSK_Undeclared) {
9292 // Since the only prior class template specialization with these
9293 // arguments was referenced but not declared, reuse that
9294 // declaration node as our own, updating the source location
9295 // for the template name to reflect our new declaration.
9296 // (Other source locations will be updated later.)
9297 Specialization = PrevDecl;
9298 Specialization->setLocation(TemplateNameLoc);
9302 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
9303 DLLImportExplicitInstantiationDef) {
9304 // The new specialization might add a dllimport attribute.
9305 HasNoEffect = false;
9309 if (!Specialization) {
9310 // Create a new class template specialization declaration node for
9311 // this explicit specialization.
9313 = ClassTemplateSpecializationDecl::Create(Context, Kind,
9314 ClassTemplate->getDeclContext(),
9315 KWLoc, TemplateNameLoc,
9319 SetNestedNameSpecifier(*this, Specialization, SS);
9321 if (!HasNoEffect && !PrevDecl) {
9322 // Insert the new specialization.
9323 ClassTemplate->AddSpecialization(Specialization, InsertPos);
9327 // Build the fully-sugared type for this explicit instantiation as
9328 // the user wrote in the explicit instantiation itself. This means
9329 // that we'll pretty-print the type retrieved from the
9330 // specialization's declaration the way that the user actually wrote
9331 // the explicit instantiation, rather than formatting the name based
9332 // on the "canonical" representation used to store the template
9333 // arguments in the specialization.
9334 TypeSourceInfo *WrittenTy
9335 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
9337 Context.getTypeDeclType(Specialization));
9338 Specialization->setTypeAsWritten(WrittenTy);
9340 // Set source locations for keywords.
9341 Specialization->setExternLoc(ExternLoc);
9342 Specialization->setTemplateKeywordLoc(TemplateLoc);
9343 Specialization->setBraceRange(SourceRange());
9345 bool PreviouslyDLLExported = Specialization->hasAttr<DLLExportAttr>();
9346 ProcessDeclAttributeList(S, Specialization, Attr);
9348 // Add the explicit instantiation into its lexical context. However,
9349 // since explicit instantiations are never found by name lookup, we
9350 // just put it into the declaration context directly.
9351 Specialization->setLexicalDeclContext(CurContext);
9352 CurContext->addDecl(Specialization);
9354 // Syntax is now OK, so return if it has no other effect on semantics.
9356 // Set the template specialization kind.
9357 Specialization->setTemplateSpecializationKind(TSK);
9358 return Specialization;
9361 // C++ [temp.explicit]p3:
9362 // A definition of a class template or class member template
9363 // shall be in scope at the point of the explicit instantiation of
9364 // the class template or class member template.
9366 // This check comes when we actually try to perform the
9368 ClassTemplateSpecializationDecl *Def
9369 = cast_or_null<ClassTemplateSpecializationDecl>(
9370 Specialization->getDefinition());
9372 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
9373 else if (TSK == TSK_ExplicitInstantiationDefinition) {
9374 MarkVTableUsed(TemplateNameLoc, Specialization, true);
9375 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
9378 // Instantiate the members of this class template specialization.
9379 Def = cast_or_null<ClassTemplateSpecializationDecl>(
9380 Specialization->getDefinition());
9382 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
9383 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
9384 // TSK_ExplicitInstantiationDefinition
9385 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
9386 (TSK == TSK_ExplicitInstantiationDefinition ||
9387 DLLImportExplicitInstantiationDef)) {
9388 // FIXME: Need to notify the ASTMutationListener that we did this.
9389 Def->setTemplateSpecializationKind(TSK);
9391 if (!getDLLAttr(Def) && getDLLAttr(Specialization) &&
9392 (Context.getTargetInfo().getCXXABI().isMicrosoft() ||
9393 Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())) {
9394 // In the MS ABI, an explicit instantiation definition can add a dll
9395 // attribute to a template with a previous instantiation declaration.
9396 // MinGW doesn't allow this.
9397 auto *A = cast<InheritableAttr>(
9398 getDLLAttr(Specialization)->clone(getASTContext()));
9399 A->setInherited(true);
9401 dllExportImportClassTemplateSpecialization(*this, Def);
9405 // Fix a TSK_ImplicitInstantiation followed by a
9406 // TSK_ExplicitInstantiationDefinition
9407 bool NewlyDLLExported =
9408 !PreviouslyDLLExported && Specialization->hasAttr<DLLExportAttr>();
9409 if (Old_TSK == TSK_ImplicitInstantiation && NewlyDLLExported &&
9410 (Context.getTargetInfo().getCXXABI().isMicrosoft() ||
9411 Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())) {
9412 // In the MS ABI, an explicit instantiation definition can add a dll
9413 // attribute to a template with a previous implicit instantiation.
9414 // MinGW doesn't allow this. We limit clang to only adding dllexport, to
9415 // avoid potentially strange codegen behavior. For example, if we extend
9416 // this conditional to dllimport, and we have a source file calling a
9417 // method on an implicitly instantiated template class instance and then
9418 // declaring a dllimport explicit instantiation definition for the same
9419 // template class, the codegen for the method call will not respect the
9420 // dllimport, while it will with cl. The Def will already have the DLL
9421 // attribute, since the Def and Specialization will be the same in the
9422 // case of Old_TSK == TSK_ImplicitInstantiation, and we already added the
9423 // attribute to the Specialization; we just need to make it take effect.
9424 assert(Def == Specialization &&
9425 "Def and Specialization should match for implicit instantiation");
9426 dllExportImportClassTemplateSpecialization(*this, Def);
9429 // In MinGW mode, export the template instantiation if the declaration
9430 // was marked dllexport.
9431 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
9432 Context.getTargetInfo().getTriple().isWindowsGNUEnvironment() &&
9433 PrevDecl->hasAttr<DLLExportAttr>()) {
9434 dllExportImportClassTemplateSpecialization(*this, Def);
9437 // Set the template specialization kind. Make sure it is set before
9438 // instantiating the members which will trigger ASTConsumer callbacks.
9439 Specialization->setTemplateSpecializationKind(TSK);
9440 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
9443 // Set the template specialization kind.
9444 Specialization->setTemplateSpecializationKind(TSK);
9447 return Specialization;
9450 // Explicit instantiation of a member class of a class template.
9452 Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc,
9453 SourceLocation TemplateLoc, unsigned TagSpec,
9454 SourceLocation KWLoc, CXXScopeSpec &SS,
9455 IdentifierInfo *Name, SourceLocation NameLoc,
9456 const ParsedAttributesView &Attr) {
9459 bool IsDependent = false;
9460 Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference,
9461 KWLoc, SS, Name, NameLoc, Attr, AS_none,
9462 /*ModulePrivateLoc=*/SourceLocation(),
9463 MultiTemplateParamsArg(), Owned, IsDependent,
9464 SourceLocation(), false, TypeResult(),
9465 /*IsTypeSpecifier*/false,
9466 /*IsTemplateParamOrArg*/false);
9467 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
9472 TagDecl *Tag = cast<TagDecl>(TagD);
9473 assert(!Tag->isEnum() && "shouldn't see enumerations here");
9475 if (Tag->isInvalidDecl())
9478 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
9479 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
9481 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
9482 << Context.getTypeDeclType(Record);
9483 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
9487 // C++0x [temp.explicit]p2:
9488 // If the explicit instantiation is for a class or member class, the
9489 // elaborated-type-specifier in the declaration shall include a
9490 // simple-template-id.
9492 // C++98 has the same restriction, just worded differently.
9493 if (!ScopeSpecifierHasTemplateId(SS))
9494 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
9495 << Record << SS.getRange();
9497 // C++0x [temp.explicit]p2:
9498 // There are two forms of explicit instantiation: an explicit instantiation
9499 // definition and an explicit instantiation declaration. An explicit
9500 // instantiation declaration begins with the extern keyword. [...]
9501 TemplateSpecializationKind TSK
9502 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
9503 : TSK_ExplicitInstantiationDeclaration;
9505 CheckExplicitInstantiation(*this, Record, NameLoc, true, TSK);
9507 // Verify that it is okay to explicitly instantiate here.
9508 CXXRecordDecl *PrevDecl
9509 = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
9510 if (!PrevDecl && Record->getDefinition())
9513 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
9514 bool HasNoEffect = false;
9515 assert(MSInfo && "No member specialization information?");
9516 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
9518 MSInfo->getTemplateSpecializationKind(),
9519 MSInfo->getPointOfInstantiation(),
9526 CXXRecordDecl *RecordDef
9527 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
9529 // C++ [temp.explicit]p3:
9530 // A definition of a member class of a class template shall be in scope
9531 // at the point of an explicit instantiation of the member class.
9533 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
9535 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
9536 << 0 << Record->getDeclName() << Record->getDeclContext();
9537 Diag(Pattern->getLocation(), diag::note_forward_declaration)
9541 if (InstantiateClass(NameLoc, Record, Def,
9542 getTemplateInstantiationArgs(Record),
9546 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
9552 // Instantiate all of the members of the class.
9553 InstantiateClassMembers(NameLoc, RecordDef,
9554 getTemplateInstantiationArgs(Record), TSK);
9556 if (TSK == TSK_ExplicitInstantiationDefinition)
9557 MarkVTableUsed(NameLoc, RecordDef, true);
9559 // FIXME: We don't have any representation for explicit instantiations of
9560 // member classes. Such a representation is not needed for compilation, but it
9561 // should be available for clients that want to see all of the declarations in
9566 DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
9567 SourceLocation ExternLoc,
9568 SourceLocation TemplateLoc,
9570 // Explicit instantiations always require a name.
9571 // TODO: check if/when DNInfo should replace Name.
9572 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
9573 DeclarationName Name = NameInfo.getName();
9575 if (!D.isInvalidType())
9576 Diag(D.getDeclSpec().getBeginLoc(),
9577 diag::err_explicit_instantiation_requires_name)
9578 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
9583 // The scope passed in may not be a decl scope. Zip up the scope tree until
9584 // we find one that is.
9585 while ((S->getFlags() & Scope::DeclScope) == 0 ||
9586 (S->getFlags() & Scope::TemplateParamScope) != 0)
9589 // Determine the type of the declaration.
9590 TypeSourceInfo *T = GetTypeForDeclarator(D, S);
9591 QualType R = T->getType();
9596 // A storage-class-specifier shall not be specified in [...] an explicit
9597 // instantiation (14.7.2) directive.
9598 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
9599 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
9602 } else if (D.getDeclSpec().getStorageClassSpec()
9603 != DeclSpec::SCS_unspecified) {
9604 // Complain about then remove the storage class specifier.
9605 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
9606 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
9608 D.getMutableDeclSpec().ClearStorageClassSpecs();
9611 // C++0x [temp.explicit]p1:
9612 // [...] An explicit instantiation of a function template shall not use the
9613 // inline or constexpr specifiers.
9614 // Presumably, this also applies to member functions of class templates as
9616 if (D.getDeclSpec().isInlineSpecified())
9617 Diag(D.getDeclSpec().getInlineSpecLoc(),
9618 getLangOpts().CPlusPlus11 ?
9619 diag::err_explicit_instantiation_inline :
9620 diag::warn_explicit_instantiation_inline_0x)
9621 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
9622 if (D.getDeclSpec().hasConstexprSpecifier() && R->isFunctionType())
9623 // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
9624 // not already specified.
9625 Diag(D.getDeclSpec().getConstexprSpecLoc(),
9626 diag::err_explicit_instantiation_constexpr);
9628 // A deduction guide is not on the list of entities that can be explicitly
9630 if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
9631 Diag(D.getDeclSpec().getBeginLoc(), diag::err_deduction_guide_specialized)
9632 << /*explicit instantiation*/ 0;
9636 // C++0x [temp.explicit]p2:
9637 // There are two forms of explicit instantiation: an explicit instantiation
9638 // definition and an explicit instantiation declaration. An explicit
9639 // instantiation declaration begins with the extern keyword. [...]
9640 TemplateSpecializationKind TSK
9641 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
9642 : TSK_ExplicitInstantiationDeclaration;
9644 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
9645 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
9647 if (!R->isFunctionType()) {
9648 // C++ [temp.explicit]p1:
9649 // A [...] static data member of a class template can be explicitly
9650 // instantiated from the member definition associated with its class
9652 // C++1y [temp.explicit]p1:
9653 // A [...] variable [...] template specialization can be explicitly
9654 // instantiated from its template.
9655 if (Previous.isAmbiguous())
9658 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
9659 VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
9661 if (!PrevTemplate) {
9662 if (!Prev || !Prev->isStaticDataMember()) {
9663 // We expect to see a static data member here.
9664 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
9666 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
9668 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
9672 if (!Prev->getInstantiatedFromStaticDataMember()) {
9673 // FIXME: Check for explicit specialization?
9674 Diag(D.getIdentifierLoc(),
9675 diag::err_explicit_instantiation_data_member_not_instantiated)
9677 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
9678 // FIXME: Can we provide a note showing where this was declared?
9682 // Explicitly instantiate a variable template.
9684 // C++1y [dcl.spec.auto]p6:
9685 // ... A program that uses auto or decltype(auto) in a context not
9686 // explicitly allowed in this section is ill-formed.
9688 // This includes auto-typed variable template instantiations.
9689 if (R->isUndeducedType()) {
9690 Diag(T->getTypeLoc().getBeginLoc(),
9691 diag::err_auto_not_allowed_var_inst);
9695 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
9696 // C++1y [temp.explicit]p3:
9697 // If the explicit instantiation is for a variable, the unqualified-id
9698 // in the declaration shall be a template-id.
9699 Diag(D.getIdentifierLoc(),
9700 diag::err_explicit_instantiation_without_template_id)
9702 Diag(PrevTemplate->getLocation(),
9703 diag::note_explicit_instantiation_here);
9707 // Translate the parser's template argument list into our AST format.
9708 TemplateArgumentListInfo TemplateArgs =
9709 makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
9711 DeclResult Res = CheckVarTemplateId(PrevTemplate, TemplateLoc,
9712 D.getIdentifierLoc(), TemplateArgs);
9713 if (Res.isInvalid())
9716 // Ignore access control bits, we don't need them for redeclaration
9718 Prev = cast<VarDecl>(Res.get());
9721 // C++0x [temp.explicit]p2:
9722 // If the explicit instantiation is for a member function, a member class
9723 // or a static data member of a class template specialization, the name of
9724 // the class template specialization in the qualified-id for the member
9725 // name shall be a simple-template-id.
9727 // C++98 has the same restriction, just worded differently.
9729 // This does not apply to variable template specializations, where the
9730 // template-id is in the unqualified-id instead.
9731 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate)
9732 Diag(D.getIdentifierLoc(),
9733 diag::ext_explicit_instantiation_without_qualified_id)
9734 << Prev << D.getCXXScopeSpec().getRange();
9736 CheckExplicitInstantiation(*this, Prev, D.getIdentifierLoc(), true, TSK);
9738 // Verify that it is okay to explicitly instantiate here.
9739 TemplateSpecializationKind PrevTSK = Prev->getTemplateSpecializationKind();
9740 SourceLocation POI = Prev->getPointOfInstantiation();
9741 bool HasNoEffect = false;
9742 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
9743 PrevTSK, POI, HasNoEffect))
9747 // Instantiate static data member or variable template.
9748 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
9749 // Merge attributes.
9750 ProcessDeclAttributeList(S, Prev, D.getDeclSpec().getAttributes());
9751 if (TSK == TSK_ExplicitInstantiationDefinition)
9752 InstantiateVariableDefinition(D.getIdentifierLoc(), Prev);
9755 // Check the new variable specialization against the parsed input.
9756 if (PrevTemplate && Prev && !Context.hasSameType(Prev->getType(), R)) {
9757 Diag(T->getTypeLoc().getBeginLoc(),
9758 diag::err_invalid_var_template_spec_type)
9759 << 0 << PrevTemplate << R << Prev->getType();
9760 Diag(PrevTemplate->getLocation(), diag::note_template_declared_here)
9761 << 2 << PrevTemplate->getDeclName();
9765 // FIXME: Create an ExplicitInstantiation node?
9766 return (Decl*) nullptr;
9769 // If the declarator is a template-id, translate the parser's template
9770 // argument list into our AST format.
9771 bool HasExplicitTemplateArgs = false;
9772 TemplateArgumentListInfo TemplateArgs;
9773 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
9774 TemplateArgs = makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
9775 HasExplicitTemplateArgs = true;
9778 // C++ [temp.explicit]p1:
9779 // A [...] function [...] can be explicitly instantiated from its template.
9780 // A member function [...] of a class template can be explicitly
9781 // instantiated from the member definition associated with its class
9783 UnresolvedSet<8> TemplateMatches;
9784 FunctionDecl *NonTemplateMatch = nullptr;
9785 TemplateSpecCandidateSet FailedCandidates(D.getIdentifierLoc());
9786 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
9788 NamedDecl *Prev = *P;
9789 if (!HasExplicitTemplateArgs) {
9790 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
9791 QualType Adjusted = adjustCCAndNoReturn(R, Method->getType(),
9792 /*AdjustExceptionSpec*/true);
9793 if (Context.hasSameUnqualifiedType(Method->getType(), Adjusted)) {
9794 if (Method->getPrimaryTemplate()) {
9795 TemplateMatches.addDecl(Method, P.getAccess());
9797 // FIXME: Can this assert ever happen? Needs a test.
9798 assert(!NonTemplateMatch && "Multiple NonTemplateMatches");
9799 NonTemplateMatch = Method;
9805 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
9809 TemplateDeductionInfo Info(FailedCandidates.getLocation());
9810 FunctionDecl *Specialization = nullptr;
9811 if (TemplateDeductionResult TDK
9812 = DeduceTemplateArguments(FunTmpl,
9813 (HasExplicitTemplateArgs ? &TemplateArgs
9815 R, Specialization, Info)) {
9816 // Keep track of almost-matches.
9817 FailedCandidates.addCandidate()
9818 .set(P.getPair(), FunTmpl->getTemplatedDecl(),
9819 MakeDeductionFailureInfo(Context, TDK, Info));
9824 // Target attributes are part of the cuda function signature, so
9825 // the cuda target of the instantiated function must match that of its
9826 // template. Given that C++ template deduction does not take
9827 // target attributes into account, we reject candidates here that
9828 // have a different target.
9829 if (LangOpts.CUDA &&
9830 IdentifyCUDATarget(Specialization,
9831 /* IgnoreImplicitHDAttr = */ true) !=
9832 IdentifyCUDATarget(D.getDeclSpec().getAttributes())) {
9833 FailedCandidates.addCandidate().set(
9834 P.getPair(), FunTmpl->getTemplatedDecl(),
9835 MakeDeductionFailureInfo(Context, TDK_CUDATargetMismatch, Info));
9839 TemplateMatches.addDecl(Specialization, P.getAccess());
9842 FunctionDecl *Specialization = NonTemplateMatch;
9843 if (!Specialization) {
9844 // Find the most specialized function template specialization.
9845 UnresolvedSetIterator Result = getMostSpecialized(
9846 TemplateMatches.begin(), TemplateMatches.end(), FailedCandidates,
9847 D.getIdentifierLoc(),
9848 PDiag(diag::err_explicit_instantiation_not_known) << Name,
9849 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
9850 PDiag(diag::note_explicit_instantiation_candidate));
9852 if (Result == TemplateMatches.end())
9855 // Ignore access control bits, we don't need them for redeclaration checking.
9856 Specialization = cast<FunctionDecl>(*Result);
9859 // C++11 [except.spec]p4
9860 // In an explicit instantiation an exception-specification may be specified,
9861 // but is not required.
9862 // If an exception-specification is specified in an explicit instantiation
9863 // directive, it shall be compatible with the exception-specifications of
9864 // other declarations of that function.
9865 if (auto *FPT = R->getAs<FunctionProtoType>())
9866 if (FPT->hasExceptionSpec()) {
9868 diag::err_mismatched_exception_spec_explicit_instantiation;
9869 if (getLangOpts().MicrosoftExt)
9870 DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
9871 bool Result = CheckEquivalentExceptionSpec(
9872 PDiag(DiagID) << Specialization->getType(),
9873 PDiag(diag::note_explicit_instantiation_here),
9874 Specialization->getType()->getAs<FunctionProtoType>(),
9875 Specialization->getLocation(), FPT, D.getBeginLoc());
9876 // In Microsoft mode, mismatching exception specifications just cause a
9878 if (!getLangOpts().MicrosoftExt && Result)
9882 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
9883 Diag(D.getIdentifierLoc(),
9884 diag::err_explicit_instantiation_member_function_not_instantiated)
9886 << (Specialization->getTemplateSpecializationKind() ==
9887 TSK_ExplicitSpecialization);
9888 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
9892 FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
9893 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
9894 PrevDecl = Specialization;
9897 bool HasNoEffect = false;
9898 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
9900 PrevDecl->getTemplateSpecializationKind(),
9901 PrevDecl->getPointOfInstantiation(),
9905 // FIXME: We may still want to build some representation of this
9906 // explicit specialization.
9908 return (Decl*) nullptr;
9911 // HACK: libc++ has a bug where it attempts to explicitly instantiate the
9913 // valarray<size_t>::valarray(size_t) and
9914 // valarray<size_t>::~valarray()
9915 // that it declared to have internal linkage with the internal_linkage
9916 // attribute. Ignore the explicit instantiation declaration in this case.
9917 if (Specialization->hasAttr<InternalLinkageAttr>() &&
9918 TSK == TSK_ExplicitInstantiationDeclaration) {
9919 if (auto *RD = dyn_cast<CXXRecordDecl>(Specialization->getDeclContext()))
9920 if (RD->getIdentifier() && RD->getIdentifier()->isStr("valarray") &&
9921 RD->isInStdNamespace())
9922 return (Decl*) nullptr;
9925 ProcessDeclAttributeList(S, Specialization, D.getDeclSpec().getAttributes());
9927 // In MSVC mode, dllimported explicit instantiation definitions are treated as
9928 // instantiation declarations.
9929 if (TSK == TSK_ExplicitInstantiationDefinition &&
9930 Specialization->hasAttr<DLLImportAttr>() &&
9931 Context.getTargetInfo().getCXXABI().isMicrosoft())
9932 TSK = TSK_ExplicitInstantiationDeclaration;
9934 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
9936 if (Specialization->isDefined()) {
9937 // Let the ASTConsumer know that this function has been explicitly
9938 // instantiated now, and its linkage might have changed.
9939 Consumer.HandleTopLevelDecl(DeclGroupRef(Specialization));
9940 } else if (TSK == TSK_ExplicitInstantiationDefinition)
9941 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
9943 // C++0x [temp.explicit]p2:
9944 // If the explicit instantiation is for a member function, a member class
9945 // or a static data member of a class template specialization, the name of
9946 // the class template specialization in the qualified-id for the member
9947 // name shall be a simple-template-id.
9949 // C++98 has the same restriction, just worded differently.
9950 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
9951 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId && !FunTmpl &&
9952 D.getCXXScopeSpec().isSet() &&
9953 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
9954 Diag(D.getIdentifierLoc(),
9955 diag::ext_explicit_instantiation_without_qualified_id)
9956 << Specialization << D.getCXXScopeSpec().getRange();
9958 CheckExplicitInstantiation(
9960 FunTmpl ? (NamedDecl *)FunTmpl
9961 : Specialization->getInstantiatedFromMemberFunction(),
9962 D.getIdentifierLoc(), D.getCXXScopeSpec().isSet(), TSK);
9964 // FIXME: Create some kind of ExplicitInstantiationDecl here.
9965 return (Decl*) nullptr;
9969 Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
9970 const CXXScopeSpec &SS, IdentifierInfo *Name,
9971 SourceLocation TagLoc, SourceLocation NameLoc) {
9972 // This has to hold, because SS is expected to be defined.
9973 assert(Name && "Expected a name in a dependent tag");
9975 NestedNameSpecifier *NNS = SS.getScopeRep();
9979 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
9981 if (TUK == TUK_Declaration || TUK == TUK_Definition) {
9982 Diag(NameLoc, diag::err_dependent_tag_decl)
9983 << (TUK == TUK_Definition) << Kind << SS.getRange();
9987 // Create the resulting type.
9988 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
9989 QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
9991 // Create type-source location information for this type.
9993 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(Result);
9994 TL.setElaboratedKeywordLoc(TagLoc);
9995 TL.setQualifierLoc(SS.getWithLocInContext(Context));
9996 TL.setNameLoc(NameLoc);
9997 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
10001 Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
10002 const CXXScopeSpec &SS, const IdentifierInfo &II,
10003 SourceLocation IdLoc) {
10004 if (SS.isInvalid())
10007 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
10009 getLangOpts().CPlusPlus11 ?
10010 diag::warn_cxx98_compat_typename_outside_of_template :
10011 diag::ext_typename_outside_of_template)
10012 << FixItHint::CreateRemoval(TypenameLoc);
10014 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
10015 QualType T = CheckTypenameType(TypenameLoc.isValid()? ETK_Typename : ETK_None,
10016 TypenameLoc, QualifierLoc, II, IdLoc);
10020 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
10021 if (isa<DependentNameType>(T)) {
10022 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
10023 TL.setElaboratedKeywordLoc(TypenameLoc);
10024 TL.setQualifierLoc(QualifierLoc);
10025 TL.setNameLoc(IdLoc);
10027 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
10028 TL.setElaboratedKeywordLoc(TypenameLoc);
10029 TL.setQualifierLoc(QualifierLoc);
10030 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
10033 return CreateParsedType(T, TSI);
10037 Sema::ActOnTypenameType(Scope *S,
10038 SourceLocation TypenameLoc,
10039 const CXXScopeSpec &SS,
10040 SourceLocation TemplateKWLoc,
10041 TemplateTy TemplateIn,
10042 IdentifierInfo *TemplateII,
10043 SourceLocation TemplateIILoc,
10044 SourceLocation LAngleLoc,
10045 ASTTemplateArgsPtr TemplateArgsIn,
10046 SourceLocation RAngleLoc) {
10047 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
10049 getLangOpts().CPlusPlus11 ?
10050 diag::warn_cxx98_compat_typename_outside_of_template :
10051 diag::ext_typename_outside_of_template)
10052 << FixItHint::CreateRemoval(TypenameLoc);
10054 // Strangely, non-type results are not ignored by this lookup, so the
10055 // program is ill-formed if it finds an injected-class-name.
10056 if (TypenameLoc.isValid()) {
10058 dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, false));
10059 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
10060 Diag(TemplateIILoc,
10061 diag::ext_out_of_line_qualified_id_type_names_constructor)
10062 << TemplateII << 0 /*injected-class-name used as template name*/
10063 << (TemplateKWLoc.isValid() ? 1 : 0 /*'template'/'typename' keyword*/);
10067 // Translate the parser's template argument list in our AST format.
10068 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
10069 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
10071 TemplateName Template = TemplateIn.get();
10072 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
10073 // Construct a dependent template specialization type.
10074 assert(DTN && "dependent template has non-dependent name?");
10075 assert(DTN->getQualifier() == SS.getScopeRep());
10076 QualType T = Context.getDependentTemplateSpecializationType(ETK_Typename,
10077 DTN->getQualifier(),
10078 DTN->getIdentifier(),
10081 // Create source-location information for this type.
10082 TypeLocBuilder Builder;
10083 DependentTemplateSpecializationTypeLoc SpecTL
10084 = Builder.push<DependentTemplateSpecializationTypeLoc>(T);
10085 SpecTL.setElaboratedKeywordLoc(TypenameLoc);
10086 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
10087 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
10088 SpecTL.setTemplateNameLoc(TemplateIILoc);
10089 SpecTL.setLAngleLoc(LAngleLoc);
10090 SpecTL.setRAngleLoc(RAngleLoc);
10091 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
10092 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
10093 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
10096 QualType T = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
10100 // Provide source-location information for the template specialization type.
10101 TypeLocBuilder Builder;
10102 TemplateSpecializationTypeLoc SpecTL
10103 = Builder.push<TemplateSpecializationTypeLoc>(T);
10104 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
10105 SpecTL.setTemplateNameLoc(TemplateIILoc);
10106 SpecTL.setLAngleLoc(LAngleLoc);
10107 SpecTL.setRAngleLoc(RAngleLoc);
10108 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
10109 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
10111 T = Context.getElaboratedType(ETK_Typename, SS.getScopeRep(), T);
10112 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
10113 TL.setElaboratedKeywordLoc(TypenameLoc);
10114 TL.setQualifierLoc(SS.getWithLocInContext(Context));
10116 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
10117 return CreateParsedType(T, TSI);
10121 /// Determine whether this failed name lookup should be treated as being
10122 /// disabled by a usage of std::enable_if.
10123 static bool isEnableIf(NestedNameSpecifierLoc NNS, const IdentifierInfo &II,
10124 SourceRange &CondRange, Expr *&Cond) {
10125 // We must be looking for a ::type...
10126 if (!II.isStr("type"))
10129 // ... within an explicitly-written template specialization...
10130 if (!NNS || !NNS.getNestedNameSpecifier()->getAsType())
10132 TypeLoc EnableIfTy = NNS.getTypeLoc();
10133 TemplateSpecializationTypeLoc EnableIfTSTLoc =
10134 EnableIfTy.getAs<TemplateSpecializationTypeLoc>();
10135 if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
10137 const TemplateSpecializationType *EnableIfTST = EnableIfTSTLoc.getTypePtr();
10139 // ... which names a complete class template declaration...
10140 const TemplateDecl *EnableIfDecl =
10141 EnableIfTST->getTemplateName().getAsTemplateDecl();
10142 if (!EnableIfDecl || EnableIfTST->isIncompleteType())
10145 // ... called "enable_if".
10146 const IdentifierInfo *EnableIfII =
10147 EnableIfDecl->getDeclName().getAsIdentifierInfo();
10148 if (!EnableIfII || !EnableIfII->isStr("enable_if"))
10151 // Assume the first template argument is the condition.
10152 CondRange = EnableIfTSTLoc.getArgLoc(0).getSourceRange();
10154 // Dig out the condition.
10156 if (EnableIfTSTLoc.getArgLoc(0).getArgument().getKind()
10157 != TemplateArgument::Expression)
10160 Cond = EnableIfTSTLoc.getArgLoc(0).getSourceExpression();
10162 // Ignore Boolean literals; they add no value.
10163 if (isa<CXXBoolLiteralExpr>(Cond->IgnoreParenCasts()))
10169 /// Build the type that describes a C++ typename specifier,
10170 /// e.g., "typename T::type".
10172 Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
10173 SourceLocation KeywordLoc,
10174 NestedNameSpecifierLoc QualifierLoc,
10175 const IdentifierInfo &II,
10176 SourceLocation IILoc) {
10178 SS.Adopt(QualifierLoc);
10180 DeclContext *Ctx = computeDeclContext(SS);
10182 // If the nested-name-specifier is dependent and couldn't be
10183 // resolved to a type, build a typename type.
10184 assert(QualifierLoc.getNestedNameSpecifier()->isDependent());
10185 return Context.getDependentNameType(Keyword,
10186 QualifierLoc.getNestedNameSpecifier(),
10190 // If the nested-name-specifier refers to the current instantiation,
10191 // the "typename" keyword itself is superfluous. In C++03, the
10192 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
10193 // allows such extraneous "typename" keywords, and we retroactively
10194 // apply this DR to C++03 code with only a warning. In any case we continue.
10196 if (RequireCompleteDeclContext(SS, Ctx))
10199 DeclarationName Name(&II);
10200 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
10201 LookupQualifiedName(Result, Ctx, SS);
10202 unsigned DiagID = 0;
10203 Decl *Referenced = nullptr;
10204 switch (Result.getResultKind()) {
10205 case LookupResult::NotFound: {
10206 // If we're looking up 'type' within a template named 'enable_if', produce
10207 // a more specific diagnostic.
10208 SourceRange CondRange;
10209 Expr *Cond = nullptr;
10210 if (isEnableIf(QualifierLoc, II, CondRange, Cond)) {
10211 // If we have a condition, narrow it down to the specific failed
10215 std::string FailedDescription;
10216 std::tie(FailedCond, FailedDescription) =
10217 findFailedBooleanCondition(Cond);
10219 Diag(FailedCond->getExprLoc(),
10220 diag::err_typename_nested_not_found_requirement)
10221 << FailedDescription
10222 << FailedCond->getSourceRange();
10226 Diag(CondRange.getBegin(), diag::err_typename_nested_not_found_enable_if)
10227 << Ctx << CondRange;
10231 DiagID = diag::err_typename_nested_not_found;
10235 case LookupResult::FoundUnresolvedValue: {
10236 // We found a using declaration that is a value. Most likely, the using
10237 // declaration itself is meant to have the 'typename' keyword.
10238 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
10240 Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
10241 << Name << Ctx << FullRange;
10242 if (UnresolvedUsingValueDecl *Using
10243 = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
10244 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
10245 Diag(Loc, diag::note_using_value_decl_missing_typename)
10246 << FixItHint::CreateInsertion(Loc, "typename ");
10249 // Fall through to create a dependent typename type, from which we can recover
10253 case LookupResult::NotFoundInCurrentInstantiation:
10254 // Okay, it's a member of an unknown instantiation.
10255 return Context.getDependentNameType(Keyword,
10256 QualifierLoc.getNestedNameSpecifier(),
10259 case LookupResult::Found:
10260 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
10261 // C++ [class.qual]p2:
10262 // In a lookup in which function names are not ignored and the
10263 // nested-name-specifier nominates a class C, if the name specified
10264 // after the nested-name-specifier, when looked up in C, is the
10265 // injected-class-name of C [...] then the name is instead considered
10266 // to name the constructor of class C.
10268 // Unlike in an elaborated-type-specifier, function names are not ignored
10269 // in typename-specifier lookup. However, they are ignored in all the
10270 // contexts where we form a typename type with no keyword (that is, in
10271 // mem-initializer-ids, base-specifiers, and elaborated-type-specifiers).
10273 // FIXME: That's not strictly true: mem-initializer-id lookup does not
10274 // ignore functions, but that appears to be an oversight.
10275 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(Ctx);
10276 auto *FoundRD = dyn_cast<CXXRecordDecl>(Type);
10277 if (Keyword == ETK_Typename && LookupRD && FoundRD &&
10278 FoundRD->isInjectedClassName() &&
10279 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
10280 Diag(IILoc, diag::ext_out_of_line_qualified_id_type_names_constructor)
10281 << &II << 1 << 0 /*'typename' keyword used*/;
10283 // We found a type. Build an ElaboratedType, since the
10284 // typename-specifier was just sugar.
10285 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
10286 return Context.getElaboratedType(Keyword,
10287 QualifierLoc.getNestedNameSpecifier(),
10288 Context.getTypeDeclType(Type));
10291 // C++ [dcl.type.simple]p2:
10292 // A type-specifier of the form
10293 // typename[opt] nested-name-specifier[opt] template-name
10294 // is a placeholder for a deduced class type [...].
10295 if (getLangOpts().CPlusPlus17) {
10296 if (auto *TD = getAsTypeTemplateDecl(Result.getFoundDecl())) {
10297 return Context.getElaboratedType(
10298 Keyword, QualifierLoc.getNestedNameSpecifier(),
10299 Context.getDeducedTemplateSpecializationType(TemplateName(TD),
10300 QualType(), false));
10304 DiagID = diag::err_typename_nested_not_type;
10305 Referenced = Result.getFoundDecl();
10308 case LookupResult::FoundOverloaded:
10309 DiagID = diag::err_typename_nested_not_type;
10310 Referenced = *Result.begin();
10313 case LookupResult::Ambiguous:
10317 // If we get here, it's because name lookup did not find a
10318 // type. Emit an appropriate diagnostic and return an error.
10319 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
10321 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
10323 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
10329 // See Sema::RebuildTypeInCurrentInstantiation
10330 class CurrentInstantiationRebuilder
10331 : public TreeTransform<CurrentInstantiationRebuilder> {
10332 SourceLocation Loc;
10333 DeclarationName Entity;
10336 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
10338 CurrentInstantiationRebuilder(Sema &SemaRef,
10339 SourceLocation Loc,
10340 DeclarationName Entity)
10341 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
10342 Loc(Loc), Entity(Entity) { }
10344 /// Determine whether the given type \p T has already been
10347 /// For the purposes of type reconstruction, a type has already been
10348 /// transformed if it is NULL or if it is not dependent.
10349 bool AlreadyTransformed(QualType T) {
10350 return T.isNull() || !T->isDependentType();
10353 /// Returns the location of the entity whose type is being
10355 SourceLocation getBaseLocation() { return Loc; }
10357 /// Returns the name of the entity whose type is being rebuilt.
10358 DeclarationName getBaseEntity() { return Entity; }
10360 /// Sets the "base" location and entity when that
10361 /// information is known based on another transformation.
10362 void setBase(SourceLocation Loc, DeclarationName Entity) {
10364 this->Entity = Entity;
10367 ExprResult TransformLambdaExpr(LambdaExpr *E) {
10368 // Lambdas never need to be transformed.
10372 } // end anonymous namespace
10374 /// Rebuilds a type within the context of the current instantiation.
10376 /// The type \p T is part of the type of an out-of-line member definition of
10377 /// a class template (or class template partial specialization) that was parsed
10378 /// and constructed before we entered the scope of the class template (or
10379 /// partial specialization thereof). This routine will rebuild that type now
10380 /// that we have entered the declarator's scope, which may produce different
10381 /// canonical types, e.g.,
10384 /// template<typename T>
10386 /// typedef T* pointer;
10387 /// pointer data();
10390 /// template<typename T>
10391 /// typename X<T>::pointer X<T>::data() { ... }
10394 /// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
10395 /// since we do not know that we can look into X<T> when we parsed the type.
10396 /// This function will rebuild the type, performing the lookup of "pointer"
10397 /// in X<T> and returning an ElaboratedType whose canonical type is the same
10398 /// as the canonical type of T*, allowing the return types of the out-of-line
10399 /// definition and the declaration to match.
10400 TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
10401 SourceLocation Loc,
10402 DeclarationName Name) {
10403 if (!T || !T->getType()->isDependentType())
10406 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
10407 return Rebuilder.TransformType(T);
10410 ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
10411 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
10412 DeclarationName());
10413 return Rebuilder.TransformExpr(E);
10416 bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
10417 if (SS.isInvalid())
10420 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
10421 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
10422 DeclarationName());
10423 NestedNameSpecifierLoc Rebuilt
10424 = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
10432 /// Rebuild the template parameters now that we know we're in a current
10434 bool Sema::RebuildTemplateParamsInCurrentInstantiation(
10435 TemplateParameterList *Params) {
10436 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
10437 Decl *Param = Params->getParam(I);
10439 // There is nothing to rebuild in a type parameter.
10440 if (isa<TemplateTypeParmDecl>(Param))
10443 // Rebuild the template parameter list of a template template parameter.
10444 if (TemplateTemplateParmDecl *TTP
10445 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
10446 if (RebuildTemplateParamsInCurrentInstantiation(
10447 TTP->getTemplateParameters()))
10453 // Rebuild the type of a non-type template parameter.
10454 NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Param);
10455 TypeSourceInfo *NewTSI
10456 = RebuildTypeInCurrentInstantiation(NTTP->getTypeSourceInfo(),
10457 NTTP->getLocation(),
10458 NTTP->getDeclName());
10462 if (NewTSI->getType()->isUndeducedType()) {
10463 // C++17 [temp.dep.expr]p3:
10464 // An id-expression is type-dependent if it contains
10465 // - an identifier associated by name lookup with a non-type
10466 // template-parameter declared with a type that contains a
10467 // placeholder type (7.1.7.4),
10468 NewTSI = SubstAutoTypeSourceInfo(NewTSI, Context.DependentTy);
10471 if (NewTSI != NTTP->getTypeSourceInfo()) {
10472 NTTP->setTypeSourceInfo(NewTSI);
10473 NTTP->setType(NewTSI->getType());
10480 /// Produces a formatted string that describes the binding of
10481 /// template parameters to template arguments.
10483 Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
10484 const TemplateArgumentList &Args) {
10485 return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
10489 Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
10490 const TemplateArgument *Args,
10491 unsigned NumArgs) {
10492 SmallString<128> Str;
10493 llvm::raw_svector_ostream Out(Str);
10495 if (!Params || Params->size() == 0 || NumArgs == 0)
10496 return std::string();
10498 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
10507 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
10508 Out << Id->getName();
10514 Args[I].print(getPrintingPolicy(), Out);
10521 void Sema::MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
10522 CachedTokens &Toks) {
10526 auto LPT = std::make_unique<LateParsedTemplate>();
10528 // Take tokens to avoid allocations
10529 LPT->Toks.swap(Toks);
10531 LateParsedTemplateMap.insert(std::make_pair(FD, std::move(LPT)));
10533 FD->setLateTemplateParsed(true);
10536 void Sema::UnmarkAsLateParsedTemplate(FunctionDecl *FD) {
10539 FD->setLateTemplateParsed(false);
10542 bool Sema::IsInsideALocalClassWithinATemplateFunction() {
10543 DeclContext *DC = CurContext;
10546 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
10547 const FunctionDecl *FD = RD->isLocalClass();
10548 return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
10549 } else if (DC->isTranslationUnit() || DC->isNamespace())
10552 DC = DC->getParent();
10558 /// Walk the path from which a declaration was instantiated, and check
10559 /// that every explicit specialization along that path is visible. This enforces
10560 /// C++ [temp.expl.spec]/6:
10562 /// If a template, a member template or a member of a class template is
10563 /// explicitly specialized then that specialization shall be declared before
10564 /// the first use of that specialization that would cause an implicit
10565 /// instantiation to take place, in every translation unit in which such a
10566 /// use occurs; no diagnostic is required.
10568 /// and also C++ [temp.class.spec]/1:
10570 /// A partial specialization shall be declared before the first use of a
10571 /// class template specialization that would make use of the partial
10572 /// specialization as the result of an implicit or explicit instantiation
10573 /// in every translation unit in which such a use occurs; no diagnostic is
10575 class ExplicitSpecializationVisibilityChecker {
10577 SourceLocation Loc;
10578 llvm::SmallVector<Module *, 8> Modules;
10581 ExplicitSpecializationVisibilityChecker(Sema &S, SourceLocation Loc)
10582 : S(S), Loc(Loc) {}
10584 void check(NamedDecl *ND) {
10585 if (auto *FD = dyn_cast<FunctionDecl>(ND))
10586 return checkImpl(FD);
10587 if (auto *RD = dyn_cast<CXXRecordDecl>(ND))
10588 return checkImpl(RD);
10589 if (auto *VD = dyn_cast<VarDecl>(ND))
10590 return checkImpl(VD);
10591 if (auto *ED = dyn_cast<EnumDecl>(ND))
10592 return checkImpl(ED);
10596 void diagnose(NamedDecl *D, bool IsPartialSpec) {
10597 auto Kind = IsPartialSpec ? Sema::MissingImportKind::PartialSpecialization
10598 : Sema::MissingImportKind::ExplicitSpecialization;
10599 const bool Recover = true;
10601 // If we got a custom set of modules (because only a subset of the
10602 // declarations are interesting), use them, otherwise let
10603 // diagnoseMissingImport intelligently pick some.
10604 if (Modules.empty())
10605 S.diagnoseMissingImport(Loc, D, Kind, Recover);
10607 S.diagnoseMissingImport(Loc, D, D->getLocation(), Modules, Kind, Recover);
10610 // Check a specific declaration. There are three problematic cases:
10612 // 1) The declaration is an explicit specialization of a template
10614 // 2) The declaration is an explicit specialization of a member of an
10615 // templated class.
10616 // 3) The declaration is an instantiation of a template, and that template
10617 // is an explicit specialization of a member of a templated class.
10619 // We don't need to go any deeper than that, as the instantiation of the
10620 // surrounding class / etc is not triggered by whatever triggered this
10621 // instantiation, and thus should be checked elsewhere.
10622 template<typename SpecDecl>
10623 void checkImpl(SpecDecl *Spec) {
10624 bool IsHiddenExplicitSpecialization = false;
10625 if (Spec->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) {
10626 IsHiddenExplicitSpecialization =
10627 Spec->getMemberSpecializationInfo()
10628 ? !S.hasVisibleMemberSpecialization(Spec, &Modules)
10629 : !S.hasVisibleExplicitSpecialization(Spec, &Modules);
10631 checkInstantiated(Spec);
10634 if (IsHiddenExplicitSpecialization)
10635 diagnose(Spec->getMostRecentDecl(), false);
10638 void checkInstantiated(FunctionDecl *FD) {
10639 if (auto *TD = FD->getPrimaryTemplate())
10643 void checkInstantiated(CXXRecordDecl *RD) {
10644 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD);
10648 auto From = SD->getSpecializedTemplateOrPartial();
10649 if (auto *TD = From.dyn_cast<ClassTemplateDecl *>())
10651 else if (auto *TD =
10652 From.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
10653 if (!S.hasVisibleDeclaration(TD))
10654 diagnose(TD, true);
10659 void checkInstantiated(VarDecl *RD) {
10660 auto *SD = dyn_cast<VarTemplateSpecializationDecl>(RD);
10664 auto From = SD->getSpecializedTemplateOrPartial();
10665 if (auto *TD = From.dyn_cast<VarTemplateDecl *>())
10667 else if (auto *TD =
10668 From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
10669 if (!S.hasVisibleDeclaration(TD))
10670 diagnose(TD, true);
10675 void checkInstantiated(EnumDecl *FD) {}
10677 template<typename TemplDecl>
10678 void checkTemplate(TemplDecl *TD) {
10679 if (TD->isMemberSpecialization()) {
10680 if (!S.hasVisibleMemberSpecialization(TD, &Modules))
10681 diagnose(TD->getMostRecentDecl(), false);
10685 } // end anonymous namespace
10687 void Sema::checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec) {
10688 if (!getLangOpts().Modules)
10691 ExplicitSpecializationVisibilityChecker(*this, Loc).check(Spec);
10694 /// Check whether a template partial specialization that we've discovered
10695 /// is hidden, and produce suitable diagnostics if so.
10696 void Sema::checkPartialSpecializationVisibility(SourceLocation Loc,
10698 llvm::SmallVector<Module *, 8> Modules;
10699 if (!hasVisibleDeclaration(Spec, &Modules))
10700 diagnoseMissingImport(Loc, Spec, Spec->getLocation(), Modules,
10701 MissingImportKind::PartialSpecialization,