xref: /freebsd/contrib/llvm-project/clang/lib/Sema/SemaTemplate.cpp (revision 62987288060ff68c817b7056815aa9fb8ba8ecd7)
1 //===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===//
2 //
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 //===----------------------------------------------------------------------===//
7 //
8 //  This file implements semantic analysis for C++ templates.
9 //===----------------------------------------------------------------------===//
10 
11 #include "TreeTransform.h"
12 #include "clang/AST/ASTConsumer.h"
13 #include "clang/AST/ASTContext.h"
14 #include "clang/AST/Decl.h"
15 #include "clang/AST/DeclFriend.h"
16 #include "clang/AST/DeclTemplate.h"
17 #include "clang/AST/Expr.h"
18 #include "clang/AST/ExprCXX.h"
19 #include "clang/AST/RecursiveASTVisitor.h"
20 #include "clang/AST/TemplateName.h"
21 #include "clang/AST/TypeVisitor.h"
22 #include "clang/Basic/Builtins.h"
23 #include "clang/Basic/DiagnosticSema.h"
24 #include "clang/Basic/LangOptions.h"
25 #include "clang/Basic/PartialDiagnostic.h"
26 #include "clang/Basic/SourceLocation.h"
27 #include "clang/Basic/Stack.h"
28 #include "clang/Basic/TargetInfo.h"
29 #include "clang/Sema/DeclSpec.h"
30 #include "clang/Sema/EnterExpressionEvaluationContext.h"
31 #include "clang/Sema/Initialization.h"
32 #include "clang/Sema/Lookup.h"
33 #include "clang/Sema/Overload.h"
34 #include "clang/Sema/ParsedTemplate.h"
35 #include "clang/Sema/Scope.h"
36 #include "clang/Sema/SemaCUDA.h"
37 #include "clang/Sema/SemaInternal.h"
38 #include "clang/Sema/Template.h"
39 #include "clang/Sema/TemplateDeduction.h"
40 #include "llvm/ADT/BitVector.h"
41 #include "llvm/ADT/SmallBitVector.h"
42 #include "llvm/ADT/SmallString.h"
43 #include "llvm/ADT/StringExtras.h"
44 
45 #include <iterator>
46 #include <optional>
47 using namespace clang;
48 using namespace sema;
49 
50 // Exported for use by Parser.
51 SourceRange
getTemplateParamsRange(TemplateParameterList const * const * Ps,unsigned N)52 clang::getTemplateParamsRange(TemplateParameterList const * const *Ps,
53                               unsigned N) {
54   if (!N) return SourceRange();
55   return SourceRange(Ps[0]->getTemplateLoc(), Ps[N-1]->getRAngleLoc());
56 }
57 
getTemplateDepth(Scope * S) const58 unsigned Sema::getTemplateDepth(Scope *S) const {
59   unsigned Depth = 0;
60 
61   // Each template parameter scope represents one level of template parameter
62   // depth.
63   for (Scope *TempParamScope = S->getTemplateParamParent(); TempParamScope;
64        TempParamScope = TempParamScope->getParent()->getTemplateParamParent()) {
65     ++Depth;
66   }
67 
68   // Note that there are template parameters with the given depth.
69   auto ParamsAtDepth = [&](unsigned D) { Depth = std::max(Depth, D + 1); };
70 
71   // Look for parameters of an enclosing generic lambda. We don't create a
72   // template parameter scope for these.
73   for (FunctionScopeInfo *FSI : getFunctionScopes()) {
74     if (auto *LSI = dyn_cast<LambdaScopeInfo>(FSI)) {
75       if (!LSI->TemplateParams.empty()) {
76         ParamsAtDepth(LSI->AutoTemplateParameterDepth);
77         break;
78       }
79       if (LSI->GLTemplateParameterList) {
80         ParamsAtDepth(LSI->GLTemplateParameterList->getDepth());
81         break;
82       }
83     }
84   }
85 
86   // Look for parameters of an enclosing terse function template. We don't
87   // create a template parameter scope for these either.
88   for (const InventedTemplateParameterInfo &Info :
89        getInventedParameterInfos()) {
90     if (!Info.TemplateParams.empty()) {
91       ParamsAtDepth(Info.AutoTemplateParameterDepth);
92       break;
93     }
94   }
95 
96   return Depth;
97 }
98 
99 /// \brief Determine whether the declaration found is acceptable as the name
100 /// of a template and, if so, return that template declaration. Otherwise,
101 /// returns null.
102 ///
103 /// Note that this may return an UnresolvedUsingValueDecl if AllowDependent
104 /// is true. In all other cases it will return a TemplateDecl (or null).
getAsTemplateNameDecl(NamedDecl * D,bool AllowFunctionTemplates,bool AllowDependent)105 NamedDecl *Sema::getAsTemplateNameDecl(NamedDecl *D,
106                                        bool AllowFunctionTemplates,
107                                        bool AllowDependent) {
108   D = D->getUnderlyingDecl();
109 
110   if (isa<TemplateDecl>(D)) {
111     if (!AllowFunctionTemplates && isa<FunctionTemplateDecl>(D))
112       return nullptr;
113 
114     return D;
115   }
116 
117   if (const auto *Record = dyn_cast<CXXRecordDecl>(D)) {
118     // C++ [temp.local]p1:
119     //   Like normal (non-template) classes, class templates have an
120     //   injected-class-name (Clause 9). The injected-class-name
121     //   can be used with or without a template-argument-list. When
122     //   it is used without a template-argument-list, it is
123     //   equivalent to the injected-class-name followed by the
124     //   template-parameters of the class template enclosed in
125     //   <>. When it is used with a template-argument-list, it
126     //   refers to the specified class template specialization,
127     //   which could be the current specialization or another
128     //   specialization.
129     if (Record->isInjectedClassName()) {
130       Record = cast<CXXRecordDecl>(Record->getDeclContext());
131       if (Record->getDescribedClassTemplate())
132         return Record->getDescribedClassTemplate();
133 
134       if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(Record))
135         return Spec->getSpecializedTemplate();
136     }
137 
138     return nullptr;
139   }
140 
141   // 'using Dependent::foo;' can resolve to a template name.
142   // 'using typename Dependent::foo;' cannot (not even if 'foo' is an
143   // injected-class-name).
144   if (AllowDependent && isa<UnresolvedUsingValueDecl>(D))
145     return D;
146 
147   return nullptr;
148 }
149 
FilterAcceptableTemplateNames(LookupResult & R,bool AllowFunctionTemplates,bool AllowDependent)150 void Sema::FilterAcceptableTemplateNames(LookupResult &R,
151                                          bool AllowFunctionTemplates,
152                                          bool AllowDependent) {
153   LookupResult::Filter filter = R.makeFilter();
154   while (filter.hasNext()) {
155     NamedDecl *Orig = filter.next();
156     if (!getAsTemplateNameDecl(Orig, AllowFunctionTemplates, AllowDependent))
157       filter.erase();
158   }
159   filter.done();
160 }
161 
hasAnyAcceptableTemplateNames(LookupResult & R,bool AllowFunctionTemplates,bool AllowDependent,bool AllowNonTemplateFunctions)162 bool Sema::hasAnyAcceptableTemplateNames(LookupResult &R,
163                                          bool AllowFunctionTemplates,
164                                          bool AllowDependent,
165                                          bool AllowNonTemplateFunctions) {
166   for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
167     if (getAsTemplateNameDecl(*I, AllowFunctionTemplates, AllowDependent))
168       return true;
169     if (AllowNonTemplateFunctions &&
170         isa<FunctionDecl>((*I)->getUnderlyingDecl()))
171       return true;
172   }
173 
174   return false;
175 }
176 
isTemplateName(Scope * S,CXXScopeSpec & SS,bool hasTemplateKeyword,const UnqualifiedId & Name,ParsedType ObjectTypePtr,bool EnteringContext,TemplateTy & TemplateResult,bool & MemberOfUnknownSpecialization,bool Disambiguation)177 TemplateNameKind Sema::isTemplateName(Scope *S,
178                                       CXXScopeSpec &SS,
179                                       bool hasTemplateKeyword,
180                                       const UnqualifiedId &Name,
181                                       ParsedType ObjectTypePtr,
182                                       bool EnteringContext,
183                                       TemplateTy &TemplateResult,
184                                       bool &MemberOfUnknownSpecialization,
185                                       bool Disambiguation) {
186   assert(getLangOpts().CPlusPlus && "No template names in C!");
187 
188   DeclarationName TName;
189   MemberOfUnknownSpecialization = false;
190 
191   switch (Name.getKind()) {
192   case UnqualifiedIdKind::IK_Identifier:
193     TName = DeclarationName(Name.Identifier);
194     break;
195 
196   case UnqualifiedIdKind::IK_OperatorFunctionId:
197     TName = Context.DeclarationNames.getCXXOperatorName(
198                                               Name.OperatorFunctionId.Operator);
199     break;
200 
201   case UnqualifiedIdKind::IK_LiteralOperatorId:
202     TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
203     break;
204 
205   default:
206     return TNK_Non_template;
207   }
208 
209   QualType ObjectType = ObjectTypePtr.get();
210 
211   AssumedTemplateKind AssumedTemplate;
212   LookupResult R(*this, TName, Name.getBeginLoc(), LookupOrdinaryName);
213   if (LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
214                          /*RequiredTemplate=*/SourceLocation(),
215                          &AssumedTemplate,
216                          /*AllowTypoCorrection=*/!Disambiguation))
217     return TNK_Non_template;
218   MemberOfUnknownSpecialization = R.wasNotFoundInCurrentInstantiation();
219 
220   if (AssumedTemplate != AssumedTemplateKind::None) {
221     TemplateResult = TemplateTy::make(Context.getAssumedTemplateName(TName));
222     // Let the parser know whether we found nothing or found functions; if we
223     // found nothing, we want to more carefully check whether this is actually
224     // a function template name versus some other kind of undeclared identifier.
225     return AssumedTemplate == AssumedTemplateKind::FoundNothing
226                ? TNK_Undeclared_template
227                : TNK_Function_template;
228   }
229 
230   if (R.empty())
231     return TNK_Non_template;
232 
233   NamedDecl *D = nullptr;
234   UsingShadowDecl *FoundUsingShadow = dyn_cast<UsingShadowDecl>(*R.begin());
235   if (R.isAmbiguous()) {
236     // If we got an ambiguity involving a non-function template, treat this
237     // as a template name, and pick an arbitrary template for error recovery.
238     bool AnyFunctionTemplates = false;
239     for (NamedDecl *FoundD : R) {
240       if (NamedDecl *FoundTemplate = getAsTemplateNameDecl(FoundD)) {
241         if (isa<FunctionTemplateDecl>(FoundTemplate))
242           AnyFunctionTemplates = true;
243         else {
244           D = FoundTemplate;
245           FoundUsingShadow = dyn_cast<UsingShadowDecl>(FoundD);
246           break;
247         }
248       }
249     }
250 
251     // If we didn't find any templates at all, this isn't a template name.
252     // Leave the ambiguity for a later lookup to diagnose.
253     if (!D && !AnyFunctionTemplates) {
254       R.suppressDiagnostics();
255       return TNK_Non_template;
256     }
257 
258     // If the only templates were function templates, filter out the rest.
259     // We'll diagnose the ambiguity later.
260     if (!D)
261       FilterAcceptableTemplateNames(R);
262   }
263 
264   // At this point, we have either picked a single template name declaration D
265   // or we have a non-empty set of results R containing either one template name
266   // declaration or a set of function templates.
267 
268   TemplateName Template;
269   TemplateNameKind TemplateKind;
270 
271   unsigned ResultCount = R.end() - R.begin();
272   if (!D && ResultCount > 1) {
273     // We assume that we'll preserve the qualifier from a function
274     // template name in other ways.
275     Template = Context.getOverloadedTemplateName(R.begin(), R.end());
276     TemplateKind = TNK_Function_template;
277 
278     // We'll do this lookup again later.
279     R.suppressDiagnostics();
280   } else {
281     if (!D) {
282       D = getAsTemplateNameDecl(*R.begin());
283       assert(D && "unambiguous result is not a template name");
284     }
285 
286     if (isa<UnresolvedUsingValueDecl>(D)) {
287       // We don't yet know whether this is a template-name or not.
288       MemberOfUnknownSpecialization = true;
289       return TNK_Non_template;
290     }
291 
292     TemplateDecl *TD = cast<TemplateDecl>(D);
293     Template =
294         FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD);
295     assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD);
296     if (!SS.isInvalid()) {
297       NestedNameSpecifier *Qualifier = SS.getScopeRep();
298       Template = Context.getQualifiedTemplateName(Qualifier, hasTemplateKeyword,
299                                                   Template);
300     }
301 
302     if (isa<FunctionTemplateDecl>(TD)) {
303       TemplateKind = TNK_Function_template;
304 
305       // We'll do this lookup again later.
306       R.suppressDiagnostics();
307     } else {
308       assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) ||
309              isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD) ||
310              isa<BuiltinTemplateDecl>(TD) || isa<ConceptDecl>(TD));
311       TemplateKind =
312           isa<VarTemplateDecl>(TD) ? TNK_Var_template :
313           isa<ConceptDecl>(TD) ? TNK_Concept_template :
314           TNK_Type_template;
315     }
316   }
317 
318   TemplateResult = TemplateTy::make(Template);
319   return TemplateKind;
320 }
321 
isDeductionGuideName(Scope * S,const IdentifierInfo & Name,SourceLocation NameLoc,CXXScopeSpec & SS,ParsedTemplateTy * Template)322 bool Sema::isDeductionGuideName(Scope *S, const IdentifierInfo &Name,
323                                 SourceLocation NameLoc, CXXScopeSpec &SS,
324                                 ParsedTemplateTy *Template /*=nullptr*/) {
325   // We could use redeclaration lookup here, but we don't need to: the
326   // syntactic form of a deduction guide is enough to identify it even
327   // if we can't look up the template name at all.
328   LookupResult R(*this, DeclarationName(&Name), NameLoc, LookupOrdinaryName);
329   if (LookupTemplateName(R, S, SS, /*ObjectType*/ QualType(),
330                          /*EnteringContext*/ false))
331     return false;
332 
333   if (R.empty()) return false;
334   if (R.isAmbiguous()) {
335     // FIXME: Diagnose an ambiguity if we find at least one template.
336     R.suppressDiagnostics();
337     return false;
338   }
339 
340   // We only treat template-names that name type templates as valid deduction
341   // guide names.
342   TemplateDecl *TD = R.getAsSingle<TemplateDecl>();
343   if (!TD || !getAsTypeTemplateDecl(TD))
344     return false;
345 
346   if (Template) {
347     TemplateName Name = Context.getQualifiedTemplateName(
348         SS.getScopeRep(), /*TemplateKeyword=*/false, TemplateName(TD));
349     *Template = TemplateTy::make(Name);
350   }
351   return true;
352 }
353 
DiagnoseUnknownTemplateName(const IdentifierInfo & II,SourceLocation IILoc,Scope * S,const CXXScopeSpec * SS,TemplateTy & SuggestedTemplate,TemplateNameKind & SuggestedKind)354 bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II,
355                                        SourceLocation IILoc,
356                                        Scope *S,
357                                        const CXXScopeSpec *SS,
358                                        TemplateTy &SuggestedTemplate,
359                                        TemplateNameKind &SuggestedKind) {
360   // We can't recover unless there's a dependent scope specifier preceding the
361   // template name.
362   // FIXME: Typo correction?
363   if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
364       computeDeclContext(*SS))
365     return false;
366 
367   // The code is missing a 'template' keyword prior to the dependent template
368   // name.
369   NestedNameSpecifier *Qualifier = (NestedNameSpecifier*)SS->getScopeRep();
370   Diag(IILoc, diag::err_template_kw_missing)
371     << Qualifier << II.getName()
372     << FixItHint::CreateInsertion(IILoc, "template ");
373   SuggestedTemplate
374     = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II));
375   SuggestedKind = TNK_Dependent_template_name;
376   return true;
377 }
378 
LookupTemplateName(LookupResult & Found,Scope * S,CXXScopeSpec & SS,QualType ObjectType,bool EnteringContext,RequiredTemplateKind RequiredTemplate,AssumedTemplateKind * ATK,bool AllowTypoCorrection)379 bool Sema::LookupTemplateName(LookupResult &Found, Scope *S, CXXScopeSpec &SS,
380                               QualType ObjectType, bool EnteringContext,
381                               RequiredTemplateKind RequiredTemplate,
382                               AssumedTemplateKind *ATK,
383                               bool AllowTypoCorrection) {
384   if (ATK)
385     *ATK = AssumedTemplateKind::None;
386 
387   if (SS.isInvalid())
388     return true;
389 
390   Found.setTemplateNameLookup(true);
391 
392   // Determine where to perform name lookup
393   DeclContext *LookupCtx = nullptr;
394   bool IsDependent = false;
395   if (!ObjectType.isNull()) {
396     // This nested-name-specifier occurs in a member access expression, e.g.,
397     // x->B::f, and we are looking into the type of the object.
398     assert(SS.isEmpty() && "ObjectType and scope specifier cannot coexist");
399     LookupCtx = computeDeclContext(ObjectType);
400     IsDependent = !LookupCtx && ObjectType->isDependentType();
401     assert((IsDependent || !ObjectType->isIncompleteType() ||
402             !ObjectType->getAs<TagType>() ||
403             ObjectType->castAs<TagType>()->isBeingDefined()) &&
404            "Caller should have completed object type");
405 
406     // Template names cannot appear inside an Objective-C class or object type
407     // or a vector type.
408     //
409     // FIXME: This is wrong. For example:
410     //
411     //   template<typename T> using Vec = T __attribute__((ext_vector_type(4)));
412     //   Vec<int> vi;
413     //   vi.Vec<int>::~Vec<int>();
414     //
415     // ... should be accepted but we will not treat 'Vec' as a template name
416     // here. The right thing to do would be to check if the name is a valid
417     // vector component name, and look up a template name if not. And similarly
418     // for lookups into Objective-C class and object types, where the same
419     // problem can arise.
420     if (ObjectType->isObjCObjectOrInterfaceType() ||
421         ObjectType->isVectorType()) {
422       Found.clear();
423       return false;
424     }
425   } else if (SS.isNotEmpty()) {
426     // This nested-name-specifier occurs after another nested-name-specifier,
427     // so long into the context associated with the prior nested-name-specifier.
428     LookupCtx = computeDeclContext(SS, EnteringContext);
429     IsDependent = !LookupCtx && isDependentScopeSpecifier(SS);
430 
431     // The declaration context must be complete.
432     if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
433       return true;
434   }
435 
436   bool ObjectTypeSearchedInScope = false;
437   bool AllowFunctionTemplatesInLookup = true;
438   if (LookupCtx) {
439     // Perform "qualified" name lookup into the declaration context we
440     // computed, which is either the type of the base of a member access
441     // expression or the declaration context associated with a prior
442     // nested-name-specifier.
443     LookupQualifiedName(Found, LookupCtx);
444 
445     // FIXME: The C++ standard does not clearly specify what happens in the
446     // case where the object type is dependent, and implementations vary. In
447     // Clang, we treat a name after a . or -> as a template-name if lookup
448     // finds a non-dependent member or member of the current instantiation that
449     // is a type template, or finds no such members and lookup in the context
450     // of the postfix-expression finds a type template. In the latter case, the
451     // name is nonetheless dependent, and we may resolve it to a member of an
452     // unknown specialization when we come to instantiate the template.
453     IsDependent |= Found.wasNotFoundInCurrentInstantiation();
454   }
455 
456   if (SS.isEmpty() && (ObjectType.isNull() || Found.empty())) {
457     // C++ [basic.lookup.classref]p1:
458     //   In a class member access expression (5.2.5), if the . or -> token is
459     //   immediately followed by an identifier followed by a <, the
460     //   identifier must be looked up to determine whether the < is the
461     //   beginning of a template argument list (14.2) or a less-than operator.
462     //   The identifier is first looked up in the class of the object
463     //   expression. If the identifier is not found, it is then looked up in
464     //   the context of the entire postfix-expression and shall name a class
465     //   template.
466     if (S)
467       LookupName(Found, S);
468 
469     if (!ObjectType.isNull()) {
470       //  FIXME: We should filter out all non-type templates here, particularly
471       //  variable templates and concepts. But the exclusion of alias templates
472       //  and template template parameters is a wording defect.
473       AllowFunctionTemplatesInLookup = false;
474       ObjectTypeSearchedInScope = true;
475     }
476 
477     IsDependent |= Found.wasNotFoundInCurrentInstantiation();
478   }
479 
480   if (Found.isAmbiguous())
481     return false;
482 
483   if (ATK && SS.isEmpty() && ObjectType.isNull() &&
484       !RequiredTemplate.hasTemplateKeyword()) {
485     // C++2a [temp.names]p2:
486     //   A name is also considered to refer to a template if it is an
487     //   unqualified-id followed by a < and name lookup finds either one or more
488     //   functions or finds nothing.
489     //
490     // To keep our behavior consistent, we apply the "finds nothing" part in
491     // all language modes, and diagnose the empty lookup in ActOnCallExpr if we
492     // successfully form a call to an undeclared template-id.
493     bool AllFunctions =
494         getLangOpts().CPlusPlus20 && llvm::all_of(Found, [](NamedDecl *ND) {
495           return isa<FunctionDecl>(ND->getUnderlyingDecl());
496         });
497     if (AllFunctions || (Found.empty() && !IsDependent)) {
498       // If lookup found any functions, or if this is a name that can only be
499       // used for a function, then strongly assume this is a function
500       // template-id.
501       *ATK = (Found.empty() && Found.getLookupName().isIdentifier())
502                  ? AssumedTemplateKind::FoundNothing
503                  : AssumedTemplateKind::FoundFunctions;
504       Found.clear();
505       return false;
506     }
507   }
508 
509   if (Found.empty() && !IsDependent && AllowTypoCorrection) {
510     // If we did not find any names, and this is not a disambiguation, attempt
511     // to correct any typos.
512     DeclarationName Name = Found.getLookupName();
513     Found.clear();
514     // Simple filter callback that, for keywords, only accepts the C++ *_cast
515     DefaultFilterCCC FilterCCC{};
516     FilterCCC.WantTypeSpecifiers = false;
517     FilterCCC.WantExpressionKeywords = false;
518     FilterCCC.WantRemainingKeywords = false;
519     FilterCCC.WantCXXNamedCasts = true;
520     if (TypoCorrection Corrected =
521             CorrectTypo(Found.getLookupNameInfo(), Found.getLookupKind(), S,
522                         &SS, FilterCCC, CTK_ErrorRecovery, LookupCtx)) {
523       if (auto *ND = Corrected.getFoundDecl())
524         Found.addDecl(ND);
525       FilterAcceptableTemplateNames(Found);
526       if (Found.isAmbiguous()) {
527         Found.clear();
528       } else if (!Found.empty()) {
529         Found.setLookupName(Corrected.getCorrection());
530         if (LookupCtx) {
531           std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
532           bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
533                                   Name.getAsString() == CorrectedStr;
534           diagnoseTypo(Corrected, PDiag(diag::err_no_member_template_suggest)
535                                     << Name << LookupCtx << DroppedSpecifier
536                                     << SS.getRange());
537         } else {
538           diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest) << Name);
539         }
540       }
541     }
542   }
543 
544   NamedDecl *ExampleLookupResult =
545       Found.empty() ? nullptr : Found.getRepresentativeDecl();
546   FilterAcceptableTemplateNames(Found, AllowFunctionTemplatesInLookup);
547   if (Found.empty()) {
548     if (IsDependent) {
549       Found.setNotFoundInCurrentInstantiation();
550       return false;
551     }
552 
553     // If a 'template' keyword was used, a lookup that finds only non-template
554     // names is an error.
555     if (ExampleLookupResult && RequiredTemplate) {
556       Diag(Found.getNameLoc(), diag::err_template_kw_refers_to_non_template)
557           << Found.getLookupName() << SS.getRange()
558           << RequiredTemplate.hasTemplateKeyword()
559           << RequiredTemplate.getTemplateKeywordLoc();
560       Diag(ExampleLookupResult->getUnderlyingDecl()->getLocation(),
561            diag::note_template_kw_refers_to_non_template)
562           << Found.getLookupName();
563       return true;
564     }
565 
566     return false;
567   }
568 
569   if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope &&
570       !getLangOpts().CPlusPlus11) {
571     // C++03 [basic.lookup.classref]p1:
572     //   [...] If the lookup in the class of the object expression finds a
573     //   template, the name is also looked up in the context of the entire
574     //   postfix-expression and [...]
575     //
576     // Note: C++11 does not perform this second lookup.
577     LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
578                             LookupOrdinaryName);
579     FoundOuter.setTemplateNameLookup(true);
580     LookupName(FoundOuter, S);
581     // FIXME: We silently accept an ambiguous lookup here, in violation of
582     // [basic.lookup]/1.
583     FilterAcceptableTemplateNames(FoundOuter, /*AllowFunctionTemplates=*/false);
584 
585     NamedDecl *OuterTemplate;
586     if (FoundOuter.empty()) {
587       //   - if the name is not found, the name found in the class of the
588       //     object expression is used, otherwise
589     } else if (FoundOuter.isAmbiguous() || !FoundOuter.isSingleResult() ||
590                !(OuterTemplate =
591                      getAsTemplateNameDecl(FoundOuter.getFoundDecl()))) {
592       //   - if the name is found in the context of the entire
593       //     postfix-expression and does not name a class template, the name
594       //     found in the class of the object expression is used, otherwise
595       FoundOuter.clear();
596     } else if (!Found.isSuppressingAmbiguousDiagnostics()) {
597       //   - if the name found is a class template, it must refer to the same
598       //     entity as the one found in the class of the object expression,
599       //     otherwise the program is ill-formed.
600       if (!Found.isSingleResult() ||
601           getAsTemplateNameDecl(Found.getFoundDecl())->getCanonicalDecl() !=
602               OuterTemplate->getCanonicalDecl()) {
603         Diag(Found.getNameLoc(),
604              diag::ext_nested_name_member_ref_lookup_ambiguous)
605           << Found.getLookupName()
606           << ObjectType;
607         Diag(Found.getRepresentativeDecl()->getLocation(),
608              diag::note_ambig_member_ref_object_type)
609           << ObjectType;
610         Diag(FoundOuter.getFoundDecl()->getLocation(),
611              diag::note_ambig_member_ref_scope);
612 
613         // Recover by taking the template that we found in the object
614         // expression's type.
615       }
616     }
617   }
618 
619   return false;
620 }
621 
diagnoseExprIntendedAsTemplateName(Scope * S,ExprResult TemplateName,SourceLocation Less,SourceLocation Greater)622 void Sema::diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName,
623                                               SourceLocation Less,
624                                               SourceLocation Greater) {
625   if (TemplateName.isInvalid())
626     return;
627 
628   DeclarationNameInfo NameInfo;
629   CXXScopeSpec SS;
630   LookupNameKind LookupKind;
631 
632   DeclContext *LookupCtx = nullptr;
633   NamedDecl *Found = nullptr;
634   bool MissingTemplateKeyword = false;
635 
636   // Figure out what name we looked up.
637   if (auto *DRE = dyn_cast<DeclRefExpr>(TemplateName.get())) {
638     NameInfo = DRE->getNameInfo();
639     SS.Adopt(DRE->getQualifierLoc());
640     LookupKind = LookupOrdinaryName;
641     Found = DRE->getFoundDecl();
642   } else if (auto *ME = dyn_cast<MemberExpr>(TemplateName.get())) {
643     NameInfo = ME->getMemberNameInfo();
644     SS.Adopt(ME->getQualifierLoc());
645     LookupKind = LookupMemberName;
646     LookupCtx = ME->getBase()->getType()->getAsCXXRecordDecl();
647     Found = ME->getMemberDecl();
648   } else if (auto *DSDRE =
649                  dyn_cast<DependentScopeDeclRefExpr>(TemplateName.get())) {
650     NameInfo = DSDRE->getNameInfo();
651     SS.Adopt(DSDRE->getQualifierLoc());
652     MissingTemplateKeyword = true;
653   } else if (auto *DSME =
654                  dyn_cast<CXXDependentScopeMemberExpr>(TemplateName.get())) {
655     NameInfo = DSME->getMemberNameInfo();
656     SS.Adopt(DSME->getQualifierLoc());
657     MissingTemplateKeyword = true;
658   } else {
659     llvm_unreachable("unexpected kind of potential template name");
660   }
661 
662   // If this is a dependent-scope lookup, diagnose that the 'template' keyword
663   // was missing.
664   if (MissingTemplateKeyword) {
665     Diag(NameInfo.getBeginLoc(), diag::err_template_kw_missing)
666         << "" << NameInfo.getName().getAsString() << SourceRange(Less, Greater);
667     return;
668   }
669 
670   // Try to correct the name by looking for templates and C++ named casts.
671   struct TemplateCandidateFilter : CorrectionCandidateCallback {
672     Sema &S;
673     TemplateCandidateFilter(Sema &S) : S(S) {
674       WantTypeSpecifiers = false;
675       WantExpressionKeywords = false;
676       WantRemainingKeywords = false;
677       WantCXXNamedCasts = true;
678     };
679     bool ValidateCandidate(const TypoCorrection &Candidate) override {
680       if (auto *ND = Candidate.getCorrectionDecl())
681         return S.getAsTemplateNameDecl(ND);
682       return Candidate.isKeyword();
683     }
684 
685     std::unique_ptr<CorrectionCandidateCallback> clone() override {
686       return std::make_unique<TemplateCandidateFilter>(*this);
687     }
688   };
689 
690   DeclarationName Name = NameInfo.getName();
691   TemplateCandidateFilter CCC(*this);
692   if (TypoCorrection Corrected = CorrectTypo(NameInfo, LookupKind, S, &SS, CCC,
693                                              CTK_ErrorRecovery, LookupCtx)) {
694     auto *ND = Corrected.getFoundDecl();
695     if (ND)
696       ND = getAsTemplateNameDecl(ND);
697     if (ND || Corrected.isKeyword()) {
698       if (LookupCtx) {
699         std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
700         bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
701                                 Name.getAsString() == CorrectedStr;
702         diagnoseTypo(Corrected,
703                      PDiag(diag::err_non_template_in_member_template_id_suggest)
704                          << Name << LookupCtx << DroppedSpecifier
705                          << SS.getRange(), false);
706       } else {
707         diagnoseTypo(Corrected,
708                      PDiag(diag::err_non_template_in_template_id_suggest)
709                          << Name, false);
710       }
711       if (Found)
712         Diag(Found->getLocation(),
713              diag::note_non_template_in_template_id_found);
714       return;
715     }
716   }
717 
718   Diag(NameInfo.getLoc(), diag::err_non_template_in_template_id)
719     << Name << SourceRange(Less, Greater);
720   if (Found)
721     Diag(Found->getLocation(), diag::note_non_template_in_template_id_found);
722 }
723 
724 ExprResult
ActOnDependentIdExpression(const CXXScopeSpec & SS,SourceLocation TemplateKWLoc,const DeclarationNameInfo & NameInfo,bool isAddressOfOperand,const TemplateArgumentListInfo * TemplateArgs)725 Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
726                                  SourceLocation TemplateKWLoc,
727                                  const DeclarationNameInfo &NameInfo,
728                                  bool isAddressOfOperand,
729                            const TemplateArgumentListInfo *TemplateArgs) {
730   if (SS.isEmpty()) {
731     // FIXME: This codepath is only used by dependent unqualified names
732     // (e.g. a dependent conversion-function-id, or operator= once we support
733     // it). It doesn't quite do the right thing, and it will silently fail if
734     // getCurrentThisType() returns null.
735     QualType ThisType = getCurrentThisType();
736     if (ThisType.isNull())
737       return ExprError();
738 
739     return CXXDependentScopeMemberExpr::Create(
740         Context, /*Base=*/nullptr, ThisType,
741         /*IsArrow=*/!Context.getLangOpts().HLSL,
742         /*OperatorLoc=*/SourceLocation(),
743         /*QualifierLoc=*/NestedNameSpecifierLoc(), TemplateKWLoc,
744         /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
745   }
746   return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
747 }
748 
749 ExprResult
BuildDependentDeclRefExpr(const CXXScopeSpec & SS,SourceLocation TemplateKWLoc,const DeclarationNameInfo & NameInfo,const TemplateArgumentListInfo * TemplateArgs)750 Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
751                                 SourceLocation TemplateKWLoc,
752                                 const DeclarationNameInfo &NameInfo,
753                                 const TemplateArgumentListInfo *TemplateArgs) {
754   // DependentScopeDeclRefExpr::Create requires a valid NestedNameSpecifierLoc
755   if (!SS.isValid())
756     return CreateRecoveryExpr(
757         SS.getBeginLoc(),
758         TemplateArgs ? TemplateArgs->getRAngleLoc() : NameInfo.getEndLoc(), {});
759 
760   return DependentScopeDeclRefExpr::Create(
761       Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
762       TemplateArgs);
763 }
764 
DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation,NamedDecl * Instantiation,bool InstantiatedFromMember,const NamedDecl * Pattern,const NamedDecl * PatternDef,TemplateSpecializationKind TSK,bool Complain)765 bool Sema::DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation,
766                                           NamedDecl *Instantiation,
767                                           bool InstantiatedFromMember,
768                                           const NamedDecl *Pattern,
769                                           const NamedDecl *PatternDef,
770                                           TemplateSpecializationKind TSK,
771                                           bool Complain /*= true*/) {
772   assert(isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) ||
773          isa<VarDecl>(Instantiation));
774 
775   bool IsEntityBeingDefined = false;
776   if (const TagDecl *TD = dyn_cast_or_null<TagDecl>(PatternDef))
777     IsEntityBeingDefined = TD->isBeingDefined();
778 
779   if (PatternDef && !IsEntityBeingDefined) {
780     NamedDecl *SuggestedDef = nullptr;
781     if (!hasReachableDefinition(const_cast<NamedDecl *>(PatternDef),
782                                 &SuggestedDef,
783                                 /*OnlyNeedComplete*/ false)) {
784       // If we're allowed to diagnose this and recover, do so.
785       bool Recover = Complain && !isSFINAEContext();
786       if (Complain)
787         diagnoseMissingImport(PointOfInstantiation, SuggestedDef,
788                               Sema::MissingImportKind::Definition, Recover);
789       return !Recover;
790     }
791     return false;
792   }
793 
794   if (!Complain || (PatternDef && PatternDef->isInvalidDecl()))
795     return true;
796 
797   QualType InstantiationTy;
798   if (TagDecl *TD = dyn_cast<TagDecl>(Instantiation))
799     InstantiationTy = Context.getTypeDeclType(TD);
800   if (PatternDef) {
801     Diag(PointOfInstantiation,
802          diag::err_template_instantiate_within_definition)
803       << /*implicit|explicit*/(TSK != TSK_ImplicitInstantiation)
804       << InstantiationTy;
805     // Not much point in noting the template declaration here, since
806     // we're lexically inside it.
807     Instantiation->setInvalidDecl();
808   } else if (InstantiatedFromMember) {
809     if (isa<FunctionDecl>(Instantiation)) {
810       Diag(PointOfInstantiation,
811            diag::err_explicit_instantiation_undefined_member)
812         << /*member function*/ 1 << Instantiation->getDeclName()
813         << Instantiation->getDeclContext();
814       Diag(Pattern->getLocation(), diag::note_explicit_instantiation_here);
815     } else {
816       assert(isa<TagDecl>(Instantiation) && "Must be a TagDecl!");
817       Diag(PointOfInstantiation,
818            diag::err_implicit_instantiate_member_undefined)
819         << InstantiationTy;
820       Diag(Pattern->getLocation(), diag::note_member_declared_at);
821     }
822   } else {
823     if (isa<FunctionDecl>(Instantiation)) {
824       Diag(PointOfInstantiation,
825            diag::err_explicit_instantiation_undefined_func_template)
826         << Pattern;
827       Diag(Pattern->getLocation(), diag::note_explicit_instantiation_here);
828     } else if (isa<TagDecl>(Instantiation)) {
829       Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
830         << (TSK != TSK_ImplicitInstantiation)
831         << InstantiationTy;
832       NoteTemplateLocation(*Pattern);
833     } else {
834       assert(isa<VarDecl>(Instantiation) && "Must be a VarDecl!");
835       if (isa<VarTemplateSpecializationDecl>(Instantiation)) {
836         Diag(PointOfInstantiation,
837              diag::err_explicit_instantiation_undefined_var_template)
838           << Instantiation;
839         Instantiation->setInvalidDecl();
840       } else
841         Diag(PointOfInstantiation,
842              diag::err_explicit_instantiation_undefined_member)
843           << /*static data member*/ 2 << Instantiation->getDeclName()
844           << Instantiation->getDeclContext();
845       Diag(Pattern->getLocation(), diag::note_explicit_instantiation_here);
846     }
847   }
848 
849   // In general, Instantiation isn't marked invalid to get more than one
850   // error for multiple undefined instantiations. But the code that does
851   // explicit declaration -> explicit definition conversion can't handle
852   // invalid declarations, so mark as invalid in that case.
853   if (TSK == TSK_ExplicitInstantiationDeclaration)
854     Instantiation->setInvalidDecl();
855   return true;
856 }
857 
DiagnoseTemplateParameterShadow(SourceLocation Loc,Decl * PrevDecl,bool SupportedForCompatibility)858 void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl,
859                                            bool SupportedForCompatibility) {
860   assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
861 
862   // C++23 [temp.local]p6:
863   //   The name of a template-parameter shall not be bound to any following.
864   //   declaration whose locus is contained by the scope to which the
865   //   template-parameter belongs.
866   //
867   // When MSVC compatibility is enabled, the diagnostic is always a warning
868   // by default. Otherwise, it an error unless SupportedForCompatibility is
869   // true, in which case it is a default-to-error warning.
870   unsigned DiagId =
871       getLangOpts().MSVCCompat
872           ? diag::ext_template_param_shadow
873           : (SupportedForCompatibility ? diag::ext_compat_template_param_shadow
874                                        : diag::err_template_param_shadow);
875   const auto *ND = cast<NamedDecl>(PrevDecl);
876   Diag(Loc, DiagId) << ND->getDeclName();
877   NoteTemplateParameterLocation(*ND);
878 }
879 
AdjustDeclIfTemplate(Decl * & D)880 TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) {
881   if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
882     D = Temp->getTemplatedDecl();
883     return Temp;
884   }
885   return nullptr;
886 }
887 
getTemplatePackExpansion(SourceLocation EllipsisLoc) const888 ParsedTemplateArgument ParsedTemplateArgument::getTemplatePackExpansion(
889                                              SourceLocation EllipsisLoc) const {
890   assert(Kind == Template &&
891          "Only template template arguments can be pack expansions here");
892   assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
893          "Template template argument pack expansion without packs");
894   ParsedTemplateArgument Result(*this);
895   Result.EllipsisLoc = EllipsisLoc;
896   return Result;
897 }
898 
translateTemplateArgument(Sema & SemaRef,const ParsedTemplateArgument & Arg)899 static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
900                                             const ParsedTemplateArgument &Arg) {
901 
902   switch (Arg.getKind()) {
903   case ParsedTemplateArgument::Type: {
904     TypeSourceInfo *DI;
905     QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
906     if (!DI)
907       DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
908     return TemplateArgumentLoc(TemplateArgument(T), DI);
909   }
910 
911   case ParsedTemplateArgument::NonType: {
912     Expr *E = static_cast<Expr *>(Arg.getAsExpr());
913     return TemplateArgumentLoc(TemplateArgument(E), E);
914   }
915 
916   case ParsedTemplateArgument::Template: {
917     TemplateName Template = Arg.getAsTemplate().get();
918     TemplateArgument TArg;
919     if (Arg.getEllipsisLoc().isValid())
920       TArg = TemplateArgument(Template, std::optional<unsigned int>());
921     else
922       TArg = Template;
923     return TemplateArgumentLoc(
924         SemaRef.Context, TArg,
925         Arg.getScopeSpec().getWithLocInContext(SemaRef.Context),
926         Arg.getLocation(), Arg.getEllipsisLoc());
927   }
928   }
929 
930   llvm_unreachable("Unhandled parsed template argument");
931 }
932 
translateTemplateArguments(const ASTTemplateArgsPtr & TemplateArgsIn,TemplateArgumentListInfo & TemplateArgs)933 void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
934                                       TemplateArgumentListInfo &TemplateArgs) {
935  for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
936    TemplateArgs.addArgument(translateTemplateArgument(*this,
937                                                       TemplateArgsIn[I]));
938 }
939 
maybeDiagnoseTemplateParameterShadow(Sema & SemaRef,Scope * S,SourceLocation Loc,const IdentifierInfo * Name)940 static void maybeDiagnoseTemplateParameterShadow(Sema &SemaRef, Scope *S,
941                                                  SourceLocation Loc,
942                                                  const IdentifierInfo *Name) {
943   NamedDecl *PrevDecl =
944       SemaRef.LookupSingleName(S, Name, Loc, Sema::LookupOrdinaryName,
945                                RedeclarationKind::ForVisibleRedeclaration);
946   if (PrevDecl && PrevDecl->isTemplateParameter())
947     SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
948 }
949 
ActOnTemplateTypeArgument(TypeResult ParsedType)950 ParsedTemplateArgument Sema::ActOnTemplateTypeArgument(TypeResult ParsedType) {
951   TypeSourceInfo *TInfo;
952   QualType T = GetTypeFromParser(ParsedType.get(), &TInfo);
953   if (T.isNull())
954     return ParsedTemplateArgument();
955   assert(TInfo && "template argument with no location");
956 
957   // If we might have formed a deduced template specialization type, convert
958   // it to a template template argument.
959   if (getLangOpts().CPlusPlus17) {
960     TypeLoc TL = TInfo->getTypeLoc();
961     SourceLocation EllipsisLoc;
962     if (auto PET = TL.getAs<PackExpansionTypeLoc>()) {
963       EllipsisLoc = PET.getEllipsisLoc();
964       TL = PET.getPatternLoc();
965     }
966 
967     CXXScopeSpec SS;
968     if (auto ET = TL.getAs<ElaboratedTypeLoc>()) {
969       SS.Adopt(ET.getQualifierLoc());
970       TL = ET.getNamedTypeLoc();
971     }
972 
973     if (auto DTST = TL.getAs<DeducedTemplateSpecializationTypeLoc>()) {
974       TemplateName Name = DTST.getTypePtr()->getTemplateName();
975       ParsedTemplateArgument Result(SS, TemplateTy::make(Name),
976                                     DTST.getTemplateNameLoc());
977       if (EllipsisLoc.isValid())
978         Result = Result.getTemplatePackExpansion(EllipsisLoc);
979       return Result;
980     }
981   }
982 
983   // This is a normal type template argument. Note, if the type template
984   // argument is an injected-class-name for a template, it has a dual nature
985   // and can be used as either a type or a template. We handle that in
986   // convertTypeTemplateArgumentToTemplate.
987   return ParsedTemplateArgument(ParsedTemplateArgument::Type,
988                                 ParsedType.get().getAsOpaquePtr(),
989                                 TInfo->getTypeLoc().getBeginLoc());
990 }
991 
ActOnTypeParameter(Scope * S,bool Typename,SourceLocation EllipsisLoc,SourceLocation KeyLoc,IdentifierInfo * ParamName,SourceLocation ParamNameLoc,unsigned Depth,unsigned Position,SourceLocation EqualLoc,ParsedType DefaultArg,bool HasTypeConstraint)992 NamedDecl *Sema::ActOnTypeParameter(Scope *S, bool Typename,
993                                     SourceLocation EllipsisLoc,
994                                     SourceLocation KeyLoc,
995                                     IdentifierInfo *ParamName,
996                                     SourceLocation ParamNameLoc,
997                                     unsigned Depth, unsigned Position,
998                                     SourceLocation EqualLoc,
999                                     ParsedType DefaultArg,
1000                                     bool HasTypeConstraint) {
1001   assert(S->isTemplateParamScope() &&
1002          "Template type parameter not in template parameter scope!");
1003 
1004   bool IsParameterPack = EllipsisLoc.isValid();
1005   TemplateTypeParmDecl *Param
1006     = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
1007                                    KeyLoc, ParamNameLoc, Depth, Position,
1008                                    ParamName, Typename, IsParameterPack,
1009                                    HasTypeConstraint);
1010   Param->setAccess(AS_public);
1011 
1012   if (Param->isParameterPack())
1013     if (auto *LSI = getEnclosingLambda())
1014       LSI->LocalPacks.push_back(Param);
1015 
1016   if (ParamName) {
1017     maybeDiagnoseTemplateParameterShadow(*this, S, ParamNameLoc, ParamName);
1018 
1019     // Add the template parameter into the current scope.
1020     S->AddDecl(Param);
1021     IdResolver.AddDecl(Param);
1022   }
1023 
1024   // C++0x [temp.param]p9:
1025   //   A default template-argument may be specified for any kind of
1026   //   template-parameter that is not a template parameter pack.
1027   if (DefaultArg && IsParameterPack) {
1028     Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1029     DefaultArg = nullptr;
1030   }
1031 
1032   // Handle the default argument, if provided.
1033   if (DefaultArg) {
1034     TypeSourceInfo *DefaultTInfo;
1035     GetTypeFromParser(DefaultArg, &DefaultTInfo);
1036 
1037     assert(DefaultTInfo && "expected source information for type");
1038 
1039     // Check for unexpanded parameter packs.
1040     if (DiagnoseUnexpandedParameterPack(ParamNameLoc, DefaultTInfo,
1041                                         UPPC_DefaultArgument))
1042       return Param;
1043 
1044     // Check the template argument itself.
1045     if (CheckTemplateArgument(DefaultTInfo)) {
1046       Param->setInvalidDecl();
1047       return Param;
1048     }
1049 
1050     Param->setDefaultArgument(
1051         Context, TemplateArgumentLoc(DefaultTInfo->getType(), DefaultTInfo));
1052   }
1053 
1054   return Param;
1055 }
1056 
1057 /// Convert the parser's template argument list representation into our form.
1058 static TemplateArgumentListInfo
makeTemplateArgumentListInfo(Sema & S,TemplateIdAnnotation & TemplateId)1059 makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId) {
1060   TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
1061                                         TemplateId.RAngleLoc);
1062   ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
1063                                      TemplateId.NumArgs);
1064   S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
1065   return TemplateArgs;
1066 }
1067 
CheckTypeConstraint(TemplateIdAnnotation * TypeConstr)1068 bool Sema::CheckTypeConstraint(TemplateIdAnnotation *TypeConstr) {
1069 
1070   TemplateName TN = TypeConstr->Template.get();
1071   ConceptDecl *CD = cast<ConceptDecl>(TN.getAsTemplateDecl());
1072 
1073   // C++2a [temp.param]p4:
1074   //     [...] The concept designated by a type-constraint shall be a type
1075   //     concept ([temp.concept]).
1076   if (!CD->isTypeConcept()) {
1077     Diag(TypeConstr->TemplateNameLoc,
1078          diag::err_type_constraint_non_type_concept);
1079     return true;
1080   }
1081 
1082   bool WereArgsSpecified = TypeConstr->LAngleLoc.isValid();
1083 
1084   if (!WereArgsSpecified &&
1085       CD->getTemplateParameters()->getMinRequiredArguments() > 1) {
1086     Diag(TypeConstr->TemplateNameLoc,
1087          diag::err_type_constraint_missing_arguments)
1088         << CD;
1089     return true;
1090   }
1091   return false;
1092 }
1093 
ActOnTypeConstraint(const CXXScopeSpec & SS,TemplateIdAnnotation * TypeConstr,TemplateTypeParmDecl * ConstrainedParameter,SourceLocation EllipsisLoc)1094 bool Sema::ActOnTypeConstraint(const CXXScopeSpec &SS,
1095                                TemplateIdAnnotation *TypeConstr,
1096                                TemplateTypeParmDecl *ConstrainedParameter,
1097                                SourceLocation EllipsisLoc) {
1098   return BuildTypeConstraint(SS, TypeConstr, ConstrainedParameter, EllipsisLoc,
1099                              false);
1100 }
1101 
BuildTypeConstraint(const CXXScopeSpec & SS,TemplateIdAnnotation * TypeConstr,TemplateTypeParmDecl * ConstrainedParameter,SourceLocation EllipsisLoc,bool AllowUnexpandedPack)1102 bool Sema::BuildTypeConstraint(const CXXScopeSpec &SS,
1103                                TemplateIdAnnotation *TypeConstr,
1104                                TemplateTypeParmDecl *ConstrainedParameter,
1105                                SourceLocation EllipsisLoc,
1106                                bool AllowUnexpandedPack) {
1107 
1108   if (CheckTypeConstraint(TypeConstr))
1109     return true;
1110 
1111   TemplateName TN = TypeConstr->Template.get();
1112   ConceptDecl *CD = cast<ConceptDecl>(TN.getAsTemplateDecl());
1113   UsingShadowDecl *USD = TN.getAsUsingShadowDecl();
1114 
1115   DeclarationNameInfo ConceptName(DeclarationName(TypeConstr->Name),
1116                                   TypeConstr->TemplateNameLoc);
1117 
1118   TemplateArgumentListInfo TemplateArgs;
1119   if (TypeConstr->LAngleLoc.isValid()) {
1120     TemplateArgs =
1121         makeTemplateArgumentListInfo(*this, *TypeConstr);
1122 
1123     if (EllipsisLoc.isInvalid() && !AllowUnexpandedPack) {
1124       for (TemplateArgumentLoc Arg : TemplateArgs.arguments()) {
1125         if (DiagnoseUnexpandedParameterPack(Arg, UPPC_TypeConstraint))
1126           return true;
1127       }
1128     }
1129   }
1130   return AttachTypeConstraint(
1131       SS.isSet() ? SS.getWithLocInContext(Context) : NestedNameSpecifierLoc(),
1132       ConceptName, CD, /*FoundDecl=*/USD ? cast<NamedDecl>(USD) : CD,
1133       TypeConstr->LAngleLoc.isValid() ? &TemplateArgs : nullptr,
1134       ConstrainedParameter, EllipsisLoc);
1135 }
1136 
1137 template <typename ArgumentLocAppender>
formImmediatelyDeclaredConstraint(Sema & S,NestedNameSpecifierLoc NS,DeclarationNameInfo NameInfo,ConceptDecl * NamedConcept,NamedDecl * FoundDecl,SourceLocation LAngleLoc,SourceLocation RAngleLoc,QualType ConstrainedType,SourceLocation ParamNameLoc,ArgumentLocAppender Appender,SourceLocation EllipsisLoc)1138 static ExprResult formImmediatelyDeclaredConstraint(
1139     Sema &S, NestedNameSpecifierLoc NS, DeclarationNameInfo NameInfo,
1140     ConceptDecl *NamedConcept, NamedDecl *FoundDecl, SourceLocation LAngleLoc,
1141     SourceLocation RAngleLoc, QualType ConstrainedType,
1142     SourceLocation ParamNameLoc, ArgumentLocAppender Appender,
1143     SourceLocation EllipsisLoc) {
1144 
1145   TemplateArgumentListInfo ConstraintArgs;
1146   ConstraintArgs.addArgument(
1147     S.getTrivialTemplateArgumentLoc(TemplateArgument(ConstrainedType),
1148                                     /*NTTPType=*/QualType(), ParamNameLoc));
1149 
1150   ConstraintArgs.setRAngleLoc(RAngleLoc);
1151   ConstraintArgs.setLAngleLoc(LAngleLoc);
1152   Appender(ConstraintArgs);
1153 
1154   // C++2a [temp.param]p4:
1155   //     [...] This constraint-expression E is called the immediately-declared
1156   //     constraint of T. [...]
1157   CXXScopeSpec SS;
1158   SS.Adopt(NS);
1159   ExprResult ImmediatelyDeclaredConstraint = S.CheckConceptTemplateId(
1160       SS, /*TemplateKWLoc=*/SourceLocation(), NameInfo,
1161       /*FoundDecl=*/FoundDecl ? FoundDecl : NamedConcept, NamedConcept,
1162       &ConstraintArgs);
1163   if (ImmediatelyDeclaredConstraint.isInvalid() || !EllipsisLoc.isValid())
1164     return ImmediatelyDeclaredConstraint;
1165 
1166   // C++2a [temp.param]p4:
1167   //     [...] If T is not a pack, then E is E', otherwise E is (E' && ...).
1168   //
1169   // We have the following case:
1170   //
1171   // template<typename T> concept C1 = true;
1172   // template<C1... T> struct s1;
1173   //
1174   // The constraint: (C1<T> && ...)
1175   //
1176   // Note that the type of C1<T> is known to be 'bool', so we don't need to do
1177   // any unqualified lookups for 'operator&&' here.
1178   return S.BuildCXXFoldExpr(/*UnqualifiedLookup=*/nullptr,
1179                             /*LParenLoc=*/SourceLocation(),
1180                             ImmediatelyDeclaredConstraint.get(), BO_LAnd,
1181                             EllipsisLoc, /*RHS=*/nullptr,
1182                             /*RParenLoc=*/SourceLocation(),
1183                             /*NumExpansions=*/std::nullopt);
1184 }
1185 
AttachTypeConstraint(NestedNameSpecifierLoc NS,DeclarationNameInfo NameInfo,ConceptDecl * NamedConcept,NamedDecl * FoundDecl,const TemplateArgumentListInfo * TemplateArgs,TemplateTypeParmDecl * ConstrainedParameter,SourceLocation EllipsisLoc)1186 bool Sema::AttachTypeConstraint(NestedNameSpecifierLoc NS,
1187                                 DeclarationNameInfo NameInfo,
1188                                 ConceptDecl *NamedConcept, NamedDecl *FoundDecl,
1189                                 const TemplateArgumentListInfo *TemplateArgs,
1190                                 TemplateTypeParmDecl *ConstrainedParameter,
1191                                 SourceLocation EllipsisLoc) {
1192   // C++2a [temp.param]p4:
1193   //     [...] If Q is of the form C<A1, ..., An>, then let E' be
1194   //     C<T, A1, ..., An>. Otherwise, let E' be C<T>. [...]
1195   const ASTTemplateArgumentListInfo *ArgsAsWritten =
1196     TemplateArgs ? ASTTemplateArgumentListInfo::Create(Context,
1197                                                        *TemplateArgs) : nullptr;
1198 
1199   QualType ParamAsArgument(ConstrainedParameter->getTypeForDecl(), 0);
1200 
1201   ExprResult ImmediatelyDeclaredConstraint = formImmediatelyDeclaredConstraint(
1202       *this, NS, NameInfo, NamedConcept, FoundDecl,
1203       TemplateArgs ? TemplateArgs->getLAngleLoc() : SourceLocation(),
1204       TemplateArgs ? TemplateArgs->getRAngleLoc() : SourceLocation(),
1205       ParamAsArgument, ConstrainedParameter->getLocation(),
1206       [&](TemplateArgumentListInfo &ConstraintArgs) {
1207         if (TemplateArgs)
1208           for (const auto &ArgLoc : TemplateArgs->arguments())
1209             ConstraintArgs.addArgument(ArgLoc);
1210       },
1211       EllipsisLoc);
1212   if (ImmediatelyDeclaredConstraint.isInvalid())
1213     return true;
1214 
1215   auto *CL = ConceptReference::Create(Context, /*NNS=*/NS,
1216                                       /*TemplateKWLoc=*/SourceLocation{},
1217                                       /*ConceptNameInfo=*/NameInfo,
1218                                       /*FoundDecl=*/FoundDecl,
1219                                       /*NamedConcept=*/NamedConcept,
1220                                       /*ArgsWritten=*/ArgsAsWritten);
1221   ConstrainedParameter->setTypeConstraint(CL,
1222                                           ImmediatelyDeclaredConstraint.get());
1223   return false;
1224 }
1225 
AttachTypeConstraint(AutoTypeLoc TL,NonTypeTemplateParmDecl * NewConstrainedParm,NonTypeTemplateParmDecl * OrigConstrainedParm,SourceLocation EllipsisLoc)1226 bool Sema::AttachTypeConstraint(AutoTypeLoc TL,
1227                                 NonTypeTemplateParmDecl *NewConstrainedParm,
1228                                 NonTypeTemplateParmDecl *OrigConstrainedParm,
1229                                 SourceLocation EllipsisLoc) {
1230   if (NewConstrainedParm->getType() != TL.getType() ||
1231       TL.getAutoKeyword() != AutoTypeKeyword::Auto) {
1232     Diag(NewConstrainedParm->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
1233          diag::err_unsupported_placeholder_constraint)
1234         << NewConstrainedParm->getTypeSourceInfo()
1235                ->getTypeLoc()
1236                .getSourceRange();
1237     return true;
1238   }
1239   // FIXME: Concepts: This should be the type of the placeholder, but this is
1240   // unclear in the wording right now.
1241   DeclRefExpr *Ref =
1242       BuildDeclRefExpr(OrigConstrainedParm, OrigConstrainedParm->getType(),
1243                        VK_PRValue, OrigConstrainedParm->getLocation());
1244   if (!Ref)
1245     return true;
1246   ExprResult ImmediatelyDeclaredConstraint = formImmediatelyDeclaredConstraint(
1247       *this, TL.getNestedNameSpecifierLoc(), TL.getConceptNameInfo(),
1248       TL.getNamedConcept(), /*FoundDecl=*/TL.getFoundDecl(), TL.getLAngleLoc(),
1249       TL.getRAngleLoc(), BuildDecltypeType(Ref),
1250       OrigConstrainedParm->getLocation(),
1251       [&](TemplateArgumentListInfo &ConstraintArgs) {
1252         for (unsigned I = 0, C = TL.getNumArgs(); I != C; ++I)
1253           ConstraintArgs.addArgument(TL.getArgLoc(I));
1254       },
1255       EllipsisLoc);
1256   if (ImmediatelyDeclaredConstraint.isInvalid() ||
1257       !ImmediatelyDeclaredConstraint.isUsable())
1258     return true;
1259 
1260   NewConstrainedParm->setPlaceholderTypeConstraint(
1261       ImmediatelyDeclaredConstraint.get());
1262   return false;
1263 }
1264 
CheckNonTypeTemplateParameterType(TypeSourceInfo * & TSI,SourceLocation Loc)1265 QualType Sema::CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI,
1266                                                  SourceLocation Loc) {
1267   if (TSI->getType()->isUndeducedType()) {
1268     // C++17 [temp.dep.expr]p3:
1269     //   An id-expression is type-dependent if it contains
1270     //    - an identifier associated by name lookup with a non-type
1271     //      template-parameter declared with a type that contains a
1272     //      placeholder type (7.1.7.4),
1273     TSI = SubstAutoTypeSourceInfoDependent(TSI);
1274   }
1275 
1276   return CheckNonTypeTemplateParameterType(TSI->getType(), Loc);
1277 }
1278 
RequireStructuralType(QualType T,SourceLocation Loc)1279 bool Sema::RequireStructuralType(QualType T, SourceLocation Loc) {
1280   if (T->isDependentType())
1281     return false;
1282 
1283   if (RequireCompleteType(Loc, T, diag::err_template_nontype_parm_incomplete))
1284     return true;
1285 
1286   if (T->isStructuralType())
1287     return false;
1288 
1289   // Structural types are required to be object types or lvalue references.
1290   if (T->isRValueReferenceType()) {
1291     Diag(Loc, diag::err_template_nontype_parm_rvalue_ref) << T;
1292     return true;
1293   }
1294 
1295   // Don't mention structural types in our diagnostic prior to C++20. Also,
1296   // there's not much more we can say about non-scalar non-class types --
1297   // because we can't see functions or arrays here, those can only be language
1298   // extensions.
1299   if (!getLangOpts().CPlusPlus20 ||
1300       (!T->isScalarType() && !T->isRecordType())) {
1301     Diag(Loc, diag::err_template_nontype_parm_bad_type) << T;
1302     return true;
1303   }
1304 
1305   // Structural types are required to be literal types.
1306   if (RequireLiteralType(Loc, T, diag::err_template_nontype_parm_not_literal))
1307     return true;
1308 
1309   Diag(Loc, diag::err_template_nontype_parm_not_structural) << T;
1310 
1311   // Drill down into the reason why the class is non-structural.
1312   while (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
1313     // All members are required to be public and non-mutable, and can't be of
1314     // rvalue reference type. Check these conditions first to prefer a "local"
1315     // reason over a more distant one.
1316     for (const FieldDecl *FD : RD->fields()) {
1317       if (FD->getAccess() != AS_public) {
1318         Diag(FD->getLocation(), diag::note_not_structural_non_public) << T << 0;
1319         return true;
1320       }
1321       if (FD->isMutable()) {
1322         Diag(FD->getLocation(), diag::note_not_structural_mutable_field) << T;
1323         return true;
1324       }
1325       if (FD->getType()->isRValueReferenceType()) {
1326         Diag(FD->getLocation(), diag::note_not_structural_rvalue_ref_field)
1327             << T;
1328         return true;
1329       }
1330     }
1331 
1332     // All bases are required to be public.
1333     for (const auto &BaseSpec : RD->bases()) {
1334       if (BaseSpec.getAccessSpecifier() != AS_public) {
1335         Diag(BaseSpec.getBaseTypeLoc(), diag::note_not_structural_non_public)
1336             << T << 1;
1337         return true;
1338       }
1339     }
1340 
1341     // All subobjects are required to be of structural types.
1342     SourceLocation SubLoc;
1343     QualType SubType;
1344     int Kind = -1;
1345 
1346     for (const FieldDecl *FD : RD->fields()) {
1347       QualType T = Context.getBaseElementType(FD->getType());
1348       if (!T->isStructuralType()) {
1349         SubLoc = FD->getLocation();
1350         SubType = T;
1351         Kind = 0;
1352         break;
1353       }
1354     }
1355 
1356     if (Kind == -1) {
1357       for (const auto &BaseSpec : RD->bases()) {
1358         QualType T = BaseSpec.getType();
1359         if (!T->isStructuralType()) {
1360           SubLoc = BaseSpec.getBaseTypeLoc();
1361           SubType = T;
1362           Kind = 1;
1363           break;
1364         }
1365       }
1366     }
1367 
1368     assert(Kind != -1 && "couldn't find reason why type is not structural");
1369     Diag(SubLoc, diag::note_not_structural_subobject)
1370         << T << Kind << SubType;
1371     T = SubType;
1372     RD = T->getAsCXXRecordDecl();
1373   }
1374 
1375   return true;
1376 }
1377 
CheckNonTypeTemplateParameterType(QualType T,SourceLocation Loc)1378 QualType Sema::CheckNonTypeTemplateParameterType(QualType T,
1379                                                  SourceLocation Loc) {
1380   // We don't allow variably-modified types as the type of non-type template
1381   // parameters.
1382   if (T->isVariablyModifiedType()) {
1383     Diag(Loc, diag::err_variably_modified_nontype_template_param)
1384       << T;
1385     return QualType();
1386   }
1387 
1388   // C++ [temp.param]p4:
1389   //
1390   // A non-type template-parameter shall have one of the following
1391   // (optionally cv-qualified) types:
1392   //
1393   //       -- integral or enumeration type,
1394   if (T->isIntegralOrEnumerationType() ||
1395       //   -- pointer to object or pointer to function,
1396       T->isPointerType() ||
1397       //   -- lvalue reference to object or lvalue reference to function,
1398       T->isLValueReferenceType() ||
1399       //   -- pointer to member,
1400       T->isMemberPointerType() ||
1401       //   -- std::nullptr_t, or
1402       T->isNullPtrType() ||
1403       //   -- a type that contains a placeholder type.
1404       T->isUndeducedType()) {
1405     // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
1406     // are ignored when determining its type.
1407     return T.getUnqualifiedType();
1408   }
1409 
1410   // C++ [temp.param]p8:
1411   //
1412   //   A non-type template-parameter of type "array of T" or
1413   //   "function returning T" is adjusted to be of type "pointer to
1414   //   T" or "pointer to function returning T", respectively.
1415   if (T->isArrayType() || T->isFunctionType())
1416     return Context.getDecayedType(T);
1417 
1418   // If T is a dependent type, we can't do the check now, so we
1419   // assume that it is well-formed. Note that stripping off the
1420   // qualifiers here is not really correct if T turns out to be
1421   // an array type, but we'll recompute the type everywhere it's
1422   // used during instantiation, so that should be OK. (Using the
1423   // qualified type is equally wrong.)
1424   if (T->isDependentType())
1425     return T.getUnqualifiedType();
1426 
1427   // C++20 [temp.param]p6:
1428   //   -- a structural type
1429   if (RequireStructuralType(T, Loc))
1430     return QualType();
1431 
1432   if (!getLangOpts().CPlusPlus20) {
1433     // FIXME: Consider allowing structural types as an extension in C++17. (In
1434     // earlier language modes, the template argument evaluation rules are too
1435     // inflexible.)
1436     Diag(Loc, diag::err_template_nontype_parm_bad_structural_type) << T;
1437     return QualType();
1438   }
1439 
1440   Diag(Loc, diag::warn_cxx17_compat_template_nontype_parm_type) << T;
1441   return T.getUnqualifiedType();
1442 }
1443 
ActOnNonTypeTemplateParameter(Scope * S,Declarator & D,unsigned Depth,unsigned Position,SourceLocation EqualLoc,Expr * Default)1444 NamedDecl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
1445                                           unsigned Depth,
1446                                           unsigned Position,
1447                                           SourceLocation EqualLoc,
1448                                           Expr *Default) {
1449   TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
1450 
1451   // Check that we have valid decl-specifiers specified.
1452   auto CheckValidDeclSpecifiers = [this, &D] {
1453     // C++ [temp.param]
1454     // p1
1455     //   template-parameter:
1456     //     ...
1457     //     parameter-declaration
1458     // p2
1459     //   ... A storage class shall not be specified in a template-parameter
1460     //   declaration.
1461     // [dcl.typedef]p1:
1462     //   The typedef specifier [...] shall not be used in the decl-specifier-seq
1463     //   of a parameter-declaration
1464     const DeclSpec &DS = D.getDeclSpec();
1465     auto EmitDiag = [this](SourceLocation Loc) {
1466       Diag(Loc, diag::err_invalid_decl_specifier_in_nontype_parm)
1467           << FixItHint::CreateRemoval(Loc);
1468     };
1469     if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified)
1470       EmitDiag(DS.getStorageClassSpecLoc());
1471 
1472     if (DS.getThreadStorageClassSpec() != TSCS_unspecified)
1473       EmitDiag(DS.getThreadStorageClassSpecLoc());
1474 
1475     // [dcl.inline]p1:
1476     //   The inline specifier can be applied only to the declaration or
1477     //   definition of a variable or function.
1478 
1479     if (DS.isInlineSpecified())
1480       EmitDiag(DS.getInlineSpecLoc());
1481 
1482     // [dcl.constexpr]p1:
1483     //   The constexpr specifier shall be applied only to the definition of a
1484     //   variable or variable template or the declaration of a function or
1485     //   function template.
1486 
1487     if (DS.hasConstexprSpecifier())
1488       EmitDiag(DS.getConstexprSpecLoc());
1489 
1490     // [dcl.fct.spec]p1:
1491     //   Function-specifiers can be used only in function declarations.
1492 
1493     if (DS.isVirtualSpecified())
1494       EmitDiag(DS.getVirtualSpecLoc());
1495 
1496     if (DS.hasExplicitSpecifier())
1497       EmitDiag(DS.getExplicitSpecLoc());
1498 
1499     if (DS.isNoreturnSpecified())
1500       EmitDiag(DS.getNoreturnSpecLoc());
1501   };
1502 
1503   CheckValidDeclSpecifiers();
1504 
1505   if (const auto *T = TInfo->getType()->getContainedDeducedType())
1506     if (isa<AutoType>(T))
1507       Diag(D.getIdentifierLoc(),
1508            diag::warn_cxx14_compat_template_nontype_parm_auto_type)
1509           << QualType(TInfo->getType()->getContainedAutoType(), 0);
1510 
1511   assert(S->isTemplateParamScope() &&
1512          "Non-type template parameter not in template parameter scope!");
1513   bool Invalid = false;
1514 
1515   QualType T = CheckNonTypeTemplateParameterType(TInfo, D.getIdentifierLoc());
1516   if (T.isNull()) {
1517     T = Context.IntTy; // Recover with an 'int' type.
1518     Invalid = true;
1519   }
1520 
1521   CheckFunctionOrTemplateParamDeclarator(S, D);
1522 
1523   const IdentifierInfo *ParamName = D.getIdentifier();
1524   bool IsParameterPack = D.hasEllipsis();
1525   NonTypeTemplateParmDecl *Param = NonTypeTemplateParmDecl::Create(
1526       Context, Context.getTranslationUnitDecl(), D.getBeginLoc(),
1527       D.getIdentifierLoc(), Depth, Position, ParamName, T, IsParameterPack,
1528       TInfo);
1529   Param->setAccess(AS_public);
1530 
1531   if (AutoTypeLoc TL = TInfo->getTypeLoc().getContainedAutoTypeLoc())
1532     if (TL.isConstrained())
1533       if (AttachTypeConstraint(TL, Param, Param, D.getEllipsisLoc()))
1534         Invalid = true;
1535 
1536   if (Invalid)
1537     Param->setInvalidDecl();
1538 
1539   if (Param->isParameterPack())
1540     if (auto *LSI = getEnclosingLambda())
1541       LSI->LocalPacks.push_back(Param);
1542 
1543   if (ParamName) {
1544     maybeDiagnoseTemplateParameterShadow(*this, S, D.getIdentifierLoc(),
1545                                          ParamName);
1546 
1547     // Add the template parameter into the current scope.
1548     S->AddDecl(Param);
1549     IdResolver.AddDecl(Param);
1550   }
1551 
1552   // C++0x [temp.param]p9:
1553   //   A default template-argument may be specified for any kind of
1554   //   template-parameter that is not a template parameter pack.
1555   if (Default && IsParameterPack) {
1556     Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1557     Default = nullptr;
1558   }
1559 
1560   // Check the well-formedness of the default template argument, if provided.
1561   if (Default) {
1562     // Check for unexpanded parameter packs.
1563     if (DiagnoseUnexpandedParameterPack(Default, UPPC_DefaultArgument))
1564       return Param;
1565 
1566     Param->setDefaultArgument(
1567         Context, getTrivialTemplateArgumentLoc(TemplateArgument(Default),
1568                                                QualType(), SourceLocation()));
1569   }
1570 
1571   return Param;
1572 }
1573 
ActOnTemplateTemplateParameter(Scope * S,SourceLocation TmpLoc,TemplateParameterList * Params,bool Typename,SourceLocation EllipsisLoc,IdentifierInfo * Name,SourceLocation NameLoc,unsigned Depth,unsigned Position,SourceLocation EqualLoc,ParsedTemplateArgument Default)1574 NamedDecl *Sema::ActOnTemplateTemplateParameter(
1575     Scope *S, SourceLocation TmpLoc, TemplateParameterList *Params,
1576     bool Typename, SourceLocation EllipsisLoc, IdentifierInfo *Name,
1577     SourceLocation NameLoc, unsigned Depth, unsigned Position,
1578     SourceLocation EqualLoc, ParsedTemplateArgument Default) {
1579   assert(S->isTemplateParamScope() &&
1580          "Template template parameter not in template parameter scope!");
1581 
1582   // Construct the parameter object.
1583   bool IsParameterPack = EllipsisLoc.isValid();
1584   TemplateTemplateParmDecl *Param = TemplateTemplateParmDecl::Create(
1585       Context, Context.getTranslationUnitDecl(),
1586       NameLoc.isInvalid() ? TmpLoc : NameLoc, Depth, Position, IsParameterPack,
1587       Name, Typename, Params);
1588   Param->setAccess(AS_public);
1589 
1590   if (Param->isParameterPack())
1591     if (auto *LSI = getEnclosingLambda())
1592       LSI->LocalPacks.push_back(Param);
1593 
1594   // If the template template parameter has a name, then link the identifier
1595   // into the scope and lookup mechanisms.
1596   if (Name) {
1597     maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name);
1598 
1599     S->AddDecl(Param);
1600     IdResolver.AddDecl(Param);
1601   }
1602 
1603   if (Params->size() == 0) {
1604     Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
1605     << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
1606     Param->setInvalidDecl();
1607   }
1608 
1609   // C++0x [temp.param]p9:
1610   //   A default template-argument may be specified for any kind of
1611   //   template-parameter that is not a template parameter pack.
1612   if (IsParameterPack && !Default.isInvalid()) {
1613     Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1614     Default = ParsedTemplateArgument();
1615   }
1616 
1617   if (!Default.isInvalid()) {
1618     // Check only that we have a template template argument. We don't want to
1619     // try to check well-formedness now, because our template template parameter
1620     // might have dependent types in its template parameters, which we wouldn't
1621     // be able to match now.
1622     //
1623     // If none of the template template parameter's template arguments mention
1624     // other template parameters, we could actually perform more checking here.
1625     // However, it isn't worth doing.
1626     TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
1627     if (DefaultArg.getArgument().getAsTemplate().isNull()) {
1628       Diag(DefaultArg.getLocation(), diag::err_template_arg_not_valid_template)
1629         << DefaultArg.getSourceRange();
1630       return Param;
1631     }
1632 
1633     // Check for unexpanded parameter packs.
1634     if (DiagnoseUnexpandedParameterPack(DefaultArg.getLocation(),
1635                                         DefaultArg.getArgument().getAsTemplate(),
1636                                         UPPC_DefaultArgument))
1637       return Param;
1638 
1639     Param->setDefaultArgument(Context, DefaultArg);
1640   }
1641 
1642   return Param;
1643 }
1644 
1645 namespace {
1646 class ConstraintRefersToContainingTemplateChecker
1647     : public TreeTransform<ConstraintRefersToContainingTemplateChecker> {
1648   bool Result = false;
1649   const FunctionDecl *Friend = nullptr;
1650   unsigned TemplateDepth = 0;
1651 
1652   // Check a record-decl that we've seen to see if it is a lexical parent of the
1653   // Friend, likely because it was referred to without its template arguments.
CheckIfContainingRecord(const CXXRecordDecl * CheckingRD)1654   void CheckIfContainingRecord(const CXXRecordDecl *CheckingRD) {
1655     CheckingRD = CheckingRD->getMostRecentDecl();
1656     if (!CheckingRD->isTemplated())
1657       return;
1658 
1659     for (const DeclContext *DC = Friend->getLexicalDeclContext();
1660          DC && !DC->isFileContext(); DC = DC->getParent())
1661       if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
1662         if (CheckingRD == RD->getMostRecentDecl())
1663           Result = true;
1664   }
1665 
CheckNonTypeTemplateParmDecl(NonTypeTemplateParmDecl * D)1666   void CheckNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
1667     assert(D->getDepth() <= TemplateDepth &&
1668            "Nothing should reference a value below the actual template depth, "
1669            "depth is likely wrong");
1670     if (D->getDepth() != TemplateDepth)
1671       Result = true;
1672 
1673     // Necessary because the type of the NTTP might be what refers to the parent
1674     // constriant.
1675     TransformType(D->getType());
1676   }
1677 
1678 public:
1679   using inherited = TreeTransform<ConstraintRefersToContainingTemplateChecker>;
1680 
ConstraintRefersToContainingTemplateChecker(Sema & SemaRef,const FunctionDecl * Friend,unsigned TemplateDepth)1681   ConstraintRefersToContainingTemplateChecker(Sema &SemaRef,
1682                                               const FunctionDecl *Friend,
1683                                               unsigned TemplateDepth)
1684       : inherited(SemaRef), Friend(Friend), TemplateDepth(TemplateDepth) {}
getResult() const1685   bool getResult() const { return Result; }
1686 
1687   // This should be the only template parm type that we have to deal with.
1688   // SubstTempalteTypeParmPack, SubstNonTypeTemplateParmPack, and
1689   // FunctionParmPackExpr are all partially substituted, which cannot happen
1690   // with concepts at this point in translation.
1691   using inherited::TransformTemplateTypeParmType;
TransformTemplateTypeParmType(TypeLocBuilder & TLB,TemplateTypeParmTypeLoc TL,bool)1692   QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
1693                                          TemplateTypeParmTypeLoc TL, bool) {
1694     assert(TL.getDecl()->getDepth() <= TemplateDepth &&
1695            "Nothing should reference a value below the actual template depth, "
1696            "depth is likely wrong");
1697     if (TL.getDecl()->getDepth() != TemplateDepth)
1698       Result = true;
1699     return inherited::TransformTemplateTypeParmType(
1700         TLB, TL,
1701         /*SuppressObjCLifetime=*/false);
1702   }
1703 
TransformDecl(SourceLocation Loc,Decl * D)1704   Decl *TransformDecl(SourceLocation Loc, Decl *D) {
1705     if (!D)
1706       return D;
1707     // FIXME : This is possibly an incomplete list, but it is unclear what other
1708     // Decl kinds could be used to refer to the template parameters.  This is a
1709     // best guess so far based on examples currently available, but the
1710     // unreachable should catch future instances/cases.
1711     if (auto *TD = dyn_cast<TypedefNameDecl>(D))
1712       TransformType(TD->getUnderlyingType());
1713     else if (auto *NTTPD = dyn_cast<NonTypeTemplateParmDecl>(D))
1714       CheckNonTypeTemplateParmDecl(NTTPD);
1715     else if (auto *VD = dyn_cast<ValueDecl>(D))
1716       TransformType(VD->getType());
1717     else if (auto *TD = dyn_cast<TemplateDecl>(D))
1718       TransformTemplateParameterList(TD->getTemplateParameters());
1719     else if (auto *RD = dyn_cast<CXXRecordDecl>(D))
1720       CheckIfContainingRecord(RD);
1721     else if (isa<NamedDecl>(D)) {
1722       // No direct types to visit here I believe.
1723     } else
1724       llvm_unreachable("Don't know how to handle this declaration type yet");
1725     return D;
1726   }
1727 };
1728 } // namespace
1729 
ConstraintExpressionDependsOnEnclosingTemplate(const FunctionDecl * Friend,unsigned TemplateDepth,const Expr * Constraint)1730 bool Sema::ConstraintExpressionDependsOnEnclosingTemplate(
1731     const FunctionDecl *Friend, unsigned TemplateDepth,
1732     const Expr *Constraint) {
1733   assert(Friend->getFriendObjectKind() && "Only works on a friend");
1734   ConstraintRefersToContainingTemplateChecker Checker(*this, Friend,
1735                                                       TemplateDepth);
1736   Checker.TransformExpr(const_cast<Expr *>(Constraint));
1737   return Checker.getResult();
1738 }
1739 
1740 TemplateParameterList *
ActOnTemplateParameterList(unsigned Depth,SourceLocation ExportLoc,SourceLocation TemplateLoc,SourceLocation LAngleLoc,ArrayRef<NamedDecl * > Params,SourceLocation RAngleLoc,Expr * RequiresClause)1741 Sema::ActOnTemplateParameterList(unsigned Depth,
1742                                  SourceLocation ExportLoc,
1743                                  SourceLocation TemplateLoc,
1744                                  SourceLocation LAngleLoc,
1745                                  ArrayRef<NamedDecl *> Params,
1746                                  SourceLocation RAngleLoc,
1747                                  Expr *RequiresClause) {
1748   if (ExportLoc.isValid())
1749     Diag(ExportLoc, diag::warn_template_export_unsupported);
1750 
1751   for (NamedDecl *P : Params)
1752     warnOnReservedIdentifier(P);
1753 
1754   return TemplateParameterList::Create(
1755       Context, TemplateLoc, LAngleLoc,
1756       llvm::ArrayRef(Params.data(), Params.size()), RAngleLoc, RequiresClause);
1757 }
1758 
SetNestedNameSpecifier(Sema & S,TagDecl * T,const CXXScopeSpec & SS)1759 static void SetNestedNameSpecifier(Sema &S, TagDecl *T,
1760                                    const CXXScopeSpec &SS) {
1761   if (SS.isSet())
1762     T->setQualifierInfo(SS.getWithLocInContext(S.Context));
1763 }
1764 
1765 // Returns the template parameter list with all default template argument
1766 // information.
GetTemplateParameterList(TemplateDecl * TD)1767 TemplateParameterList *Sema::GetTemplateParameterList(TemplateDecl *TD) {
1768   // Make sure we get the template parameter list from the most
1769   // recent declaration, since that is the only one that is guaranteed to
1770   // have all the default template argument information.
1771   Decl *D = TD->getMostRecentDecl();
1772   // C++11 N3337 [temp.param]p12:
1773   // A default template argument shall not be specified in a friend class
1774   // template declaration.
1775   //
1776   // Skip past friend *declarations* because they are not supposed to contain
1777   // default template arguments. Moreover, these declarations may introduce
1778   // template parameters living in different template depths than the
1779   // corresponding template parameters in TD, causing unmatched constraint
1780   // substitution.
1781   //
1782   // FIXME: Diagnose such cases within a class template:
1783   //  template <class T>
1784   //  struct S {
1785   //    template <class = void> friend struct C;
1786   //  };
1787   //  template struct S<int>;
1788   while (D->getFriendObjectKind() != Decl::FriendObjectKind::FOK_None &&
1789          D->getPreviousDecl())
1790     D = D->getPreviousDecl();
1791   return cast<TemplateDecl>(D)->getTemplateParameters();
1792 }
1793 
CheckClassTemplate(Scope * S,unsigned TagSpec,TagUseKind TUK,SourceLocation KWLoc,CXXScopeSpec & SS,IdentifierInfo * Name,SourceLocation NameLoc,const ParsedAttributesView & Attr,TemplateParameterList * TemplateParams,AccessSpecifier AS,SourceLocation ModulePrivateLoc,SourceLocation FriendLoc,unsigned NumOuterTemplateParamLists,TemplateParameterList ** OuterTemplateParamLists,SkipBodyInfo * SkipBody)1794 DeclResult Sema::CheckClassTemplate(
1795     Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
1796     CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
1797     const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams,
1798     AccessSpecifier AS, SourceLocation ModulePrivateLoc,
1799     SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists,
1800     TemplateParameterList **OuterTemplateParamLists, SkipBodyInfo *SkipBody) {
1801   assert(TemplateParams && TemplateParams->size() > 0 &&
1802          "No template parameters");
1803   assert(TUK != TagUseKind::Reference &&
1804          "Can only declare or define class templates");
1805   bool Invalid = false;
1806 
1807   // Check that we can declare a template here.
1808   if (CheckTemplateDeclScope(S, TemplateParams))
1809     return true;
1810 
1811   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
1812   assert(Kind != TagTypeKind::Enum &&
1813          "can't build template of enumerated type");
1814 
1815   // There is no such thing as an unnamed class template.
1816   if (!Name) {
1817     Diag(KWLoc, diag::err_template_unnamed_class);
1818     return true;
1819   }
1820 
1821   // Find any previous declaration with this name. For a friend with no
1822   // scope explicitly specified, we only look for tag declarations (per
1823   // C++11 [basic.lookup.elab]p2).
1824   DeclContext *SemanticContext;
1825   LookupResult Previous(*this, Name, NameLoc,
1826                         (SS.isEmpty() && TUK == TagUseKind::Friend)
1827                             ? LookupTagName
1828                             : LookupOrdinaryName,
1829                         forRedeclarationInCurContext());
1830   if (SS.isNotEmpty() && !SS.isInvalid()) {
1831     SemanticContext = computeDeclContext(SS, true);
1832     if (!SemanticContext) {
1833       // FIXME: Horrible, horrible hack! We can't currently represent this
1834       // in the AST, and historically we have just ignored such friend
1835       // class templates, so don't complain here.
1836       Diag(NameLoc, TUK == TagUseKind::Friend
1837                         ? diag::warn_template_qualified_friend_ignored
1838                         : diag::err_template_qualified_declarator_no_match)
1839           << SS.getScopeRep() << SS.getRange();
1840       return TUK != TagUseKind::Friend;
1841     }
1842 
1843     if (RequireCompleteDeclContext(SS, SemanticContext))
1844       return true;
1845 
1846     // If we're adding a template to a dependent context, we may need to
1847     // rebuilding some of the types used within the template parameter list,
1848     // now that we know what the current instantiation is.
1849     if (SemanticContext->isDependentContext()) {
1850       ContextRAII SavedContext(*this, SemanticContext);
1851       if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
1852         Invalid = true;
1853     }
1854 
1855     if (TUK != TagUseKind::Friend && TUK != TagUseKind::Reference)
1856       diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc,
1857                                    /*TemplateId-*/ nullptr,
1858                                    /*IsMemberSpecialization*/ false);
1859 
1860     LookupQualifiedName(Previous, SemanticContext);
1861   } else {
1862     SemanticContext = CurContext;
1863 
1864     // C++14 [class.mem]p14:
1865     //   If T is the name of a class, then each of the following shall have a
1866     //   name different from T:
1867     //    -- every member template of class T
1868     if (TUK != TagUseKind::Friend &&
1869         DiagnoseClassNameShadow(SemanticContext,
1870                                 DeclarationNameInfo(Name, NameLoc)))
1871       return true;
1872 
1873     LookupName(Previous, S);
1874   }
1875 
1876   if (Previous.isAmbiguous())
1877     return true;
1878 
1879   NamedDecl *PrevDecl = nullptr;
1880   if (Previous.begin() != Previous.end())
1881     PrevDecl = (*Previous.begin())->getUnderlyingDecl();
1882 
1883   if (PrevDecl && PrevDecl->isTemplateParameter()) {
1884     // Maybe we will complain about the shadowed template parameter.
1885     DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
1886     // Just pretend that we didn't see the previous declaration.
1887     PrevDecl = nullptr;
1888   }
1889 
1890   // If there is a previous declaration with the same name, check
1891   // whether this is a valid redeclaration.
1892   ClassTemplateDecl *PrevClassTemplate =
1893       dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
1894 
1895   // We may have found the injected-class-name of a class template,
1896   // class template partial specialization, or class template specialization.
1897   // In these cases, grab the template that is being defined or specialized.
1898   if (!PrevClassTemplate && isa_and_nonnull<CXXRecordDecl>(PrevDecl) &&
1899       cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
1900     PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
1901     PrevClassTemplate
1902       = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
1903     if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
1904       PrevClassTemplate
1905         = cast<ClassTemplateSpecializationDecl>(PrevDecl)
1906             ->getSpecializedTemplate();
1907     }
1908   }
1909 
1910   if (TUK == TagUseKind::Friend) {
1911     // C++ [namespace.memdef]p3:
1912     //   [...] When looking for a prior declaration of a class or a function
1913     //   declared as a friend, and when the name of the friend class or
1914     //   function is neither a qualified name nor a template-id, scopes outside
1915     //   the innermost enclosing namespace scope are not considered.
1916     if (!SS.isSet()) {
1917       DeclContext *OutermostContext = CurContext;
1918       while (!OutermostContext->isFileContext())
1919         OutermostContext = OutermostContext->getLookupParent();
1920 
1921       if (PrevDecl &&
1922           (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
1923            OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
1924         SemanticContext = PrevDecl->getDeclContext();
1925       } else {
1926         // Declarations in outer scopes don't matter. However, the outermost
1927         // context we computed is the semantic context for our new
1928         // declaration.
1929         PrevDecl = PrevClassTemplate = nullptr;
1930         SemanticContext = OutermostContext;
1931 
1932         // Check that the chosen semantic context doesn't already contain a
1933         // declaration of this name as a non-tag type.
1934         Previous.clear(LookupOrdinaryName);
1935         DeclContext *LookupContext = SemanticContext;
1936         while (LookupContext->isTransparentContext())
1937           LookupContext = LookupContext->getLookupParent();
1938         LookupQualifiedName(Previous, LookupContext);
1939 
1940         if (Previous.isAmbiguous())
1941           return true;
1942 
1943         if (Previous.begin() != Previous.end())
1944           PrevDecl = (*Previous.begin())->getUnderlyingDecl();
1945       }
1946     }
1947   } else if (PrevDecl && !isDeclInScope(Previous.getRepresentativeDecl(),
1948                                         SemanticContext, S, SS.isValid()))
1949     PrevDecl = PrevClassTemplate = nullptr;
1950 
1951   if (auto *Shadow = dyn_cast_or_null<UsingShadowDecl>(
1952           PrevDecl ? Previous.getRepresentativeDecl() : nullptr)) {
1953     if (SS.isEmpty() &&
1954         !(PrevClassTemplate &&
1955           PrevClassTemplate->getDeclContext()->getRedeclContext()->Equals(
1956               SemanticContext->getRedeclContext()))) {
1957       Diag(KWLoc, diag::err_using_decl_conflict_reverse);
1958       Diag(Shadow->getTargetDecl()->getLocation(),
1959            diag::note_using_decl_target);
1960       Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
1961       // Recover by ignoring the old declaration.
1962       PrevDecl = PrevClassTemplate = nullptr;
1963     }
1964   }
1965 
1966   if (PrevClassTemplate) {
1967     // Ensure that the template parameter lists are compatible. Skip this check
1968     // for a friend in a dependent context: the template parameter list itself
1969     // could be dependent.
1970     if (!(TUK == TagUseKind::Friend && CurContext->isDependentContext()) &&
1971         !TemplateParameterListsAreEqual(
1972             TemplateCompareNewDeclInfo(SemanticContext ? SemanticContext
1973                                                        : CurContext,
1974                                        CurContext, KWLoc),
1975             TemplateParams, PrevClassTemplate,
1976             PrevClassTemplate->getTemplateParameters(), /*Complain=*/true,
1977             TPL_TemplateMatch))
1978       return true;
1979 
1980     // C++ [temp.class]p4:
1981     //   In a redeclaration, partial specialization, explicit
1982     //   specialization or explicit instantiation of a class template,
1983     //   the class-key shall agree in kind with the original class
1984     //   template declaration (7.1.5.3).
1985     RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
1986     if (!isAcceptableTagRedeclaration(
1987             PrevRecordDecl, Kind, TUK == TagUseKind::Definition, KWLoc, Name)) {
1988       Diag(KWLoc, diag::err_use_with_wrong_tag)
1989         << Name
1990         << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
1991       Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
1992       Kind = PrevRecordDecl->getTagKind();
1993     }
1994 
1995     // Check for redefinition of this class template.
1996     if (TUK == TagUseKind::Definition) {
1997       if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
1998         // If we have a prior definition that is not visible, treat this as
1999         // simply making that previous definition visible.
2000         NamedDecl *Hidden = nullptr;
2001         if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
2002           SkipBody->ShouldSkip = true;
2003           SkipBody->Previous = Def;
2004           auto *Tmpl = cast<CXXRecordDecl>(Hidden)->getDescribedClassTemplate();
2005           assert(Tmpl && "original definition of a class template is not a "
2006                          "class template?");
2007           makeMergedDefinitionVisible(Hidden);
2008           makeMergedDefinitionVisible(Tmpl);
2009         } else {
2010           Diag(NameLoc, diag::err_redefinition) << Name;
2011           Diag(Def->getLocation(), diag::note_previous_definition);
2012           // FIXME: Would it make sense to try to "forget" the previous
2013           // definition, as part of error recovery?
2014           return true;
2015         }
2016       }
2017     }
2018   } else if (PrevDecl) {
2019     // C++ [temp]p5:
2020     //   A class template shall not have the same name as any other
2021     //   template, class, function, object, enumeration, enumerator,
2022     //   namespace, or type in the same scope (3.3), except as specified
2023     //   in (14.5.4).
2024     Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
2025     Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2026     return true;
2027   }
2028 
2029   // Check the template parameter list of this declaration, possibly
2030   // merging in the template parameter list from the previous class
2031   // template declaration. Skip this check for a friend in a dependent
2032   // context, because the template parameter list might be dependent.
2033   if (!(TUK == TagUseKind::Friend && CurContext->isDependentContext()) &&
2034       CheckTemplateParameterList(
2035           TemplateParams,
2036           PrevClassTemplate ? GetTemplateParameterList(PrevClassTemplate)
2037                             : nullptr,
2038           (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
2039            SemanticContext->isDependentContext())
2040               ? TPC_ClassTemplateMember
2041           : TUK == TagUseKind::Friend ? TPC_FriendClassTemplate
2042                                       : TPC_ClassTemplate,
2043           SkipBody))
2044     Invalid = true;
2045 
2046   if (SS.isSet()) {
2047     // If the name of the template was qualified, we must be defining the
2048     // template out-of-line.
2049     if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
2050       Diag(NameLoc, TUK == TagUseKind::Friend
2051                         ? diag::err_friend_decl_does_not_match
2052                         : diag::err_member_decl_does_not_match)
2053           << Name << SemanticContext << /*IsDefinition*/ true << SS.getRange();
2054       Invalid = true;
2055     }
2056   }
2057 
2058   // If this is a templated friend in a dependent context we should not put it
2059   // on the redecl chain. In some cases, the templated friend can be the most
2060   // recent declaration tricking the template instantiator to make substitutions
2061   // there.
2062   // FIXME: Figure out how to combine with shouldLinkDependentDeclWithPrevious
2063   bool ShouldAddRedecl =
2064       !(TUK == TagUseKind::Friend && CurContext->isDependentContext());
2065 
2066   CXXRecordDecl *NewClass =
2067     CXXRecordDecl::Create(Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
2068                           PrevClassTemplate && ShouldAddRedecl ?
2069                             PrevClassTemplate->getTemplatedDecl() : nullptr,
2070                           /*DelayTypeCreation=*/true);
2071   SetNestedNameSpecifier(*this, NewClass, SS);
2072   if (NumOuterTemplateParamLists > 0)
2073     NewClass->setTemplateParameterListsInfo(
2074         Context,
2075         llvm::ArrayRef(OuterTemplateParamLists, NumOuterTemplateParamLists));
2076 
2077   // Add alignment attributes if necessary; these attributes are checked when
2078   // the ASTContext lays out the structure.
2079   if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
2080     AddAlignmentAttributesForRecord(NewClass);
2081     AddMsStructLayoutForRecord(NewClass);
2082   }
2083 
2084   ClassTemplateDecl *NewTemplate
2085     = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
2086                                 DeclarationName(Name), TemplateParams,
2087                                 NewClass);
2088 
2089   if (ShouldAddRedecl)
2090     NewTemplate->setPreviousDecl(PrevClassTemplate);
2091 
2092   NewClass->setDescribedClassTemplate(NewTemplate);
2093 
2094   if (ModulePrivateLoc.isValid())
2095     NewTemplate->setModulePrivate();
2096 
2097   // Build the type for the class template declaration now.
2098   QualType T = NewTemplate->getInjectedClassNameSpecialization();
2099   T = Context.getInjectedClassNameType(NewClass, T);
2100   assert(T->isDependentType() && "Class template type is not dependent?");
2101   (void)T;
2102 
2103   // If we are providing an explicit specialization of a member that is a
2104   // class template, make a note of that.
2105   if (PrevClassTemplate &&
2106       PrevClassTemplate->getInstantiatedFromMemberTemplate())
2107     PrevClassTemplate->setMemberSpecialization();
2108 
2109   // Set the access specifier.
2110   if (!Invalid && TUK != TagUseKind::Friend &&
2111       NewTemplate->getDeclContext()->isRecord())
2112     SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
2113 
2114   // Set the lexical context of these templates
2115   NewClass->setLexicalDeclContext(CurContext);
2116   NewTemplate->setLexicalDeclContext(CurContext);
2117 
2118   if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip))
2119     NewClass->startDefinition();
2120 
2121   ProcessDeclAttributeList(S, NewClass, Attr);
2122   ProcessAPINotes(NewClass);
2123 
2124   if (PrevClassTemplate)
2125     mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
2126 
2127   AddPushedVisibilityAttribute(NewClass);
2128   inferGslOwnerPointerAttribute(NewClass);
2129   inferNullableClassAttribute(NewClass);
2130 
2131   if (TUK != TagUseKind::Friend) {
2132     // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
2133     Scope *Outer = S;
2134     while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
2135       Outer = Outer->getParent();
2136     PushOnScopeChains(NewTemplate, Outer);
2137   } else {
2138     if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
2139       NewTemplate->setAccess(PrevClassTemplate->getAccess());
2140       NewClass->setAccess(PrevClassTemplate->getAccess());
2141     }
2142 
2143     NewTemplate->setObjectOfFriendDecl();
2144 
2145     // Friend templates are visible in fairly strange ways.
2146     if (!CurContext->isDependentContext()) {
2147       DeclContext *DC = SemanticContext->getRedeclContext();
2148       DC->makeDeclVisibleInContext(NewTemplate);
2149       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
2150         PushOnScopeChains(NewTemplate, EnclosingScope,
2151                           /* AddToContext = */ false);
2152     }
2153 
2154     FriendDecl *Friend = FriendDecl::Create(
2155         Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc);
2156     Friend->setAccess(AS_public);
2157     CurContext->addDecl(Friend);
2158   }
2159 
2160   if (PrevClassTemplate)
2161     CheckRedeclarationInModule(NewTemplate, PrevClassTemplate);
2162 
2163   if (Invalid) {
2164     NewTemplate->setInvalidDecl();
2165     NewClass->setInvalidDecl();
2166   }
2167 
2168   ActOnDocumentableDecl(NewTemplate);
2169 
2170   if (SkipBody && SkipBody->ShouldSkip)
2171     return SkipBody->Previous;
2172 
2173   return NewTemplate;
2174 }
2175 
2176 /// Diagnose the presence of a default template argument on a
2177 /// template parameter, which is ill-formed in certain contexts.
2178 ///
2179 /// \returns true if the default template argument should be dropped.
DiagnoseDefaultTemplateArgument(Sema & S,Sema::TemplateParamListContext TPC,SourceLocation ParamLoc,SourceRange DefArgRange)2180 static bool DiagnoseDefaultTemplateArgument(Sema &S,
2181                                             Sema::TemplateParamListContext TPC,
2182                                             SourceLocation ParamLoc,
2183                                             SourceRange DefArgRange) {
2184   switch (TPC) {
2185   case Sema::TPC_ClassTemplate:
2186   case Sema::TPC_VarTemplate:
2187   case Sema::TPC_TypeAliasTemplate:
2188     return false;
2189 
2190   case Sema::TPC_FunctionTemplate:
2191   case Sema::TPC_FriendFunctionTemplateDefinition:
2192     // C++ [temp.param]p9:
2193     //   A default template-argument shall not be specified in a
2194     //   function template declaration or a function template
2195     //   definition [...]
2196     //   If a friend function template declaration specifies a default
2197     //   template-argument, that declaration shall be a definition and shall be
2198     //   the only declaration of the function template in the translation unit.
2199     // (C++98/03 doesn't have this wording; see DR226).
2200     S.Diag(ParamLoc, S.getLangOpts().CPlusPlus11 ?
2201          diag::warn_cxx98_compat_template_parameter_default_in_function_template
2202            : diag::ext_template_parameter_default_in_function_template)
2203       << DefArgRange;
2204     return false;
2205 
2206   case Sema::TPC_ClassTemplateMember:
2207     // C++0x [temp.param]p9:
2208     //   A default template-argument shall not be specified in the
2209     //   template-parameter-lists of the definition of a member of a
2210     //   class template that appears outside of the member's class.
2211     S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
2212       << DefArgRange;
2213     return true;
2214 
2215   case Sema::TPC_FriendClassTemplate:
2216   case Sema::TPC_FriendFunctionTemplate:
2217     // C++ [temp.param]p9:
2218     //   A default template-argument shall not be specified in a
2219     //   friend template declaration.
2220     S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
2221       << DefArgRange;
2222     return true;
2223 
2224     // FIXME: C++0x [temp.param]p9 allows default template-arguments
2225     // for friend function templates if there is only a single
2226     // declaration (and it is a definition). Strange!
2227   }
2228 
2229   llvm_unreachable("Invalid TemplateParamListContext!");
2230 }
2231 
2232 /// Check for unexpanded parameter packs within the template parameters
2233 /// of a template template parameter, recursively.
DiagnoseUnexpandedParameterPacks(Sema & S,TemplateTemplateParmDecl * TTP)2234 static bool DiagnoseUnexpandedParameterPacks(Sema &S,
2235                                              TemplateTemplateParmDecl *TTP) {
2236   // A template template parameter which is a parameter pack is also a pack
2237   // expansion.
2238   if (TTP->isParameterPack())
2239     return false;
2240 
2241   TemplateParameterList *Params = TTP->getTemplateParameters();
2242   for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2243     NamedDecl *P = Params->getParam(I);
2244     if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(P)) {
2245       if (!TTP->isParameterPack())
2246         if (const TypeConstraint *TC = TTP->getTypeConstraint())
2247           if (TC->hasExplicitTemplateArgs())
2248             for (auto &ArgLoc : TC->getTemplateArgsAsWritten()->arguments())
2249               if (S.DiagnoseUnexpandedParameterPack(ArgLoc,
2250                                                     Sema::UPPC_TypeConstraint))
2251                 return true;
2252       continue;
2253     }
2254 
2255     if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
2256       if (!NTTP->isParameterPack() &&
2257           S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
2258                                             NTTP->getTypeSourceInfo(),
2259                                       Sema::UPPC_NonTypeTemplateParameterType))
2260         return true;
2261 
2262       continue;
2263     }
2264 
2265     if (TemplateTemplateParmDecl *InnerTTP
2266                                         = dyn_cast<TemplateTemplateParmDecl>(P))
2267       if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
2268         return true;
2269   }
2270 
2271   return false;
2272 }
2273 
CheckTemplateParameterList(TemplateParameterList * NewParams,TemplateParameterList * OldParams,TemplateParamListContext TPC,SkipBodyInfo * SkipBody)2274 bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
2275                                       TemplateParameterList *OldParams,
2276                                       TemplateParamListContext TPC,
2277                                       SkipBodyInfo *SkipBody) {
2278   bool Invalid = false;
2279 
2280   // C++ [temp.param]p10:
2281   //   The set of default template-arguments available for use with a
2282   //   template declaration or definition is obtained by merging the
2283   //   default arguments from the definition (if in scope) and all
2284   //   declarations in scope in the same way default function
2285   //   arguments are (8.3.6).
2286   bool SawDefaultArgument = false;
2287   SourceLocation PreviousDefaultArgLoc;
2288 
2289   // Dummy initialization to avoid warnings.
2290   TemplateParameterList::iterator OldParam = NewParams->end();
2291   if (OldParams)
2292     OldParam = OldParams->begin();
2293 
2294   bool RemoveDefaultArguments = false;
2295   for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2296                                     NewParamEnd = NewParams->end();
2297        NewParam != NewParamEnd; ++NewParam) {
2298     // Whether we've seen a duplicate default argument in the same translation
2299     // unit.
2300     bool RedundantDefaultArg = false;
2301     // Whether we've found inconsis inconsitent default arguments in different
2302     // translation unit.
2303     bool InconsistentDefaultArg = false;
2304     // The name of the module which contains the inconsistent default argument.
2305     std::string PrevModuleName;
2306 
2307     SourceLocation OldDefaultLoc;
2308     SourceLocation NewDefaultLoc;
2309 
2310     // Variable used to diagnose missing default arguments
2311     bool MissingDefaultArg = false;
2312 
2313     // Variable used to diagnose non-final parameter packs
2314     bool SawParameterPack = false;
2315 
2316     if (TemplateTypeParmDecl *NewTypeParm
2317           = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
2318       // Check the presence of a default argument here.
2319       if (NewTypeParm->hasDefaultArgument() &&
2320           DiagnoseDefaultTemplateArgument(
2321               *this, TPC, NewTypeParm->getLocation(),
2322               NewTypeParm->getDefaultArgument().getSourceRange()))
2323         NewTypeParm->removeDefaultArgument();
2324 
2325       // Merge default arguments for template type parameters.
2326       TemplateTypeParmDecl *OldTypeParm
2327           = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr;
2328       if (NewTypeParm->isParameterPack()) {
2329         assert(!NewTypeParm->hasDefaultArgument() &&
2330                "Parameter packs can't have a default argument!");
2331         SawParameterPack = true;
2332       } else if (OldTypeParm && hasVisibleDefaultArgument(OldTypeParm) &&
2333                  NewTypeParm->hasDefaultArgument() &&
2334                  (!SkipBody || !SkipBody->ShouldSkip)) {
2335         OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
2336         NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
2337         SawDefaultArgument = true;
2338 
2339         if (!OldTypeParm->getOwningModule())
2340           RedundantDefaultArg = true;
2341         else if (!getASTContext().isSameDefaultTemplateArgument(OldTypeParm,
2342                                                                 NewTypeParm)) {
2343           InconsistentDefaultArg = true;
2344           PrevModuleName =
2345               OldTypeParm->getImportedOwningModule()->getFullModuleName();
2346         }
2347         PreviousDefaultArgLoc = NewDefaultLoc;
2348       } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
2349         // Merge the default argument from the old declaration to the
2350         // new declaration.
2351         NewTypeParm->setInheritedDefaultArgument(Context, OldTypeParm);
2352         PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
2353       } else if (NewTypeParm->hasDefaultArgument()) {
2354         SawDefaultArgument = true;
2355         PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
2356       } else if (SawDefaultArgument)
2357         MissingDefaultArg = true;
2358     } else if (NonTypeTemplateParmDecl *NewNonTypeParm
2359                = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
2360       // Check for unexpanded parameter packs.
2361       if (!NewNonTypeParm->isParameterPack() &&
2362           DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
2363                                           NewNonTypeParm->getTypeSourceInfo(),
2364                                           UPPC_NonTypeTemplateParameterType)) {
2365         Invalid = true;
2366         continue;
2367       }
2368 
2369       // Check the presence of a default argument here.
2370       if (NewNonTypeParm->hasDefaultArgument() &&
2371           DiagnoseDefaultTemplateArgument(
2372               *this, TPC, NewNonTypeParm->getLocation(),
2373               NewNonTypeParm->getDefaultArgument().getSourceRange())) {
2374         NewNonTypeParm->removeDefaultArgument();
2375       }
2376 
2377       // Merge default arguments for non-type template parameters
2378       NonTypeTemplateParmDecl *OldNonTypeParm
2379         = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr;
2380       if (NewNonTypeParm->isParameterPack()) {
2381         assert(!NewNonTypeParm->hasDefaultArgument() &&
2382                "Parameter packs can't have a default argument!");
2383         if (!NewNonTypeParm->isPackExpansion())
2384           SawParameterPack = true;
2385       } else if (OldNonTypeParm && hasVisibleDefaultArgument(OldNonTypeParm) &&
2386                  NewNonTypeParm->hasDefaultArgument() &&
2387                  (!SkipBody || !SkipBody->ShouldSkip)) {
2388         OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
2389         NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
2390         SawDefaultArgument = true;
2391         if (!OldNonTypeParm->getOwningModule())
2392           RedundantDefaultArg = true;
2393         else if (!getASTContext().isSameDefaultTemplateArgument(
2394                      OldNonTypeParm, NewNonTypeParm)) {
2395           InconsistentDefaultArg = true;
2396           PrevModuleName =
2397               OldNonTypeParm->getImportedOwningModule()->getFullModuleName();
2398         }
2399         PreviousDefaultArgLoc = NewDefaultLoc;
2400       } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
2401         // Merge the default argument from the old declaration to the
2402         // new declaration.
2403         NewNonTypeParm->setInheritedDefaultArgument(Context, OldNonTypeParm);
2404         PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
2405       } else if (NewNonTypeParm->hasDefaultArgument()) {
2406         SawDefaultArgument = true;
2407         PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
2408       } else if (SawDefaultArgument)
2409         MissingDefaultArg = true;
2410     } else {
2411       TemplateTemplateParmDecl *NewTemplateParm
2412         = cast<TemplateTemplateParmDecl>(*NewParam);
2413 
2414       // Check for unexpanded parameter packs, recursively.
2415       if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
2416         Invalid = true;
2417         continue;
2418       }
2419 
2420       // Check the presence of a default argument here.
2421       if (NewTemplateParm->hasDefaultArgument() &&
2422           DiagnoseDefaultTemplateArgument(*this, TPC,
2423                                           NewTemplateParm->getLocation(),
2424                      NewTemplateParm->getDefaultArgument().getSourceRange()))
2425         NewTemplateParm->removeDefaultArgument();
2426 
2427       // Merge default arguments for template template parameters
2428       TemplateTemplateParmDecl *OldTemplateParm
2429         = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr;
2430       if (NewTemplateParm->isParameterPack()) {
2431         assert(!NewTemplateParm->hasDefaultArgument() &&
2432                "Parameter packs can't have a default argument!");
2433         if (!NewTemplateParm->isPackExpansion())
2434           SawParameterPack = true;
2435       } else if (OldTemplateParm &&
2436                  hasVisibleDefaultArgument(OldTemplateParm) &&
2437                  NewTemplateParm->hasDefaultArgument() &&
2438                  (!SkipBody || !SkipBody->ShouldSkip)) {
2439         OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
2440         NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
2441         SawDefaultArgument = true;
2442         if (!OldTemplateParm->getOwningModule())
2443           RedundantDefaultArg = true;
2444         else if (!getASTContext().isSameDefaultTemplateArgument(
2445                      OldTemplateParm, NewTemplateParm)) {
2446           InconsistentDefaultArg = true;
2447           PrevModuleName =
2448               OldTemplateParm->getImportedOwningModule()->getFullModuleName();
2449         }
2450         PreviousDefaultArgLoc = NewDefaultLoc;
2451       } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
2452         // Merge the default argument from the old declaration to the
2453         // new declaration.
2454         NewTemplateParm->setInheritedDefaultArgument(Context, OldTemplateParm);
2455         PreviousDefaultArgLoc
2456           = OldTemplateParm->getDefaultArgument().getLocation();
2457       } else if (NewTemplateParm->hasDefaultArgument()) {
2458         SawDefaultArgument = true;
2459         PreviousDefaultArgLoc
2460           = NewTemplateParm->getDefaultArgument().getLocation();
2461       } else if (SawDefaultArgument)
2462         MissingDefaultArg = true;
2463     }
2464 
2465     // C++11 [temp.param]p11:
2466     //   If a template parameter of a primary class template or alias template
2467     //   is a template parameter pack, it shall be the last template parameter.
2468     if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
2469         (TPC == TPC_ClassTemplate || TPC == TPC_VarTemplate ||
2470          TPC == TPC_TypeAliasTemplate)) {
2471       Diag((*NewParam)->getLocation(),
2472            diag::err_template_param_pack_must_be_last_template_parameter);
2473       Invalid = true;
2474     }
2475 
2476     // [basic.def.odr]/13:
2477     //     There can be more than one definition of a
2478     //     ...
2479     //     default template argument
2480     //     ...
2481     //     in a program provided that each definition appears in a different
2482     //     translation unit and the definitions satisfy the [same-meaning
2483     //     criteria of the ODR].
2484     //
2485     // Simply, the design of modules allows the definition of template default
2486     // argument to be repeated across translation unit. Note that the ODR is
2487     // checked elsewhere. But it is still not allowed to repeat template default
2488     // argument in the same translation unit.
2489     if (RedundantDefaultArg) {
2490       Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
2491       Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
2492       Invalid = true;
2493     } else if (InconsistentDefaultArg) {
2494       // We could only diagnose about the case that the OldParam is imported.
2495       // The case NewParam is imported should be handled in ASTReader.
2496       Diag(NewDefaultLoc,
2497            diag::err_template_param_default_arg_inconsistent_redefinition);
2498       Diag(OldDefaultLoc,
2499            diag::note_template_param_prev_default_arg_in_other_module)
2500           << PrevModuleName;
2501       Invalid = true;
2502     } else if (MissingDefaultArg &&
2503                (TPC == TPC_ClassTemplate || TPC == TPC_FriendClassTemplate ||
2504                 TPC == TPC_VarTemplate || TPC == TPC_TypeAliasTemplate)) {
2505       // C++ 23[temp.param]p14:
2506       // If a template-parameter of a class template, variable template, or
2507       // alias template has a default template argument, each subsequent
2508       // template-parameter shall either have a default template argument
2509       // supplied or be a template parameter pack.
2510       Diag((*NewParam)->getLocation(),
2511            diag::err_template_param_default_arg_missing);
2512       Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
2513       Invalid = true;
2514       RemoveDefaultArguments = true;
2515     }
2516 
2517     // If we have an old template parameter list that we're merging
2518     // in, move on to the next parameter.
2519     if (OldParams)
2520       ++OldParam;
2521   }
2522 
2523   // We were missing some default arguments at the end of the list, so remove
2524   // all of the default arguments.
2525   if (RemoveDefaultArguments) {
2526     for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2527                                       NewParamEnd = NewParams->end();
2528          NewParam != NewParamEnd; ++NewParam) {
2529       if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
2530         TTP->removeDefaultArgument();
2531       else if (NonTypeTemplateParmDecl *NTTP
2532                                 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
2533         NTTP->removeDefaultArgument();
2534       else
2535         cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
2536     }
2537   }
2538 
2539   return Invalid;
2540 }
2541 
2542 namespace {
2543 
2544 /// A class which looks for a use of a certain level of template
2545 /// parameter.
2546 struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
2547   typedef RecursiveASTVisitor<DependencyChecker> super;
2548 
2549   unsigned Depth;
2550 
2551   // Whether we're looking for a use of a template parameter that makes the
2552   // overall construct type-dependent / a dependent type. This is strictly
2553   // best-effort for now; we may fail to match at all for a dependent type
2554   // in some cases if this is set.
2555   bool IgnoreNonTypeDependent;
2556 
2557   bool Match;
2558   SourceLocation MatchLoc;
2559 
DependencyChecker__anon75c807110811::DependencyChecker2560   DependencyChecker(unsigned Depth, bool IgnoreNonTypeDependent)
2561       : Depth(Depth), IgnoreNonTypeDependent(IgnoreNonTypeDependent),
2562         Match(false) {}
2563 
DependencyChecker__anon75c807110811::DependencyChecker2564   DependencyChecker(TemplateParameterList *Params, bool IgnoreNonTypeDependent)
2565       : IgnoreNonTypeDependent(IgnoreNonTypeDependent), Match(false) {
2566     NamedDecl *ND = Params->getParam(0);
2567     if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
2568       Depth = PD->getDepth();
2569     } else if (NonTypeTemplateParmDecl *PD =
2570                  dyn_cast<NonTypeTemplateParmDecl>(ND)) {
2571       Depth = PD->getDepth();
2572     } else {
2573       Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
2574     }
2575   }
2576 
Matches__anon75c807110811::DependencyChecker2577   bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
2578     if (ParmDepth >= Depth) {
2579       Match = true;
2580       MatchLoc = Loc;
2581       return true;
2582     }
2583     return false;
2584   }
2585 
TraverseStmt__anon75c807110811::DependencyChecker2586   bool TraverseStmt(Stmt *S, DataRecursionQueue *Q = nullptr) {
2587     // Prune out non-type-dependent expressions if requested. This can
2588     // sometimes result in us failing to find a template parameter reference
2589     // (if a value-dependent expression creates a dependent type), but this
2590     // mode is best-effort only.
2591     if (auto *E = dyn_cast_or_null<Expr>(S))
2592       if (IgnoreNonTypeDependent && !E->isTypeDependent())
2593         return true;
2594     return super::TraverseStmt(S, Q);
2595   }
2596 
TraverseTypeLoc__anon75c807110811::DependencyChecker2597   bool TraverseTypeLoc(TypeLoc TL) {
2598     if (IgnoreNonTypeDependent && !TL.isNull() &&
2599         !TL.getType()->isDependentType())
2600       return true;
2601     return super::TraverseTypeLoc(TL);
2602   }
2603 
VisitTemplateTypeParmTypeLoc__anon75c807110811::DependencyChecker2604   bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
2605     return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());
2606   }
2607 
VisitTemplateTypeParmType__anon75c807110811::DependencyChecker2608   bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
2609     // For a best-effort search, keep looking until we find a location.
2610     return IgnoreNonTypeDependent || !Matches(T->getDepth());
2611   }
2612 
TraverseTemplateName__anon75c807110811::DependencyChecker2613   bool TraverseTemplateName(TemplateName N) {
2614     if (TemplateTemplateParmDecl *PD =
2615           dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
2616       if (Matches(PD->getDepth()))
2617         return false;
2618     return super::TraverseTemplateName(N);
2619   }
2620 
VisitDeclRefExpr__anon75c807110811::DependencyChecker2621   bool VisitDeclRefExpr(DeclRefExpr *E) {
2622     if (NonTypeTemplateParmDecl *PD =
2623           dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
2624       if (Matches(PD->getDepth(), E->getExprLoc()))
2625         return false;
2626     return super::VisitDeclRefExpr(E);
2627   }
2628 
VisitSubstTemplateTypeParmType__anon75c807110811::DependencyChecker2629   bool VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
2630     return TraverseType(T->getReplacementType());
2631   }
2632 
2633   bool
VisitSubstTemplateTypeParmPackType__anon75c807110811::DependencyChecker2634   VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *T) {
2635     return TraverseTemplateArgument(T->getArgumentPack());
2636   }
2637 
TraverseInjectedClassNameType__anon75c807110811::DependencyChecker2638   bool TraverseInjectedClassNameType(const InjectedClassNameType *T) {
2639     return TraverseType(T->getInjectedSpecializationType());
2640   }
2641 };
2642 } // end anonymous namespace
2643 
2644 /// Determines whether a given type depends on the given parameter
2645 /// list.
2646 static bool
DependsOnTemplateParameters(QualType T,TemplateParameterList * Params)2647 DependsOnTemplateParameters(QualType T, TemplateParameterList *Params) {
2648   if (!Params->size())
2649     return false;
2650 
2651   DependencyChecker Checker(Params, /*IgnoreNonTypeDependent*/false);
2652   Checker.TraverseType(T);
2653   return Checker.Match;
2654 }
2655 
2656 // Find the source range corresponding to the named type in the given
2657 // nested-name-specifier, if any.
getRangeOfTypeInNestedNameSpecifier(ASTContext & Context,QualType T,const CXXScopeSpec & SS)2658 static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context,
2659                                                        QualType T,
2660                                                        const CXXScopeSpec &SS) {
2661   NestedNameSpecifierLoc NNSLoc(SS.getScopeRep(), SS.location_data());
2662   while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) {
2663     if (const Type *CurType = NNS->getAsType()) {
2664       if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0)))
2665         return NNSLoc.getTypeLoc().getSourceRange();
2666     } else
2667       break;
2668 
2669     NNSLoc = NNSLoc.getPrefix();
2670   }
2671 
2672   return SourceRange();
2673 }
2674 
MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,SourceLocation DeclLoc,const CXXScopeSpec & SS,TemplateIdAnnotation * TemplateId,ArrayRef<TemplateParameterList * > ParamLists,bool IsFriend,bool & IsMemberSpecialization,bool & Invalid,bool SuppressDiagnostic)2675 TemplateParameterList *Sema::MatchTemplateParametersToScopeSpecifier(
2676     SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
2677     TemplateIdAnnotation *TemplateId,
2678     ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
2679     bool &IsMemberSpecialization, bool &Invalid, bool SuppressDiagnostic) {
2680   IsMemberSpecialization = false;
2681   Invalid = false;
2682 
2683   // The sequence of nested types to which we will match up the template
2684   // parameter lists. We first build this list by starting with the type named
2685   // by the nested-name-specifier and walking out until we run out of types.
2686   SmallVector<QualType, 4> NestedTypes;
2687   QualType T;
2688   if (SS.getScopeRep()) {
2689     if (CXXRecordDecl *Record
2690               = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
2691       T = Context.getTypeDeclType(Record);
2692     else
2693       T = QualType(SS.getScopeRep()->getAsType(), 0);
2694   }
2695 
2696   // If we found an explicit specialization that prevents us from needing
2697   // 'template<>' headers, this will be set to the location of that
2698   // explicit specialization.
2699   SourceLocation ExplicitSpecLoc;
2700 
2701   while (!T.isNull()) {
2702     NestedTypes.push_back(T);
2703 
2704     // Retrieve the parent of a record type.
2705     if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
2706       // If this type is an explicit specialization, we're done.
2707       if (ClassTemplateSpecializationDecl *Spec
2708           = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
2709         if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) &&
2710             Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
2711           ExplicitSpecLoc = Spec->getLocation();
2712           break;
2713         }
2714       } else if (Record->getTemplateSpecializationKind()
2715                                                 == TSK_ExplicitSpecialization) {
2716         ExplicitSpecLoc = Record->getLocation();
2717         break;
2718       }
2719 
2720       if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
2721         T = Context.getTypeDeclType(Parent);
2722       else
2723         T = QualType();
2724       continue;
2725     }
2726 
2727     if (const TemplateSpecializationType *TST
2728                                      = T->getAs<TemplateSpecializationType>()) {
2729       if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
2730         if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
2731           T = Context.getTypeDeclType(Parent);
2732         else
2733           T = QualType();
2734         continue;
2735       }
2736     }
2737 
2738     // Look one step prior in a dependent template specialization type.
2739     if (const DependentTemplateSpecializationType *DependentTST
2740                           = T->getAs<DependentTemplateSpecializationType>()) {
2741       if (NestedNameSpecifier *NNS = DependentTST->getQualifier())
2742         T = QualType(NNS->getAsType(), 0);
2743       else
2744         T = QualType();
2745       continue;
2746     }
2747 
2748     // Look one step prior in a dependent name type.
2749     if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
2750       if (NestedNameSpecifier *NNS = DependentName->getQualifier())
2751         T = QualType(NNS->getAsType(), 0);
2752       else
2753         T = QualType();
2754       continue;
2755     }
2756 
2757     // Retrieve the parent of an enumeration type.
2758     if (const EnumType *EnumT = T->getAs<EnumType>()) {
2759       // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
2760       // check here.
2761       EnumDecl *Enum = EnumT->getDecl();
2762 
2763       // Get to the parent type.
2764       if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
2765         T = Context.getTypeDeclType(Parent);
2766       else
2767         T = QualType();
2768       continue;
2769     }
2770 
2771     T = QualType();
2772   }
2773   // Reverse the nested types list, since we want to traverse from the outermost
2774   // to the innermost while checking template-parameter-lists.
2775   std::reverse(NestedTypes.begin(), NestedTypes.end());
2776 
2777   // C++0x [temp.expl.spec]p17:
2778   //   A member or a member template may be nested within many
2779   //   enclosing class templates. In an explicit specialization for
2780   //   such a member, the member declaration shall be preceded by a
2781   //   template<> for each enclosing class template that is
2782   //   explicitly specialized.
2783   bool SawNonEmptyTemplateParameterList = false;
2784 
2785   auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
2786     if (SawNonEmptyTemplateParameterList) {
2787       if (!SuppressDiagnostic)
2788         Diag(DeclLoc, diag::err_specialize_member_of_template)
2789           << !Recovery << Range;
2790       Invalid = true;
2791       IsMemberSpecialization = false;
2792       return true;
2793     }
2794 
2795     return false;
2796   };
2797 
2798   auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
2799     // Check that we can have an explicit specialization here.
2800     if (CheckExplicitSpecialization(Range, true))
2801       return true;
2802 
2803     // We don't have a template header, but we should.
2804     SourceLocation ExpectedTemplateLoc;
2805     if (!ParamLists.empty())
2806       ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
2807     else
2808       ExpectedTemplateLoc = DeclStartLoc;
2809 
2810     if (!SuppressDiagnostic)
2811       Diag(DeclLoc, diag::err_template_spec_needs_header)
2812         << Range
2813         << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
2814     return false;
2815   };
2816 
2817   unsigned ParamIdx = 0;
2818   for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
2819        ++TypeIdx) {
2820     T = NestedTypes[TypeIdx];
2821 
2822     // Whether we expect a 'template<>' header.
2823     bool NeedEmptyTemplateHeader = false;
2824 
2825     // Whether we expect a template header with parameters.
2826     bool NeedNonemptyTemplateHeader = false;
2827 
2828     // For a dependent type, the set of template parameters that we
2829     // expect to see.
2830     TemplateParameterList *ExpectedTemplateParams = nullptr;
2831 
2832     // C++0x [temp.expl.spec]p15:
2833     //   A member or a member template may be nested within many enclosing
2834     //   class templates. In an explicit specialization for such a member, the
2835     //   member declaration shall be preceded by a template<> for each
2836     //   enclosing class template that is explicitly specialized.
2837     if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
2838       if (ClassTemplatePartialSpecializationDecl *Partial
2839             = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
2840         ExpectedTemplateParams = Partial->getTemplateParameters();
2841         NeedNonemptyTemplateHeader = true;
2842       } else if (Record->isDependentType()) {
2843         if (Record->getDescribedClassTemplate()) {
2844           ExpectedTemplateParams = Record->getDescribedClassTemplate()
2845                                                       ->getTemplateParameters();
2846           NeedNonemptyTemplateHeader = true;
2847         }
2848       } else if (ClassTemplateSpecializationDecl *Spec
2849                      = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
2850         // C++0x [temp.expl.spec]p4:
2851         //   Members of an explicitly specialized class template are defined
2852         //   in the same manner as members of normal classes, and not using
2853         //   the template<> syntax.
2854         if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
2855           NeedEmptyTemplateHeader = true;
2856         else
2857           continue;
2858       } else if (Record->getTemplateSpecializationKind()) {
2859         if (Record->getTemplateSpecializationKind()
2860                                                 != TSK_ExplicitSpecialization &&
2861             TypeIdx == NumTypes - 1)
2862           IsMemberSpecialization = true;
2863 
2864         continue;
2865       }
2866     } else if (const TemplateSpecializationType *TST
2867                                      = T->getAs<TemplateSpecializationType>()) {
2868       if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
2869         ExpectedTemplateParams = Template->getTemplateParameters();
2870         NeedNonemptyTemplateHeader = true;
2871       }
2872     } else if (T->getAs<DependentTemplateSpecializationType>()) {
2873       // FIXME:  We actually could/should check the template arguments here
2874       // against the corresponding template parameter list.
2875       NeedNonemptyTemplateHeader = false;
2876     }
2877 
2878     // C++ [temp.expl.spec]p16:
2879     //   In an explicit specialization declaration for a member of a class
2880     //   template or a member template that appears in namespace scope, the
2881     //   member template and some of its enclosing class templates may remain
2882     //   unspecialized, except that the declaration shall not explicitly
2883     //   specialize a class member template if its enclosing class templates
2884     //   are not explicitly specialized as well.
2885     if (ParamIdx < ParamLists.size()) {
2886       if (ParamLists[ParamIdx]->size() == 0) {
2887         if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
2888                                         false))
2889           return nullptr;
2890       } else
2891         SawNonEmptyTemplateParameterList = true;
2892     }
2893 
2894     if (NeedEmptyTemplateHeader) {
2895       // If we're on the last of the types, and we need a 'template<>' header
2896       // here, then it's a member specialization.
2897       if (TypeIdx == NumTypes - 1)
2898         IsMemberSpecialization = true;
2899 
2900       if (ParamIdx < ParamLists.size()) {
2901         if (ParamLists[ParamIdx]->size() > 0) {
2902           // The header has template parameters when it shouldn't. Complain.
2903           if (!SuppressDiagnostic)
2904             Diag(ParamLists[ParamIdx]->getTemplateLoc(),
2905                  diag::err_template_param_list_matches_nontemplate)
2906               << T
2907               << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
2908                              ParamLists[ParamIdx]->getRAngleLoc())
2909               << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
2910           Invalid = true;
2911           return nullptr;
2912         }
2913 
2914         // Consume this template header.
2915         ++ParamIdx;
2916         continue;
2917       }
2918 
2919       if (!IsFriend)
2920         if (DiagnoseMissingExplicitSpecialization(
2921                 getRangeOfTypeInNestedNameSpecifier(Context, T, SS)))
2922           return nullptr;
2923 
2924       continue;
2925     }
2926 
2927     if (NeedNonemptyTemplateHeader) {
2928       // In friend declarations we can have template-ids which don't
2929       // depend on the corresponding template parameter lists.  But
2930       // assume that empty parameter lists are supposed to match this
2931       // template-id.
2932       if (IsFriend && T->isDependentType()) {
2933         if (ParamIdx < ParamLists.size() &&
2934             DependsOnTemplateParameters(T, ParamLists[ParamIdx]))
2935           ExpectedTemplateParams = nullptr;
2936         else
2937           continue;
2938       }
2939 
2940       if (ParamIdx < ParamLists.size()) {
2941         // Check the template parameter list, if we can.
2942         if (ExpectedTemplateParams &&
2943             !TemplateParameterListsAreEqual(ParamLists[ParamIdx],
2944                                             ExpectedTemplateParams,
2945                                             !SuppressDiagnostic, TPL_TemplateMatch))
2946           Invalid = true;
2947 
2948         if (!Invalid &&
2949             CheckTemplateParameterList(ParamLists[ParamIdx], nullptr,
2950                                        TPC_ClassTemplateMember))
2951           Invalid = true;
2952 
2953         ++ParamIdx;
2954         continue;
2955       }
2956 
2957       if (!SuppressDiagnostic)
2958         Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
2959           << T
2960           << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
2961       Invalid = true;
2962       continue;
2963     }
2964   }
2965 
2966   // If there were at least as many template-ids as there were template
2967   // parameter lists, then there are no template parameter lists remaining for
2968   // the declaration itself.
2969   if (ParamIdx >= ParamLists.size()) {
2970     if (TemplateId && !IsFriend) {
2971       // We don't have a template header for the declaration itself, but we
2972       // should.
2973       DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
2974                                                         TemplateId->RAngleLoc));
2975 
2976       // Fabricate an empty template parameter list for the invented header.
2977       return TemplateParameterList::Create(Context, SourceLocation(),
2978                                            SourceLocation(), std::nullopt,
2979                                            SourceLocation(), nullptr);
2980     }
2981 
2982     return nullptr;
2983   }
2984 
2985   // If there were too many template parameter lists, complain about that now.
2986   if (ParamIdx < ParamLists.size() - 1) {
2987     bool HasAnyExplicitSpecHeader = false;
2988     bool AllExplicitSpecHeaders = true;
2989     for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
2990       if (ParamLists[I]->size() == 0)
2991         HasAnyExplicitSpecHeader = true;
2992       else
2993         AllExplicitSpecHeaders = false;
2994     }
2995 
2996     if (!SuppressDiagnostic)
2997       Diag(ParamLists[ParamIdx]->getTemplateLoc(),
2998            AllExplicitSpecHeaders ? diag::ext_template_spec_extra_headers
2999                                   : diag::err_template_spec_extra_headers)
3000           << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
3001                          ParamLists[ParamLists.size() - 2]->getRAngleLoc());
3002 
3003     // If there was a specialization somewhere, such that 'template<>' is
3004     // not required, and there were any 'template<>' headers, note where the
3005     // specialization occurred.
3006     if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader &&
3007         !SuppressDiagnostic)
3008       Diag(ExplicitSpecLoc,
3009            diag::note_explicit_template_spec_does_not_need_header)
3010         << NestedTypes.back();
3011 
3012     // We have a template parameter list with no corresponding scope, which
3013     // means that the resulting template declaration can't be instantiated
3014     // properly (we'll end up with dependent nodes when we shouldn't).
3015     if (!AllExplicitSpecHeaders)
3016       Invalid = true;
3017   }
3018 
3019   // C++ [temp.expl.spec]p16:
3020   //   In an explicit specialization declaration for a member of a class
3021   //   template or a member template that ap- pears in namespace scope, the
3022   //   member template and some of its enclosing class templates may remain
3023   //   unspecialized, except that the declaration shall not explicitly
3024   //   specialize a class member template if its en- closing class templates
3025   //   are not explicitly specialized as well.
3026   if (ParamLists.back()->size() == 0 &&
3027       CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
3028                                   false))
3029     return nullptr;
3030 
3031   // Return the last template parameter list, which corresponds to the
3032   // entity being declared.
3033   return ParamLists.back();
3034 }
3035 
NoteAllFoundTemplates(TemplateName Name)3036 void Sema::NoteAllFoundTemplates(TemplateName Name) {
3037   if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3038     Diag(Template->getLocation(), diag::note_template_declared_here)
3039         << (isa<FunctionTemplateDecl>(Template)
3040                 ? 0
3041                 : isa<ClassTemplateDecl>(Template)
3042                       ? 1
3043                       : isa<VarTemplateDecl>(Template)
3044                             ? 2
3045                             : isa<TypeAliasTemplateDecl>(Template) ? 3 : 4)
3046         << Template->getDeclName();
3047     return;
3048   }
3049 
3050   if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
3051     for (OverloadedTemplateStorage::iterator I = OST->begin(),
3052                                           IEnd = OST->end();
3053          I != IEnd; ++I)
3054       Diag((*I)->getLocation(), diag::note_template_declared_here)
3055         << 0 << (*I)->getDeclName();
3056 
3057     return;
3058   }
3059 }
3060 
3061 static QualType
checkBuiltinTemplateIdType(Sema & SemaRef,BuiltinTemplateDecl * BTD,ArrayRef<TemplateArgument> Converted,SourceLocation TemplateLoc,TemplateArgumentListInfo & TemplateArgs)3062 checkBuiltinTemplateIdType(Sema &SemaRef, BuiltinTemplateDecl *BTD,
3063                            ArrayRef<TemplateArgument> Converted,
3064                            SourceLocation TemplateLoc,
3065                            TemplateArgumentListInfo &TemplateArgs) {
3066   ASTContext &Context = SemaRef.getASTContext();
3067 
3068   switch (BTD->getBuiltinTemplateKind()) {
3069   case BTK__make_integer_seq: {
3070     // Specializations of __make_integer_seq<S, T, N> are treated like
3071     // S<T, 0, ..., N-1>.
3072 
3073     QualType OrigType = Converted[1].getAsType();
3074     // C++14 [inteseq.intseq]p1:
3075     //   T shall be an integer type.
3076     if (!OrigType->isDependentType() && !OrigType->isIntegralType(Context)) {
3077       SemaRef.Diag(TemplateArgs[1].getLocation(),
3078                    diag::err_integer_sequence_integral_element_type);
3079       return QualType();
3080     }
3081 
3082     TemplateArgument NumArgsArg = Converted[2];
3083     if (NumArgsArg.isDependent())
3084       return Context.getCanonicalTemplateSpecializationType(TemplateName(BTD),
3085                                                             Converted);
3086 
3087     TemplateArgumentListInfo SyntheticTemplateArgs;
3088     // The type argument, wrapped in substitution sugar, gets reused as the
3089     // first template argument in the synthetic template argument list.
3090     SyntheticTemplateArgs.addArgument(
3091         TemplateArgumentLoc(TemplateArgument(OrigType),
3092                             SemaRef.Context.getTrivialTypeSourceInfo(
3093                                 OrigType, TemplateArgs[1].getLocation())));
3094 
3095     if (llvm::APSInt NumArgs = NumArgsArg.getAsIntegral(); NumArgs >= 0) {
3096       // Expand N into 0 ... N-1.
3097       for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned());
3098            I < NumArgs; ++I) {
3099         TemplateArgument TA(Context, I, OrigType);
3100         SyntheticTemplateArgs.addArgument(SemaRef.getTrivialTemplateArgumentLoc(
3101             TA, OrigType, TemplateArgs[2].getLocation()));
3102       }
3103     } else {
3104       // C++14 [inteseq.make]p1:
3105       //   If N is negative the program is ill-formed.
3106       SemaRef.Diag(TemplateArgs[2].getLocation(),
3107                    diag::err_integer_sequence_negative_length);
3108       return QualType();
3109     }
3110 
3111     // The first template argument will be reused as the template decl that
3112     // our synthetic template arguments will be applied to.
3113     return SemaRef.CheckTemplateIdType(Converted[0].getAsTemplate(),
3114                                        TemplateLoc, SyntheticTemplateArgs);
3115   }
3116 
3117   case BTK__type_pack_element:
3118     // Specializations of
3119     //    __type_pack_element<Index, T_1, ..., T_N>
3120     // are treated like T_Index.
3121     assert(Converted.size() == 2 &&
3122       "__type_pack_element should be given an index and a parameter pack");
3123 
3124     TemplateArgument IndexArg = Converted[0], Ts = Converted[1];
3125     if (IndexArg.isDependent() || Ts.isDependent())
3126       return Context.getCanonicalTemplateSpecializationType(TemplateName(BTD),
3127                                                             Converted);
3128 
3129     llvm::APSInt Index = IndexArg.getAsIntegral();
3130     assert(Index >= 0 && "the index used with __type_pack_element should be of "
3131                          "type std::size_t, and hence be non-negative");
3132     // If the Index is out of bounds, the program is ill-formed.
3133     if (Index >= Ts.pack_size()) {
3134       SemaRef.Diag(TemplateArgs[0].getLocation(),
3135                    diag::err_type_pack_element_out_of_bounds);
3136       return QualType();
3137     }
3138 
3139     // We simply return the type at index `Index`.
3140     int64_t N = Index.getExtValue();
3141     return Ts.getPackAsArray()[N].getAsType();
3142   }
3143   llvm_unreachable("unexpected BuiltinTemplateDecl!");
3144 }
3145 
3146 /// Determine whether this alias template is "enable_if_t".
3147 /// libc++ >=14 uses "__enable_if_t" in C++11 mode.
isEnableIfAliasTemplate(TypeAliasTemplateDecl * AliasTemplate)3148 static bool isEnableIfAliasTemplate(TypeAliasTemplateDecl *AliasTemplate) {
3149   return AliasTemplate->getName() == "enable_if_t" ||
3150          AliasTemplate->getName() == "__enable_if_t";
3151 }
3152 
3153 /// Collect all of the separable terms in the given condition, which
3154 /// might be a conjunction.
3155 ///
3156 /// FIXME: The right answer is to convert the logical expression into
3157 /// disjunctive normal form, so we can find the first failed term
3158 /// within each possible clause.
collectConjunctionTerms(Expr * Clause,SmallVectorImpl<Expr * > & Terms)3159 static void collectConjunctionTerms(Expr *Clause,
3160                                     SmallVectorImpl<Expr *> &Terms) {
3161   if (auto BinOp = dyn_cast<BinaryOperator>(Clause->IgnoreParenImpCasts())) {
3162     if (BinOp->getOpcode() == BO_LAnd) {
3163       collectConjunctionTerms(BinOp->getLHS(), Terms);
3164       collectConjunctionTerms(BinOp->getRHS(), Terms);
3165       return;
3166     }
3167   }
3168 
3169   Terms.push_back(Clause);
3170 }
3171 
3172 // The ranges-v3 library uses an odd pattern of a top-level "||" with
3173 // a left-hand side that is value-dependent but never true. Identify
3174 // the idiom and ignore that term.
lookThroughRangesV3Condition(Preprocessor & PP,Expr * Cond)3175 static Expr *lookThroughRangesV3Condition(Preprocessor &PP, Expr *Cond) {
3176   // Top-level '||'.
3177   auto *BinOp = dyn_cast<BinaryOperator>(Cond->IgnoreParenImpCasts());
3178   if (!BinOp) return Cond;
3179 
3180   if (BinOp->getOpcode() != BO_LOr) return Cond;
3181 
3182   // With an inner '==' that has a literal on the right-hand side.
3183   Expr *LHS = BinOp->getLHS();
3184   auto *InnerBinOp = dyn_cast<BinaryOperator>(LHS->IgnoreParenImpCasts());
3185   if (!InnerBinOp) return Cond;
3186 
3187   if (InnerBinOp->getOpcode() != BO_EQ ||
3188       !isa<IntegerLiteral>(InnerBinOp->getRHS()))
3189     return Cond;
3190 
3191   // If the inner binary operation came from a macro expansion named
3192   // CONCEPT_REQUIRES or CONCEPT_REQUIRES_, return the right-hand side
3193   // of the '||', which is the real, user-provided condition.
3194   SourceLocation Loc = InnerBinOp->getExprLoc();
3195   if (!Loc.isMacroID()) return Cond;
3196 
3197   StringRef MacroName = PP.getImmediateMacroName(Loc);
3198   if (MacroName == "CONCEPT_REQUIRES" || MacroName == "CONCEPT_REQUIRES_")
3199     return BinOp->getRHS();
3200 
3201   return Cond;
3202 }
3203 
3204 namespace {
3205 
3206 // A PrinterHelper that prints more helpful diagnostics for some sub-expressions
3207 // within failing boolean expression, such as substituting template parameters
3208 // for actual types.
3209 class FailedBooleanConditionPrinterHelper : public PrinterHelper {
3210 public:
FailedBooleanConditionPrinterHelper(const PrintingPolicy & P)3211   explicit FailedBooleanConditionPrinterHelper(const PrintingPolicy &P)
3212       : Policy(P) {}
3213 
handledStmt(Stmt * E,raw_ostream & OS)3214   bool handledStmt(Stmt *E, raw_ostream &OS) override {
3215     const auto *DR = dyn_cast<DeclRefExpr>(E);
3216     if (DR && DR->getQualifier()) {
3217       // If this is a qualified name, expand the template arguments in nested
3218       // qualifiers.
3219       DR->getQualifier()->print(OS, Policy, true);
3220       // Then print the decl itself.
3221       const ValueDecl *VD = DR->getDecl();
3222       OS << VD->getName();
3223       if (const auto *IV = dyn_cast<VarTemplateSpecializationDecl>(VD)) {
3224         // This is a template variable, print the expanded template arguments.
3225         printTemplateArgumentList(
3226             OS, IV->getTemplateArgs().asArray(), Policy,
3227             IV->getSpecializedTemplate()->getTemplateParameters());
3228       }
3229       return true;
3230     }
3231     return false;
3232   }
3233 
3234 private:
3235   const PrintingPolicy Policy;
3236 };
3237 
3238 } // end anonymous namespace
3239 
3240 std::pair<Expr *, std::string>
findFailedBooleanCondition(Expr * Cond)3241 Sema::findFailedBooleanCondition(Expr *Cond) {
3242   Cond = lookThroughRangesV3Condition(PP, Cond);
3243 
3244   // Separate out all of the terms in a conjunction.
3245   SmallVector<Expr *, 4> Terms;
3246   collectConjunctionTerms(Cond, Terms);
3247 
3248   // Determine which term failed.
3249   Expr *FailedCond = nullptr;
3250   for (Expr *Term : Terms) {
3251     Expr *TermAsWritten = Term->IgnoreParenImpCasts();
3252 
3253     // Literals are uninteresting.
3254     if (isa<CXXBoolLiteralExpr>(TermAsWritten) ||
3255         isa<IntegerLiteral>(TermAsWritten))
3256       continue;
3257 
3258     // The initialization of the parameter from the argument is
3259     // a constant-evaluated context.
3260     EnterExpressionEvaluationContext ConstantEvaluated(
3261       *this, Sema::ExpressionEvaluationContext::ConstantEvaluated);
3262 
3263     bool Succeeded;
3264     if (Term->EvaluateAsBooleanCondition(Succeeded, Context) &&
3265         !Succeeded) {
3266       FailedCond = TermAsWritten;
3267       break;
3268     }
3269   }
3270   if (!FailedCond)
3271     FailedCond = Cond->IgnoreParenImpCasts();
3272 
3273   std::string Description;
3274   {
3275     llvm::raw_string_ostream Out(Description);
3276     PrintingPolicy Policy = getPrintingPolicy();
3277     Policy.PrintCanonicalTypes = true;
3278     FailedBooleanConditionPrinterHelper Helper(Policy);
3279     FailedCond->printPretty(Out, &Helper, Policy, 0, "\n", nullptr);
3280   }
3281   return { FailedCond, Description };
3282 }
3283 
CheckTemplateIdType(TemplateName Name,SourceLocation TemplateLoc,TemplateArgumentListInfo & TemplateArgs)3284 QualType Sema::CheckTemplateIdType(TemplateName Name,
3285                                    SourceLocation TemplateLoc,
3286                                    TemplateArgumentListInfo &TemplateArgs) {
3287   DependentTemplateName *DTN
3288     = Name.getUnderlying().getAsDependentTemplateName();
3289   if (DTN && DTN->isIdentifier())
3290     // When building a template-id where the template-name is dependent,
3291     // assume the template is a type template. Either our assumption is
3292     // correct, or the code is ill-formed and will be diagnosed when the
3293     // dependent name is substituted.
3294     return Context.getDependentTemplateSpecializationType(
3295         ElaboratedTypeKeyword::None, DTN->getQualifier(), DTN->getIdentifier(),
3296         TemplateArgs.arguments());
3297 
3298   if (Name.getAsAssumedTemplateName() &&
3299       resolveAssumedTemplateNameAsType(/*Scope*/nullptr, Name, TemplateLoc))
3300     return QualType();
3301 
3302   TemplateDecl *Template = Name.getAsTemplateDecl();
3303   if (!Template || isa<FunctionTemplateDecl>(Template) ||
3304       isa<VarTemplateDecl>(Template) || isa<ConceptDecl>(Template)) {
3305     // We might have a substituted template template parameter pack. If so,
3306     // build a template specialization type for it.
3307     if (Name.getAsSubstTemplateTemplateParmPack())
3308       return Context.getTemplateSpecializationType(Name,
3309                                                    TemplateArgs.arguments());
3310 
3311     Diag(TemplateLoc, diag::err_template_id_not_a_type)
3312       << Name;
3313     NoteAllFoundTemplates(Name);
3314     return QualType();
3315   }
3316 
3317   // Check that the template argument list is well-formed for this
3318   // template.
3319   SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
3320   if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs, false,
3321                                 SugaredConverted, CanonicalConverted,
3322                                 /*UpdateArgsWithConversions=*/true))
3323     return QualType();
3324 
3325   QualType CanonType;
3326 
3327   if (TypeAliasTemplateDecl *AliasTemplate =
3328           dyn_cast<TypeAliasTemplateDecl>(Template)) {
3329 
3330     // Find the canonical type for this type alias template specialization.
3331     TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
3332     if (Pattern->isInvalidDecl())
3333       return QualType();
3334 
3335     // Only substitute for the innermost template argument list.
3336     MultiLevelTemplateArgumentList TemplateArgLists;
3337     TemplateArgLists.addOuterTemplateArguments(Template, CanonicalConverted,
3338                                                /*Final=*/false);
3339     TemplateArgLists.addOuterRetainedLevels(
3340         AliasTemplate->getTemplateParameters()->getDepth());
3341 
3342     LocalInstantiationScope Scope(*this);
3343     InstantiatingTemplate Inst(
3344         *this, /*PointOfInstantiation=*/TemplateLoc,
3345         /*Entity=*/AliasTemplate,
3346         /*TemplateArgs=*/TemplateArgLists.getInnermost());
3347 
3348     // Diagnose uses of this alias.
3349     (void)DiagnoseUseOfDecl(AliasTemplate, TemplateLoc);
3350 
3351     if (Inst.isInvalid())
3352       return QualType();
3353 
3354     std::optional<ContextRAII> SavedContext;
3355     if (!AliasTemplate->getDeclContext()->isFileContext())
3356       SavedContext.emplace(*this, AliasTemplate->getDeclContext());
3357 
3358     CanonType =
3359         SubstType(Pattern->getUnderlyingType(), TemplateArgLists,
3360                   AliasTemplate->getLocation(), AliasTemplate->getDeclName());
3361     if (CanonType.isNull()) {
3362       // If this was enable_if and we failed to find the nested type
3363       // within enable_if in a SFINAE context, dig out the specific
3364       // enable_if condition that failed and present that instead.
3365       if (isEnableIfAliasTemplate(AliasTemplate)) {
3366         if (auto DeductionInfo = isSFINAEContext()) {
3367           if (*DeductionInfo &&
3368               (*DeductionInfo)->hasSFINAEDiagnostic() &&
3369               (*DeductionInfo)->peekSFINAEDiagnostic().second.getDiagID() ==
3370                 diag::err_typename_nested_not_found_enable_if &&
3371               TemplateArgs[0].getArgument().getKind()
3372                 == TemplateArgument::Expression) {
3373             Expr *FailedCond;
3374             std::string FailedDescription;
3375             std::tie(FailedCond, FailedDescription) =
3376               findFailedBooleanCondition(TemplateArgs[0].getSourceExpression());
3377 
3378             // Remove the old SFINAE diagnostic.
3379             PartialDiagnosticAt OldDiag =
3380               {SourceLocation(), PartialDiagnostic::NullDiagnostic()};
3381             (*DeductionInfo)->takeSFINAEDiagnostic(OldDiag);
3382 
3383             // Add a new SFINAE diagnostic specifying which condition
3384             // failed.
3385             (*DeductionInfo)->addSFINAEDiagnostic(
3386               OldDiag.first,
3387               PDiag(diag::err_typename_nested_not_found_requirement)
3388                 << FailedDescription
3389                 << FailedCond->getSourceRange());
3390           }
3391         }
3392       }
3393 
3394       return QualType();
3395     }
3396   } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Template)) {
3397     CanonType = checkBuiltinTemplateIdType(*this, BTD, SugaredConverted,
3398                                            TemplateLoc, TemplateArgs);
3399   } else if (Name.isDependent() ||
3400              TemplateSpecializationType::anyDependentTemplateArguments(
3401                  TemplateArgs, CanonicalConverted)) {
3402     // This class template specialization is a dependent
3403     // type. Therefore, its canonical type is another class template
3404     // specialization type that contains all of the converted
3405     // arguments in canonical form. This ensures that, e.g., A<T> and
3406     // A<T, T> have identical types when A is declared as:
3407     //
3408     //   template<typename T, typename U = T> struct A;
3409     CanonType = Context.getCanonicalTemplateSpecializationType(
3410         Name, CanonicalConverted);
3411 
3412     // This might work out to be a current instantiation, in which
3413     // case the canonical type needs to be the InjectedClassNameType.
3414     //
3415     // TODO: in theory this could be a simple hashtable lookup; most
3416     // changes to CurContext don't change the set of current
3417     // instantiations.
3418     if (isa<ClassTemplateDecl>(Template)) {
3419       for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
3420         // If we get out to a namespace, we're done.
3421         if (Ctx->isFileContext()) break;
3422 
3423         // If this isn't a record, keep looking.
3424         CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
3425         if (!Record) continue;
3426 
3427         // Look for one of the two cases with InjectedClassNameTypes
3428         // and check whether it's the same template.
3429         if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
3430             !Record->getDescribedClassTemplate())
3431           continue;
3432 
3433         // Fetch the injected class name type and check whether its
3434         // injected type is equal to the type we just built.
3435         QualType ICNT = Context.getTypeDeclType(Record);
3436         QualType Injected = cast<InjectedClassNameType>(ICNT)
3437           ->getInjectedSpecializationType();
3438 
3439         if (CanonType != Injected->getCanonicalTypeInternal())
3440           continue;
3441 
3442         // If so, the canonical type of this TST is the injected
3443         // class name type of the record we just found.
3444         assert(ICNT.isCanonical());
3445         CanonType = ICNT;
3446         break;
3447       }
3448     }
3449   } else if (ClassTemplateDecl *ClassTemplate =
3450                  dyn_cast<ClassTemplateDecl>(Template)) {
3451     // Find the class template specialization declaration that
3452     // corresponds to these arguments.
3453     void *InsertPos = nullptr;
3454     ClassTemplateSpecializationDecl *Decl =
3455         ClassTemplate->findSpecialization(CanonicalConverted, InsertPos);
3456     if (!Decl) {
3457       // This is the first time we have referenced this class template
3458       // specialization. Create the canonical declaration and add it to
3459       // the set of specializations.
3460       Decl = ClassTemplateSpecializationDecl::Create(
3461           Context, ClassTemplate->getTemplatedDecl()->getTagKind(),
3462           ClassTemplate->getDeclContext(),
3463           ClassTemplate->getTemplatedDecl()->getBeginLoc(),
3464           ClassTemplate->getLocation(), ClassTemplate, CanonicalConverted,
3465           nullptr);
3466       ClassTemplate->AddSpecialization(Decl, InsertPos);
3467       if (ClassTemplate->isOutOfLine())
3468         Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
3469     }
3470 
3471     if (Decl->getSpecializationKind() == TSK_Undeclared &&
3472         ClassTemplate->getTemplatedDecl()->hasAttrs()) {
3473       InstantiatingTemplate Inst(*this, TemplateLoc, Decl);
3474       if (!Inst.isInvalid()) {
3475         MultiLevelTemplateArgumentList TemplateArgLists(Template,
3476                                                         CanonicalConverted,
3477                                                         /*Final=*/false);
3478         InstantiateAttrsForDecl(TemplateArgLists,
3479                                 ClassTemplate->getTemplatedDecl(), Decl);
3480       }
3481     }
3482 
3483     // Diagnose uses of this specialization.
3484     (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
3485 
3486     CanonType = Context.getTypeDeclType(Decl);
3487     assert(isa<RecordType>(CanonType) &&
3488            "type of non-dependent specialization is not a RecordType");
3489   } else {
3490     llvm_unreachable("Unhandled template kind");
3491   }
3492 
3493   // Build the fully-sugared type for this class template
3494   // specialization, which refers back to the class template
3495   // specialization we created or found.
3496   return Context.getTemplateSpecializationType(Name, TemplateArgs.arguments(),
3497                                                CanonType);
3498 }
3499 
ActOnUndeclaredTypeTemplateName(Scope * S,TemplateTy & ParsedName,TemplateNameKind & TNK,SourceLocation NameLoc,IdentifierInfo * & II)3500 void Sema::ActOnUndeclaredTypeTemplateName(Scope *S, TemplateTy &ParsedName,
3501                                            TemplateNameKind &TNK,
3502                                            SourceLocation NameLoc,
3503                                            IdentifierInfo *&II) {
3504   assert(TNK == TNK_Undeclared_template && "not an undeclared template name");
3505 
3506   TemplateName Name = ParsedName.get();
3507   auto *ATN = Name.getAsAssumedTemplateName();
3508   assert(ATN && "not an assumed template name");
3509   II = ATN->getDeclName().getAsIdentifierInfo();
3510 
3511   if (!resolveAssumedTemplateNameAsType(S, Name, NameLoc, /*Diagnose*/false)) {
3512     // Resolved to a type template name.
3513     ParsedName = TemplateTy::make(Name);
3514     TNK = TNK_Type_template;
3515   }
3516 }
3517 
resolveAssumedTemplateNameAsType(Scope * S,TemplateName & Name,SourceLocation NameLoc,bool Diagnose)3518 bool Sema::resolveAssumedTemplateNameAsType(Scope *S, TemplateName &Name,
3519                                             SourceLocation NameLoc,
3520                                             bool Diagnose) {
3521   // We assumed this undeclared identifier to be an (ADL-only) function
3522   // template name, but it was used in a context where a type was required.
3523   // Try to typo-correct it now.
3524   AssumedTemplateStorage *ATN = Name.getAsAssumedTemplateName();
3525   assert(ATN && "not an assumed template name");
3526 
3527   LookupResult R(*this, ATN->getDeclName(), NameLoc, LookupOrdinaryName);
3528   struct CandidateCallback : CorrectionCandidateCallback {
3529     bool ValidateCandidate(const TypoCorrection &TC) override {
3530       return TC.getCorrectionDecl() &&
3531              getAsTypeTemplateDecl(TC.getCorrectionDecl());
3532     }
3533     std::unique_ptr<CorrectionCandidateCallback> clone() override {
3534       return std::make_unique<CandidateCallback>(*this);
3535     }
3536   } FilterCCC;
3537 
3538   TypoCorrection Corrected =
3539       CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, nullptr,
3540                   FilterCCC, CTK_ErrorRecovery);
3541   if (Corrected && Corrected.getFoundDecl()) {
3542     diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest)
3543                                 << ATN->getDeclName());
3544     Name = TemplateName(Corrected.getCorrectionDeclAs<TemplateDecl>());
3545     return false;
3546   }
3547 
3548   if (Diagnose)
3549     Diag(R.getNameLoc(), diag::err_no_template) << R.getLookupName();
3550   return true;
3551 }
3552 
ActOnTemplateIdType(Scope * S,CXXScopeSpec & SS,SourceLocation TemplateKWLoc,TemplateTy TemplateD,const IdentifierInfo * TemplateII,SourceLocation TemplateIILoc,SourceLocation LAngleLoc,ASTTemplateArgsPtr TemplateArgsIn,SourceLocation RAngleLoc,bool IsCtorOrDtorName,bool IsClassName,ImplicitTypenameContext AllowImplicitTypename)3553 TypeResult Sema::ActOnTemplateIdType(
3554     Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
3555     TemplateTy TemplateD, const IdentifierInfo *TemplateII,
3556     SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
3557     ASTTemplateArgsPtr TemplateArgsIn, SourceLocation RAngleLoc,
3558     bool IsCtorOrDtorName, bool IsClassName,
3559     ImplicitTypenameContext AllowImplicitTypename) {
3560   if (SS.isInvalid())
3561     return true;
3562 
3563   if (!IsCtorOrDtorName && !IsClassName && SS.isSet()) {
3564     DeclContext *LookupCtx = computeDeclContext(SS, /*EnteringContext*/false);
3565 
3566     // C++ [temp.res]p3:
3567     //   A qualified-id that refers to a type and in which the
3568     //   nested-name-specifier depends on a template-parameter (14.6.2)
3569     //   shall be prefixed by the keyword typename to indicate that the
3570     //   qualified-id denotes a type, forming an
3571     //   elaborated-type-specifier (7.1.5.3).
3572     if (!LookupCtx && isDependentScopeSpecifier(SS)) {
3573       // C++2a relaxes some of those restrictions in [temp.res]p5.
3574       if (AllowImplicitTypename == ImplicitTypenameContext::Yes) {
3575         if (getLangOpts().CPlusPlus20)
3576           Diag(SS.getBeginLoc(), diag::warn_cxx17_compat_implicit_typename);
3577         else
3578           Diag(SS.getBeginLoc(), diag::ext_implicit_typename)
3579               << SS.getScopeRep() << TemplateII->getName()
3580               << FixItHint::CreateInsertion(SS.getBeginLoc(), "typename ");
3581       } else
3582         Diag(SS.getBeginLoc(), diag::err_typename_missing_template)
3583             << SS.getScopeRep() << TemplateII->getName();
3584 
3585       // FIXME: This is not quite correct recovery as we don't transform SS
3586       // into the corresponding dependent form (and we don't diagnose missing
3587       // 'template' keywords within SS as a result).
3588       return ActOnTypenameType(nullptr, SourceLocation(), SS, TemplateKWLoc,
3589                                TemplateD, TemplateII, TemplateIILoc, LAngleLoc,
3590                                TemplateArgsIn, RAngleLoc);
3591     }
3592 
3593     // Per C++ [class.qual]p2, if the template-id was an injected-class-name,
3594     // it's not actually allowed to be used as a type in most cases. Because
3595     // we annotate it before we know whether it's valid, we have to check for
3596     // this case here.
3597     auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
3598     if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
3599       Diag(TemplateIILoc,
3600            TemplateKWLoc.isInvalid()
3601                ? diag::err_out_of_line_qualified_id_type_names_constructor
3602                : diag::ext_out_of_line_qualified_id_type_names_constructor)
3603         << TemplateII << 0 /*injected-class-name used as template name*/
3604         << 1 /*if any keyword was present, it was 'template'*/;
3605     }
3606   }
3607 
3608   TemplateName Template = TemplateD.get();
3609   if (Template.getAsAssumedTemplateName() &&
3610       resolveAssumedTemplateNameAsType(S, Template, TemplateIILoc))
3611     return true;
3612 
3613   // Translate the parser's template argument list in our AST format.
3614   TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
3615   translateTemplateArguments(TemplateArgsIn, TemplateArgs);
3616 
3617   if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
3618     assert(SS.getScopeRep() == DTN->getQualifier());
3619     QualType T = Context.getDependentTemplateSpecializationType(
3620         ElaboratedTypeKeyword::None, DTN->getQualifier(), DTN->getIdentifier(),
3621         TemplateArgs.arguments());
3622     // Build type-source information.
3623     TypeLocBuilder TLB;
3624     DependentTemplateSpecializationTypeLoc SpecTL
3625       = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
3626     SpecTL.setElaboratedKeywordLoc(SourceLocation());
3627     SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
3628     SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3629     SpecTL.setTemplateNameLoc(TemplateIILoc);
3630     SpecTL.setLAngleLoc(LAngleLoc);
3631     SpecTL.setRAngleLoc(RAngleLoc);
3632     for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
3633       SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
3634     return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
3635   }
3636 
3637   QualType SpecTy = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
3638   if (SpecTy.isNull())
3639     return true;
3640 
3641   // Build type-source information.
3642   TypeLocBuilder TLB;
3643   TemplateSpecializationTypeLoc SpecTL =
3644       TLB.push<TemplateSpecializationTypeLoc>(SpecTy);
3645   SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3646   SpecTL.setTemplateNameLoc(TemplateIILoc);
3647   SpecTL.setLAngleLoc(LAngleLoc);
3648   SpecTL.setRAngleLoc(RAngleLoc);
3649   for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
3650     SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
3651 
3652   // Create an elaborated-type-specifier containing the nested-name-specifier.
3653   QualType ElTy =
3654       getElaboratedType(ElaboratedTypeKeyword::None,
3655                         !IsCtorOrDtorName ? SS : CXXScopeSpec(), SpecTy);
3656   ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(ElTy);
3657   ElabTL.setElaboratedKeywordLoc(SourceLocation());
3658   if (!ElabTL.isEmpty())
3659     ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
3660   return CreateParsedType(ElTy, TLB.getTypeSourceInfo(Context, ElTy));
3661 }
3662 
ActOnTagTemplateIdType(TagUseKind TUK,TypeSpecifierType TagSpec,SourceLocation TagLoc,CXXScopeSpec & SS,SourceLocation TemplateKWLoc,TemplateTy TemplateD,SourceLocation TemplateLoc,SourceLocation LAngleLoc,ASTTemplateArgsPtr TemplateArgsIn,SourceLocation RAngleLoc)3663 TypeResult Sema::ActOnTagTemplateIdType(TagUseKind TUK,
3664                                         TypeSpecifierType TagSpec,
3665                                         SourceLocation TagLoc,
3666                                         CXXScopeSpec &SS,
3667                                         SourceLocation TemplateKWLoc,
3668                                         TemplateTy TemplateD,
3669                                         SourceLocation TemplateLoc,
3670                                         SourceLocation LAngleLoc,
3671                                         ASTTemplateArgsPtr TemplateArgsIn,
3672                                         SourceLocation RAngleLoc) {
3673   if (SS.isInvalid())
3674     return TypeResult(true);
3675 
3676   TemplateName Template = TemplateD.get();
3677 
3678   // Translate the parser's template argument list in our AST format.
3679   TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
3680   translateTemplateArguments(TemplateArgsIn, TemplateArgs);
3681 
3682   // Determine the tag kind
3683   TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
3684   ElaboratedTypeKeyword Keyword
3685     = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
3686 
3687   if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
3688     assert(SS.getScopeRep() == DTN->getQualifier());
3689     QualType T = Context.getDependentTemplateSpecializationType(
3690         Keyword, DTN->getQualifier(), DTN->getIdentifier(),
3691         TemplateArgs.arguments());
3692 
3693     // Build type-source information.
3694     TypeLocBuilder TLB;
3695     DependentTemplateSpecializationTypeLoc SpecTL
3696       = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
3697     SpecTL.setElaboratedKeywordLoc(TagLoc);
3698     SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
3699     SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3700     SpecTL.setTemplateNameLoc(TemplateLoc);
3701     SpecTL.setLAngleLoc(LAngleLoc);
3702     SpecTL.setRAngleLoc(RAngleLoc);
3703     for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
3704       SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
3705     return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
3706   }
3707 
3708   if (TypeAliasTemplateDecl *TAT =
3709         dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) {
3710     // C++0x [dcl.type.elab]p2:
3711     //   If the identifier resolves to a typedef-name or the simple-template-id
3712     //   resolves to an alias template specialization, the
3713     //   elaborated-type-specifier is ill-formed.
3714     Diag(TemplateLoc, diag::err_tag_reference_non_tag)
3715         << TAT << NTK_TypeAliasTemplate << llvm::to_underlying(TagKind);
3716     Diag(TAT->getLocation(), diag::note_declared_at);
3717   }
3718 
3719   QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
3720   if (Result.isNull())
3721     return TypeResult(true);
3722 
3723   // Check the tag kind
3724   if (const RecordType *RT = Result->getAs<RecordType>()) {
3725     RecordDecl *D = RT->getDecl();
3726 
3727     IdentifierInfo *Id = D->getIdentifier();
3728     assert(Id && "templated class must have an identifier");
3729 
3730     if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TagUseKind::Definition,
3731                                       TagLoc, Id)) {
3732       Diag(TagLoc, diag::err_use_with_wrong_tag)
3733         << Result
3734         << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
3735       Diag(D->getLocation(), diag::note_previous_use);
3736     }
3737   }
3738 
3739   // Provide source-location information for the template specialization.
3740   TypeLocBuilder TLB;
3741   TemplateSpecializationTypeLoc SpecTL
3742     = TLB.push<TemplateSpecializationTypeLoc>(Result);
3743   SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3744   SpecTL.setTemplateNameLoc(TemplateLoc);
3745   SpecTL.setLAngleLoc(LAngleLoc);
3746   SpecTL.setRAngleLoc(RAngleLoc);
3747   for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
3748     SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
3749 
3750   // Construct an elaborated type containing the nested-name-specifier (if any)
3751   // and tag keyword.
3752   Result = Context.getElaboratedType(Keyword, SS.getScopeRep(), Result);
3753   ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
3754   ElabTL.setElaboratedKeywordLoc(TagLoc);
3755   ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
3756   return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
3757 }
3758 
3759 static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
3760                                              NamedDecl *PrevDecl,
3761                                              SourceLocation Loc,
3762                                              bool IsPartialSpecialization);
3763 
3764 static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D);
3765 
isTemplateArgumentTemplateParameter(const TemplateArgument & Arg,unsigned Depth,unsigned Index)3766 static bool isTemplateArgumentTemplateParameter(
3767     const TemplateArgument &Arg, unsigned Depth, unsigned Index) {
3768   switch (Arg.getKind()) {
3769   case TemplateArgument::Null:
3770   case TemplateArgument::NullPtr:
3771   case TemplateArgument::Integral:
3772   case TemplateArgument::Declaration:
3773   case TemplateArgument::StructuralValue:
3774   case TemplateArgument::Pack:
3775   case TemplateArgument::TemplateExpansion:
3776     return false;
3777 
3778   case TemplateArgument::Type: {
3779     QualType Type = Arg.getAsType();
3780     const TemplateTypeParmType *TPT =
3781         Arg.getAsType()->getAs<TemplateTypeParmType>();
3782     return TPT && !Type.hasQualifiers() &&
3783            TPT->getDepth() == Depth && TPT->getIndex() == Index;
3784   }
3785 
3786   case TemplateArgument::Expression: {
3787     DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
3788     if (!DRE || !DRE->getDecl())
3789       return false;
3790     const NonTypeTemplateParmDecl *NTTP =
3791         dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
3792     return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
3793   }
3794 
3795   case TemplateArgument::Template:
3796     const TemplateTemplateParmDecl *TTP =
3797         dyn_cast_or_null<TemplateTemplateParmDecl>(
3798             Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl());
3799     return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
3800   }
3801   llvm_unreachable("unexpected kind of template argument");
3802 }
3803 
isSameAsPrimaryTemplate(TemplateParameterList * Params,ArrayRef<TemplateArgument> Args)3804 static bool isSameAsPrimaryTemplate(TemplateParameterList *Params,
3805                                     ArrayRef<TemplateArgument> Args) {
3806   if (Params->size() != Args.size())
3807     return false;
3808 
3809   unsigned Depth = Params->getDepth();
3810 
3811   for (unsigned I = 0, N = Args.size(); I != N; ++I) {
3812     TemplateArgument Arg = Args[I];
3813 
3814     // If the parameter is a pack expansion, the argument must be a pack
3815     // whose only element is a pack expansion.
3816     if (Params->getParam(I)->isParameterPack()) {
3817       if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
3818           !Arg.pack_begin()->isPackExpansion())
3819         return false;
3820       Arg = Arg.pack_begin()->getPackExpansionPattern();
3821     }
3822 
3823     if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))
3824       return false;
3825   }
3826 
3827   return true;
3828 }
3829 
3830 template<typename PartialSpecDecl>
checkMoreSpecializedThanPrimary(Sema & S,PartialSpecDecl * Partial)3831 static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial) {
3832   if (Partial->getDeclContext()->isDependentContext())
3833     return;
3834 
3835   // FIXME: Get the TDK from deduction in order to provide better diagnostics
3836   // for non-substitution-failure issues?
3837   TemplateDeductionInfo Info(Partial->getLocation());
3838   if (S.isMoreSpecializedThanPrimary(Partial, Info))
3839     return;
3840 
3841   auto *Template = Partial->getSpecializedTemplate();
3842   S.Diag(Partial->getLocation(),
3843          diag::ext_partial_spec_not_more_specialized_than_primary)
3844       << isa<VarTemplateDecl>(Template);
3845 
3846   if (Info.hasSFINAEDiagnostic()) {
3847     PartialDiagnosticAt Diag = {SourceLocation(),
3848                                 PartialDiagnostic::NullDiagnostic()};
3849     Info.takeSFINAEDiagnostic(Diag);
3850     SmallString<128> SFINAEArgString;
3851     Diag.second.EmitToString(S.getDiagnostics(), SFINAEArgString);
3852     S.Diag(Diag.first,
3853            diag::note_partial_spec_not_more_specialized_than_primary)
3854       << SFINAEArgString;
3855   }
3856 
3857   S.NoteTemplateLocation(*Template);
3858   SmallVector<const Expr *, 3> PartialAC, TemplateAC;
3859   Template->getAssociatedConstraints(TemplateAC);
3860   Partial->getAssociatedConstraints(PartialAC);
3861   S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(Partial, PartialAC, Template,
3862                                                   TemplateAC);
3863 }
3864 
3865 static void
noteNonDeducibleParameters(Sema & S,TemplateParameterList * TemplateParams,const llvm::SmallBitVector & DeducibleParams)3866 noteNonDeducibleParameters(Sema &S, TemplateParameterList *TemplateParams,
3867                            const llvm::SmallBitVector &DeducibleParams) {
3868   for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
3869     if (!DeducibleParams[I]) {
3870       NamedDecl *Param = TemplateParams->getParam(I);
3871       if (Param->getDeclName())
3872         S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
3873             << Param->getDeclName();
3874       else
3875         S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
3876             << "(anonymous)";
3877     }
3878   }
3879 }
3880 
3881 
3882 template<typename PartialSpecDecl>
checkTemplatePartialSpecialization(Sema & S,PartialSpecDecl * Partial)3883 static void checkTemplatePartialSpecialization(Sema &S,
3884                                                PartialSpecDecl *Partial) {
3885   // C++1z [temp.class.spec]p8: (DR1495)
3886   //   - The specialization shall be more specialized than the primary
3887   //     template (14.5.5.2).
3888   checkMoreSpecializedThanPrimary(S, Partial);
3889 
3890   // C++ [temp.class.spec]p8: (DR1315)
3891   //   - Each template-parameter shall appear at least once in the
3892   //     template-id outside a non-deduced context.
3893   // C++1z [temp.class.spec.match]p3 (P0127R2)
3894   //   If the template arguments of a partial specialization cannot be
3895   //   deduced because of the structure of its template-parameter-list
3896   //   and the template-id, the program is ill-formed.
3897   auto *TemplateParams = Partial->getTemplateParameters();
3898   llvm::SmallBitVector DeducibleParams(TemplateParams->size());
3899   S.MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
3900                                TemplateParams->getDepth(), DeducibleParams);
3901 
3902   if (!DeducibleParams.all()) {
3903     unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
3904     S.Diag(Partial->getLocation(), diag::ext_partial_specs_not_deducible)
3905       << isa<VarTemplatePartialSpecializationDecl>(Partial)
3906       << (NumNonDeducible > 1)
3907       << SourceRange(Partial->getLocation(),
3908                      Partial->getTemplateArgsAsWritten()->RAngleLoc);
3909     noteNonDeducibleParameters(S, TemplateParams, DeducibleParams);
3910   }
3911 }
3912 
CheckTemplatePartialSpecialization(ClassTemplatePartialSpecializationDecl * Partial)3913 void Sema::CheckTemplatePartialSpecialization(
3914     ClassTemplatePartialSpecializationDecl *Partial) {
3915   checkTemplatePartialSpecialization(*this, Partial);
3916 }
3917 
CheckTemplatePartialSpecialization(VarTemplatePartialSpecializationDecl * Partial)3918 void Sema::CheckTemplatePartialSpecialization(
3919     VarTemplatePartialSpecializationDecl *Partial) {
3920   checkTemplatePartialSpecialization(*this, Partial);
3921 }
3922 
CheckDeductionGuideTemplate(FunctionTemplateDecl * TD)3923 void Sema::CheckDeductionGuideTemplate(FunctionTemplateDecl *TD) {
3924   // C++1z [temp.param]p11:
3925   //   A template parameter of a deduction guide template that does not have a
3926   //   default-argument shall be deducible from the parameter-type-list of the
3927   //   deduction guide template.
3928   auto *TemplateParams = TD->getTemplateParameters();
3929   llvm::SmallBitVector DeducibleParams(TemplateParams->size());
3930   MarkDeducedTemplateParameters(TD, DeducibleParams);
3931   for (unsigned I = 0; I != TemplateParams->size(); ++I) {
3932     // A parameter pack is deducible (to an empty pack).
3933     auto *Param = TemplateParams->getParam(I);
3934     if (Param->isParameterPack() || hasVisibleDefaultArgument(Param))
3935       DeducibleParams[I] = true;
3936   }
3937 
3938   if (!DeducibleParams.all()) {
3939     unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
3940     Diag(TD->getLocation(), diag::err_deduction_guide_template_not_deducible)
3941       << (NumNonDeducible > 1);
3942     noteNonDeducibleParameters(*this, TemplateParams, DeducibleParams);
3943   }
3944 }
3945 
ActOnVarTemplateSpecialization(Scope * S,Declarator & D,TypeSourceInfo * DI,LookupResult & Previous,SourceLocation TemplateKWLoc,TemplateParameterList * TemplateParams,StorageClass SC,bool IsPartialSpecialization)3946 DeclResult Sema::ActOnVarTemplateSpecialization(
3947     Scope *S, Declarator &D, TypeSourceInfo *DI, LookupResult &Previous,
3948     SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
3949     StorageClass SC, bool IsPartialSpecialization) {
3950   // D must be variable template id.
3951   assert(D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId &&
3952          "Variable template specialization is declared with a template id.");
3953 
3954   TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
3955   TemplateArgumentListInfo TemplateArgs =
3956       makeTemplateArgumentListInfo(*this, *TemplateId);
3957   SourceLocation TemplateNameLoc = D.getIdentifierLoc();
3958   SourceLocation LAngleLoc = TemplateId->LAngleLoc;
3959   SourceLocation RAngleLoc = TemplateId->RAngleLoc;
3960 
3961   TemplateName Name = TemplateId->Template.get();
3962 
3963   // The template-id must name a variable template.
3964   VarTemplateDecl *VarTemplate =
3965       dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
3966   if (!VarTemplate) {
3967     NamedDecl *FnTemplate;
3968     if (auto *OTS = Name.getAsOverloadedTemplate())
3969       FnTemplate = *OTS->begin();
3970     else
3971       FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
3972     if (FnTemplate)
3973       return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
3974                << FnTemplate->getDeclName();
3975     return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
3976              << IsPartialSpecialization;
3977   }
3978 
3979   // Check for unexpanded parameter packs in any of the template arguments.
3980   for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
3981     if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
3982                                         IsPartialSpecialization
3983                                             ? UPPC_PartialSpecialization
3984                                             : UPPC_ExplicitSpecialization))
3985       return true;
3986 
3987   // Check that the template argument list is well-formed for this
3988   // template.
3989   SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
3990   if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
3991                                 false, SugaredConverted, CanonicalConverted,
3992                                 /*UpdateArgsWithConversions=*/true))
3993     return true;
3994 
3995   // Find the variable template (partial) specialization declaration that
3996   // corresponds to these arguments.
3997   if (IsPartialSpecialization) {
3998     if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, VarTemplate,
3999                                                TemplateArgs.size(),
4000                                                CanonicalConverted))
4001       return true;
4002 
4003     // FIXME: Move these checks to CheckTemplatePartialSpecializationArgs so we
4004     // also do them during instantiation.
4005     if (!Name.isDependent() &&
4006         !TemplateSpecializationType::anyDependentTemplateArguments(
4007             TemplateArgs, CanonicalConverted)) {
4008       Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
4009           << VarTemplate->getDeclName();
4010       IsPartialSpecialization = false;
4011     }
4012 
4013     if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(),
4014                                 CanonicalConverted) &&
4015         (!Context.getLangOpts().CPlusPlus20 ||
4016          !TemplateParams->hasAssociatedConstraints())) {
4017       // C++ [temp.class.spec]p9b3:
4018       //
4019       //   -- The argument list of the specialization shall not be identical
4020       //      to the implicit argument list of the primary template.
4021       Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
4022         << /*variable template*/ 1
4023         << /*is definition*/(SC != SC_Extern && !CurContext->isRecord())
4024         << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
4025       // FIXME: Recover from this by treating the declaration as a redeclaration
4026       // of the primary template.
4027       return true;
4028     }
4029   }
4030 
4031   void *InsertPos = nullptr;
4032   VarTemplateSpecializationDecl *PrevDecl = nullptr;
4033 
4034   if (IsPartialSpecialization)
4035     PrevDecl = VarTemplate->findPartialSpecialization(
4036         CanonicalConverted, TemplateParams, InsertPos);
4037   else
4038     PrevDecl = VarTemplate->findSpecialization(CanonicalConverted, InsertPos);
4039 
4040   VarTemplateSpecializationDecl *Specialization = nullptr;
4041 
4042   // Check whether we can declare a variable template specialization in
4043   // the current scope.
4044   if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
4045                                        TemplateNameLoc,
4046                                        IsPartialSpecialization))
4047     return true;
4048 
4049   if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
4050     // Since the only prior variable template specialization with these
4051     // arguments was referenced but not declared,  reuse that
4052     // declaration node as our own, updating its source location and
4053     // the list of outer template parameters to reflect our new declaration.
4054     Specialization = PrevDecl;
4055     Specialization->setLocation(TemplateNameLoc);
4056     PrevDecl = nullptr;
4057   } else if (IsPartialSpecialization) {
4058     // Create a new class template partial specialization declaration node.
4059     VarTemplatePartialSpecializationDecl *PrevPartial =
4060         cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
4061     VarTemplatePartialSpecializationDecl *Partial =
4062         VarTemplatePartialSpecializationDecl::Create(
4063             Context, VarTemplate->getDeclContext(), TemplateKWLoc,
4064             TemplateNameLoc, TemplateParams, VarTemplate, DI->getType(), DI, SC,
4065             CanonicalConverted);
4066     Partial->setTemplateArgsAsWritten(TemplateArgs);
4067 
4068     if (!PrevPartial)
4069       VarTemplate->AddPartialSpecialization(Partial, InsertPos);
4070     Specialization = Partial;
4071 
4072     // If we are providing an explicit specialization of a member variable
4073     // template specialization, make a note of that.
4074     if (PrevPartial && PrevPartial->getInstantiatedFromMember())
4075       PrevPartial->setMemberSpecialization();
4076 
4077     CheckTemplatePartialSpecialization(Partial);
4078   } else {
4079     // Create a new class template specialization declaration node for
4080     // this explicit specialization or friend declaration.
4081     Specialization = VarTemplateSpecializationDecl::Create(
4082         Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
4083         VarTemplate, DI->getType(), DI, SC, CanonicalConverted);
4084     Specialization->setTemplateArgsAsWritten(TemplateArgs);
4085 
4086     if (!PrevDecl)
4087       VarTemplate->AddSpecialization(Specialization, InsertPos);
4088   }
4089 
4090   // C++ [temp.expl.spec]p6:
4091   //   If a template, a member template or the member of a class template is
4092   //   explicitly specialized then that specialization shall be declared
4093   //   before the first use of that specialization that would cause an implicit
4094   //   instantiation to take place, in every translation unit in which such a
4095   //   use occurs; no diagnostic is required.
4096   if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
4097     bool Okay = false;
4098     for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
4099       // Is there any previous explicit specialization declaration?
4100       if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
4101         Okay = true;
4102         break;
4103       }
4104     }
4105 
4106     if (!Okay) {
4107       SourceRange Range(TemplateNameLoc, RAngleLoc);
4108       Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
4109           << Name << Range;
4110 
4111       Diag(PrevDecl->getPointOfInstantiation(),
4112            diag::note_instantiation_required_here)
4113           << (PrevDecl->getTemplateSpecializationKind() !=
4114               TSK_ImplicitInstantiation);
4115       return true;
4116     }
4117   }
4118 
4119   Specialization->setLexicalDeclContext(CurContext);
4120 
4121   // Add the specialization into its lexical context, so that it can
4122   // be seen when iterating through the list of declarations in that
4123   // context. However, specializations are not found by name lookup.
4124   CurContext->addDecl(Specialization);
4125 
4126   // Note that this is an explicit specialization.
4127   Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
4128 
4129   Previous.clear();
4130   if (PrevDecl)
4131     Previous.addDecl(PrevDecl);
4132   else if (Specialization->isStaticDataMember() &&
4133            Specialization->isOutOfLine())
4134     Specialization->setAccess(VarTemplate->getAccess());
4135 
4136   return Specialization;
4137 }
4138 
4139 namespace {
4140 /// A partial specialization whose template arguments have matched
4141 /// a given template-id.
4142 struct PartialSpecMatchResult {
4143   VarTemplatePartialSpecializationDecl *Partial;
4144   TemplateArgumentList *Args;
4145 };
4146 } // end anonymous namespace
4147 
4148 DeclResult
CheckVarTemplateId(VarTemplateDecl * Template,SourceLocation TemplateLoc,SourceLocation TemplateNameLoc,const TemplateArgumentListInfo & TemplateArgs)4149 Sema::CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc,
4150                          SourceLocation TemplateNameLoc,
4151                          const TemplateArgumentListInfo &TemplateArgs) {
4152   assert(Template && "A variable template id without template?");
4153 
4154   // Check that the template argument list is well-formed for this template.
4155   SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
4156   if (CheckTemplateArgumentList(
4157           Template, TemplateNameLoc,
4158           const_cast<TemplateArgumentListInfo &>(TemplateArgs), false,
4159           SugaredConverted, CanonicalConverted,
4160           /*UpdateArgsWithConversions=*/true))
4161     return true;
4162 
4163   // Produce a placeholder value if the specialization is dependent.
4164   if (Template->getDeclContext()->isDependentContext() ||
4165       TemplateSpecializationType::anyDependentTemplateArguments(
4166           TemplateArgs, CanonicalConverted))
4167     return DeclResult();
4168 
4169   // Find the variable template specialization declaration that
4170   // corresponds to these arguments.
4171   void *InsertPos = nullptr;
4172   if (VarTemplateSpecializationDecl *Spec =
4173           Template->findSpecialization(CanonicalConverted, InsertPos)) {
4174     checkSpecializationReachability(TemplateNameLoc, Spec);
4175     // If we already have a variable template specialization, return it.
4176     return Spec;
4177   }
4178 
4179   // This is the first time we have referenced this variable template
4180   // specialization. Create the canonical declaration and add it to
4181   // the set of specializations, based on the closest partial specialization
4182   // that it represents. That is,
4183   VarDecl *InstantiationPattern = Template->getTemplatedDecl();
4184   const TemplateArgumentList *PartialSpecArgs = nullptr;
4185   bool AmbiguousPartialSpec = false;
4186   typedef PartialSpecMatchResult MatchResult;
4187   SmallVector<MatchResult, 4> Matched;
4188   SourceLocation PointOfInstantiation = TemplateNameLoc;
4189   TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation,
4190                                             /*ForTakingAddress=*/false);
4191 
4192   // 1. Attempt to find the closest partial specialization that this
4193   // specializes, if any.
4194   // TODO: Unify with InstantiateClassTemplateSpecialization()?
4195   //       Perhaps better after unification of DeduceTemplateArguments() and
4196   //       getMoreSpecializedPartialSpecialization().
4197   SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
4198   Template->getPartialSpecializations(PartialSpecs);
4199 
4200   for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
4201     VarTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
4202     TemplateDeductionInfo Info(FailedCandidates.getLocation());
4203 
4204     if (TemplateDeductionResult Result =
4205             DeduceTemplateArguments(Partial, CanonicalConverted, Info);
4206         Result != TemplateDeductionResult::Success) {
4207       // Store the failed-deduction information for use in diagnostics, later.
4208       // TODO: Actually use the failed-deduction info?
4209       FailedCandidates.addCandidate().set(
4210           DeclAccessPair::make(Template, AS_public), Partial,
4211           MakeDeductionFailureInfo(Context, Result, Info));
4212       (void)Result;
4213     } else {
4214       Matched.push_back(PartialSpecMatchResult());
4215       Matched.back().Partial = Partial;
4216       Matched.back().Args = Info.takeCanonical();
4217     }
4218   }
4219 
4220   if (Matched.size() >= 1) {
4221     SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
4222     if (Matched.size() == 1) {
4223       //   -- If exactly one matching specialization is found, the
4224       //      instantiation is generated from that specialization.
4225       // We don't need to do anything for this.
4226     } else {
4227       //   -- If more than one matching specialization is found, the
4228       //      partial order rules (14.5.4.2) are used to determine
4229       //      whether one of the specializations is more specialized
4230       //      than the others. If none of the specializations is more
4231       //      specialized than all of the other matching
4232       //      specializations, then the use of the variable template is
4233       //      ambiguous and the program is ill-formed.
4234       for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
4235                                                  PEnd = Matched.end();
4236            P != PEnd; ++P) {
4237         if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
4238                                                     PointOfInstantiation) ==
4239             P->Partial)
4240           Best = P;
4241       }
4242 
4243       // Determine if the best partial specialization is more specialized than
4244       // the others.
4245       for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
4246                                                  PEnd = Matched.end();
4247            P != PEnd; ++P) {
4248         if (P != Best && getMoreSpecializedPartialSpecialization(
4249                              P->Partial, Best->Partial,
4250                              PointOfInstantiation) != Best->Partial) {
4251           AmbiguousPartialSpec = true;
4252           break;
4253         }
4254       }
4255     }
4256 
4257     // Instantiate using the best variable template partial specialization.
4258     InstantiationPattern = Best->Partial;
4259     PartialSpecArgs = Best->Args;
4260   } else {
4261     //   -- If no match is found, the instantiation is generated
4262     //      from the primary template.
4263     // InstantiationPattern = Template->getTemplatedDecl();
4264   }
4265 
4266   // 2. Create the canonical declaration.
4267   // Note that we do not instantiate a definition until we see an odr-use
4268   // in DoMarkVarDeclReferenced().
4269   // FIXME: LateAttrs et al.?
4270   VarTemplateSpecializationDecl *Decl = BuildVarTemplateInstantiation(
4271       Template, InstantiationPattern, PartialSpecArgs, TemplateArgs,
4272       CanonicalConverted, TemplateNameLoc /*, LateAttrs, StartingScope*/);
4273   if (!Decl)
4274     return true;
4275 
4276   if (AmbiguousPartialSpec) {
4277     // Partial ordering did not produce a clear winner. Complain.
4278     Decl->setInvalidDecl();
4279     Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
4280         << Decl;
4281 
4282     // Print the matching partial specializations.
4283     for (MatchResult P : Matched)
4284       Diag(P.Partial->getLocation(), diag::note_partial_spec_match)
4285           << getTemplateArgumentBindingsText(P.Partial->getTemplateParameters(),
4286                                              *P.Args);
4287     return true;
4288   }
4289 
4290   if (VarTemplatePartialSpecializationDecl *D =
4291           dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
4292     Decl->setInstantiationOf(D, PartialSpecArgs);
4293 
4294   checkSpecializationReachability(TemplateNameLoc, Decl);
4295 
4296   assert(Decl && "No variable template specialization?");
4297   return Decl;
4298 }
4299 
CheckVarTemplateId(const CXXScopeSpec & SS,const DeclarationNameInfo & NameInfo,VarTemplateDecl * Template,NamedDecl * FoundD,SourceLocation TemplateLoc,const TemplateArgumentListInfo * TemplateArgs)4300 ExprResult Sema::CheckVarTemplateId(
4301     const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
4302     VarTemplateDecl *Template, NamedDecl *FoundD, SourceLocation TemplateLoc,
4303     const TemplateArgumentListInfo *TemplateArgs) {
4304 
4305   DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
4306                                        *TemplateArgs);
4307   if (Decl.isInvalid())
4308     return ExprError();
4309 
4310   if (!Decl.get())
4311     return ExprResult();
4312 
4313   VarDecl *Var = cast<VarDecl>(Decl.get());
4314   if (!Var->getTemplateSpecializationKind())
4315     Var->setTemplateSpecializationKind(TSK_ImplicitInstantiation,
4316                                        NameInfo.getLoc());
4317 
4318   // Build an ordinary singleton decl ref.
4319   return BuildDeclarationNameExpr(SS, NameInfo, Var, FoundD, TemplateArgs);
4320 }
4321 
diagnoseMissingTemplateArguments(TemplateName Name,SourceLocation Loc)4322 void Sema::diagnoseMissingTemplateArguments(TemplateName Name,
4323                                             SourceLocation Loc) {
4324   Diag(Loc, diag::err_template_missing_args)
4325     << (int)getTemplateNameKindForDiagnostics(Name) << Name;
4326   if (TemplateDecl *TD = Name.getAsTemplateDecl()) {
4327     NoteTemplateLocation(*TD, TD->getTemplateParameters()->getSourceRange());
4328   }
4329 }
4330 
diagnoseMissingTemplateArguments(const CXXScopeSpec & SS,bool TemplateKeyword,TemplateDecl * TD,SourceLocation Loc)4331 void Sema::diagnoseMissingTemplateArguments(const CXXScopeSpec &SS,
4332                                             bool TemplateKeyword,
4333                                             TemplateDecl *TD,
4334                                             SourceLocation Loc) {
4335   TemplateName Name = Context.getQualifiedTemplateName(
4336       SS.getScopeRep(), TemplateKeyword, TemplateName(TD));
4337   diagnoseMissingTemplateArguments(Name, Loc);
4338 }
4339 
4340 ExprResult
CheckConceptTemplateId(const CXXScopeSpec & SS,SourceLocation TemplateKWLoc,const DeclarationNameInfo & ConceptNameInfo,NamedDecl * FoundDecl,ConceptDecl * NamedConcept,const TemplateArgumentListInfo * TemplateArgs)4341 Sema::CheckConceptTemplateId(const CXXScopeSpec &SS,
4342                              SourceLocation TemplateKWLoc,
4343                              const DeclarationNameInfo &ConceptNameInfo,
4344                              NamedDecl *FoundDecl,
4345                              ConceptDecl *NamedConcept,
4346                              const TemplateArgumentListInfo *TemplateArgs) {
4347   assert(NamedConcept && "A concept template id without a template?");
4348 
4349   llvm::SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
4350   if (CheckTemplateArgumentList(
4351           NamedConcept, ConceptNameInfo.getLoc(),
4352           const_cast<TemplateArgumentListInfo &>(*TemplateArgs),
4353           /*PartialTemplateArgs=*/false, SugaredConverted, CanonicalConverted,
4354           /*UpdateArgsWithConversions=*/false))
4355     return ExprError();
4356 
4357   DiagnoseUseOfDecl(NamedConcept, ConceptNameInfo.getLoc());
4358 
4359   auto *CSD = ImplicitConceptSpecializationDecl::Create(
4360       Context, NamedConcept->getDeclContext(), NamedConcept->getLocation(),
4361       CanonicalConverted);
4362   ConstraintSatisfaction Satisfaction;
4363   bool AreArgsDependent =
4364       TemplateSpecializationType::anyDependentTemplateArguments(
4365           *TemplateArgs, CanonicalConverted);
4366   MultiLevelTemplateArgumentList MLTAL(NamedConcept, CanonicalConverted,
4367                                        /*Final=*/false);
4368   LocalInstantiationScope Scope(*this);
4369 
4370   EnterExpressionEvaluationContext EECtx{
4371       *this, ExpressionEvaluationContext::Unevaluated, CSD};
4372 
4373   if (!AreArgsDependent &&
4374       CheckConstraintSatisfaction(
4375           NamedConcept, {NamedConcept->getConstraintExpr()}, MLTAL,
4376           SourceRange(SS.isSet() ? SS.getBeginLoc() : ConceptNameInfo.getLoc(),
4377                       TemplateArgs->getRAngleLoc()),
4378           Satisfaction))
4379     return ExprError();
4380   auto *CL = ConceptReference::Create(
4381       Context,
4382       SS.isSet() ? SS.getWithLocInContext(Context) : NestedNameSpecifierLoc{},
4383       TemplateKWLoc, ConceptNameInfo, FoundDecl, NamedConcept,
4384       ASTTemplateArgumentListInfo::Create(Context, *TemplateArgs));
4385   return ConceptSpecializationExpr::Create(
4386       Context, CL, CSD, AreArgsDependent ? nullptr : &Satisfaction);
4387 }
4388 
BuildTemplateIdExpr(const CXXScopeSpec & SS,SourceLocation TemplateKWLoc,LookupResult & R,bool RequiresADL,const TemplateArgumentListInfo * TemplateArgs)4389 ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
4390                                      SourceLocation TemplateKWLoc,
4391                                      LookupResult &R,
4392                                      bool RequiresADL,
4393                                  const TemplateArgumentListInfo *TemplateArgs) {
4394   // FIXME: Can we do any checking at this point? I guess we could check the
4395   // template arguments that we have against the template name, if the template
4396   // name refers to a single template. That's not a terribly common case,
4397   // though.
4398   // foo<int> could identify a single function unambiguously
4399   // This approach does NOT work, since f<int>(1);
4400   // gets resolved prior to resorting to overload resolution
4401   // i.e., template<class T> void f(double);
4402   //       vs template<class T, class U> void f(U);
4403 
4404   // These should be filtered out by our callers.
4405   assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
4406 
4407   // Non-function templates require a template argument list.
4408   if (auto *TD = R.getAsSingle<TemplateDecl>()) {
4409     if (!TemplateArgs && !isa<FunctionTemplateDecl>(TD)) {
4410       diagnoseMissingTemplateArguments(
4411           SS, /*TemplateKeyword=*/TemplateKWLoc.isValid(), TD, R.getNameLoc());
4412       return ExprError();
4413     }
4414   }
4415   bool KnownDependent = false;
4416   // In C++1y, check variable template ids.
4417   if (R.getAsSingle<VarTemplateDecl>()) {
4418     ExprResult Res = CheckVarTemplateId(
4419         SS, R.getLookupNameInfo(), R.getAsSingle<VarTemplateDecl>(),
4420         R.getRepresentativeDecl(), TemplateKWLoc, TemplateArgs);
4421     if (Res.isInvalid() || Res.isUsable())
4422       return Res;
4423     // Result is dependent. Carry on to build an UnresolvedLookupExpr.
4424     KnownDependent = true;
4425   }
4426 
4427   if (R.getAsSingle<ConceptDecl>()) {
4428     return CheckConceptTemplateId(SS, TemplateKWLoc, R.getLookupNameInfo(),
4429                                   R.getRepresentativeDecl(),
4430                                   R.getAsSingle<ConceptDecl>(), TemplateArgs);
4431   }
4432 
4433   // We don't want lookup warnings at this point.
4434   R.suppressDiagnostics();
4435 
4436   UnresolvedLookupExpr *ULE = UnresolvedLookupExpr::Create(
4437       Context, R.getNamingClass(), SS.getWithLocInContext(Context),
4438       TemplateKWLoc, R.getLookupNameInfo(), RequiresADL, TemplateArgs,
4439       R.begin(), R.end(), KnownDependent,
4440       /*KnownInstantiationDependent=*/false);
4441 
4442   // Model the templates with UnresolvedTemplateTy. The expression should then
4443   // either be transformed in an instantiation or be diagnosed in
4444   // CheckPlaceholderExpr.
4445   if (ULE->getType() == Context.OverloadTy && R.isSingleResult() &&
4446       !R.getFoundDecl()->getAsFunction())
4447     ULE->setType(Context.UnresolvedTemplateTy);
4448 
4449   return ULE;
4450 }
4451 
BuildQualifiedTemplateIdExpr(CXXScopeSpec & SS,SourceLocation TemplateKWLoc,const DeclarationNameInfo & NameInfo,const TemplateArgumentListInfo * TemplateArgs,bool IsAddressOfOperand)4452 ExprResult Sema::BuildQualifiedTemplateIdExpr(
4453     CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
4454     const DeclarationNameInfo &NameInfo,
4455     const TemplateArgumentListInfo *TemplateArgs, bool IsAddressOfOperand) {
4456   assert(TemplateArgs || TemplateKWLoc.isValid());
4457 
4458   LookupResult R(*this, NameInfo, LookupOrdinaryName);
4459   if (LookupTemplateName(R, /*S=*/nullptr, SS, /*ObjectType=*/QualType(),
4460                          /*EnteringContext=*/false, TemplateKWLoc))
4461     return ExprError();
4462 
4463   if (R.isAmbiguous())
4464     return ExprError();
4465 
4466   if (R.wasNotFoundInCurrentInstantiation() || SS.isInvalid())
4467     return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
4468 
4469   if (R.empty()) {
4470     DeclContext *DC = computeDeclContext(SS);
4471     Diag(NameInfo.getLoc(), diag::err_no_member)
4472       << NameInfo.getName() << DC << SS.getRange();
4473     return ExprError();
4474   }
4475 
4476   // If necessary, build an implicit class member access.
4477   if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))
4478     return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs,
4479                                            /*S=*/nullptr);
4480 
4481   return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL=*/false, TemplateArgs);
4482 }
4483 
ActOnTemplateName(Scope * S,CXXScopeSpec & SS,SourceLocation TemplateKWLoc,const UnqualifiedId & Name,ParsedType ObjectType,bool EnteringContext,TemplateTy & Result,bool AllowInjectedClassName)4484 TemplateNameKind Sema::ActOnTemplateName(Scope *S,
4485                                          CXXScopeSpec &SS,
4486                                          SourceLocation TemplateKWLoc,
4487                                          const UnqualifiedId &Name,
4488                                          ParsedType ObjectType,
4489                                          bool EnteringContext,
4490                                          TemplateTy &Result,
4491                                          bool AllowInjectedClassName) {
4492   if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
4493     Diag(TemplateKWLoc,
4494          getLangOpts().CPlusPlus11 ?
4495            diag::warn_cxx98_compat_template_outside_of_template :
4496            diag::ext_template_outside_of_template)
4497       << FixItHint::CreateRemoval(TemplateKWLoc);
4498 
4499   if (SS.isInvalid())
4500     return TNK_Non_template;
4501 
4502   // Figure out where isTemplateName is going to look.
4503   DeclContext *LookupCtx = nullptr;
4504   if (SS.isNotEmpty())
4505     LookupCtx = computeDeclContext(SS, EnteringContext);
4506   else if (ObjectType)
4507     LookupCtx = computeDeclContext(GetTypeFromParser(ObjectType));
4508 
4509   // C++0x [temp.names]p5:
4510   //   If a name prefixed by the keyword template is not the name of
4511   //   a template, the program is ill-formed. [Note: the keyword
4512   //   template may not be applied to non-template members of class
4513   //   templates. -end note ] [ Note: as is the case with the
4514   //   typename prefix, the template prefix is allowed in cases
4515   //   where it is not strictly necessary; i.e., when the
4516   //   nested-name-specifier or the expression on the left of the ->
4517   //   or . is not dependent on a template-parameter, or the use
4518   //   does not appear in the scope of a template. -end note]
4519   //
4520   // Note: C++03 was more strict here, because it banned the use of
4521   // the "template" keyword prior to a template-name that was not a
4522   // dependent name. C++ DR468 relaxed this requirement (the
4523   // "template" keyword is now permitted). We follow the C++0x
4524   // rules, even in C++03 mode with a warning, retroactively applying the DR.
4525   bool MemberOfUnknownSpecialization;
4526   TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
4527                                         ObjectType, EnteringContext, Result,
4528                                         MemberOfUnknownSpecialization);
4529   if (TNK != TNK_Non_template) {
4530     // We resolved this to a (non-dependent) template name. Return it.
4531     auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
4532     if (!AllowInjectedClassName && SS.isNotEmpty() && LookupRD &&
4533         Name.getKind() == UnqualifiedIdKind::IK_Identifier &&
4534         Name.Identifier && LookupRD->getIdentifier() == Name.Identifier) {
4535       // C++14 [class.qual]p2:
4536       //   In a lookup in which function names are not ignored and the
4537       //   nested-name-specifier nominates a class C, if the name specified
4538       //   [...] is the injected-class-name of C, [...] the name is instead
4539       //   considered to name the constructor
4540       //
4541       // We don't get here if naming the constructor would be valid, so we
4542       // just reject immediately and recover by treating the
4543       // injected-class-name as naming the template.
4544       Diag(Name.getBeginLoc(),
4545            diag::ext_out_of_line_qualified_id_type_names_constructor)
4546           << Name.Identifier
4547           << 0 /*injected-class-name used as template name*/
4548           << TemplateKWLoc.isValid();
4549     }
4550     return TNK;
4551   }
4552 
4553   if (!MemberOfUnknownSpecialization) {
4554     // Didn't find a template name, and the lookup wasn't dependent.
4555     // Do the lookup again to determine if this is a "nothing found" case or
4556     // a "not a template" case. FIXME: Refactor isTemplateName so we don't
4557     // need to do this.
4558     DeclarationNameInfo DNI = GetNameFromUnqualifiedId(Name);
4559     LookupResult R(*this, DNI.getName(), Name.getBeginLoc(),
4560                    LookupOrdinaryName);
4561     // Tell LookupTemplateName that we require a template so that it diagnoses
4562     // cases where it finds a non-template.
4563     RequiredTemplateKind RTK = TemplateKWLoc.isValid()
4564                                    ? RequiredTemplateKind(TemplateKWLoc)
4565                                    : TemplateNameIsRequired;
4566     if (!LookupTemplateName(R, S, SS, ObjectType.get(), EnteringContext, RTK,
4567                             /*ATK=*/nullptr, /*AllowTypoCorrection=*/false) &&
4568         !R.isAmbiguous()) {
4569       if (LookupCtx)
4570         Diag(Name.getBeginLoc(), diag::err_no_member)
4571             << DNI.getName() << LookupCtx << SS.getRange();
4572       else
4573         Diag(Name.getBeginLoc(), diag::err_undeclared_use)
4574             << DNI.getName() << SS.getRange();
4575     }
4576     return TNK_Non_template;
4577   }
4578 
4579   NestedNameSpecifier *Qualifier = SS.getScopeRep();
4580 
4581   switch (Name.getKind()) {
4582   case UnqualifiedIdKind::IK_Identifier:
4583     Result = TemplateTy::make(
4584         Context.getDependentTemplateName(Qualifier, Name.Identifier));
4585     return TNK_Dependent_template_name;
4586 
4587   case UnqualifiedIdKind::IK_OperatorFunctionId:
4588     Result = TemplateTy::make(Context.getDependentTemplateName(
4589         Qualifier, Name.OperatorFunctionId.Operator));
4590     return TNK_Function_template;
4591 
4592   case UnqualifiedIdKind::IK_LiteralOperatorId:
4593     // This is a kind of template name, but can never occur in a dependent
4594     // scope (literal operators can only be declared at namespace scope).
4595     break;
4596 
4597   default:
4598     break;
4599   }
4600 
4601   // This name cannot possibly name a dependent template. Diagnose this now
4602   // rather than building a dependent template name that can never be valid.
4603   Diag(Name.getBeginLoc(),
4604        diag::err_template_kw_refers_to_dependent_non_template)
4605       << GetNameFromUnqualifiedId(Name).getName() << Name.getSourceRange()
4606       << TemplateKWLoc.isValid() << TemplateKWLoc;
4607   return TNK_Non_template;
4608 }
4609 
CheckTemplateTypeArgument(TemplateTypeParmDecl * Param,TemplateArgumentLoc & AL,SmallVectorImpl<TemplateArgument> & SugaredConverted,SmallVectorImpl<TemplateArgument> & CanonicalConverted)4610 bool Sema::CheckTemplateTypeArgument(
4611     TemplateTypeParmDecl *Param, TemplateArgumentLoc &AL,
4612     SmallVectorImpl<TemplateArgument> &SugaredConverted,
4613     SmallVectorImpl<TemplateArgument> &CanonicalConverted) {
4614   const TemplateArgument &Arg = AL.getArgument();
4615   QualType ArgType;
4616   TypeSourceInfo *TSI = nullptr;
4617 
4618   // Check template type parameter.
4619   switch(Arg.getKind()) {
4620   case TemplateArgument::Type:
4621     // C++ [temp.arg.type]p1:
4622     //   A template-argument for a template-parameter which is a
4623     //   type shall be a type-id.
4624     ArgType = Arg.getAsType();
4625     TSI = AL.getTypeSourceInfo();
4626     break;
4627   case TemplateArgument::Template:
4628   case TemplateArgument::TemplateExpansion: {
4629     // We have a template type parameter but the template argument
4630     // is a template without any arguments.
4631     SourceRange SR = AL.getSourceRange();
4632     TemplateName Name = Arg.getAsTemplateOrTemplatePattern();
4633     diagnoseMissingTemplateArguments(Name, SR.getEnd());
4634     return true;
4635   }
4636   case TemplateArgument::Expression: {
4637     // We have a template type parameter but the template argument is an
4638     // expression; see if maybe it is missing the "typename" keyword.
4639     CXXScopeSpec SS;
4640     DeclarationNameInfo NameInfo;
4641 
4642    if (DependentScopeDeclRefExpr *ArgExpr =
4643                dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
4644       SS.Adopt(ArgExpr->getQualifierLoc());
4645       NameInfo = ArgExpr->getNameInfo();
4646     } else if (CXXDependentScopeMemberExpr *ArgExpr =
4647                dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
4648       if (ArgExpr->isImplicitAccess()) {
4649         SS.Adopt(ArgExpr->getQualifierLoc());
4650         NameInfo = ArgExpr->getMemberNameInfo();
4651       }
4652     }
4653 
4654     if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
4655       LookupResult Result(*this, NameInfo, LookupOrdinaryName);
4656       LookupParsedName(Result, CurScope, &SS, /*ObjectType=*/QualType());
4657 
4658       if (Result.getAsSingle<TypeDecl>() ||
4659           Result.wasNotFoundInCurrentInstantiation()) {
4660         assert(SS.getScopeRep() && "dependent scope expr must has a scope!");
4661         // Suggest that the user add 'typename' before the NNS.
4662         SourceLocation Loc = AL.getSourceRange().getBegin();
4663         Diag(Loc, getLangOpts().MSVCCompat
4664                       ? diag::ext_ms_template_type_arg_missing_typename
4665                       : diag::err_template_arg_must_be_type_suggest)
4666             << FixItHint::CreateInsertion(Loc, "typename ");
4667         NoteTemplateParameterLocation(*Param);
4668 
4669         // Recover by synthesizing a type using the location information that we
4670         // already have.
4671         ArgType = Context.getDependentNameType(ElaboratedTypeKeyword::Typename,
4672                                                SS.getScopeRep(), II);
4673         TypeLocBuilder TLB;
4674         DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(ArgType);
4675         TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
4676         TL.setQualifierLoc(SS.getWithLocInContext(Context));
4677         TL.setNameLoc(NameInfo.getLoc());
4678         TSI = TLB.getTypeSourceInfo(Context, ArgType);
4679 
4680         // Overwrite our input TemplateArgumentLoc so that we can recover
4681         // properly.
4682         AL = TemplateArgumentLoc(TemplateArgument(ArgType),
4683                                  TemplateArgumentLocInfo(TSI));
4684 
4685         break;
4686       }
4687     }
4688     // fallthrough
4689     [[fallthrough]];
4690   }
4691   default: {
4692     // We allow instantiateing a template with template argument packs when
4693     // building deduction guides.
4694     if (Arg.getKind() == TemplateArgument::Pack &&
4695         CodeSynthesisContexts.back().Kind ==
4696             Sema::CodeSynthesisContext::BuildingDeductionGuides) {
4697       SugaredConverted.push_back(Arg);
4698       CanonicalConverted.push_back(Arg);
4699       return false;
4700     }
4701     // We have a template type parameter but the template argument
4702     // is not a type.
4703     SourceRange SR = AL.getSourceRange();
4704     Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
4705     NoteTemplateParameterLocation(*Param);
4706 
4707     return true;
4708   }
4709   }
4710 
4711   if (CheckTemplateArgument(TSI))
4712     return true;
4713 
4714   // Objective-C ARC:
4715   //   If an explicitly-specified template argument type is a lifetime type
4716   //   with no lifetime qualifier, the __strong lifetime qualifier is inferred.
4717   if (getLangOpts().ObjCAutoRefCount &&
4718       ArgType->isObjCLifetimeType() &&
4719       !ArgType.getObjCLifetime()) {
4720     Qualifiers Qs;
4721     Qs.setObjCLifetime(Qualifiers::OCL_Strong);
4722     ArgType = Context.getQualifiedType(ArgType, Qs);
4723   }
4724 
4725   SugaredConverted.push_back(TemplateArgument(ArgType));
4726   CanonicalConverted.push_back(
4727       TemplateArgument(Context.getCanonicalType(ArgType)));
4728   return false;
4729 }
4730 
4731 /// Substitute template arguments into the default template argument for
4732 /// the given template type parameter.
4733 ///
4734 /// \param SemaRef the semantic analysis object for which we are performing
4735 /// the substitution.
4736 ///
4737 /// \param Template the template that we are synthesizing template arguments
4738 /// for.
4739 ///
4740 /// \param TemplateLoc the location of the template name that started the
4741 /// template-id we are checking.
4742 ///
4743 /// \param RAngleLoc the location of the right angle bracket ('>') that
4744 /// terminates the template-id.
4745 ///
4746 /// \param Param the template template parameter whose default we are
4747 /// substituting into.
4748 ///
4749 /// \param Converted the list of template arguments provided for template
4750 /// parameters that precede \p Param in the template parameter list.
4751 ///
4752 /// \param Output the resulting substituted template argument.
4753 ///
4754 /// \returns true if an error occurred.
SubstDefaultTemplateArgument(Sema & SemaRef,TemplateDecl * Template,SourceLocation TemplateLoc,SourceLocation RAngleLoc,TemplateTypeParmDecl * Param,ArrayRef<TemplateArgument> SugaredConverted,ArrayRef<TemplateArgument> CanonicalConverted,TemplateArgumentLoc & Output)4755 static bool SubstDefaultTemplateArgument(
4756     Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
4757     SourceLocation RAngleLoc, TemplateTypeParmDecl *Param,
4758     ArrayRef<TemplateArgument> SugaredConverted,
4759     ArrayRef<TemplateArgument> CanonicalConverted,
4760     TemplateArgumentLoc &Output) {
4761   Output = Param->getDefaultArgument();
4762 
4763   // If the argument type is dependent, instantiate it now based
4764   // on the previously-computed template arguments.
4765   if (Output.getArgument().isInstantiationDependent()) {
4766     Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Param, Template,
4767                                      SugaredConverted,
4768                                      SourceRange(TemplateLoc, RAngleLoc));
4769     if (Inst.isInvalid())
4770       return true;
4771 
4772     // Only substitute for the innermost template argument list.
4773     MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
4774                                                     /*Final=*/true);
4775     for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4776       TemplateArgLists.addOuterTemplateArguments(std::nullopt);
4777 
4778     bool ForLambdaCallOperator = false;
4779     if (const auto *Rec = dyn_cast<CXXRecordDecl>(Template->getDeclContext()))
4780       ForLambdaCallOperator = Rec->isLambda();
4781     Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext(),
4782                                    !ForLambdaCallOperator);
4783 
4784     if (SemaRef.SubstTemplateArgument(Output, TemplateArgLists, Output,
4785                                       Param->getDefaultArgumentLoc(),
4786                                       Param->getDeclName()))
4787       return true;
4788   }
4789 
4790   return false;
4791 }
4792 
4793 /// Substitute template arguments into the default template argument for
4794 /// the given non-type template parameter.
4795 ///
4796 /// \param SemaRef the semantic analysis object for which we are performing
4797 /// the substitution.
4798 ///
4799 /// \param Template the template that we are synthesizing template arguments
4800 /// for.
4801 ///
4802 /// \param TemplateLoc the location of the template name that started the
4803 /// template-id we are checking.
4804 ///
4805 /// \param RAngleLoc the location of the right angle bracket ('>') that
4806 /// terminates the template-id.
4807 ///
4808 /// \param Param the non-type template parameter whose default we are
4809 /// substituting into.
4810 ///
4811 /// \param Converted the list of template arguments provided for template
4812 /// parameters that precede \p Param in the template parameter list.
4813 ///
4814 /// \returns the substituted template argument, or NULL if an error occurred.
SubstDefaultTemplateArgument(Sema & SemaRef,TemplateDecl * Template,SourceLocation TemplateLoc,SourceLocation RAngleLoc,NonTypeTemplateParmDecl * Param,ArrayRef<TemplateArgument> SugaredConverted,ArrayRef<TemplateArgument> CanonicalConverted,TemplateArgumentLoc & Output)4815 static bool SubstDefaultTemplateArgument(
4816     Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
4817     SourceLocation RAngleLoc, NonTypeTemplateParmDecl *Param,
4818     ArrayRef<TemplateArgument> SugaredConverted,
4819     ArrayRef<TemplateArgument> CanonicalConverted,
4820     TemplateArgumentLoc &Output) {
4821   Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Param, Template,
4822                                    SugaredConverted,
4823                                    SourceRange(TemplateLoc, RAngleLoc));
4824   if (Inst.isInvalid())
4825     return true;
4826 
4827   // Only substitute for the innermost template argument list.
4828   MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
4829                                                   /*Final=*/true);
4830   for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4831     TemplateArgLists.addOuterTemplateArguments(std::nullopt);
4832 
4833   Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
4834   EnterExpressionEvaluationContext ConstantEvaluated(
4835       SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
4836   return SemaRef.SubstTemplateArgument(Param->getDefaultArgument(),
4837                                        TemplateArgLists, Output);
4838 }
4839 
4840 /// Substitute template arguments into the default template argument for
4841 /// the given template template parameter.
4842 ///
4843 /// \param SemaRef the semantic analysis object for which we are performing
4844 /// the substitution.
4845 ///
4846 /// \param Template the template that we are synthesizing template arguments
4847 /// for.
4848 ///
4849 /// \param TemplateLoc the location of the template name that started the
4850 /// template-id we are checking.
4851 ///
4852 /// \param RAngleLoc the location of the right angle bracket ('>') that
4853 /// terminates the template-id.
4854 ///
4855 /// \param Param the template template parameter whose default we are
4856 /// substituting into.
4857 ///
4858 /// \param Converted the list of template arguments provided for template
4859 /// parameters that precede \p Param in the template parameter list.
4860 ///
4861 /// \param QualifierLoc Will be set to the nested-name-specifier (with
4862 /// source-location information) that precedes the template name.
4863 ///
4864 /// \returns the substituted template argument, or NULL if an error occurred.
SubstDefaultTemplateArgument(Sema & SemaRef,TemplateDecl * Template,SourceLocation TemplateLoc,SourceLocation RAngleLoc,TemplateTemplateParmDecl * Param,ArrayRef<TemplateArgument> SugaredConverted,ArrayRef<TemplateArgument> CanonicalConverted,NestedNameSpecifierLoc & QualifierLoc)4865 static TemplateName SubstDefaultTemplateArgument(
4866     Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
4867     SourceLocation RAngleLoc, TemplateTemplateParmDecl *Param,
4868     ArrayRef<TemplateArgument> SugaredConverted,
4869     ArrayRef<TemplateArgument> CanonicalConverted,
4870     NestedNameSpecifierLoc &QualifierLoc) {
4871   Sema::InstantiatingTemplate Inst(
4872       SemaRef, TemplateLoc, TemplateParameter(Param), Template,
4873       SugaredConverted, SourceRange(TemplateLoc, RAngleLoc));
4874   if (Inst.isInvalid())
4875     return TemplateName();
4876 
4877   // Only substitute for the innermost template argument list.
4878   MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
4879                                                   /*Final=*/true);
4880   for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4881     TemplateArgLists.addOuterTemplateArguments(std::nullopt);
4882 
4883   Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
4884   // Substitute into the nested-name-specifier first,
4885   QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc();
4886   if (QualifierLoc) {
4887     QualifierLoc =
4888         SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgLists);
4889     if (!QualifierLoc)
4890       return TemplateName();
4891   }
4892 
4893   return SemaRef.SubstTemplateName(
4894              QualifierLoc,
4895              Param->getDefaultArgument().getArgument().getAsTemplate(),
4896              Param->getDefaultArgument().getTemplateNameLoc(),
4897              TemplateArgLists);
4898 }
4899 
SubstDefaultTemplateArgumentIfAvailable(TemplateDecl * Template,SourceLocation TemplateLoc,SourceLocation RAngleLoc,Decl * Param,ArrayRef<TemplateArgument> SugaredConverted,ArrayRef<TemplateArgument> CanonicalConverted,bool & HasDefaultArg)4900 TemplateArgumentLoc Sema::SubstDefaultTemplateArgumentIfAvailable(
4901     TemplateDecl *Template, SourceLocation TemplateLoc,
4902     SourceLocation RAngleLoc, Decl *Param,
4903     ArrayRef<TemplateArgument> SugaredConverted,
4904     ArrayRef<TemplateArgument> CanonicalConverted, bool &HasDefaultArg) {
4905   HasDefaultArg = false;
4906 
4907   if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
4908     if (!hasReachableDefaultArgument(TypeParm))
4909       return TemplateArgumentLoc();
4910 
4911     HasDefaultArg = true;
4912     TemplateArgumentLoc Output;
4913     if (SubstDefaultTemplateArgument(*this, Template, TemplateLoc, RAngleLoc,
4914                                      TypeParm, SugaredConverted,
4915                                      CanonicalConverted, Output))
4916       return TemplateArgumentLoc();
4917     return Output;
4918   }
4919 
4920   if (NonTypeTemplateParmDecl *NonTypeParm
4921         = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
4922     if (!hasReachableDefaultArgument(NonTypeParm))
4923       return TemplateArgumentLoc();
4924 
4925     HasDefaultArg = true;
4926     TemplateArgumentLoc Output;
4927     if (SubstDefaultTemplateArgument(*this, Template, TemplateLoc, RAngleLoc,
4928                                      NonTypeParm, SugaredConverted,
4929                                      CanonicalConverted, Output))
4930       return TemplateArgumentLoc();
4931     return Output;
4932   }
4933 
4934   TemplateTemplateParmDecl *TempTempParm
4935     = cast<TemplateTemplateParmDecl>(Param);
4936   if (!hasReachableDefaultArgument(TempTempParm))
4937     return TemplateArgumentLoc();
4938 
4939   HasDefaultArg = true;
4940   NestedNameSpecifierLoc QualifierLoc;
4941   TemplateName TName = SubstDefaultTemplateArgument(
4942       *this, Template, TemplateLoc, RAngleLoc, TempTempParm, SugaredConverted,
4943       CanonicalConverted, QualifierLoc);
4944   if (TName.isNull())
4945     return TemplateArgumentLoc();
4946 
4947   return TemplateArgumentLoc(
4948       Context, TemplateArgument(TName),
4949       TempTempParm->getDefaultArgument().getTemplateQualifierLoc(),
4950       TempTempParm->getDefaultArgument().getTemplateNameLoc());
4951 }
4952 
4953 /// Convert a template-argument that we parsed as a type into a template, if
4954 /// possible. C++ permits injected-class-names to perform dual service as
4955 /// template template arguments and as template type arguments.
4956 static TemplateArgumentLoc
convertTypeTemplateArgumentToTemplate(ASTContext & Context,TypeLoc TLoc)4957 convertTypeTemplateArgumentToTemplate(ASTContext &Context, TypeLoc TLoc) {
4958   // Extract and step over any surrounding nested-name-specifier.
4959   NestedNameSpecifierLoc QualLoc;
4960   if (auto ETLoc = TLoc.getAs<ElaboratedTypeLoc>()) {
4961     if (ETLoc.getTypePtr()->getKeyword() != ElaboratedTypeKeyword::None)
4962       return TemplateArgumentLoc();
4963 
4964     QualLoc = ETLoc.getQualifierLoc();
4965     TLoc = ETLoc.getNamedTypeLoc();
4966   }
4967   // If this type was written as an injected-class-name, it can be used as a
4968   // template template argument.
4969   if (auto InjLoc = TLoc.getAs<InjectedClassNameTypeLoc>())
4970     return TemplateArgumentLoc(Context, InjLoc.getTypePtr()->getTemplateName(),
4971                                QualLoc, InjLoc.getNameLoc());
4972 
4973   // If this type was written as an injected-class-name, it may have been
4974   // converted to a RecordType during instantiation. If the RecordType is
4975   // *not* wrapped in a TemplateSpecializationType and denotes a class
4976   // template specialization, it must have come from an injected-class-name.
4977   if (auto RecLoc = TLoc.getAs<RecordTypeLoc>())
4978     if (auto *CTSD =
4979             dyn_cast<ClassTemplateSpecializationDecl>(RecLoc.getDecl()))
4980       return TemplateArgumentLoc(Context,
4981                                  TemplateName(CTSD->getSpecializedTemplate()),
4982                                  QualLoc, RecLoc.getNameLoc());
4983 
4984   return TemplateArgumentLoc();
4985 }
4986 
CheckTemplateArgument(NamedDecl * Param,TemplateArgumentLoc & Arg,NamedDecl * Template,SourceLocation TemplateLoc,SourceLocation RAngleLoc,unsigned ArgumentPackIndex,SmallVectorImpl<TemplateArgument> & SugaredConverted,SmallVectorImpl<TemplateArgument> & CanonicalConverted,CheckTemplateArgumentKind CTAK)4987 bool Sema::CheckTemplateArgument(
4988     NamedDecl *Param, TemplateArgumentLoc &Arg, NamedDecl *Template,
4989     SourceLocation TemplateLoc, SourceLocation RAngleLoc,
4990     unsigned ArgumentPackIndex,
4991     SmallVectorImpl<TemplateArgument> &SugaredConverted,
4992     SmallVectorImpl<TemplateArgument> &CanonicalConverted,
4993     CheckTemplateArgumentKind CTAK) {
4994   // Check template type parameters.
4995   if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
4996     return CheckTemplateTypeArgument(TTP, Arg, SugaredConverted,
4997                                      CanonicalConverted);
4998 
4999   // Check non-type template parameters.
5000   if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
5001     // Do substitution on the type of the non-type template parameter
5002     // with the template arguments we've seen thus far.  But if the
5003     // template has a dependent context then we cannot substitute yet.
5004     QualType NTTPType = NTTP->getType();
5005     if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
5006       NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
5007 
5008     if (NTTPType->isInstantiationDependentType() &&
5009         !isa<TemplateTemplateParmDecl>(Template) &&
5010         !Template->getDeclContext()->isDependentContext()) {
5011       // Do substitution on the type of the non-type template parameter.
5012       InstantiatingTemplate Inst(*this, TemplateLoc, Template, NTTP,
5013                                  SugaredConverted,
5014                                  SourceRange(TemplateLoc, RAngleLoc));
5015       if (Inst.isInvalid())
5016         return true;
5017 
5018       MultiLevelTemplateArgumentList MLTAL(Template, SugaredConverted,
5019                                            /*Final=*/true);
5020       // If the parameter is a pack expansion, expand this slice of the pack.
5021       if (auto *PET = NTTPType->getAs<PackExpansionType>()) {
5022         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this,
5023                                                            ArgumentPackIndex);
5024         NTTPType = SubstType(PET->getPattern(), MLTAL, NTTP->getLocation(),
5025                              NTTP->getDeclName());
5026       } else {
5027         NTTPType = SubstType(NTTPType, MLTAL, NTTP->getLocation(),
5028                              NTTP->getDeclName());
5029       }
5030 
5031       // If that worked, check the non-type template parameter type
5032       // for validity.
5033       if (!NTTPType.isNull())
5034         NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
5035                                                      NTTP->getLocation());
5036       if (NTTPType.isNull())
5037         return true;
5038     }
5039 
5040     switch (Arg.getArgument().getKind()) {
5041     case TemplateArgument::Null:
5042       llvm_unreachable("Should never see a NULL template argument here");
5043 
5044     case TemplateArgument::Expression: {
5045       Expr *E = Arg.getArgument().getAsExpr();
5046       TemplateArgument SugaredResult, CanonicalResult;
5047       unsigned CurSFINAEErrors = NumSFINAEErrors;
5048       ExprResult Res = CheckTemplateArgument(NTTP, NTTPType, E, SugaredResult,
5049                                              CanonicalResult, CTAK);
5050       if (Res.isInvalid())
5051         return true;
5052       // If the current template argument causes an error, give up now.
5053       if (CurSFINAEErrors < NumSFINAEErrors)
5054         return true;
5055 
5056       // If the resulting expression is new, then use it in place of the
5057       // old expression in the template argument.
5058       if (Res.get() != E) {
5059         TemplateArgument TA(Res.get());
5060         Arg = TemplateArgumentLoc(TA, Res.get());
5061       }
5062 
5063       SugaredConverted.push_back(SugaredResult);
5064       CanonicalConverted.push_back(CanonicalResult);
5065       break;
5066     }
5067 
5068     case TemplateArgument::Declaration:
5069     case TemplateArgument::Integral:
5070     case TemplateArgument::StructuralValue:
5071     case TemplateArgument::NullPtr:
5072       // We've already checked this template argument, so just copy
5073       // it to the list of converted arguments.
5074       SugaredConverted.push_back(Arg.getArgument());
5075       CanonicalConverted.push_back(
5076           Context.getCanonicalTemplateArgument(Arg.getArgument()));
5077       break;
5078 
5079     case TemplateArgument::Template:
5080     case TemplateArgument::TemplateExpansion:
5081       // We were given a template template argument. It may not be ill-formed;
5082       // see below.
5083       if (DependentTemplateName *DTN
5084             = Arg.getArgument().getAsTemplateOrTemplatePattern()
5085                                               .getAsDependentTemplateName()) {
5086         // We have a template argument such as \c T::template X, which we
5087         // parsed as a template template argument. However, since we now
5088         // know that we need a non-type template argument, convert this
5089         // template name into an expression.
5090 
5091         DeclarationNameInfo NameInfo(DTN->getIdentifier(),
5092                                      Arg.getTemplateNameLoc());
5093 
5094         CXXScopeSpec SS;
5095         SS.Adopt(Arg.getTemplateQualifierLoc());
5096         // FIXME: the template-template arg was a DependentTemplateName,
5097         // so it was provided with a template keyword. However, its source
5098         // location is not stored in the template argument structure.
5099         SourceLocation TemplateKWLoc;
5100         ExprResult E = DependentScopeDeclRefExpr::Create(
5101             Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
5102             nullptr);
5103 
5104         // If we parsed the template argument as a pack expansion, create a
5105         // pack expansion expression.
5106         if (Arg.getArgument().getKind() == TemplateArgument::TemplateExpansion){
5107           E = ActOnPackExpansion(E.get(), Arg.getTemplateEllipsisLoc());
5108           if (E.isInvalid())
5109             return true;
5110         }
5111 
5112         TemplateArgument SugaredResult, CanonicalResult;
5113         E = CheckTemplateArgument(NTTP, NTTPType, E.get(), SugaredResult,
5114                                   CanonicalResult, CTAK_Specified);
5115         if (E.isInvalid())
5116           return true;
5117 
5118         SugaredConverted.push_back(SugaredResult);
5119         CanonicalConverted.push_back(CanonicalResult);
5120         break;
5121       }
5122 
5123       // We have a template argument that actually does refer to a class
5124       // template, alias template, or template template parameter, and
5125       // therefore cannot be a non-type template argument.
5126       Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
5127         << Arg.getSourceRange();
5128       NoteTemplateParameterLocation(*Param);
5129 
5130       return true;
5131 
5132     case TemplateArgument::Type: {
5133       // We have a non-type template parameter but the template
5134       // argument is a type.
5135 
5136       // C++ [temp.arg]p2:
5137       //   In a template-argument, an ambiguity between a type-id and
5138       //   an expression is resolved to a type-id, regardless of the
5139       //   form of the corresponding template-parameter.
5140       //
5141       // We warn specifically about this case, since it can be rather
5142       // confusing for users.
5143       QualType T = Arg.getArgument().getAsType();
5144       SourceRange SR = Arg.getSourceRange();
5145       if (T->isFunctionType())
5146         Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
5147       else
5148         Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
5149       NoteTemplateParameterLocation(*Param);
5150       return true;
5151     }
5152 
5153     case TemplateArgument::Pack:
5154       llvm_unreachable("Caller must expand template argument packs");
5155     }
5156 
5157     return false;
5158   }
5159 
5160 
5161   // Check template template parameters.
5162   TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
5163 
5164   TemplateParameterList *Params = TempParm->getTemplateParameters();
5165   if (TempParm->isExpandedParameterPack())
5166     Params = TempParm->getExpansionTemplateParameters(ArgumentPackIndex);
5167 
5168   // Substitute into the template parameter list of the template
5169   // template parameter, since previously-supplied template arguments
5170   // may appear within the template template parameter.
5171   //
5172   // FIXME: Skip this if the parameters aren't instantiation-dependent.
5173   {
5174     // Set up a template instantiation context.
5175     LocalInstantiationScope Scope(*this);
5176     InstantiatingTemplate Inst(*this, TemplateLoc, Template, TempParm,
5177                                SugaredConverted,
5178                                SourceRange(TemplateLoc, RAngleLoc));
5179     if (Inst.isInvalid())
5180       return true;
5181 
5182     Params =
5183         SubstTemplateParams(Params, CurContext,
5184                             MultiLevelTemplateArgumentList(
5185                                 Template, SugaredConverted, /*Final=*/true),
5186                             /*EvaluateConstraints=*/false);
5187     if (!Params)
5188       return true;
5189   }
5190 
5191   // C++1z [temp.local]p1: (DR1004)
5192   //   When [the injected-class-name] is used [...] as a template-argument for
5193   //   a template template-parameter [...] it refers to the class template
5194   //   itself.
5195   if (Arg.getArgument().getKind() == TemplateArgument::Type) {
5196     TemplateArgumentLoc ConvertedArg = convertTypeTemplateArgumentToTemplate(
5197         Context, Arg.getTypeSourceInfo()->getTypeLoc());
5198     if (!ConvertedArg.getArgument().isNull())
5199       Arg = ConvertedArg;
5200   }
5201 
5202   switch (Arg.getArgument().getKind()) {
5203   case TemplateArgument::Null:
5204     llvm_unreachable("Should never see a NULL template argument here");
5205 
5206   case TemplateArgument::Template:
5207   case TemplateArgument::TemplateExpansion:
5208     if (CheckTemplateTemplateArgument(TempParm, Params, Arg,
5209                                       /*IsDeduced=*/CTAK != CTAK_Specified))
5210       return true;
5211 
5212     SugaredConverted.push_back(Arg.getArgument());
5213     CanonicalConverted.push_back(
5214         Context.getCanonicalTemplateArgument(Arg.getArgument()));
5215     break;
5216 
5217   case TemplateArgument::Expression:
5218   case TemplateArgument::Type:
5219     // We have a template template parameter but the template
5220     // argument does not refer to a template.
5221     Diag(Arg.getLocation(), diag::err_template_arg_must_be_template)
5222       << getLangOpts().CPlusPlus11;
5223     return true;
5224 
5225   case TemplateArgument::Declaration:
5226   case TemplateArgument::Integral:
5227   case TemplateArgument::StructuralValue:
5228   case TemplateArgument::NullPtr:
5229     llvm_unreachable("non-type argument with template template parameter");
5230 
5231   case TemplateArgument::Pack:
5232     llvm_unreachable("Caller must expand template argument packs");
5233   }
5234 
5235   return false;
5236 }
5237 
5238 /// Diagnose a missing template argument.
5239 template<typename TemplateParmDecl>
diagnoseMissingArgument(Sema & S,SourceLocation Loc,TemplateDecl * TD,const TemplateParmDecl * D,TemplateArgumentListInfo & Args)5240 static bool diagnoseMissingArgument(Sema &S, SourceLocation Loc,
5241                                     TemplateDecl *TD,
5242                                     const TemplateParmDecl *D,
5243                                     TemplateArgumentListInfo &Args) {
5244   // Dig out the most recent declaration of the template parameter; there may be
5245   // declarations of the template that are more recent than TD.
5246   D = cast<TemplateParmDecl>(cast<TemplateDecl>(TD->getMostRecentDecl())
5247                                  ->getTemplateParameters()
5248                                  ->getParam(D->getIndex()));
5249 
5250   // If there's a default argument that's not reachable, diagnose that we're
5251   // missing a module import.
5252   llvm::SmallVector<Module*, 8> Modules;
5253   if (D->hasDefaultArgument() && !S.hasReachableDefaultArgument(D, &Modules)) {
5254     S.diagnoseMissingImport(Loc, cast<NamedDecl>(TD),
5255                             D->getDefaultArgumentLoc(), Modules,
5256                             Sema::MissingImportKind::DefaultArgument,
5257                             /*Recover*/true);
5258     return true;
5259   }
5260 
5261   // FIXME: If there's a more recent default argument that *is* visible,
5262   // diagnose that it was declared too late.
5263 
5264   TemplateParameterList *Params = TD->getTemplateParameters();
5265 
5266   S.Diag(Loc, diag::err_template_arg_list_different_arity)
5267     << /*not enough args*/0
5268     << (int)S.getTemplateNameKindForDiagnostics(TemplateName(TD))
5269     << TD;
5270   S.NoteTemplateLocation(*TD, Params->getSourceRange());
5271   return true;
5272 }
5273 
5274 /// Check that the given template argument list is well-formed
5275 /// for specializing the given template.
CheckTemplateArgumentList(TemplateDecl * Template,SourceLocation TemplateLoc,TemplateArgumentListInfo & TemplateArgs,bool PartialTemplateArgs,SmallVectorImpl<TemplateArgument> & SugaredConverted,SmallVectorImpl<TemplateArgument> & CanonicalConverted,bool UpdateArgsWithConversions,bool * ConstraintsNotSatisfied,bool PartialOrderingTTP)5276 bool Sema::CheckTemplateArgumentList(
5277     TemplateDecl *Template, SourceLocation TemplateLoc,
5278     TemplateArgumentListInfo &TemplateArgs, bool PartialTemplateArgs,
5279     SmallVectorImpl<TemplateArgument> &SugaredConverted,
5280     SmallVectorImpl<TemplateArgument> &CanonicalConverted,
5281     bool UpdateArgsWithConversions, bool *ConstraintsNotSatisfied,
5282     bool PartialOrderingTTP) {
5283 
5284   if (ConstraintsNotSatisfied)
5285     *ConstraintsNotSatisfied = false;
5286 
5287   // Make a copy of the template arguments for processing.  Only make the
5288   // changes at the end when successful in matching the arguments to the
5289   // template.
5290   TemplateArgumentListInfo NewArgs = TemplateArgs;
5291 
5292   TemplateParameterList *Params = GetTemplateParameterList(Template);
5293 
5294   SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
5295 
5296   // C++ [temp.arg]p1:
5297   //   [...] The type and form of each template-argument specified in
5298   //   a template-id shall match the type and form specified for the
5299   //   corresponding parameter declared by the template in its
5300   //   template-parameter-list.
5301   bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
5302   SmallVector<TemplateArgument, 2> SugaredArgumentPack;
5303   SmallVector<TemplateArgument, 2> CanonicalArgumentPack;
5304   unsigned ArgIdx = 0, NumArgs = NewArgs.size();
5305   LocalInstantiationScope InstScope(*this, true);
5306   for (TemplateParameterList::iterator Param = Params->begin(),
5307                                        ParamEnd = Params->end();
5308        Param != ParamEnd; /* increment in loop */) {
5309     // If we have an expanded parameter pack, make sure we don't have too
5310     // many arguments.
5311     if (std::optional<unsigned> Expansions = getExpandedPackSize(*Param)) {
5312       if (*Expansions == SugaredArgumentPack.size()) {
5313         // We're done with this parameter pack. Pack up its arguments and add
5314         // them to the list.
5315         SugaredConverted.push_back(
5316             TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack));
5317         SugaredArgumentPack.clear();
5318 
5319         CanonicalConverted.push_back(
5320             TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack));
5321         CanonicalArgumentPack.clear();
5322 
5323         // This argument is assigned to the next parameter.
5324         ++Param;
5325         continue;
5326       } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
5327         // Not enough arguments for this parameter pack.
5328         Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
5329           << /*not enough args*/0
5330           << (int)getTemplateNameKindForDiagnostics(TemplateName(Template))
5331           << Template;
5332         NoteTemplateLocation(*Template, Params->getSourceRange());
5333         return true;
5334       }
5335     }
5336 
5337     if (ArgIdx < NumArgs) {
5338       // Check the template argument we were given.
5339       if (CheckTemplateArgument(*Param, NewArgs[ArgIdx], Template, TemplateLoc,
5340                                 RAngleLoc, SugaredArgumentPack.size(),
5341                                 SugaredConverted, CanonicalConverted,
5342                                 CTAK_Specified))
5343         return true;
5344 
5345       CanonicalConverted.back().setIsDefaulted(
5346           clang::isSubstitutedDefaultArgument(
5347               Context, NewArgs[ArgIdx].getArgument(), *Param,
5348               CanonicalConverted, Params->getDepth()));
5349 
5350       bool PackExpansionIntoNonPack =
5351           NewArgs[ArgIdx].getArgument().isPackExpansion() &&
5352           (!(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param));
5353       // CWG1430: Don't diagnose this pack expansion when partial
5354       // ordering template template parameters. Some uses of the template could
5355       // be valid, and invalid uses will be diagnosed later during
5356       // instantiation.
5357       if (PackExpansionIntoNonPack && !PartialOrderingTTP &&
5358           (isa<TypeAliasTemplateDecl>(Template) ||
5359            isa<ConceptDecl>(Template))) {
5360         // CWG1430: we have a pack expansion as an argument to an
5361         // alias template, and it's not part of a parameter pack. This
5362         // can't be canonicalized, so reject it now.
5363         // As for concepts - we cannot normalize constraints where this
5364         // situation exists.
5365         Diag(NewArgs[ArgIdx].getLocation(),
5366              diag::err_template_expansion_into_fixed_list)
5367           << (isa<ConceptDecl>(Template) ? 1 : 0)
5368           << NewArgs[ArgIdx].getSourceRange();
5369         NoteTemplateParameterLocation(**Param);
5370         return true;
5371       }
5372 
5373       // We're now done with this argument.
5374       ++ArgIdx;
5375 
5376       if ((*Param)->isTemplateParameterPack()) {
5377         // The template parameter was a template parameter pack, so take the
5378         // deduced argument and place it on the argument pack. Note that we
5379         // stay on the same template parameter so that we can deduce more
5380         // arguments.
5381         SugaredArgumentPack.push_back(SugaredConverted.pop_back_val());
5382         CanonicalArgumentPack.push_back(CanonicalConverted.pop_back_val());
5383       } else {
5384         // Move to the next template parameter.
5385         ++Param;
5386       }
5387 
5388       // If we just saw a pack expansion into a non-pack, then directly convert
5389       // the remaining arguments, because we don't know what parameters they'll
5390       // match up with.
5391       if (PackExpansionIntoNonPack) {
5392         if (!SugaredArgumentPack.empty()) {
5393           // If we were part way through filling in an expanded parameter pack,
5394           // fall back to just producing individual arguments.
5395           SugaredConverted.insert(SugaredConverted.end(),
5396                                   SugaredArgumentPack.begin(),
5397                                   SugaredArgumentPack.end());
5398           SugaredArgumentPack.clear();
5399 
5400           CanonicalConverted.insert(CanonicalConverted.end(),
5401                                     CanonicalArgumentPack.begin(),
5402                                     CanonicalArgumentPack.end());
5403           CanonicalArgumentPack.clear();
5404         }
5405 
5406         while (ArgIdx < NumArgs) {
5407           const TemplateArgument &Arg = NewArgs[ArgIdx].getArgument();
5408           SugaredConverted.push_back(Arg);
5409           CanonicalConverted.push_back(
5410               Context.getCanonicalTemplateArgument(Arg));
5411           ++ArgIdx;
5412         }
5413 
5414         return false;
5415       }
5416 
5417       continue;
5418     }
5419 
5420     // If we're checking a partial template argument list, we're done.
5421     if (PartialTemplateArgs) {
5422       if ((*Param)->isTemplateParameterPack() && !SugaredArgumentPack.empty()) {
5423         SugaredConverted.push_back(
5424             TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack));
5425         CanonicalConverted.push_back(
5426             TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack));
5427       }
5428       return false;
5429     }
5430 
5431     // If we have a template parameter pack with no more corresponding
5432     // arguments, just break out now and we'll fill in the argument pack below.
5433     if ((*Param)->isTemplateParameterPack()) {
5434       assert(!getExpandedPackSize(*Param) &&
5435              "Should have dealt with this already");
5436 
5437       // A non-expanded parameter pack before the end of the parameter list
5438       // only occurs for an ill-formed template parameter list, unless we've
5439       // got a partial argument list for a function template, so just bail out.
5440       if (Param + 1 != ParamEnd) {
5441         assert(
5442             (Template->getMostRecentDecl()->getKind() != Decl::Kind::Concept) &&
5443             "Concept templates must have parameter packs at the end.");
5444         return true;
5445       }
5446 
5447       SugaredConverted.push_back(
5448           TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack));
5449       SugaredArgumentPack.clear();
5450 
5451       CanonicalConverted.push_back(
5452           TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack));
5453       CanonicalArgumentPack.clear();
5454 
5455       ++Param;
5456       continue;
5457     }
5458 
5459     // Check whether we have a default argument.
5460     TemplateArgumentLoc Arg;
5461 
5462     // Retrieve the default template argument from the template
5463     // parameter. For each kind of template parameter, we substitute the
5464     // template arguments provided thus far and any "outer" template arguments
5465     // (when the template parameter was part of a nested template) into
5466     // the default argument.
5467     if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
5468       if (!hasReachableDefaultArgument(TTP))
5469         return diagnoseMissingArgument(*this, TemplateLoc, Template, TTP,
5470                                        NewArgs);
5471 
5472       if (SubstDefaultTemplateArgument(*this, Template, TemplateLoc, RAngleLoc,
5473                                        TTP, SugaredConverted,
5474                                        CanonicalConverted, Arg))
5475         return true;
5476     } else if (NonTypeTemplateParmDecl *NTTP
5477                  = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
5478       if (!hasReachableDefaultArgument(NTTP))
5479         return diagnoseMissingArgument(*this, TemplateLoc, Template, NTTP,
5480                                        NewArgs);
5481 
5482       if (SubstDefaultTemplateArgument(*this, Template, TemplateLoc, RAngleLoc,
5483                                        NTTP, SugaredConverted,
5484                                        CanonicalConverted, Arg))
5485         return true;
5486     } else {
5487       TemplateTemplateParmDecl *TempParm
5488         = cast<TemplateTemplateParmDecl>(*Param);
5489 
5490       if (!hasReachableDefaultArgument(TempParm))
5491         return diagnoseMissingArgument(*this, TemplateLoc, Template, TempParm,
5492                                        NewArgs);
5493 
5494       NestedNameSpecifierLoc QualifierLoc;
5495       TemplateName Name = SubstDefaultTemplateArgument(
5496           *this, Template, TemplateLoc, RAngleLoc, TempParm, SugaredConverted,
5497           CanonicalConverted, QualifierLoc);
5498       if (Name.isNull())
5499         return true;
5500 
5501       Arg = TemplateArgumentLoc(
5502           Context, TemplateArgument(Name), QualifierLoc,
5503           TempParm->getDefaultArgument().getTemplateNameLoc());
5504     }
5505 
5506     // Introduce an instantiation record that describes where we are using
5507     // the default template argument. We're not actually instantiating a
5508     // template here, we just create this object to put a note into the
5509     // context stack.
5510     InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param,
5511                                SugaredConverted,
5512                                SourceRange(TemplateLoc, RAngleLoc));
5513     if (Inst.isInvalid())
5514       return true;
5515 
5516     // Check the default template argument.
5517     if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc, RAngleLoc, 0,
5518                               SugaredConverted, CanonicalConverted,
5519                               CTAK_Specified))
5520       return true;
5521 
5522     CanonicalConverted.back().setIsDefaulted(true);
5523 
5524     // Core issue 150 (assumed resolution): if this is a template template
5525     // parameter, keep track of the default template arguments from the
5526     // template definition.
5527     if (isTemplateTemplateParameter)
5528       NewArgs.addArgument(Arg);
5529 
5530     // Move to the next template parameter and argument.
5531     ++Param;
5532     ++ArgIdx;
5533   }
5534 
5535   // If we're performing a partial argument substitution, allow any trailing
5536   // pack expansions; they might be empty. This can happen even if
5537   // PartialTemplateArgs is false (the list of arguments is complete but
5538   // still dependent).
5539   if (ArgIdx < NumArgs && CurrentInstantiationScope &&
5540       CurrentInstantiationScope->getPartiallySubstitutedPack()) {
5541     while (ArgIdx < NumArgs &&
5542            NewArgs[ArgIdx].getArgument().isPackExpansion()) {
5543       const TemplateArgument &Arg = NewArgs[ArgIdx++].getArgument();
5544       SugaredConverted.push_back(Arg);
5545       CanonicalConverted.push_back(Context.getCanonicalTemplateArgument(Arg));
5546     }
5547   }
5548 
5549   // If we have any leftover arguments, then there were too many arguments.
5550   // Complain and fail.
5551   if (ArgIdx < NumArgs) {
5552     Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
5553         << /*too many args*/1
5554         << (int)getTemplateNameKindForDiagnostics(TemplateName(Template))
5555         << Template
5556         << SourceRange(NewArgs[ArgIdx].getLocation(), NewArgs.getRAngleLoc());
5557     NoteTemplateLocation(*Template, Params->getSourceRange());
5558     return true;
5559   }
5560 
5561   // No problems found with the new argument list, propagate changes back
5562   // to caller.
5563   if (UpdateArgsWithConversions)
5564     TemplateArgs = std::move(NewArgs);
5565 
5566   if (!PartialTemplateArgs) {
5567     // Setup the context/ThisScope for the case where we are needing to
5568     // re-instantiate constraints outside of normal instantiation.
5569     DeclContext *NewContext = Template->getDeclContext();
5570 
5571     // If this template is in a template, make sure we extract the templated
5572     // decl.
5573     if (auto *TD = dyn_cast<TemplateDecl>(NewContext))
5574       NewContext = Decl::castToDeclContext(TD->getTemplatedDecl());
5575     auto *RD = dyn_cast<CXXRecordDecl>(NewContext);
5576 
5577     Qualifiers ThisQuals;
5578     if (const auto *Method =
5579             dyn_cast_or_null<CXXMethodDecl>(Template->getTemplatedDecl()))
5580       ThisQuals = Method->getMethodQualifiers();
5581 
5582     ContextRAII Context(*this, NewContext);
5583     CXXThisScopeRAII(*this, RD, ThisQuals, RD != nullptr);
5584 
5585     MultiLevelTemplateArgumentList MLTAL = getTemplateInstantiationArgs(
5586         Template, NewContext, /*Final=*/false, CanonicalConverted,
5587         /*RelativeToPrimary=*/true,
5588         /*Pattern=*/nullptr,
5589         /*ForConceptInstantiation=*/true);
5590     if (EnsureTemplateArgumentListConstraints(
5591             Template, MLTAL,
5592             SourceRange(TemplateLoc, TemplateArgs.getRAngleLoc()))) {
5593       if (ConstraintsNotSatisfied)
5594         *ConstraintsNotSatisfied = true;
5595       return true;
5596     }
5597   }
5598 
5599   return false;
5600 }
5601 
5602 namespace {
5603   class UnnamedLocalNoLinkageFinder
5604     : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
5605   {
5606     Sema &S;
5607     SourceRange SR;
5608 
5609     typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
5610 
5611   public:
UnnamedLocalNoLinkageFinder(Sema & S,SourceRange SR)5612     UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
5613 
Visit(QualType T)5614     bool Visit(QualType T) {
5615       return T.isNull() ? false : inherited::Visit(T.getTypePtr());
5616     }
5617 
5618 #define TYPE(Class, Parent) \
5619     bool Visit##Class##Type(const Class##Type *);
5620 #define ABSTRACT_TYPE(Class, Parent) \
5621     bool Visit##Class##Type(const Class##Type *) { return false; }
5622 #define NON_CANONICAL_TYPE(Class, Parent) \
5623     bool Visit##Class##Type(const Class##Type *) { return false; }
5624 #include "clang/AST/TypeNodes.inc"
5625 
5626     bool VisitTagDecl(const TagDecl *Tag);
5627     bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
5628   };
5629 } // end anonymous namespace
5630 
VisitBuiltinType(const BuiltinType *)5631 bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
5632   return false;
5633 }
5634 
VisitComplexType(const ComplexType * T)5635 bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
5636   return Visit(T->getElementType());
5637 }
5638 
VisitPointerType(const PointerType * T)5639 bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
5640   return Visit(T->getPointeeType());
5641 }
5642 
VisitBlockPointerType(const BlockPointerType * T)5643 bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
5644                                                     const BlockPointerType* T) {
5645   return Visit(T->getPointeeType());
5646 }
5647 
VisitLValueReferenceType(const LValueReferenceType * T)5648 bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
5649                                                 const LValueReferenceType* T) {
5650   return Visit(T->getPointeeType());
5651 }
5652 
VisitRValueReferenceType(const RValueReferenceType * T)5653 bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
5654                                                 const RValueReferenceType* T) {
5655   return Visit(T->getPointeeType());
5656 }
5657 
VisitMemberPointerType(const MemberPointerType * T)5658 bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
5659                                                   const MemberPointerType* T) {
5660   return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
5661 }
5662 
VisitConstantArrayType(const ConstantArrayType * T)5663 bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
5664                                                   const ConstantArrayType* T) {
5665   return Visit(T->getElementType());
5666 }
5667 
VisitIncompleteArrayType(const IncompleteArrayType * T)5668 bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
5669                                                  const IncompleteArrayType* T) {
5670   return Visit(T->getElementType());
5671 }
5672 
VisitVariableArrayType(const VariableArrayType * T)5673 bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
5674                                                    const VariableArrayType* T) {
5675   return Visit(T->getElementType());
5676 }
5677 
VisitDependentSizedArrayType(const DependentSizedArrayType * T)5678 bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
5679                                             const DependentSizedArrayType* T) {
5680   return Visit(T->getElementType());
5681 }
5682 
VisitDependentSizedExtVectorType(const DependentSizedExtVectorType * T)5683 bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
5684                                          const DependentSizedExtVectorType* T) {
5685   return Visit(T->getElementType());
5686 }
5687 
VisitDependentSizedMatrixType(const DependentSizedMatrixType * T)5688 bool UnnamedLocalNoLinkageFinder::VisitDependentSizedMatrixType(
5689     const DependentSizedMatrixType *T) {
5690   return Visit(T->getElementType());
5691 }
5692 
VisitDependentAddressSpaceType(const DependentAddressSpaceType * T)5693 bool UnnamedLocalNoLinkageFinder::VisitDependentAddressSpaceType(
5694     const DependentAddressSpaceType *T) {
5695   return Visit(T->getPointeeType());
5696 }
5697 
VisitVectorType(const VectorType * T)5698 bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
5699   return Visit(T->getElementType());
5700 }
5701 
VisitDependentVectorType(const DependentVectorType * T)5702 bool UnnamedLocalNoLinkageFinder::VisitDependentVectorType(
5703     const DependentVectorType *T) {
5704   return Visit(T->getElementType());
5705 }
5706 
VisitExtVectorType(const ExtVectorType * T)5707 bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
5708   return Visit(T->getElementType());
5709 }
5710 
VisitConstantMatrixType(const ConstantMatrixType * T)5711 bool UnnamedLocalNoLinkageFinder::VisitConstantMatrixType(
5712     const ConstantMatrixType *T) {
5713   return Visit(T->getElementType());
5714 }
5715 
VisitFunctionProtoType(const FunctionProtoType * T)5716 bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
5717                                                   const FunctionProtoType* T) {
5718   for (const auto &A : T->param_types()) {
5719     if (Visit(A))
5720       return true;
5721   }
5722 
5723   return Visit(T->getReturnType());
5724 }
5725 
VisitFunctionNoProtoType(const FunctionNoProtoType * T)5726 bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
5727                                                const FunctionNoProtoType* T) {
5728   return Visit(T->getReturnType());
5729 }
5730 
VisitUnresolvedUsingType(const UnresolvedUsingType *)5731 bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
5732                                                   const UnresolvedUsingType*) {
5733   return false;
5734 }
5735 
VisitTypeOfExprType(const TypeOfExprType *)5736 bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
5737   return false;
5738 }
5739 
VisitTypeOfType(const TypeOfType * T)5740 bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
5741   return Visit(T->getUnmodifiedType());
5742 }
5743 
VisitDecltypeType(const DecltypeType *)5744 bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
5745   return false;
5746 }
5747 
VisitPackIndexingType(const PackIndexingType *)5748 bool UnnamedLocalNoLinkageFinder::VisitPackIndexingType(
5749     const PackIndexingType *) {
5750   return false;
5751 }
5752 
VisitUnaryTransformType(const UnaryTransformType *)5753 bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
5754                                                     const UnaryTransformType*) {
5755   return false;
5756 }
5757 
VisitAutoType(const AutoType * T)5758 bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
5759   return Visit(T->getDeducedType());
5760 }
5761 
VisitDeducedTemplateSpecializationType(const DeducedTemplateSpecializationType * T)5762 bool UnnamedLocalNoLinkageFinder::VisitDeducedTemplateSpecializationType(
5763     const DeducedTemplateSpecializationType *T) {
5764   return Visit(T->getDeducedType());
5765 }
5766 
VisitRecordType(const RecordType * T)5767 bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
5768   return VisitTagDecl(T->getDecl());
5769 }
5770 
VisitEnumType(const EnumType * T)5771 bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
5772   return VisitTagDecl(T->getDecl());
5773 }
5774 
VisitTemplateTypeParmType(const TemplateTypeParmType *)5775 bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
5776                                                  const TemplateTypeParmType*) {
5777   return false;
5778 }
5779 
VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *)5780 bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
5781                                         const SubstTemplateTypeParmPackType *) {
5782   return false;
5783 }
5784 
VisitTemplateSpecializationType(const TemplateSpecializationType *)5785 bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
5786                                             const TemplateSpecializationType*) {
5787   return false;
5788 }
5789 
VisitInjectedClassNameType(const InjectedClassNameType * T)5790 bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
5791                                               const InjectedClassNameType* T) {
5792   return VisitTagDecl(T->getDecl());
5793 }
5794 
VisitDependentNameType(const DependentNameType * T)5795 bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
5796                                                    const DependentNameType* T) {
5797   return VisitNestedNameSpecifier(T->getQualifier());
5798 }
5799 
VisitDependentTemplateSpecializationType(const DependentTemplateSpecializationType * T)5800 bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
5801                                  const DependentTemplateSpecializationType* T) {
5802   if (auto *Q = T->getQualifier())
5803     return VisitNestedNameSpecifier(Q);
5804   return false;
5805 }
5806 
VisitPackExpansionType(const PackExpansionType * T)5807 bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
5808                                                    const PackExpansionType* T) {
5809   return Visit(T->getPattern());
5810 }
5811 
VisitObjCObjectType(const ObjCObjectType *)5812 bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
5813   return false;
5814 }
5815 
VisitObjCInterfaceType(const ObjCInterfaceType *)5816 bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
5817                                                    const ObjCInterfaceType *) {
5818   return false;
5819 }
5820 
VisitObjCObjectPointerType(const ObjCObjectPointerType *)5821 bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
5822                                                 const ObjCObjectPointerType *) {
5823   return false;
5824 }
5825 
VisitAtomicType(const AtomicType * T)5826 bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
5827   return Visit(T->getValueType());
5828 }
5829 
VisitPipeType(const PipeType * T)5830 bool UnnamedLocalNoLinkageFinder::VisitPipeType(const PipeType* T) {
5831   return false;
5832 }
5833 
VisitBitIntType(const BitIntType * T)5834 bool UnnamedLocalNoLinkageFinder::VisitBitIntType(const BitIntType *T) {
5835   return false;
5836 }
5837 
VisitArrayParameterType(const ArrayParameterType * T)5838 bool UnnamedLocalNoLinkageFinder::VisitArrayParameterType(
5839     const ArrayParameterType *T) {
5840   return VisitConstantArrayType(T);
5841 }
5842 
VisitDependentBitIntType(const DependentBitIntType * T)5843 bool UnnamedLocalNoLinkageFinder::VisitDependentBitIntType(
5844     const DependentBitIntType *T) {
5845   return false;
5846 }
5847 
VisitTagDecl(const TagDecl * Tag)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;
5855     return true;
5856   }
5857 
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);
5864     return true;
5865   }
5866 
5867   return false;
5868 }
5869 
VisitNestedNameSpecifier(NestedNameSpecifier * NNS)5870 bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
5871                                                     NestedNameSpecifier *NNS) {
5872   assert(NNS);
5873   if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
5874     return true;
5875 
5876   switch (NNS->getKind()) {
5877   case NestedNameSpecifier::Identifier:
5878   case NestedNameSpecifier::Namespace:
5879   case NestedNameSpecifier::NamespaceAlias:
5880   case NestedNameSpecifier::Global:
5881   case NestedNameSpecifier::Super:
5882     return false;
5883 
5884   case NestedNameSpecifier::TypeSpec:
5885   case NestedNameSpecifier::TypeSpecWithTemplate:
5886     return Visit(QualType(NNS->getAsType(), 0));
5887   }
5888   llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
5889 }
5890 
CheckTemplateArgument(TypeSourceInfo * ArgInfo)5891 bool Sema::CheckTemplateArgument(TypeSourceInfo *ArgInfo) {
5892   assert(ArgInfo && "invalid TypeSourceInfo");
5893   QualType Arg = ArgInfo->getType();
5894   SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
5895   QualType CanonArg = Context.getCanonicalType(Arg);
5896 
5897   if (CanonArg->isVariablyModifiedType()) {
5898     return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
5899   } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
5900     return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
5901   }
5902 
5903   // C++03 [temp.arg.type]p2:
5904   //   A local type, a type with no linkage, an unnamed type or a type
5905   //   compounded from any of these types shall not be used as a
5906   //   template-argument for a template type-parameter.
5907   //
5908   // C++11 allows these, and even in C++03 we allow them as an extension with
5909   // a warning.
5910   if (LangOpts.CPlusPlus11 || CanonArg->hasUnnamedOrLocalType()) {
5911     UnnamedLocalNoLinkageFinder Finder(*this, SR);
5912     (void)Finder.Visit(CanonArg);
5913   }
5914 
5915   return false;
5916 }
5917 
5918 enum NullPointerValueKind {
5919   NPV_NotNullPointer,
5920   NPV_NullPointer,
5921   NPV_Error
5922 };
5923 
5924 /// Determine whether the given template argument is a null pointer
5925 /// value of the appropriate type.
5926 static NullPointerValueKind
isNullPointerValueTemplateArgument(Sema & S,NonTypeTemplateParmDecl * Param,QualType ParamType,Expr * Arg,Decl * Entity=nullptr)5927 isNullPointerValueTemplateArgument(Sema &S, NonTypeTemplateParmDecl *Param,
5928                                    QualType ParamType, Expr *Arg,
5929                                    Decl *Entity = nullptr) {
5930   if (Arg->isValueDependent() || Arg->isTypeDependent())
5931     return NPV_NotNullPointer;
5932 
5933   // dllimport'd entities aren't constant but are available inside of template
5934   // arguments.
5935   if (Entity && Entity->hasAttr<DLLImportAttr>())
5936     return NPV_NotNullPointer;
5937 
5938   if (!S.isCompleteType(Arg->getExprLoc(), ParamType))
5939     llvm_unreachable(
5940         "Incomplete parameter type in isNullPointerValueTemplateArgument!");
5941 
5942   if (!S.getLangOpts().CPlusPlus11)
5943     return NPV_NotNullPointer;
5944 
5945   // Determine whether we have a constant expression.
5946   ExprResult ArgRV = S.DefaultFunctionArrayConversion(Arg);
5947   if (ArgRV.isInvalid())
5948     return NPV_Error;
5949   Arg = ArgRV.get();
5950 
5951   Expr::EvalResult EvalResult;
5952   SmallVector<PartialDiagnosticAt, 8> Notes;
5953   EvalResult.Diag = &Notes;
5954   if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
5955       EvalResult.HasSideEffects) {
5956     SourceLocation DiagLoc = Arg->getExprLoc();
5957 
5958     // If our only note is the usual "invalid subexpression" note, just point
5959     // the caret at its location rather than producing an essentially
5960     // redundant note.
5961     if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
5962         diag::note_invalid_subexpr_in_const_expr) {
5963       DiagLoc = Notes[0].first;
5964       Notes.clear();
5965     }
5966 
5967     S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
5968       << Arg->getType() << Arg->getSourceRange();
5969     for (unsigned I = 0, N = Notes.size(); I != N; ++I)
5970       S.Diag(Notes[I].first, Notes[I].second);
5971 
5972     S.NoteTemplateParameterLocation(*Param);
5973     return NPV_Error;
5974   }
5975 
5976   // C++11 [temp.arg.nontype]p1:
5977   //   - an address constant expression of type std::nullptr_t
5978   if (Arg->getType()->isNullPtrType())
5979     return NPV_NullPointer;
5980 
5981   //   - a constant expression that evaluates to a null pointer value (4.10); or
5982   //   - a constant expression that evaluates to a null member pointer value
5983   //     (4.11); or
5984   if ((EvalResult.Val.isLValue() && EvalResult.Val.isNullPointer()) ||
5985       (EvalResult.Val.isMemberPointer() &&
5986        !EvalResult.Val.getMemberPointerDecl())) {
5987     // If our expression has an appropriate type, we've succeeded.
5988     bool ObjCLifetimeConversion;
5989     if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
5990         S.IsQualificationConversion(Arg->getType(), ParamType, false,
5991                                      ObjCLifetimeConversion))
5992       return NPV_NullPointer;
5993 
5994     // The types didn't match, but we know we got a null pointer; complain,
5995     // then recover as if the types were correct.
5996     S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
5997       << Arg->getType() << ParamType << Arg->getSourceRange();
5998     S.NoteTemplateParameterLocation(*Param);
5999     return NPV_NullPointer;
6000   }
6001 
6002   if (EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) {
6003     // We found a pointer that isn't null, but doesn't refer to an object.
6004     // We could just return NPV_NotNullPointer, but we can print a better
6005     // message with the information we have here.
6006     S.Diag(Arg->getExprLoc(), diag::err_template_arg_invalid)
6007       << EvalResult.Val.getAsString(S.Context, ParamType);
6008     S.NoteTemplateParameterLocation(*Param);
6009     return NPV_Error;
6010   }
6011 
6012   // If we don't have a null pointer value, but we do have a NULL pointer
6013   // constant, suggest a cast to the appropriate type.
6014   if (Arg->isNullPointerConstant(S.Context, Expr::NPC_NeverValueDependent)) {
6015     std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
6016     S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
6017         << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), Code)
6018         << FixItHint::CreateInsertion(S.getLocForEndOfToken(Arg->getEndLoc()),
6019                                       ")");
6020     S.NoteTemplateParameterLocation(*Param);
6021     return NPV_NullPointer;
6022   }
6023 
6024   // FIXME: If we ever want to support general, address-constant expressions
6025   // as non-type template arguments, we should return the ExprResult here to
6026   // be interpreted by the caller.
6027   return NPV_NotNullPointer;
6028 }
6029 
6030 /// Checks whether the given template argument is compatible with its
6031 /// template parameter.
CheckTemplateArgumentIsCompatibleWithParameter(Sema & S,NonTypeTemplateParmDecl * Param,QualType ParamType,Expr * ArgIn,Expr * Arg,QualType ArgType)6032 static bool CheckTemplateArgumentIsCompatibleWithParameter(
6033     Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
6034     Expr *Arg, QualType ArgType) {
6035   bool ObjCLifetimeConversion;
6036   if (ParamType->isPointerType() &&
6037       !ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType() &&
6038       S.IsQualificationConversion(ArgType, ParamType, false,
6039                                   ObjCLifetimeConversion)) {
6040     // For pointer-to-object types, qualification conversions are
6041     // permitted.
6042   } else {
6043     if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
6044       if (!ParamRef->getPointeeType()->isFunctionType()) {
6045         // C++ [temp.arg.nontype]p5b3:
6046         //   For a non-type template-parameter of type reference to
6047         //   object, no conversions apply. The type referred to by the
6048         //   reference may be more cv-qualified than the (otherwise
6049         //   identical) type of the template- argument. The
6050         //   template-parameter is bound directly to the
6051         //   template-argument, which shall be an lvalue.
6052 
6053         // FIXME: Other qualifiers?
6054         unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
6055         unsigned ArgQuals = ArgType.getCVRQualifiers();
6056 
6057         if ((ParamQuals | ArgQuals) != ParamQuals) {
6058           S.Diag(Arg->getBeginLoc(),
6059                  diag::err_template_arg_ref_bind_ignores_quals)
6060               << ParamType << Arg->getType() << Arg->getSourceRange();
6061           S.NoteTemplateParameterLocation(*Param);
6062           return true;
6063         }
6064       }
6065     }
6066 
6067     // At this point, the template argument refers to an object or
6068     // function with external linkage. We now need to check whether the
6069     // argument and parameter types are compatible.
6070     if (!S.Context.hasSameUnqualifiedType(ArgType,
6071                                           ParamType.getNonReferenceType())) {
6072       // We can't perform this conversion or binding.
6073       if (ParamType->isReferenceType())
6074         S.Diag(Arg->getBeginLoc(), diag::err_template_arg_no_ref_bind)
6075             << ParamType << ArgIn->getType() << Arg->getSourceRange();
6076       else
6077         S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_convertible)
6078             << ArgIn->getType() << ParamType << Arg->getSourceRange();
6079       S.NoteTemplateParameterLocation(*Param);
6080       return true;
6081     }
6082   }
6083 
6084   return false;
6085 }
6086 
6087 /// Checks whether the given template argument is the address
6088 /// of an object or function according to C++ [temp.arg.nontype]p1.
CheckTemplateArgumentAddressOfObjectOrFunction(Sema & S,NonTypeTemplateParmDecl * Param,QualType ParamType,Expr * ArgIn,TemplateArgument & SugaredConverted,TemplateArgument & CanonicalConverted)6089 static bool CheckTemplateArgumentAddressOfObjectOrFunction(
6090     Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
6091     TemplateArgument &SugaredConverted, TemplateArgument &CanonicalConverted) {
6092   bool Invalid = false;
6093   Expr *Arg = ArgIn;
6094   QualType ArgType = Arg->getType();
6095 
6096   bool AddressTaken = false;
6097   SourceLocation AddrOpLoc;
6098   if (S.getLangOpts().MicrosoftExt) {
6099     // Microsoft Visual C++ strips all casts, allows an arbitrary number of
6100     // dereference and address-of operators.
6101     Arg = Arg->IgnoreParenCasts();
6102 
6103     bool ExtWarnMSTemplateArg = false;
6104     UnaryOperatorKind FirstOpKind;
6105     SourceLocation FirstOpLoc;
6106     while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
6107       UnaryOperatorKind UnOpKind = UnOp->getOpcode();
6108       if (UnOpKind == UO_Deref)
6109         ExtWarnMSTemplateArg = true;
6110       if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
6111         Arg = UnOp->getSubExpr()->IgnoreParenCasts();
6112         if (!AddrOpLoc.isValid()) {
6113           FirstOpKind = UnOpKind;
6114           FirstOpLoc = UnOp->getOperatorLoc();
6115         }
6116       } else
6117         break;
6118     }
6119     if (FirstOpLoc.isValid()) {
6120       if (ExtWarnMSTemplateArg)
6121         S.Diag(ArgIn->getBeginLoc(), diag::ext_ms_deref_template_argument)
6122             << ArgIn->getSourceRange();
6123 
6124       if (FirstOpKind == UO_AddrOf)
6125         AddressTaken = true;
6126       else if (Arg->getType()->isPointerType()) {
6127         // We cannot let pointers get dereferenced here, that is obviously not a
6128         // constant expression.
6129         assert(FirstOpKind == UO_Deref);
6130         S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
6131             << Arg->getSourceRange();
6132       }
6133     }
6134   } else {
6135     // See through any implicit casts we added to fix the type.
6136     Arg = Arg->IgnoreImpCasts();
6137 
6138     // C++ [temp.arg.nontype]p1:
6139     //
6140     //   A template-argument for a non-type, non-template
6141     //   template-parameter shall be one of: [...]
6142     //
6143     //     -- the address of an object or function with external
6144     //        linkage, including function templates and function
6145     //        template-ids but excluding non-static class members,
6146     //        expressed as & id-expression where the & is optional if
6147     //        the name refers to a function or array, or if the
6148     //        corresponding template-parameter is a reference; or
6149 
6150     // In C++98/03 mode, give an extension warning on any extra parentheses.
6151     // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
6152     bool ExtraParens = false;
6153     while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
6154       if (!Invalid && !ExtraParens) {
6155         S.Diag(Arg->getBeginLoc(),
6156                S.getLangOpts().CPlusPlus11
6157                    ? diag::warn_cxx98_compat_template_arg_extra_parens
6158                    : diag::ext_template_arg_extra_parens)
6159             << Arg->getSourceRange();
6160         ExtraParens = true;
6161       }
6162 
6163       Arg = Parens->getSubExpr();
6164     }
6165 
6166     while (SubstNonTypeTemplateParmExpr *subst =
6167                dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
6168       Arg = subst->getReplacement()->IgnoreImpCasts();
6169 
6170     if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
6171       if (UnOp->getOpcode() == UO_AddrOf) {
6172         Arg = UnOp->getSubExpr();
6173         AddressTaken = true;
6174         AddrOpLoc = UnOp->getOperatorLoc();
6175       }
6176     }
6177 
6178     while (SubstNonTypeTemplateParmExpr *subst =
6179                dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
6180       Arg = subst->getReplacement()->IgnoreImpCasts();
6181   }
6182 
6183   ValueDecl *Entity = nullptr;
6184   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg))
6185     Entity = DRE->getDecl();
6186   else if (CXXUuidofExpr *CUE = dyn_cast<CXXUuidofExpr>(Arg))
6187     Entity = CUE->getGuidDecl();
6188 
6189   // If our parameter has pointer type, check for a null template value.
6190   if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
6191     switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn,
6192                                                Entity)) {
6193     case NPV_NullPointer:
6194       S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
6195       SugaredConverted = TemplateArgument(ParamType,
6196                                           /*isNullPtr=*/true);
6197       CanonicalConverted =
6198           TemplateArgument(S.Context.getCanonicalType(ParamType),
6199                            /*isNullPtr=*/true);
6200       return false;
6201 
6202     case NPV_Error:
6203       return true;
6204 
6205     case NPV_NotNullPointer:
6206       break;
6207     }
6208   }
6209 
6210   // Stop checking the precise nature of the argument if it is value dependent,
6211   // it should be checked when instantiated.
6212   if (Arg->isValueDependent()) {
6213     SugaredConverted = TemplateArgument(ArgIn);
6214     CanonicalConverted =
6215         S.Context.getCanonicalTemplateArgument(SugaredConverted);
6216     return false;
6217   }
6218 
6219   if (!Entity) {
6220     S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
6221         << Arg->getSourceRange();
6222     S.NoteTemplateParameterLocation(*Param);
6223     return true;
6224   }
6225 
6226   // Cannot refer to non-static data members
6227   if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) {
6228     S.Diag(Arg->getBeginLoc(), diag::err_template_arg_field)
6229         << Entity << Arg->getSourceRange();
6230     S.NoteTemplateParameterLocation(*Param);
6231     return true;
6232   }
6233 
6234   // Cannot refer to non-static member functions
6235   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
6236     if (!Method->isStatic()) {
6237       S.Diag(Arg->getBeginLoc(), diag::err_template_arg_method)
6238           << Method << Arg->getSourceRange();
6239       S.NoteTemplateParameterLocation(*Param);
6240       return true;
6241     }
6242   }
6243 
6244   FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
6245   VarDecl *Var = dyn_cast<VarDecl>(Entity);
6246   MSGuidDecl *Guid = dyn_cast<MSGuidDecl>(Entity);
6247 
6248   // A non-type template argument must refer to an object or function.
6249   if (!Func && !Var && !Guid) {
6250     // We found something, but we don't know specifically what it is.
6251     S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_object_or_func)
6252         << Arg->getSourceRange();
6253     S.Diag(Entity->getLocation(), diag::note_template_arg_refers_here);
6254     return true;
6255   }
6256 
6257   // Address / reference template args must have external linkage in C++98.
6258   if (Entity->getFormalLinkage() == Linkage::Internal) {
6259     S.Diag(Arg->getBeginLoc(),
6260            S.getLangOpts().CPlusPlus11
6261                ? diag::warn_cxx98_compat_template_arg_object_internal
6262                : diag::ext_template_arg_object_internal)
6263         << !Func << Entity << Arg->getSourceRange();
6264     S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
6265       << !Func;
6266   } else if (!Entity->hasLinkage()) {
6267     S.Diag(Arg->getBeginLoc(), diag::err_template_arg_object_no_linkage)
6268         << !Func << Entity << Arg->getSourceRange();
6269     S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
6270       << !Func;
6271     return true;
6272   }
6273 
6274   if (Var) {
6275     // A value of reference type is not an object.
6276     if (Var->getType()->isReferenceType()) {
6277       S.Diag(Arg->getBeginLoc(), diag::err_template_arg_reference_var)
6278           << Var->getType() << Arg->getSourceRange();
6279       S.NoteTemplateParameterLocation(*Param);
6280       return true;
6281     }
6282 
6283     // A template argument must have static storage duration.
6284     if (Var->getTLSKind()) {
6285       S.Diag(Arg->getBeginLoc(), diag::err_template_arg_thread_local)
6286           << Arg->getSourceRange();
6287       S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
6288       return true;
6289     }
6290   }
6291 
6292   if (AddressTaken && ParamType->isReferenceType()) {
6293     // If we originally had an address-of operator, but the
6294     // parameter has reference type, complain and (if things look
6295     // like they will work) drop the address-of operator.
6296     if (!S.Context.hasSameUnqualifiedType(Entity->getType(),
6297                                           ParamType.getNonReferenceType())) {
6298       S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
6299         << ParamType;
6300       S.NoteTemplateParameterLocation(*Param);
6301       return true;
6302     }
6303 
6304     S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
6305       << ParamType
6306       << FixItHint::CreateRemoval(AddrOpLoc);
6307     S.NoteTemplateParameterLocation(*Param);
6308 
6309     ArgType = Entity->getType();
6310   }
6311 
6312   // If the template parameter has pointer type, either we must have taken the
6313   // address or the argument must decay to a pointer.
6314   if (!AddressTaken && ParamType->isPointerType()) {
6315     if (Func) {
6316       // Function-to-pointer decay.
6317       ArgType = S.Context.getPointerType(Func->getType());
6318     } else if (Entity->getType()->isArrayType()) {
6319       // Array-to-pointer decay.
6320       ArgType = S.Context.getArrayDecayedType(Entity->getType());
6321     } else {
6322       // If the template parameter has pointer type but the address of
6323       // this object was not taken, complain and (possibly) recover by
6324       // taking the address of the entity.
6325       ArgType = S.Context.getPointerType(Entity->getType());
6326       if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
6327         S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of)
6328           << ParamType;
6329         S.NoteTemplateParameterLocation(*Param);
6330         return true;
6331       }
6332 
6333       S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of)
6334         << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), "&");
6335 
6336       S.NoteTemplateParameterLocation(*Param);
6337     }
6338   }
6339 
6340   if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
6341                                                      Arg, ArgType))
6342     return true;
6343 
6344   // Create the template argument.
6345   SugaredConverted = TemplateArgument(Entity, ParamType);
6346   CanonicalConverted =
6347       TemplateArgument(cast<ValueDecl>(Entity->getCanonicalDecl()),
6348                        S.Context.getCanonicalType(ParamType));
6349   S.MarkAnyDeclReferenced(Arg->getBeginLoc(), Entity, false);
6350   return false;
6351 }
6352 
6353 /// Checks whether the given template argument is a pointer to
6354 /// member constant according to C++ [temp.arg.nontype]p1.
6355 static bool
CheckTemplateArgumentPointerToMember(Sema & S,NonTypeTemplateParmDecl * Param,QualType ParamType,Expr * & ResultArg,TemplateArgument & SugaredConverted,TemplateArgument & CanonicalConverted)6356 CheckTemplateArgumentPointerToMember(Sema &S, NonTypeTemplateParmDecl *Param,
6357                                      QualType ParamType, Expr *&ResultArg,
6358                                      TemplateArgument &SugaredConverted,
6359                                      TemplateArgument &CanonicalConverted) {
6360   bool Invalid = false;
6361 
6362   Expr *Arg = ResultArg;
6363   bool ObjCLifetimeConversion;
6364 
6365   // C++ [temp.arg.nontype]p1:
6366   //
6367   //   A template-argument for a non-type, non-template
6368   //   template-parameter shall be one of: [...]
6369   //
6370   //     -- a pointer to member expressed as described in 5.3.1.
6371   DeclRefExpr *DRE = nullptr;
6372 
6373   // In C++98/03 mode, give an extension warning on any extra parentheses.
6374   // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
6375   bool ExtraParens = false;
6376   while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
6377     if (!Invalid && !ExtraParens) {
6378       S.Diag(Arg->getBeginLoc(),
6379              S.getLangOpts().CPlusPlus11
6380                  ? diag::warn_cxx98_compat_template_arg_extra_parens
6381                  : diag::ext_template_arg_extra_parens)
6382           << Arg->getSourceRange();
6383       ExtraParens = true;
6384     }
6385 
6386     Arg = Parens->getSubExpr();
6387   }
6388 
6389   while (SubstNonTypeTemplateParmExpr *subst =
6390            dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
6391     Arg = subst->getReplacement()->IgnoreImpCasts();
6392 
6393   // A pointer-to-member constant written &Class::member.
6394   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
6395     if (UnOp->getOpcode() == UO_AddrOf) {
6396       DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
6397       if (DRE && !DRE->getQualifier())
6398         DRE = nullptr;
6399     }
6400   }
6401   // A constant of pointer-to-member type.
6402   else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
6403     ValueDecl *VD = DRE->getDecl();
6404     if (VD->getType()->isMemberPointerType()) {
6405       if (isa<NonTypeTemplateParmDecl>(VD)) {
6406         if (Arg->isTypeDependent() || Arg->isValueDependent()) {
6407           SugaredConverted = TemplateArgument(Arg);
6408           CanonicalConverted =
6409               S.Context.getCanonicalTemplateArgument(SugaredConverted);
6410         } else {
6411           SugaredConverted = TemplateArgument(VD, ParamType);
6412           CanonicalConverted =
6413               TemplateArgument(cast<ValueDecl>(VD->getCanonicalDecl()),
6414                                S.Context.getCanonicalType(ParamType));
6415         }
6416         return Invalid;
6417       }
6418     }
6419 
6420     DRE = nullptr;
6421   }
6422 
6423   ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
6424 
6425   // Check for a null pointer value.
6426   switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ResultArg,
6427                                              Entity)) {
6428   case NPV_Error:
6429     return true;
6430   case NPV_NullPointer:
6431     S.Diag(ResultArg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
6432     SugaredConverted = TemplateArgument(ParamType,
6433                                         /*isNullPtr*/ true);
6434     CanonicalConverted = TemplateArgument(S.Context.getCanonicalType(ParamType),
6435                                           /*isNullPtr*/ true);
6436     return false;
6437   case NPV_NotNullPointer:
6438     break;
6439   }
6440 
6441   if (S.IsQualificationConversion(ResultArg->getType(),
6442                                   ParamType.getNonReferenceType(), false,
6443                                   ObjCLifetimeConversion)) {
6444     ResultArg = S.ImpCastExprToType(ResultArg, ParamType, CK_NoOp,
6445                                     ResultArg->getValueKind())
6446                     .get();
6447   } else if (!S.Context.hasSameUnqualifiedType(
6448                  ResultArg->getType(), ParamType.getNonReferenceType())) {
6449     // We can't perform this conversion.
6450     S.Diag(ResultArg->getBeginLoc(), diag::err_template_arg_not_convertible)
6451         << ResultArg->getType() << ParamType << ResultArg->getSourceRange();
6452     S.NoteTemplateParameterLocation(*Param);
6453     return true;
6454   }
6455 
6456   if (!DRE)
6457     return S.Diag(Arg->getBeginLoc(),
6458                   diag::err_template_arg_not_pointer_to_member_form)
6459            << Arg->getSourceRange();
6460 
6461   if (isa<FieldDecl>(DRE->getDecl()) ||
6462       isa<IndirectFieldDecl>(DRE->getDecl()) ||
6463       isa<CXXMethodDecl>(DRE->getDecl())) {
6464     assert((isa<FieldDecl>(DRE->getDecl()) ||
6465             isa<IndirectFieldDecl>(DRE->getDecl()) ||
6466             cast<CXXMethodDecl>(DRE->getDecl())
6467                 ->isImplicitObjectMemberFunction()) &&
6468            "Only non-static member pointers can make it here");
6469 
6470     // Okay: this is the address of a non-static member, and therefore
6471     // a member pointer constant.
6472     if (Arg->isTypeDependent() || Arg->isValueDependent()) {
6473       SugaredConverted = TemplateArgument(Arg);
6474       CanonicalConverted =
6475           S.Context.getCanonicalTemplateArgument(SugaredConverted);
6476     } else {
6477       ValueDecl *D = DRE->getDecl();
6478       SugaredConverted = TemplateArgument(D, ParamType);
6479       CanonicalConverted =
6480           TemplateArgument(cast<ValueDecl>(D->getCanonicalDecl()),
6481                            S.Context.getCanonicalType(ParamType));
6482     }
6483     return Invalid;
6484   }
6485 
6486   // We found something else, but we don't know specifically what it is.
6487   S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_pointer_to_member_form)
6488       << Arg->getSourceRange();
6489   S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
6490   return true;
6491 }
6492 
CheckTemplateArgument(NonTypeTemplateParmDecl * Param,QualType ParamType,Expr * Arg,TemplateArgument & SugaredConverted,TemplateArgument & CanonicalConverted,CheckTemplateArgumentKind CTAK)6493 ExprResult Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
6494                                        QualType ParamType, Expr *Arg,
6495                                        TemplateArgument &SugaredConverted,
6496                                        TemplateArgument &CanonicalConverted,
6497                                        CheckTemplateArgumentKind CTAK) {
6498   SourceLocation StartLoc = Arg->getBeginLoc();
6499 
6500   // If the parameter type somehow involves auto, deduce the type now.
6501   DeducedType *DeducedT = ParamType->getContainedDeducedType();
6502   if (getLangOpts().CPlusPlus17 && DeducedT && !DeducedT->isDeduced()) {
6503     // During template argument deduction, we allow 'decltype(auto)' to
6504     // match an arbitrary dependent argument.
6505     // FIXME: The language rules don't say what happens in this case.
6506     // FIXME: We get an opaque dependent type out of decltype(auto) if the
6507     // expression is merely instantiation-dependent; is this enough?
6508     if (Arg->isTypeDependent()) {
6509       auto *AT = dyn_cast<AutoType>(DeducedT);
6510       if (AT && AT->isDecltypeAuto()) {
6511         SugaredConverted = TemplateArgument(Arg);
6512         CanonicalConverted = TemplateArgument(
6513             Context.getCanonicalTemplateArgument(SugaredConverted));
6514         return Arg;
6515       }
6516     }
6517 
6518     // When checking a deduced template argument, deduce from its type even if
6519     // the type is dependent, in order to check the types of non-type template
6520     // arguments line up properly in partial ordering.
6521     Expr *DeductionArg = Arg;
6522     if (auto *PE = dyn_cast<PackExpansionExpr>(DeductionArg))
6523       DeductionArg = PE->getPattern();
6524     TypeSourceInfo *TSI =
6525         Context.getTrivialTypeSourceInfo(ParamType, Param->getLocation());
6526     if (isa<DeducedTemplateSpecializationType>(DeducedT)) {
6527       InitializedEntity Entity =
6528           InitializedEntity::InitializeTemplateParameter(ParamType, Param);
6529       InitializationKind Kind = InitializationKind::CreateForInit(
6530           DeductionArg->getBeginLoc(), /*DirectInit*/false, DeductionArg);
6531       Expr *Inits[1] = {DeductionArg};
6532       ParamType =
6533           DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind, Inits);
6534       if (ParamType.isNull())
6535         return ExprError();
6536     } else {
6537       TemplateDeductionInfo Info(DeductionArg->getExprLoc(),
6538                                  Param->getDepth() + 1);
6539       ParamType = QualType();
6540       TemplateDeductionResult Result =
6541           DeduceAutoType(TSI->getTypeLoc(), DeductionArg, ParamType, Info,
6542                          /*DependentDeduction=*/true,
6543                          // We do not check constraints right now because the
6544                          // immediately-declared constraint of the auto type is
6545                          // also an associated constraint, and will be checked
6546                          // along with the other associated constraints after
6547                          // checking the template argument list.
6548                          /*IgnoreConstraints=*/true);
6549       if (Result == TemplateDeductionResult::AlreadyDiagnosed) {
6550         if (ParamType.isNull())
6551           return ExprError();
6552       } else if (Result != TemplateDeductionResult::Success) {
6553         Diag(Arg->getExprLoc(),
6554              diag::err_non_type_template_parm_type_deduction_failure)
6555             << Param->getDeclName() << Param->getType() << Arg->getType()
6556             << Arg->getSourceRange();
6557         NoteTemplateParameterLocation(*Param);
6558         return ExprError();
6559       }
6560     }
6561     // CheckNonTypeTemplateParameterType will produce a diagnostic if there's
6562     // an error. The error message normally references the parameter
6563     // declaration, but here we'll pass the argument location because that's
6564     // where the parameter type is deduced.
6565     ParamType = CheckNonTypeTemplateParameterType(ParamType, Arg->getExprLoc());
6566     if (ParamType.isNull()) {
6567       NoteTemplateParameterLocation(*Param);
6568       return ExprError();
6569     }
6570   }
6571 
6572   // We should have already dropped all cv-qualifiers by now.
6573   assert(!ParamType.hasQualifiers() &&
6574          "non-type template parameter type cannot be qualified");
6575 
6576   // FIXME: When Param is a reference, should we check that Arg is an lvalue?
6577   if (CTAK == CTAK_Deduced &&
6578       (ParamType->isReferenceType()
6579            ? !Context.hasSameType(ParamType.getNonReferenceType(),
6580                                   Arg->getType())
6581            : !Context.hasSameUnqualifiedType(ParamType, Arg->getType()))) {
6582     // FIXME: If either type is dependent, we skip the check. This isn't
6583     // correct, since during deduction we're supposed to have replaced each
6584     // template parameter with some unique (non-dependent) placeholder.
6585     // FIXME: If the argument type contains 'auto', we carry on and fail the
6586     // type check in order to force specific types to be more specialized than
6587     // 'auto'. It's not clear how partial ordering with 'auto' is supposed to
6588     // work. Similarly for CTAD, when comparing 'A<x>' against 'A'.
6589     if ((ParamType->isDependentType() || Arg->isTypeDependent()) &&
6590         !Arg->getType()->getContainedDeducedType()) {
6591       SugaredConverted = TemplateArgument(Arg);
6592       CanonicalConverted = TemplateArgument(
6593           Context.getCanonicalTemplateArgument(SugaredConverted));
6594       return Arg;
6595     }
6596     // FIXME: This attempts to implement C++ [temp.deduct.type]p17. Per DR1770,
6597     // we should actually be checking the type of the template argument in P,
6598     // not the type of the template argument deduced from A, against the
6599     // template parameter type.
6600     Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
6601       << Arg->getType()
6602       << ParamType.getUnqualifiedType();
6603     NoteTemplateParameterLocation(*Param);
6604     return ExprError();
6605   }
6606 
6607   // If either the parameter has a dependent type or the argument is
6608   // type-dependent, there's nothing we can check now.
6609   if (ParamType->isDependentType() || Arg->isTypeDependent()) {
6610     // Force the argument to the type of the parameter to maintain invariants.
6611     auto *PE = dyn_cast<PackExpansionExpr>(Arg);
6612     if (PE)
6613       Arg = PE->getPattern();
6614     ExprResult E = ImpCastExprToType(
6615         Arg, ParamType.getNonLValueExprType(Context), CK_Dependent,
6616         ParamType->isLValueReferenceType()   ? VK_LValue
6617         : ParamType->isRValueReferenceType() ? VK_XValue
6618                                              : VK_PRValue);
6619     if (E.isInvalid())
6620       return ExprError();
6621     if (PE) {
6622       // Recreate a pack expansion if we unwrapped one.
6623       E = new (Context)
6624           PackExpansionExpr(E.get()->getType(), E.get(), PE->getEllipsisLoc(),
6625                             PE->getNumExpansions());
6626     }
6627     SugaredConverted = TemplateArgument(E.get());
6628     CanonicalConverted = TemplateArgument(
6629         Context.getCanonicalTemplateArgument(SugaredConverted));
6630     return E;
6631   }
6632 
6633   QualType CanonParamType = Context.getCanonicalType(ParamType);
6634   // Avoid making a copy when initializing a template parameter of class type
6635   // from a template parameter object of the same type. This is going beyond
6636   // the standard, but is required for soundness: in
6637   //   template<A a> struct X { X *p; X<a> *q; };
6638   // ... we need p and q to have the same type.
6639   //
6640   // Similarly, don't inject a call to a copy constructor when initializing
6641   // from a template parameter of the same type.
6642   Expr *InnerArg = Arg->IgnoreParenImpCasts();
6643   if (ParamType->isRecordType() && isa<DeclRefExpr>(InnerArg) &&
6644       Context.hasSameUnqualifiedType(ParamType, InnerArg->getType())) {
6645     NamedDecl *ND = cast<DeclRefExpr>(InnerArg)->getDecl();
6646     if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(ND)) {
6647 
6648       SugaredConverted = TemplateArgument(TPO, ParamType);
6649       CanonicalConverted =
6650           TemplateArgument(TPO->getCanonicalDecl(), CanonParamType);
6651       return Arg;
6652     }
6653     if (isa<NonTypeTemplateParmDecl>(ND)) {
6654       SugaredConverted = TemplateArgument(Arg);
6655       CanonicalConverted =
6656           Context.getCanonicalTemplateArgument(SugaredConverted);
6657       return Arg;
6658     }
6659   }
6660 
6661   // The initialization of the parameter from the argument is
6662   // a constant-evaluated context.
6663   EnterExpressionEvaluationContext ConstantEvaluated(
6664       *this, Sema::ExpressionEvaluationContext::ConstantEvaluated);
6665 
6666   bool IsConvertedConstantExpression = true;
6667   if (isa<InitListExpr>(Arg) || ParamType->isRecordType()) {
6668     InitializationKind Kind = InitializationKind::CreateForInit(
6669         Arg->getBeginLoc(), /*DirectInit=*/false, Arg);
6670     Expr *Inits[1] = {Arg};
6671     InitializedEntity Entity =
6672         InitializedEntity::InitializeTemplateParameter(ParamType, Param);
6673     InitializationSequence InitSeq(*this, Entity, Kind, Inits);
6674     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Inits);
6675     if (Result.isInvalid() || !Result.get())
6676       return ExprError();
6677     Result = ActOnConstantExpression(Result.get());
6678     if (Result.isInvalid() || !Result.get())
6679       return ExprError();
6680     Arg = ActOnFinishFullExpr(Result.get(), Arg->getBeginLoc(),
6681                               /*DiscardedValue=*/false,
6682                               /*IsConstexpr=*/true, /*IsTemplateArgument=*/true)
6683               .get();
6684     IsConvertedConstantExpression = false;
6685   }
6686 
6687   if (getLangOpts().CPlusPlus17) {
6688     // C++17 [temp.arg.nontype]p1:
6689     //   A template-argument for a non-type template parameter shall be
6690     //   a converted constant expression of the type of the template-parameter.
6691     APValue Value;
6692     ExprResult ArgResult;
6693     if (IsConvertedConstantExpression) {
6694       ArgResult = BuildConvertedConstantExpression(Arg, ParamType,
6695                                                    CCEK_TemplateArg, Param);
6696       if (ArgResult.isInvalid())
6697         return ExprError();
6698     } else {
6699       ArgResult = Arg;
6700     }
6701 
6702     // For a value-dependent argument, CheckConvertedConstantExpression is
6703     // permitted (and expected) to be unable to determine a value.
6704     if (ArgResult.get()->isValueDependent()) {
6705       SugaredConverted = TemplateArgument(ArgResult.get());
6706       CanonicalConverted =
6707           Context.getCanonicalTemplateArgument(SugaredConverted);
6708       return ArgResult;
6709     }
6710 
6711     APValue PreNarrowingValue;
6712     ArgResult = EvaluateConvertedConstantExpression(
6713         ArgResult.get(), ParamType, Value, CCEK_TemplateArg, /*RequireInt=*/
6714         false, PreNarrowingValue);
6715     if (ArgResult.isInvalid())
6716       return ExprError();
6717 
6718     if (Value.isLValue()) {
6719       APValue::LValueBase Base = Value.getLValueBase();
6720       auto *VD = const_cast<ValueDecl *>(Base.dyn_cast<const ValueDecl *>());
6721       //   For a non-type template-parameter of pointer or reference type,
6722       //   the value of the constant expression shall not refer to
6723       assert(ParamType->isPointerType() || ParamType->isReferenceType() ||
6724              ParamType->isNullPtrType());
6725       // -- a temporary object
6726       // -- a string literal
6727       // -- the result of a typeid expression, or
6728       // -- a predefined __func__ variable
6729       if (Base &&
6730           (!VD ||
6731            isa<LifetimeExtendedTemporaryDecl, UnnamedGlobalConstantDecl>(VD))) {
6732         Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
6733             << Arg->getSourceRange();
6734         return ExprError();
6735       }
6736 
6737       if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 && VD &&
6738           VD->getType()->isArrayType() &&
6739           Value.getLValuePath()[0].getAsArrayIndex() == 0 &&
6740           !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
6741         SugaredConverted = TemplateArgument(VD, ParamType);
6742         CanonicalConverted = TemplateArgument(
6743             cast<ValueDecl>(VD->getCanonicalDecl()), CanonParamType);
6744         return ArgResult.get();
6745       }
6746 
6747       // -- a subobject [until C++20]
6748       if (!getLangOpts().CPlusPlus20) {
6749         if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
6750             Value.isLValueOnePastTheEnd()) {
6751           Diag(StartLoc, diag::err_non_type_template_arg_subobject)
6752               << Value.getAsString(Context, ParamType);
6753           return ExprError();
6754         }
6755         assert((VD || !ParamType->isReferenceType()) &&
6756                "null reference should not be a constant expression");
6757         assert((!VD || !ParamType->isNullPtrType()) &&
6758                "non-null value of type nullptr_t?");
6759       }
6760     }
6761 
6762     if (Value.isAddrLabelDiff())
6763       return Diag(StartLoc, diag::err_non_type_template_arg_addr_label_diff);
6764 
6765     SugaredConverted = TemplateArgument(Context, ParamType, Value);
6766     CanonicalConverted = TemplateArgument(Context, CanonParamType, Value);
6767     return ArgResult.get();
6768   }
6769 
6770   // C++ [temp.arg.nontype]p5:
6771   //   The following conversions are performed on each expression used
6772   //   as a non-type template-argument. If a non-type
6773   //   template-argument cannot be converted to the type of the
6774   //   corresponding template-parameter then the program is
6775   //   ill-formed.
6776   if (ParamType->isIntegralOrEnumerationType()) {
6777     // C++11:
6778     //   -- for a non-type template-parameter of integral or
6779     //      enumeration type, conversions permitted in a converted
6780     //      constant expression are applied.
6781     //
6782     // C++98:
6783     //   -- for a non-type template-parameter of integral or
6784     //      enumeration type, integral promotions (4.5) and integral
6785     //      conversions (4.7) are applied.
6786 
6787     if (getLangOpts().CPlusPlus11) {
6788       // C++ [temp.arg.nontype]p1:
6789       //   A template-argument for a non-type, non-template template-parameter
6790       //   shall be one of:
6791       //
6792       //     -- for a non-type template-parameter of integral or enumeration
6793       //        type, a converted constant expression of the type of the
6794       //        template-parameter; or
6795       llvm::APSInt Value;
6796       ExprResult ArgResult =
6797         CheckConvertedConstantExpression(Arg, ParamType, Value,
6798                                          CCEK_TemplateArg);
6799       if (ArgResult.isInvalid())
6800         return ExprError();
6801 
6802       // We can't check arbitrary value-dependent arguments.
6803       if (ArgResult.get()->isValueDependent()) {
6804         SugaredConverted = TemplateArgument(ArgResult.get());
6805         CanonicalConverted =
6806             Context.getCanonicalTemplateArgument(SugaredConverted);
6807         return ArgResult;
6808       }
6809 
6810       // Widen the argument value to sizeof(parameter type). This is almost
6811       // always a no-op, except when the parameter type is bool. In
6812       // that case, this may extend the argument from 1 bit to 8 bits.
6813       QualType IntegerType = ParamType;
6814       if (const EnumType *Enum = IntegerType->getAs<EnumType>())
6815         IntegerType = Enum->getDecl()->getIntegerType();
6816       Value = Value.extOrTrunc(IntegerType->isBitIntType()
6817                                    ? Context.getIntWidth(IntegerType)
6818                                    : Context.getTypeSize(IntegerType));
6819 
6820       SugaredConverted = TemplateArgument(Context, Value, ParamType);
6821       CanonicalConverted =
6822           TemplateArgument(Context, Value, Context.getCanonicalType(ParamType));
6823       return ArgResult;
6824     }
6825 
6826     ExprResult ArgResult = DefaultLvalueConversion(Arg);
6827     if (ArgResult.isInvalid())
6828       return ExprError();
6829     Arg = ArgResult.get();
6830 
6831     QualType ArgType = Arg->getType();
6832 
6833     // C++ [temp.arg.nontype]p1:
6834     //   A template-argument for a non-type, non-template
6835     //   template-parameter shall be one of:
6836     //
6837     //     -- an integral constant-expression of integral or enumeration
6838     //        type; or
6839     //     -- the name of a non-type template-parameter; or
6840     llvm::APSInt Value;
6841     if (!ArgType->isIntegralOrEnumerationType()) {
6842       Diag(Arg->getBeginLoc(), diag::err_template_arg_not_integral_or_enumeral)
6843           << ArgType << Arg->getSourceRange();
6844       NoteTemplateParameterLocation(*Param);
6845       return ExprError();
6846     } else if (!Arg->isValueDependent()) {
6847       class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
6848         QualType T;
6849 
6850       public:
6851         TmplArgICEDiagnoser(QualType T) : T(T) { }
6852 
6853         SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
6854                                              SourceLocation Loc) override {
6855           return S.Diag(Loc, diag::err_template_arg_not_ice) << T;
6856         }
6857       } Diagnoser(ArgType);
6858 
6859       Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser).get();
6860       if (!Arg)
6861         return ExprError();
6862     }
6863 
6864     // From here on out, all we care about is the unqualified form
6865     // of the argument type.
6866     ArgType = ArgType.getUnqualifiedType();
6867 
6868     // Try to convert the argument to the parameter's type.
6869     if (Context.hasSameType(ParamType, ArgType)) {
6870       // Okay: no conversion necessary
6871     } else if (ParamType->isBooleanType()) {
6872       // This is an integral-to-boolean conversion.
6873       Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).get();
6874     } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
6875                !ParamType->isEnumeralType()) {
6876       // This is an integral promotion or conversion.
6877       Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).get();
6878     } else {
6879       // We can't perform this conversion.
6880       Diag(Arg->getBeginLoc(), diag::err_template_arg_not_convertible)
6881           << Arg->getType() << ParamType << Arg->getSourceRange();
6882       NoteTemplateParameterLocation(*Param);
6883       return ExprError();
6884     }
6885 
6886     // Add the value of this argument to the list of converted
6887     // arguments. We use the bitwidth and signedness of the template
6888     // parameter.
6889     if (Arg->isValueDependent()) {
6890       // The argument is value-dependent. Create a new
6891       // TemplateArgument with the converted expression.
6892       SugaredConverted = TemplateArgument(Arg);
6893       CanonicalConverted =
6894           Context.getCanonicalTemplateArgument(SugaredConverted);
6895       return Arg;
6896     }
6897 
6898     QualType IntegerType = ParamType;
6899     if (const EnumType *Enum = IntegerType->getAs<EnumType>()) {
6900       IntegerType = Enum->getDecl()->getIntegerType();
6901     }
6902 
6903     if (ParamType->isBooleanType()) {
6904       // Value must be zero or one.
6905       Value = Value != 0;
6906       unsigned AllowedBits = Context.getTypeSize(IntegerType);
6907       if (Value.getBitWidth() != AllowedBits)
6908         Value = Value.extOrTrunc(AllowedBits);
6909       Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
6910     } else {
6911       llvm::APSInt OldValue = Value;
6912 
6913       // Coerce the template argument's value to the value it will have
6914       // based on the template parameter's type.
6915       unsigned AllowedBits = IntegerType->isBitIntType()
6916                                  ? Context.getIntWidth(IntegerType)
6917                                  : Context.getTypeSize(IntegerType);
6918       if (Value.getBitWidth() != AllowedBits)
6919         Value = Value.extOrTrunc(AllowedBits);
6920       Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
6921 
6922       // Complain if an unsigned parameter received a negative value.
6923       if (IntegerType->isUnsignedIntegerOrEnumerationType() &&
6924           (OldValue.isSigned() && OldValue.isNegative())) {
6925         Diag(Arg->getBeginLoc(), diag::warn_template_arg_negative)
6926             << toString(OldValue, 10) << toString(Value, 10) << Param->getType()
6927             << Arg->getSourceRange();
6928         NoteTemplateParameterLocation(*Param);
6929       }
6930 
6931       // Complain if we overflowed the template parameter's type.
6932       unsigned RequiredBits;
6933       if (IntegerType->isUnsignedIntegerOrEnumerationType())
6934         RequiredBits = OldValue.getActiveBits();
6935       else if (OldValue.isUnsigned())
6936         RequiredBits = OldValue.getActiveBits() + 1;
6937       else
6938         RequiredBits = OldValue.getSignificantBits();
6939       if (RequiredBits > AllowedBits) {
6940         Diag(Arg->getBeginLoc(), diag::warn_template_arg_too_large)
6941             << toString(OldValue, 10) << toString(Value, 10) << Param->getType()
6942             << Arg->getSourceRange();
6943         NoteTemplateParameterLocation(*Param);
6944       }
6945     }
6946 
6947     QualType T = ParamType->isEnumeralType() ? ParamType : IntegerType;
6948     SugaredConverted = TemplateArgument(Context, Value, T);
6949     CanonicalConverted =
6950         TemplateArgument(Context, Value, Context.getCanonicalType(T));
6951     return Arg;
6952   }
6953 
6954   QualType ArgType = Arg->getType();
6955   DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
6956 
6957   // Handle pointer-to-function, reference-to-function, and
6958   // pointer-to-member-function all in (roughly) the same way.
6959   if (// -- For a non-type template-parameter of type pointer to
6960       //    function, only the function-to-pointer conversion (4.3) is
6961       //    applied. If the template-argument represents a set of
6962       //    overloaded functions (or a pointer to such), the matching
6963       //    function is selected from the set (13.4).
6964       (ParamType->isPointerType() &&
6965        ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType()) ||
6966       // -- For a non-type template-parameter of type reference to
6967       //    function, no conversions apply. If the template-argument
6968       //    represents a set of overloaded functions, the matching
6969       //    function is selected from the set (13.4).
6970       (ParamType->isReferenceType() &&
6971        ParamType->castAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
6972       // -- For a non-type template-parameter of type pointer to
6973       //    member function, no conversions apply. If the
6974       //    template-argument represents a set of overloaded member
6975       //    functions, the matching member function is selected from
6976       //    the set (13.4).
6977       (ParamType->isMemberPointerType() &&
6978        ParamType->castAs<MemberPointerType>()->getPointeeType()
6979          ->isFunctionType())) {
6980 
6981     if (Arg->getType() == Context.OverloadTy) {
6982       if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
6983                                                                 true,
6984                                                                 FoundResult)) {
6985         if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc()))
6986           return ExprError();
6987 
6988         ExprResult Res = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
6989         if (Res.isInvalid())
6990           return ExprError();
6991         Arg = Res.get();
6992         ArgType = Arg->getType();
6993       } else
6994         return ExprError();
6995     }
6996 
6997     if (!ParamType->isMemberPointerType()) {
6998       if (CheckTemplateArgumentAddressOfObjectOrFunction(
6999               *this, Param, ParamType, Arg, SugaredConverted,
7000               CanonicalConverted))
7001         return ExprError();
7002       return Arg;
7003     }
7004 
7005     if (CheckTemplateArgumentPointerToMember(
7006             *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
7007       return ExprError();
7008     return Arg;
7009   }
7010 
7011   if (ParamType->isPointerType()) {
7012     //   -- for a non-type template-parameter of type pointer to
7013     //      object, qualification conversions (4.4) and the
7014     //      array-to-pointer conversion (4.2) are applied.
7015     // C++0x also allows a value of std::nullptr_t.
7016     assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
7017            "Only object pointers allowed here");
7018 
7019     if (CheckTemplateArgumentAddressOfObjectOrFunction(
7020             *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
7021       return ExprError();
7022     return Arg;
7023   }
7024 
7025   if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
7026     //   -- For a non-type template-parameter of type reference to
7027     //      object, no conversions apply. The type referred to by the
7028     //      reference may be more cv-qualified than the (otherwise
7029     //      identical) type of the template-argument. The
7030     //      template-parameter is bound directly to the
7031     //      template-argument, which must be an lvalue.
7032     assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
7033            "Only object references allowed here");
7034 
7035     if (Arg->getType() == Context.OverloadTy) {
7036       if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
7037                                                  ParamRefType->getPointeeType(),
7038                                                                 true,
7039                                                                 FoundResult)) {
7040         if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc()))
7041           return ExprError();
7042         ExprResult Res = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
7043         if (Res.isInvalid())
7044           return ExprError();
7045         Arg = Res.get();
7046         ArgType = Arg->getType();
7047       } else
7048         return ExprError();
7049     }
7050 
7051     if (CheckTemplateArgumentAddressOfObjectOrFunction(
7052             *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
7053       return ExprError();
7054     return Arg;
7055   }
7056 
7057   // Deal with parameters of type std::nullptr_t.
7058   if (ParamType->isNullPtrType()) {
7059     if (Arg->isTypeDependent() || Arg->isValueDependent()) {
7060       SugaredConverted = TemplateArgument(Arg);
7061       CanonicalConverted =
7062           Context.getCanonicalTemplateArgument(SugaredConverted);
7063       return Arg;
7064     }
7065 
7066     switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) {
7067     case NPV_NotNullPointer:
7068       Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
7069         << Arg->getType() << ParamType;
7070       NoteTemplateParameterLocation(*Param);
7071       return ExprError();
7072 
7073     case NPV_Error:
7074       return ExprError();
7075 
7076     case NPV_NullPointer:
7077       Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
7078       SugaredConverted = TemplateArgument(ParamType,
7079                                           /*isNullPtr=*/true);
7080       CanonicalConverted = TemplateArgument(Context.getCanonicalType(ParamType),
7081                                             /*isNullPtr=*/true);
7082       return Arg;
7083     }
7084   }
7085 
7086   //     -- For a non-type template-parameter of type pointer to data
7087   //        member, qualification conversions (4.4) are applied.
7088   assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
7089 
7090   if (CheckTemplateArgumentPointerToMember(
7091           *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
7092     return ExprError();
7093   return Arg;
7094 }
7095 
7096 static void DiagnoseTemplateParameterListArityMismatch(
7097     Sema &S, TemplateParameterList *New, TemplateParameterList *Old,
7098     Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc);
7099 
CheckTemplateTemplateArgument(TemplateTemplateParmDecl * Param,TemplateParameterList * Params,TemplateArgumentLoc & Arg,bool IsDeduced)7100 bool Sema::CheckTemplateTemplateArgument(TemplateTemplateParmDecl *Param,
7101                                          TemplateParameterList *Params,
7102                                          TemplateArgumentLoc &Arg,
7103                                          bool IsDeduced) {
7104   TemplateName Name = Arg.getArgument().getAsTemplateOrTemplatePattern();
7105   TemplateDecl *Template = Name.getAsTemplateDecl();
7106   if (!Template) {
7107     // Any dependent template name is fine.
7108     assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
7109     return false;
7110   }
7111 
7112   if (Template->isInvalidDecl())
7113     return true;
7114 
7115   // C++0x [temp.arg.template]p1:
7116   //   A template-argument for a template template-parameter shall be
7117   //   the name of a class template or an alias template, expressed as an
7118   //   id-expression. When the template-argument names a class template, only
7119   //   primary class templates are considered when matching the
7120   //   template template argument with the corresponding parameter;
7121   //   partial specializations are not considered even if their
7122   //   parameter lists match that of the template template parameter.
7123   //
7124   // Note that we also allow template template parameters here, which
7125   // will happen when we are dealing with, e.g., class template
7126   // partial specializations.
7127   if (!isa<ClassTemplateDecl>(Template) &&
7128       !isa<TemplateTemplateParmDecl>(Template) &&
7129       !isa<TypeAliasTemplateDecl>(Template) &&
7130       !isa<BuiltinTemplateDecl>(Template)) {
7131     assert(isa<FunctionTemplateDecl>(Template) &&
7132            "Only function templates are possible here");
7133     Diag(Arg.getLocation(), diag::err_template_arg_not_valid_template);
7134     Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
7135       << Template;
7136   }
7137 
7138   // C++1z [temp.arg.template]p3: (DR 150)
7139   //   A template-argument matches a template template-parameter P when P
7140   //   is at least as specialized as the template-argument A.
7141   if (getLangOpts().RelaxedTemplateTemplateArgs) {
7142     // Quick check for the common case:
7143     //   If P contains a parameter pack, then A [...] matches P if each of A's
7144     //   template parameters matches the corresponding template parameter in
7145     //   the template-parameter-list of P.
7146     if (TemplateParameterListsAreEqual(
7147             Template->getTemplateParameters(), Params, false,
7148             TPL_TemplateTemplateArgumentMatch, Arg.getLocation()) &&
7149         // If the argument has no associated constraints, then the parameter is
7150         // definitely at least as specialized as the argument.
7151         // Otherwise - we need a more thorough check.
7152         !Template->hasAssociatedConstraints())
7153       return false;
7154 
7155     if (isTemplateTemplateParameterAtLeastAsSpecializedAs(
7156             Params, Template, Arg.getLocation(), IsDeduced)) {
7157       // P2113
7158       // C++20[temp.func.order]p2
7159       //   [...] If both deductions succeed, the partial ordering selects the
7160       // more constrained template (if one exists) as determined below.
7161       SmallVector<const Expr *, 3> ParamsAC, TemplateAC;
7162       Params->getAssociatedConstraints(ParamsAC);
7163       // C++2a[temp.arg.template]p3
7164       //   [...] In this comparison, if P is unconstrained, the constraints on A
7165       //   are not considered.
7166       if (ParamsAC.empty())
7167         return false;
7168 
7169       Template->getAssociatedConstraints(TemplateAC);
7170 
7171       bool IsParamAtLeastAsConstrained;
7172       if (IsAtLeastAsConstrained(Param, ParamsAC, Template, TemplateAC,
7173                                  IsParamAtLeastAsConstrained))
7174         return true;
7175       if (!IsParamAtLeastAsConstrained) {
7176         Diag(Arg.getLocation(),
7177              diag::err_template_template_parameter_not_at_least_as_constrained)
7178             << Template << Param << Arg.getSourceRange();
7179         Diag(Param->getLocation(), diag::note_entity_declared_at) << Param;
7180         Diag(Template->getLocation(), diag::note_entity_declared_at)
7181             << Template;
7182         MaybeEmitAmbiguousAtomicConstraintsDiagnostic(Param, ParamsAC, Template,
7183                                                       TemplateAC);
7184         return true;
7185       }
7186       return false;
7187     }
7188     // FIXME: Produce better diagnostics for deduction failures.
7189   }
7190 
7191   return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
7192                                          Params,
7193                                          true,
7194                                          TPL_TemplateTemplateArgumentMatch,
7195                                          Arg.getLocation());
7196 }
7197 
noteLocation(Sema & S,const NamedDecl & Decl,unsigned HereDiagID,unsigned ExternalDiagID)7198 static Sema::SemaDiagnosticBuilder noteLocation(Sema &S, const NamedDecl &Decl,
7199                                                 unsigned HereDiagID,
7200                                                 unsigned ExternalDiagID) {
7201   if (Decl.getLocation().isValid())
7202     return S.Diag(Decl.getLocation(), HereDiagID);
7203 
7204   SmallString<128> Str;
7205   llvm::raw_svector_ostream Out(Str);
7206   PrintingPolicy PP = S.getPrintingPolicy();
7207   PP.TerseOutput = 1;
7208   Decl.print(Out, PP);
7209   return S.Diag(Decl.getLocation(), ExternalDiagID) << Out.str();
7210 }
7211 
NoteTemplateLocation(const NamedDecl & Decl,std::optional<SourceRange> ParamRange)7212 void Sema::NoteTemplateLocation(const NamedDecl &Decl,
7213                                 std::optional<SourceRange> ParamRange) {
7214   SemaDiagnosticBuilder DB =
7215       noteLocation(*this, Decl, diag::note_template_decl_here,
7216                    diag::note_template_decl_external);
7217   if (ParamRange && ParamRange->isValid()) {
7218     assert(Decl.getLocation().isValid() &&
7219            "Parameter range has location when Decl does not");
7220     DB << *ParamRange;
7221   }
7222 }
7223 
NoteTemplateParameterLocation(const NamedDecl & Decl)7224 void Sema::NoteTemplateParameterLocation(const NamedDecl &Decl) {
7225   noteLocation(*this, Decl, diag::note_template_param_here,
7226                diag::note_template_param_external);
7227 }
7228 
BuildExpressionFromDeclTemplateArgument(const TemplateArgument & Arg,QualType ParamType,SourceLocation Loc,NamedDecl * TemplateParam)7229 ExprResult Sema::BuildExpressionFromDeclTemplateArgument(
7230     const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc,
7231     NamedDecl *TemplateParam) {
7232   // C++ [temp.param]p8:
7233   //
7234   //   A non-type template-parameter of type "array of T" or
7235   //   "function returning T" is adjusted to be of type "pointer to
7236   //   T" or "pointer to function returning T", respectively.
7237   if (ParamType->isArrayType())
7238     ParamType = Context.getArrayDecayedType(ParamType);
7239   else if (ParamType->isFunctionType())
7240     ParamType = Context.getPointerType(ParamType);
7241 
7242   // For a NULL non-type template argument, return nullptr casted to the
7243   // parameter's type.
7244   if (Arg.getKind() == TemplateArgument::NullPtr) {
7245     return ImpCastExprToType(
7246              new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),
7247                              ParamType,
7248                              ParamType->getAs<MemberPointerType>()
7249                                ? CK_NullToMemberPointer
7250                                : CK_NullToPointer);
7251   }
7252   assert(Arg.getKind() == TemplateArgument::Declaration &&
7253          "Only declaration template arguments permitted here");
7254 
7255   ValueDecl *VD = Arg.getAsDecl();
7256 
7257   CXXScopeSpec SS;
7258   if (ParamType->isMemberPointerType()) {
7259     // If this is a pointer to member, we need to use a qualified name to
7260     // form a suitable pointer-to-member constant.
7261     assert(VD->getDeclContext()->isRecord() &&
7262            (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
7263             isa<IndirectFieldDecl>(VD)));
7264     QualType ClassType
7265       = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
7266     NestedNameSpecifier *Qualifier
7267       = NestedNameSpecifier::Create(Context, nullptr, false,
7268                                     ClassType.getTypePtr());
7269     SS.MakeTrivial(Context, Qualifier, Loc);
7270   }
7271 
7272   ExprResult RefExpr = BuildDeclarationNameExpr(
7273       SS, DeclarationNameInfo(VD->getDeclName(), Loc), VD);
7274   if (RefExpr.isInvalid())
7275     return ExprError();
7276 
7277   // For a pointer, the argument declaration is the pointee. Take its address.
7278   QualType ElemT(RefExpr.get()->getType()->getArrayElementTypeNoTypeQual(), 0);
7279   if (ParamType->isPointerType() && !ElemT.isNull() &&
7280       Context.hasSimilarType(ElemT, ParamType->getPointeeType())) {
7281     // Decay an array argument if we want a pointer to its first element.
7282     RefExpr = DefaultFunctionArrayConversion(RefExpr.get());
7283     if (RefExpr.isInvalid())
7284       return ExprError();
7285   } else if (ParamType->isPointerType() || ParamType->isMemberPointerType()) {
7286     // For any other pointer, take the address (or form a pointer-to-member).
7287     RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
7288     if (RefExpr.isInvalid())
7289       return ExprError();
7290   } else if (ParamType->isRecordType()) {
7291     assert(isa<TemplateParamObjectDecl>(VD) &&
7292            "arg for class template param not a template parameter object");
7293     // No conversions apply in this case.
7294     return RefExpr;
7295   } else {
7296     assert(ParamType->isReferenceType() &&
7297            "unexpected type for decl template argument");
7298     if (NonTypeTemplateParmDecl *NTTP =
7299             dyn_cast_if_present<NonTypeTemplateParmDecl>(TemplateParam)) {
7300       QualType TemplateParamType = NTTP->getType();
7301       const AutoType *AT = TemplateParamType->getAs<AutoType>();
7302       if (AT && AT->isDecltypeAuto()) {
7303         RefExpr = new (getASTContext()) SubstNonTypeTemplateParmExpr(
7304             ParamType->getPointeeType(), RefExpr.get()->getValueKind(),
7305             RefExpr.get()->getExprLoc(), RefExpr.get(), VD, NTTP->getIndex(),
7306             /*PackIndex=*/std::nullopt,
7307             /*RefParam=*/true);
7308       }
7309     }
7310   }
7311 
7312   // At this point we should have the right value category.
7313   assert(ParamType->isReferenceType() == RefExpr.get()->isLValue() &&
7314          "value kind mismatch for non-type template argument");
7315 
7316   // The type of the template parameter can differ from the type of the
7317   // argument in various ways; convert it now if necessary.
7318   QualType DestExprType = ParamType.getNonLValueExprType(Context);
7319   if (!Context.hasSameType(RefExpr.get()->getType(), DestExprType)) {
7320     CastKind CK;
7321     QualType Ignored;
7322     if (Context.hasSimilarType(RefExpr.get()->getType(), DestExprType) ||
7323         IsFunctionConversion(RefExpr.get()->getType(), DestExprType, Ignored)) {
7324       CK = CK_NoOp;
7325     } else if (ParamType->isVoidPointerType() &&
7326                RefExpr.get()->getType()->isPointerType()) {
7327       CK = CK_BitCast;
7328     } else {
7329       // FIXME: Pointers to members can need conversion derived-to-base or
7330       // base-to-derived conversions. We currently don't retain enough
7331       // information to convert properly (we need to track a cast path or
7332       // subobject number in the template argument).
7333       llvm_unreachable(
7334           "unexpected conversion required for non-type template argument");
7335     }
7336     RefExpr = ImpCastExprToType(RefExpr.get(), DestExprType, CK,
7337                                 RefExpr.get()->getValueKind());
7338   }
7339 
7340   return RefExpr;
7341 }
7342 
7343 /// Construct a new expression that refers to the given
7344 /// integral template argument with the given source-location
7345 /// information.
7346 ///
7347 /// This routine takes care of the mapping from an integral template
7348 /// argument (which may have any integral type) to the appropriate
7349 /// literal value.
BuildExpressionFromIntegralTemplateArgumentValue(Sema & S,QualType OrigT,const llvm::APSInt & Int,SourceLocation Loc)7350 static Expr *BuildExpressionFromIntegralTemplateArgumentValue(
7351     Sema &S, QualType OrigT, const llvm::APSInt &Int, SourceLocation Loc) {
7352   assert(OrigT->isIntegralOrEnumerationType());
7353 
7354   // If this is an enum type that we're instantiating, we need to use an integer
7355   // type the same size as the enumerator.  We don't want to build an
7356   // IntegerLiteral with enum type.  The integer type of an enum type can be of
7357   // any integral type with C++11 enum classes, make sure we create the right
7358   // type of literal for it.
7359   QualType T = OrigT;
7360   if (const EnumType *ET = OrigT->getAs<EnumType>())
7361     T = ET->getDecl()->getIntegerType();
7362 
7363   Expr *E;
7364   if (T->isAnyCharacterType()) {
7365     CharacterLiteralKind Kind;
7366     if (T->isWideCharType())
7367       Kind = CharacterLiteralKind::Wide;
7368     else if (T->isChar8Type() && S.getLangOpts().Char8)
7369       Kind = CharacterLiteralKind::UTF8;
7370     else if (T->isChar16Type())
7371       Kind = CharacterLiteralKind::UTF16;
7372     else if (T->isChar32Type())
7373       Kind = CharacterLiteralKind::UTF32;
7374     else
7375       Kind = CharacterLiteralKind::Ascii;
7376 
7377     E = new (S.Context) CharacterLiteral(Int.getZExtValue(), Kind, T, Loc);
7378   } else if (T->isBooleanType()) {
7379     E = CXXBoolLiteralExpr::Create(S.Context, Int.getBoolValue(), T, Loc);
7380   } else {
7381     E = IntegerLiteral::Create(S.Context, Int, T, Loc);
7382   }
7383 
7384   if (OrigT->isEnumeralType()) {
7385     // FIXME: This is a hack. We need a better way to handle substituted
7386     // non-type template parameters.
7387     E = CStyleCastExpr::Create(S.Context, OrigT, VK_PRValue, CK_IntegralCast, E,
7388                                nullptr, S.CurFPFeatureOverrides(),
7389                                S.Context.getTrivialTypeSourceInfo(OrigT, Loc),
7390                                Loc, Loc);
7391   }
7392 
7393   return E;
7394 }
7395 
BuildExpressionFromNonTypeTemplateArgumentValue(Sema & S,QualType T,const APValue & Val,SourceLocation Loc)7396 static Expr *BuildExpressionFromNonTypeTemplateArgumentValue(
7397     Sema &S, QualType T, const APValue &Val, SourceLocation Loc) {
7398   auto MakeInitList = [&](ArrayRef<Expr *> Elts) -> Expr * {
7399     auto *ILE = new (S.Context) InitListExpr(S.Context, Loc, Elts, Loc);
7400     ILE->setType(T);
7401     return ILE;
7402   };
7403 
7404   switch (Val.getKind()) {
7405   case APValue::AddrLabelDiff:
7406     // This cannot occur in a template argument at all.
7407   case APValue::Array:
7408   case APValue::Struct:
7409   case APValue::Union:
7410     // These can only occur within a template parameter object, which is
7411     // represented as a TemplateArgument::Declaration.
7412     llvm_unreachable("unexpected template argument value");
7413 
7414   case APValue::Int:
7415     return BuildExpressionFromIntegralTemplateArgumentValue(S, T, Val.getInt(),
7416                                                             Loc);
7417 
7418   case APValue::Float:
7419     return FloatingLiteral::Create(S.Context, Val.getFloat(), /*IsExact=*/true,
7420                                    T, Loc);
7421 
7422   case APValue::FixedPoint:
7423     return FixedPointLiteral::CreateFromRawInt(
7424         S.Context, Val.getFixedPoint().getValue(), T, Loc,
7425         Val.getFixedPoint().getScale());
7426 
7427   case APValue::ComplexInt: {
7428     QualType ElemT = T->castAs<ComplexType>()->getElementType();
7429     return MakeInitList({BuildExpressionFromIntegralTemplateArgumentValue(
7430                              S, ElemT, Val.getComplexIntReal(), Loc),
7431                          BuildExpressionFromIntegralTemplateArgumentValue(
7432                              S, ElemT, Val.getComplexIntImag(), Loc)});
7433   }
7434 
7435   case APValue::ComplexFloat: {
7436     QualType ElemT = T->castAs<ComplexType>()->getElementType();
7437     return MakeInitList(
7438         {FloatingLiteral::Create(S.Context, Val.getComplexFloatReal(), true,
7439                                  ElemT, Loc),
7440          FloatingLiteral::Create(S.Context, Val.getComplexFloatImag(), true,
7441                                  ElemT, Loc)});
7442   }
7443 
7444   case APValue::Vector: {
7445     QualType ElemT = T->castAs<VectorType>()->getElementType();
7446     llvm::SmallVector<Expr *, 8> Elts;
7447     for (unsigned I = 0, N = Val.getVectorLength(); I != N; ++I)
7448       Elts.push_back(BuildExpressionFromNonTypeTemplateArgumentValue(
7449           S, ElemT, Val.getVectorElt(I), Loc));
7450     return MakeInitList(Elts);
7451   }
7452 
7453   case APValue::None:
7454   case APValue::Indeterminate:
7455     llvm_unreachable("Unexpected APValue kind.");
7456   case APValue::LValue:
7457   case APValue::MemberPointer:
7458     // There isn't necessarily a valid equivalent source-level syntax for
7459     // these; in particular, a naive lowering might violate access control.
7460     // So for now we lower to a ConstantExpr holding the value, wrapped around
7461     // an OpaqueValueExpr.
7462     // FIXME: We should have a better representation for this.
7463     ExprValueKind VK = VK_PRValue;
7464     if (T->isReferenceType()) {
7465       T = T->getPointeeType();
7466       VK = VK_LValue;
7467     }
7468     auto *OVE = new (S.Context) OpaqueValueExpr(Loc, T, VK);
7469     return ConstantExpr::Create(S.Context, OVE, Val);
7470   }
7471   llvm_unreachable("Unhandled APValue::ValueKind enum");
7472 }
7473 
7474 ExprResult
BuildExpressionFromNonTypeTemplateArgument(const TemplateArgument & Arg,SourceLocation Loc)7475 Sema::BuildExpressionFromNonTypeTemplateArgument(const TemplateArgument &Arg,
7476                                                  SourceLocation Loc) {
7477   switch (Arg.getKind()) {
7478   case TemplateArgument::Null:
7479   case TemplateArgument::Type:
7480   case TemplateArgument::Template:
7481   case TemplateArgument::TemplateExpansion:
7482   case TemplateArgument::Pack:
7483     llvm_unreachable("not a non-type template argument");
7484 
7485   case TemplateArgument::Expression:
7486     return Arg.getAsExpr();
7487 
7488   case TemplateArgument::NullPtr:
7489   case TemplateArgument::Declaration:
7490     return BuildExpressionFromDeclTemplateArgument(
7491         Arg, Arg.getNonTypeTemplateArgumentType(), Loc);
7492 
7493   case TemplateArgument::Integral:
7494     return BuildExpressionFromIntegralTemplateArgumentValue(
7495         *this, Arg.getIntegralType(), Arg.getAsIntegral(), Loc);
7496 
7497   case TemplateArgument::StructuralValue:
7498     return BuildExpressionFromNonTypeTemplateArgumentValue(
7499         *this, Arg.getStructuralValueType(), Arg.getAsStructuralValue(), Loc);
7500   }
7501   llvm_unreachable("Unhandled TemplateArgument::ArgKind enum");
7502 }
7503 
7504 /// Match two template parameters within template parameter lists.
MatchTemplateParameterKind(Sema & S,NamedDecl * New,const Sema::TemplateCompareNewDeclInfo & NewInstFrom,NamedDecl * Old,const NamedDecl * OldInstFrom,bool Complain,Sema::TemplateParameterListEqualKind Kind,SourceLocation TemplateArgLoc)7505 static bool MatchTemplateParameterKind(
7506     Sema &S, NamedDecl *New,
7507     const Sema::TemplateCompareNewDeclInfo &NewInstFrom, NamedDecl *Old,
7508     const NamedDecl *OldInstFrom, bool Complain,
7509     Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc) {
7510   // Check the actual kind (type, non-type, template).
7511   if (Old->getKind() != New->getKind()) {
7512     if (Complain) {
7513       unsigned NextDiag = diag::err_template_param_different_kind;
7514       if (TemplateArgLoc.isValid()) {
7515         S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
7516         NextDiag = diag::note_template_param_different_kind;
7517       }
7518       S.Diag(New->getLocation(), NextDiag)
7519         << (Kind != Sema::TPL_TemplateMatch);
7520       S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
7521         << (Kind != Sema::TPL_TemplateMatch);
7522     }
7523 
7524     return false;
7525   }
7526 
7527   // Check that both are parameter packs or neither are parameter packs.
7528   // However, if we are matching a template template argument to a
7529   // template template parameter, the template template parameter can have
7530   // a parameter pack where the template template argument does not.
7531   if (Old->isTemplateParameterPack() != New->isTemplateParameterPack() &&
7532       !(Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
7533         Old->isTemplateParameterPack())) {
7534     if (Complain) {
7535       unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
7536       if (TemplateArgLoc.isValid()) {
7537         S.Diag(TemplateArgLoc,
7538              diag::err_template_arg_template_params_mismatch);
7539         NextDiag = diag::note_template_parameter_pack_non_pack;
7540       }
7541 
7542       unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
7543                       : isa<NonTypeTemplateParmDecl>(New)? 1
7544                       : 2;
7545       S.Diag(New->getLocation(), NextDiag)
7546         << ParamKind << New->isParameterPack();
7547       S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
7548         << ParamKind << Old->isParameterPack();
7549     }
7550 
7551     return false;
7552   }
7553 
7554   // For non-type template parameters, check the type of the parameter.
7555   if (NonTypeTemplateParmDecl *OldNTTP
7556                                     = dyn_cast<NonTypeTemplateParmDecl>(Old)) {
7557     NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(New);
7558 
7559     // If we are matching a template template argument to a template
7560     // template parameter and one of the non-type template parameter types
7561     // is dependent, then we must wait until template instantiation time
7562     // to actually compare the arguments.
7563     if (Kind != Sema::TPL_TemplateTemplateArgumentMatch ||
7564         (!OldNTTP->getType()->isDependentType() &&
7565          !NewNTTP->getType()->isDependentType())) {
7566       // C++20 [temp.over.link]p6:
7567       //   Two [non-type] template-parameters are equivalent [if] they have
7568       //   equivalent types ignoring the use of type-constraints for
7569       //   placeholder types
7570       QualType OldType = S.Context.getUnconstrainedType(OldNTTP->getType());
7571       QualType NewType = S.Context.getUnconstrainedType(NewNTTP->getType());
7572       if (!S.Context.hasSameType(OldType, NewType)) {
7573         if (Complain) {
7574           unsigned NextDiag = diag::err_template_nontype_parm_different_type;
7575           if (TemplateArgLoc.isValid()) {
7576             S.Diag(TemplateArgLoc,
7577                    diag::err_template_arg_template_params_mismatch);
7578             NextDiag = diag::note_template_nontype_parm_different_type;
7579           }
7580           S.Diag(NewNTTP->getLocation(), NextDiag)
7581             << NewNTTP->getType()
7582             << (Kind != Sema::TPL_TemplateMatch);
7583           S.Diag(OldNTTP->getLocation(),
7584                  diag::note_template_nontype_parm_prev_declaration)
7585             << OldNTTP->getType();
7586         }
7587 
7588         return false;
7589       }
7590     }
7591   }
7592   // For template template parameters, check the template parameter types.
7593   // The template parameter lists of template template
7594   // parameters must agree.
7595   else if (TemplateTemplateParmDecl *OldTTP =
7596                dyn_cast<TemplateTemplateParmDecl>(Old)) {
7597     TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(New);
7598     if (!S.TemplateParameterListsAreEqual(
7599             NewInstFrom, NewTTP->getTemplateParameters(), OldInstFrom,
7600             OldTTP->getTemplateParameters(), Complain,
7601             (Kind == Sema::TPL_TemplateMatch
7602                  ? Sema::TPL_TemplateTemplateParmMatch
7603                  : Kind),
7604             TemplateArgLoc))
7605       return false;
7606   }
7607 
7608   if (Kind != Sema::TPL_TemplateParamsEquivalent &&
7609       Kind != Sema::TPL_TemplateTemplateArgumentMatch &&
7610       !isa<TemplateTemplateParmDecl>(Old)) {
7611     const Expr *NewC = nullptr, *OldC = nullptr;
7612 
7613     if (isa<TemplateTypeParmDecl>(New)) {
7614       if (const auto *TC = cast<TemplateTypeParmDecl>(New)->getTypeConstraint())
7615         NewC = TC->getImmediatelyDeclaredConstraint();
7616       if (const auto *TC = cast<TemplateTypeParmDecl>(Old)->getTypeConstraint())
7617         OldC = TC->getImmediatelyDeclaredConstraint();
7618     } else if (isa<NonTypeTemplateParmDecl>(New)) {
7619       if (const Expr *E = cast<NonTypeTemplateParmDecl>(New)
7620                               ->getPlaceholderTypeConstraint())
7621         NewC = E;
7622       if (const Expr *E = cast<NonTypeTemplateParmDecl>(Old)
7623                               ->getPlaceholderTypeConstraint())
7624         OldC = E;
7625     } else
7626       llvm_unreachable("unexpected template parameter type");
7627 
7628     auto Diagnose = [&] {
7629       S.Diag(NewC ? NewC->getBeginLoc() : New->getBeginLoc(),
7630            diag::err_template_different_type_constraint);
7631       S.Diag(OldC ? OldC->getBeginLoc() : Old->getBeginLoc(),
7632            diag::note_template_prev_declaration) << /*declaration*/0;
7633     };
7634 
7635     if (!NewC != !OldC) {
7636       if (Complain)
7637         Diagnose();
7638       return false;
7639     }
7640 
7641     if (NewC) {
7642       if (!S.AreConstraintExpressionsEqual(OldInstFrom, OldC, NewInstFrom,
7643                                            NewC)) {
7644         if (Complain)
7645           Diagnose();
7646         return false;
7647       }
7648     }
7649   }
7650 
7651   return true;
7652 }
7653 
7654 /// Diagnose a known arity mismatch when comparing template argument
7655 /// lists.
7656 static
DiagnoseTemplateParameterListArityMismatch(Sema & S,TemplateParameterList * New,TemplateParameterList * Old,Sema::TemplateParameterListEqualKind Kind,SourceLocation TemplateArgLoc)7657 void DiagnoseTemplateParameterListArityMismatch(Sema &S,
7658                                                 TemplateParameterList *New,
7659                                                 TemplateParameterList *Old,
7660                                       Sema::TemplateParameterListEqualKind Kind,
7661                                                 SourceLocation TemplateArgLoc) {
7662   unsigned NextDiag = diag::err_template_param_list_different_arity;
7663   if (TemplateArgLoc.isValid()) {
7664     S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
7665     NextDiag = diag::note_template_param_list_different_arity;
7666   }
7667   S.Diag(New->getTemplateLoc(), NextDiag)
7668     << (New->size() > Old->size())
7669     << (Kind != Sema::TPL_TemplateMatch)
7670     << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
7671   S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
7672     << (Kind != Sema::TPL_TemplateMatch)
7673     << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
7674 }
7675 
TemplateParameterListsAreEqual(const TemplateCompareNewDeclInfo & NewInstFrom,TemplateParameterList * New,const NamedDecl * OldInstFrom,TemplateParameterList * Old,bool Complain,TemplateParameterListEqualKind Kind,SourceLocation TemplateArgLoc)7676 bool Sema::TemplateParameterListsAreEqual(
7677     const TemplateCompareNewDeclInfo &NewInstFrom, TemplateParameterList *New,
7678     const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain,
7679     TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc) {
7680   if (Old->size() != New->size() && Kind != TPL_TemplateTemplateArgumentMatch) {
7681     if (Complain)
7682       DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
7683                                                  TemplateArgLoc);
7684 
7685     return false;
7686   }
7687 
7688   // C++0x [temp.arg.template]p3:
7689   //   A template-argument matches a template template-parameter (call it P)
7690   //   when each of the template parameters in the template-parameter-list of
7691   //   the template-argument's corresponding class template or alias template
7692   //   (call it A) matches the corresponding template parameter in the
7693   //   template-parameter-list of P. [...]
7694   TemplateParameterList::iterator NewParm = New->begin();
7695   TemplateParameterList::iterator NewParmEnd = New->end();
7696   for (TemplateParameterList::iterator OldParm = Old->begin(),
7697                                     OldParmEnd = Old->end();
7698        OldParm != OldParmEnd; ++OldParm) {
7699     if (Kind != TPL_TemplateTemplateArgumentMatch ||
7700         !(*OldParm)->isTemplateParameterPack()) {
7701       if (NewParm == NewParmEnd) {
7702         if (Complain)
7703           DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
7704                                                      TemplateArgLoc);
7705 
7706         return false;
7707       }
7708 
7709       if (!MatchTemplateParameterKind(*this, *NewParm, NewInstFrom, *OldParm,
7710                                       OldInstFrom, Complain, Kind,
7711                                       TemplateArgLoc))
7712         return false;
7713 
7714       ++NewParm;
7715       continue;
7716     }
7717 
7718     // C++0x [temp.arg.template]p3:
7719     //   [...] When P's template- parameter-list contains a template parameter
7720     //   pack (14.5.3), the template parameter pack will match zero or more
7721     //   template parameters or template parameter packs in the
7722     //   template-parameter-list of A with the same type and form as the
7723     //   template parameter pack in P (ignoring whether those template
7724     //   parameters are template parameter packs).
7725     for (; NewParm != NewParmEnd; ++NewParm) {
7726       if (!MatchTemplateParameterKind(*this, *NewParm, NewInstFrom, *OldParm,
7727                                       OldInstFrom, Complain, Kind,
7728                                       TemplateArgLoc))
7729         return false;
7730     }
7731   }
7732 
7733   // Make sure we exhausted all of the arguments.
7734   if (NewParm != NewParmEnd) {
7735     if (Complain)
7736       DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
7737                                                  TemplateArgLoc);
7738 
7739     return false;
7740   }
7741 
7742   if (Kind != TPL_TemplateTemplateArgumentMatch &&
7743       Kind != TPL_TemplateParamsEquivalent) {
7744     const Expr *NewRC = New->getRequiresClause();
7745     const Expr *OldRC = Old->getRequiresClause();
7746 
7747     auto Diagnose = [&] {
7748       Diag(NewRC ? NewRC->getBeginLoc() : New->getTemplateLoc(),
7749            diag::err_template_different_requires_clause);
7750       Diag(OldRC ? OldRC->getBeginLoc() : Old->getTemplateLoc(),
7751            diag::note_template_prev_declaration) << /*declaration*/0;
7752     };
7753 
7754     if (!NewRC != !OldRC) {
7755       if (Complain)
7756         Diagnose();
7757       return false;
7758     }
7759 
7760     if (NewRC) {
7761       if (!AreConstraintExpressionsEqual(OldInstFrom, OldRC, NewInstFrom,
7762                                          NewRC)) {
7763         if (Complain)
7764           Diagnose();
7765         return false;
7766       }
7767     }
7768   }
7769 
7770   return true;
7771 }
7772 
7773 bool
CheckTemplateDeclScope(Scope * S,TemplateParameterList * TemplateParams)7774 Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
7775   if (!S)
7776     return false;
7777 
7778   // Find the nearest enclosing declaration scope.
7779   S = S->getDeclParent();
7780 
7781   // C++ [temp.pre]p6: [P2096]
7782   //   A template, explicit specialization, or partial specialization shall not
7783   //   have C linkage.
7784   DeclContext *Ctx = S->getEntity();
7785   if (Ctx && Ctx->isExternCContext()) {
7786     Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
7787         << TemplateParams->getSourceRange();
7788     if (const LinkageSpecDecl *LSD = Ctx->getExternCContext())
7789       Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
7790     return true;
7791   }
7792   Ctx = Ctx ? Ctx->getRedeclContext() : nullptr;
7793 
7794   // C++ [temp]p2:
7795   //   A template-declaration can appear only as a namespace scope or
7796   //   class scope declaration.
7797   // C++ [temp.expl.spec]p3:
7798   //   An explicit specialization may be declared in any scope in which the
7799   //   corresponding primary template may be defined.
7800   // C++ [temp.class.spec]p6: [P2096]
7801   //   A partial specialization may be declared in any scope in which the
7802   //   corresponding primary template may be defined.
7803   if (Ctx) {
7804     if (Ctx->isFileContext())
7805       return false;
7806     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Ctx)) {
7807       // C++ [temp.mem]p2:
7808       //   A local class shall not have member templates.
7809       if (RD->isLocalClass())
7810         return Diag(TemplateParams->getTemplateLoc(),
7811                     diag::err_template_inside_local_class)
7812           << TemplateParams->getSourceRange();
7813       else
7814         return false;
7815     }
7816   }
7817 
7818   return Diag(TemplateParams->getTemplateLoc(),
7819               diag::err_template_outside_namespace_or_class_scope)
7820     << TemplateParams->getSourceRange();
7821 }
7822 
7823 /// Determine what kind of template specialization the given declaration
7824 /// is.
getTemplateSpecializationKind(Decl * D)7825 static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D) {
7826   if (!D)
7827     return TSK_Undeclared;
7828 
7829   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
7830     return Record->getTemplateSpecializationKind();
7831   if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
7832     return Function->getTemplateSpecializationKind();
7833   if (VarDecl *Var = dyn_cast<VarDecl>(D))
7834     return Var->getTemplateSpecializationKind();
7835 
7836   return TSK_Undeclared;
7837 }
7838 
7839 /// Check whether a specialization is well-formed in the current
7840 /// context.
7841 ///
7842 /// This routine determines whether a template specialization can be declared
7843 /// in the current context (C++ [temp.expl.spec]p2).
7844 ///
7845 /// \param S the semantic analysis object for which this check is being
7846 /// performed.
7847 ///
7848 /// \param Specialized the entity being specialized or instantiated, which
7849 /// may be a kind of template (class template, function template, etc.) or
7850 /// a member of a class template (member function, static data member,
7851 /// member class).
7852 ///
7853 /// \param PrevDecl the previous declaration of this entity, if any.
7854 ///
7855 /// \param Loc the location of the explicit specialization or instantiation of
7856 /// this entity.
7857 ///
7858 /// \param IsPartialSpecialization whether this is a partial specialization of
7859 /// a class template.
7860 ///
7861 /// \returns true if there was an error that we cannot recover from, false
7862 /// otherwise.
CheckTemplateSpecializationScope(Sema & S,NamedDecl * Specialized,NamedDecl * PrevDecl,SourceLocation Loc,bool IsPartialSpecialization)7863 static bool CheckTemplateSpecializationScope(Sema &S,
7864                                              NamedDecl *Specialized,
7865                                              NamedDecl *PrevDecl,
7866                                              SourceLocation Loc,
7867                                              bool IsPartialSpecialization) {
7868   // Keep these "kind" numbers in sync with the %select statements in the
7869   // various diagnostics emitted by this routine.
7870   int EntityKind = 0;
7871   if (isa<ClassTemplateDecl>(Specialized))
7872     EntityKind = IsPartialSpecialization? 1 : 0;
7873   else if (isa<VarTemplateDecl>(Specialized))
7874     EntityKind = IsPartialSpecialization ? 3 : 2;
7875   else if (isa<FunctionTemplateDecl>(Specialized))
7876     EntityKind = 4;
7877   else if (isa<CXXMethodDecl>(Specialized))
7878     EntityKind = 5;
7879   else if (isa<VarDecl>(Specialized))
7880     EntityKind = 6;
7881   else if (isa<RecordDecl>(Specialized))
7882     EntityKind = 7;
7883   else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11)
7884     EntityKind = 8;
7885   else {
7886     S.Diag(Loc, diag::err_template_spec_unknown_kind)
7887       << S.getLangOpts().CPlusPlus11;
7888     S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
7889     return true;
7890   }
7891 
7892   // C++ [temp.expl.spec]p2:
7893   //   An explicit specialization may be declared in any scope in which
7894   //   the corresponding primary template may be defined.
7895   if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
7896     S.Diag(Loc, diag::err_template_spec_decl_function_scope)
7897       << Specialized;
7898     return true;
7899   }
7900 
7901   // C++ [temp.class.spec]p6:
7902   //   A class template partial specialization may be declared in any
7903   //   scope in which the primary template may be defined.
7904   DeclContext *SpecializedContext =
7905       Specialized->getDeclContext()->getRedeclContext();
7906   DeclContext *DC = S.CurContext->getRedeclContext();
7907 
7908   // Make sure that this redeclaration (or definition) occurs in the same
7909   // scope or an enclosing namespace.
7910   if (!(DC->isFileContext() ? DC->Encloses(SpecializedContext)
7911                             : DC->Equals(SpecializedContext))) {
7912     if (isa<TranslationUnitDecl>(SpecializedContext))
7913       S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
7914         << EntityKind << Specialized;
7915     else {
7916       auto *ND = cast<NamedDecl>(SpecializedContext);
7917       int Diag = diag::err_template_spec_redecl_out_of_scope;
7918       if (S.getLangOpts().MicrosoftExt && !DC->isRecord())
7919         Diag = diag::ext_ms_template_spec_redecl_out_of_scope;
7920       S.Diag(Loc, Diag) << EntityKind << Specialized
7921                         << ND << isa<CXXRecordDecl>(ND);
7922     }
7923 
7924     S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
7925 
7926     // Don't allow specializing in the wrong class during error recovery.
7927     // Otherwise, things can go horribly wrong.
7928     if (DC->isRecord())
7929       return true;
7930   }
7931 
7932   return false;
7933 }
7934 
findTemplateParameterInType(unsigned Depth,Expr * E)7935 static SourceRange findTemplateParameterInType(unsigned Depth, Expr *E) {
7936   if (!E->isTypeDependent())
7937     return SourceLocation();
7938   DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
7939   Checker.TraverseStmt(E);
7940   if (Checker.MatchLoc.isInvalid())
7941     return E->getSourceRange();
7942   return Checker.MatchLoc;
7943 }
7944 
findTemplateParameter(unsigned Depth,TypeLoc TL)7945 static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
7946   if (!TL.getType()->isDependentType())
7947     return SourceLocation();
7948   DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
7949   Checker.TraverseTypeLoc(TL);
7950   if (Checker.MatchLoc.isInvalid())
7951     return TL.getSourceRange();
7952   return Checker.MatchLoc;
7953 }
7954 
7955 /// Subroutine of Sema::CheckTemplatePartialSpecializationArgs
7956 /// that checks non-type template partial specialization arguments.
CheckNonTypeTemplatePartialSpecializationArgs(Sema & S,SourceLocation TemplateNameLoc,NonTypeTemplateParmDecl * Param,const TemplateArgument * Args,unsigned NumArgs,bool IsDefaultArgument)7957 static bool CheckNonTypeTemplatePartialSpecializationArgs(
7958     Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
7959     const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
7960   for (unsigned I = 0; I != NumArgs; ++I) {
7961     if (Args[I].getKind() == TemplateArgument::Pack) {
7962       if (CheckNonTypeTemplatePartialSpecializationArgs(
7963               S, TemplateNameLoc, Param, Args[I].pack_begin(),
7964               Args[I].pack_size(), IsDefaultArgument))
7965         return true;
7966 
7967       continue;
7968     }
7969 
7970     if (Args[I].getKind() != TemplateArgument::Expression)
7971       continue;
7972 
7973     Expr *ArgExpr = Args[I].getAsExpr();
7974 
7975     // We can have a pack expansion of any of the bullets below.
7976     if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
7977       ArgExpr = Expansion->getPattern();
7978 
7979     // Strip off any implicit casts we added as part of type checking.
7980     while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
7981       ArgExpr = ICE->getSubExpr();
7982 
7983     // C++ [temp.class.spec]p8:
7984     //   A non-type argument is non-specialized if it is the name of a
7985     //   non-type parameter. All other non-type arguments are
7986     //   specialized.
7987     //
7988     // Below, we check the two conditions that only apply to
7989     // specialized non-type arguments, so skip any non-specialized
7990     // arguments.
7991     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
7992       if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
7993         continue;
7994 
7995     // C++ [temp.class.spec]p9:
7996     //   Within the argument list of a class template partial
7997     //   specialization, the following restrictions apply:
7998     //     -- A partially specialized non-type argument expression
7999     //        shall not involve a template parameter of the partial
8000     //        specialization except when the argument expression is a
8001     //        simple identifier.
8002     //     -- The type of a template parameter corresponding to a
8003     //        specialized non-type argument shall not be dependent on a
8004     //        parameter of the specialization.
8005     // DR1315 removes the first bullet, leaving an incoherent set of rules.
8006     // We implement a compromise between the original rules and DR1315:
8007     //     --  A specialized non-type template argument shall not be
8008     //         type-dependent and the corresponding template parameter
8009     //         shall have a non-dependent type.
8010     SourceRange ParamUseRange =
8011         findTemplateParameterInType(Param->getDepth(), ArgExpr);
8012     if (ParamUseRange.isValid()) {
8013       if (IsDefaultArgument) {
8014         S.Diag(TemplateNameLoc,
8015                diag::err_dependent_non_type_arg_in_partial_spec);
8016         S.Diag(ParamUseRange.getBegin(),
8017                diag::note_dependent_non_type_default_arg_in_partial_spec)
8018           << ParamUseRange;
8019       } else {
8020         S.Diag(ParamUseRange.getBegin(),
8021                diag::err_dependent_non_type_arg_in_partial_spec)
8022           << ParamUseRange;
8023       }
8024       return true;
8025     }
8026 
8027     ParamUseRange = findTemplateParameter(
8028         Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc());
8029     if (ParamUseRange.isValid()) {
8030       S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getBeginLoc(),
8031              diag::err_dependent_typed_non_type_arg_in_partial_spec)
8032           << Param->getType();
8033       S.NoteTemplateParameterLocation(*Param);
8034       return true;
8035     }
8036   }
8037 
8038   return false;
8039 }
8040 
CheckTemplatePartialSpecializationArgs(SourceLocation TemplateNameLoc,TemplateDecl * PrimaryTemplate,unsigned NumExplicit,ArrayRef<TemplateArgument> TemplateArgs)8041 bool Sema::CheckTemplatePartialSpecializationArgs(
8042     SourceLocation TemplateNameLoc, TemplateDecl *PrimaryTemplate,
8043     unsigned NumExplicit, ArrayRef<TemplateArgument> TemplateArgs) {
8044   // We have to be conservative when checking a template in a dependent
8045   // context.
8046   if (PrimaryTemplate->getDeclContext()->isDependentContext())
8047     return false;
8048 
8049   TemplateParameterList *TemplateParams =
8050       PrimaryTemplate->getTemplateParameters();
8051   for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
8052     NonTypeTemplateParmDecl *Param
8053       = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
8054     if (!Param)
8055       continue;
8056 
8057     if (CheckNonTypeTemplatePartialSpecializationArgs(*this, TemplateNameLoc,
8058                                                       Param, &TemplateArgs[I],
8059                                                       1, I >= NumExplicit))
8060       return true;
8061   }
8062 
8063   return false;
8064 }
8065 
ActOnClassTemplateSpecialization(Scope * S,unsigned TagSpec,TagUseKind TUK,SourceLocation KWLoc,SourceLocation ModulePrivateLoc,CXXScopeSpec & SS,TemplateIdAnnotation & TemplateId,const ParsedAttributesView & Attr,MultiTemplateParamsArg TemplateParameterLists,SkipBodyInfo * SkipBody)8066 DeclResult Sema::ActOnClassTemplateSpecialization(
8067     Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
8068     SourceLocation ModulePrivateLoc, CXXScopeSpec &SS,
8069     TemplateIdAnnotation &TemplateId, const ParsedAttributesView &Attr,
8070     MultiTemplateParamsArg TemplateParameterLists, SkipBodyInfo *SkipBody) {
8071   assert(TUK != TagUseKind::Reference && "References are not specializations");
8072 
8073   SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
8074   SourceLocation LAngleLoc = TemplateId.LAngleLoc;
8075   SourceLocation RAngleLoc = TemplateId.RAngleLoc;
8076 
8077   // Find the class template we're specializing
8078   TemplateName Name = TemplateId.Template.get();
8079   ClassTemplateDecl *ClassTemplate
8080     = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
8081 
8082   if (!ClassTemplate) {
8083     Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
8084       << (Name.getAsTemplateDecl() &&
8085           isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
8086     return true;
8087   }
8088 
8089   bool isMemberSpecialization = false;
8090   bool isPartialSpecialization = false;
8091 
8092   if (SS.isSet()) {
8093     if (TUK != TagUseKind::Reference && TUK != TagUseKind::Friend &&
8094         diagnoseQualifiedDeclaration(SS, ClassTemplate->getDeclContext(),
8095                                      ClassTemplate->getDeclName(),
8096                                      TemplateNameLoc, &TemplateId,
8097                                      /*IsMemberSpecialization=*/false))
8098       return true;
8099   }
8100 
8101   // Check the validity of the template headers that introduce this
8102   // template.
8103   // FIXME: We probably shouldn't complain about these headers for
8104   // friend declarations.
8105   bool Invalid = false;
8106   TemplateParameterList *TemplateParams =
8107       MatchTemplateParametersToScopeSpecifier(
8108           KWLoc, TemplateNameLoc, SS, &TemplateId, TemplateParameterLists,
8109           TUK == TagUseKind::Friend, isMemberSpecialization, Invalid);
8110   if (Invalid)
8111     return true;
8112 
8113   // Check that we can declare a template specialization here.
8114   if (TemplateParams && CheckTemplateDeclScope(S, TemplateParams))
8115     return true;
8116 
8117   if (TemplateParams && TemplateParams->size() > 0) {
8118     isPartialSpecialization = true;
8119 
8120     if (TUK == TagUseKind::Friend) {
8121       Diag(KWLoc, diag::err_partial_specialization_friend)
8122         << SourceRange(LAngleLoc, RAngleLoc);
8123       return true;
8124     }
8125 
8126     // C++ [temp.class.spec]p10:
8127     //   The template parameter list of a specialization shall not
8128     //   contain default template argument values.
8129     for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
8130       Decl *Param = TemplateParams->getParam(I);
8131       if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
8132         if (TTP->hasDefaultArgument()) {
8133           Diag(TTP->getDefaultArgumentLoc(),
8134                diag::err_default_arg_in_partial_spec);
8135           TTP->removeDefaultArgument();
8136         }
8137       } else if (NonTypeTemplateParmDecl *NTTP
8138                    = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
8139         if (NTTP->hasDefaultArgument()) {
8140           Diag(NTTP->getDefaultArgumentLoc(),
8141                diag::err_default_arg_in_partial_spec)
8142               << NTTP->getDefaultArgument().getSourceRange();
8143           NTTP->removeDefaultArgument();
8144         }
8145       } else {
8146         TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
8147         if (TTP->hasDefaultArgument()) {
8148           Diag(TTP->getDefaultArgument().getLocation(),
8149                diag::err_default_arg_in_partial_spec)
8150             << TTP->getDefaultArgument().getSourceRange();
8151           TTP->removeDefaultArgument();
8152         }
8153       }
8154     }
8155   } else if (TemplateParams) {
8156     if (TUK == TagUseKind::Friend)
8157       Diag(KWLoc, diag::err_template_spec_friend)
8158         << FixItHint::CreateRemoval(
8159                                 SourceRange(TemplateParams->getTemplateLoc(),
8160                                             TemplateParams->getRAngleLoc()))
8161         << SourceRange(LAngleLoc, RAngleLoc);
8162   } else {
8163     assert(TUK == TagUseKind::Friend &&
8164            "should have a 'template<>' for this decl");
8165   }
8166 
8167   // Check that the specialization uses the same tag kind as the
8168   // original template.
8169   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
8170   assert(Kind != TagTypeKind::Enum &&
8171          "Invalid enum tag in class template spec!");
8172   if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(), Kind,
8173                                     TUK == TagUseKind::Definition, KWLoc,
8174                                     ClassTemplate->getIdentifier())) {
8175     Diag(KWLoc, diag::err_use_with_wrong_tag)
8176       << ClassTemplate
8177       << FixItHint::CreateReplacement(KWLoc,
8178                             ClassTemplate->getTemplatedDecl()->getKindName());
8179     Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
8180          diag::note_previous_use);
8181     Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
8182   }
8183 
8184   // Translate the parser's template argument list in our AST format.
8185   TemplateArgumentListInfo TemplateArgs =
8186       makeTemplateArgumentListInfo(*this, TemplateId);
8187 
8188   // Check for unexpanded parameter packs in any of the template arguments.
8189   for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
8190     if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
8191                                         isPartialSpecialization
8192                                             ? UPPC_PartialSpecialization
8193                                             : UPPC_ExplicitSpecialization))
8194       return true;
8195 
8196   // Check that the template argument list is well-formed for this
8197   // template.
8198   SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
8199   if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, TemplateArgs,
8200                                 false, SugaredConverted, CanonicalConverted,
8201                                 /*UpdateArgsWithConversions=*/true))
8202     return true;
8203 
8204   // Find the class template (partial) specialization declaration that
8205   // corresponds to these arguments.
8206   if (isPartialSpecialization) {
8207     if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, ClassTemplate,
8208                                                TemplateArgs.size(),
8209                                                CanonicalConverted))
8210       return true;
8211 
8212     // FIXME: Move this to CheckTemplatePartialSpecializationArgs so we
8213     // also do it during instantiation.
8214     if (!Name.isDependent() &&
8215         !TemplateSpecializationType::anyDependentTemplateArguments(
8216             TemplateArgs, CanonicalConverted)) {
8217       Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
8218         << ClassTemplate->getDeclName();
8219       isPartialSpecialization = false;
8220       Invalid = true;
8221     }
8222   }
8223 
8224   void *InsertPos = nullptr;
8225   ClassTemplateSpecializationDecl *PrevDecl = nullptr;
8226 
8227   if (isPartialSpecialization)
8228     PrevDecl = ClassTemplate->findPartialSpecialization(
8229         CanonicalConverted, TemplateParams, InsertPos);
8230   else
8231     PrevDecl = ClassTemplate->findSpecialization(CanonicalConverted, InsertPos);
8232 
8233   ClassTemplateSpecializationDecl *Specialization = nullptr;
8234 
8235   // Check whether we can declare a class template specialization in
8236   // the current scope.
8237   if (TUK != TagUseKind::Friend &&
8238       CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
8239                                        TemplateNameLoc,
8240                                        isPartialSpecialization))
8241     return true;
8242 
8243   // The canonical type
8244   QualType CanonType;
8245   if (isPartialSpecialization) {
8246     // Build the canonical type that describes the converted template
8247     // arguments of the class template partial specialization.
8248     TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
8249     CanonType = Context.getTemplateSpecializationType(CanonTemplate,
8250                                                       CanonicalConverted);
8251 
8252     if (Context.hasSameType(CanonType,
8253                         ClassTemplate->getInjectedClassNameSpecialization()) &&
8254         (!Context.getLangOpts().CPlusPlus20 ||
8255          !TemplateParams->hasAssociatedConstraints())) {
8256       // C++ [temp.class.spec]p9b3:
8257       //
8258       //   -- The argument list of the specialization shall not be identical
8259       //      to the implicit argument list of the primary template.
8260       //
8261       // This rule has since been removed, because it's redundant given DR1495,
8262       // but we keep it because it produces better diagnostics and recovery.
8263       Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
8264           << /*class template*/ 0 << (TUK == TagUseKind::Definition)
8265           << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
8266       return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
8267                                 ClassTemplate->getIdentifier(),
8268                                 TemplateNameLoc,
8269                                 Attr,
8270                                 TemplateParams,
8271                                 AS_none, /*ModulePrivateLoc=*/SourceLocation(),
8272                                 /*FriendLoc*/SourceLocation(),
8273                                 TemplateParameterLists.size() - 1,
8274                                 TemplateParameterLists.data());
8275     }
8276 
8277     // Create a new class template partial specialization declaration node.
8278     ClassTemplatePartialSpecializationDecl *PrevPartial
8279       = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
8280     ClassTemplatePartialSpecializationDecl *Partial =
8281         ClassTemplatePartialSpecializationDecl::Create(
8282             Context, Kind, ClassTemplate->getDeclContext(), KWLoc,
8283             TemplateNameLoc, TemplateParams, ClassTemplate, CanonicalConverted,
8284             CanonType, PrevPartial);
8285     Partial->setTemplateArgsAsWritten(TemplateArgs);
8286     SetNestedNameSpecifier(*this, Partial, SS);
8287     if (TemplateParameterLists.size() > 1 && SS.isSet()) {
8288       Partial->setTemplateParameterListsInfo(
8289           Context, TemplateParameterLists.drop_back(1));
8290     }
8291 
8292     if (!PrevPartial)
8293       ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
8294     Specialization = Partial;
8295 
8296     // If we are providing an explicit specialization of a member class
8297     // template specialization, make a note of that.
8298     if (PrevPartial && PrevPartial->getInstantiatedFromMember())
8299       PrevPartial->setMemberSpecialization();
8300 
8301     CheckTemplatePartialSpecialization(Partial);
8302   } else {
8303     // Create a new class template specialization declaration node for
8304     // this explicit specialization or friend declaration.
8305     Specialization = ClassTemplateSpecializationDecl::Create(
8306         Context, Kind, ClassTemplate->getDeclContext(), KWLoc, TemplateNameLoc,
8307         ClassTemplate, CanonicalConverted, PrevDecl);
8308     Specialization->setTemplateArgsAsWritten(TemplateArgs);
8309     SetNestedNameSpecifier(*this, Specialization, SS);
8310     if (TemplateParameterLists.size() > 0) {
8311       Specialization->setTemplateParameterListsInfo(Context,
8312                                                     TemplateParameterLists);
8313     }
8314 
8315     if (!PrevDecl)
8316       ClassTemplate->AddSpecialization(Specialization, InsertPos);
8317 
8318     if (CurContext->isDependentContext()) {
8319       TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
8320       CanonType = Context.getTemplateSpecializationType(CanonTemplate,
8321                                                         CanonicalConverted);
8322     } else {
8323       CanonType = Context.getTypeDeclType(Specialization);
8324     }
8325   }
8326 
8327   // C++ [temp.expl.spec]p6:
8328   //   If a template, a member template or the member of a class template is
8329   //   explicitly specialized then that specialization shall be declared
8330   //   before the first use of that specialization that would cause an implicit
8331   //   instantiation to take place, in every translation unit in which such a
8332   //   use occurs; no diagnostic is required.
8333   if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
8334     bool Okay = false;
8335     for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
8336       // Is there any previous explicit specialization declaration?
8337       if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
8338         Okay = true;
8339         break;
8340       }
8341     }
8342 
8343     if (!Okay) {
8344       SourceRange Range(TemplateNameLoc, RAngleLoc);
8345       Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
8346         << Context.getTypeDeclType(Specialization) << Range;
8347 
8348       Diag(PrevDecl->getPointOfInstantiation(),
8349            diag::note_instantiation_required_here)
8350         << (PrevDecl->getTemplateSpecializationKind()
8351                                                 != TSK_ImplicitInstantiation);
8352       return true;
8353     }
8354   }
8355 
8356   // If this is not a friend, note that this is an explicit specialization.
8357   if (TUK != TagUseKind::Friend)
8358     Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
8359 
8360   // Check that this isn't a redefinition of this specialization.
8361   if (TUK == TagUseKind::Definition) {
8362     RecordDecl *Def = Specialization->getDefinition();
8363     NamedDecl *Hidden = nullptr;
8364     if (Def && SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
8365       SkipBody->ShouldSkip = true;
8366       SkipBody->Previous = Def;
8367       makeMergedDefinitionVisible(Hidden);
8368     } else if (Def) {
8369       SourceRange Range(TemplateNameLoc, RAngleLoc);
8370       Diag(TemplateNameLoc, diag::err_redefinition) << Specialization << Range;
8371       Diag(Def->getLocation(), diag::note_previous_definition);
8372       Specialization->setInvalidDecl();
8373       return true;
8374     }
8375   }
8376 
8377   ProcessDeclAttributeList(S, Specialization, Attr);
8378   ProcessAPINotes(Specialization);
8379 
8380   // Add alignment attributes if necessary; these attributes are checked when
8381   // the ASTContext lays out the structure.
8382   if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
8383     AddAlignmentAttributesForRecord(Specialization);
8384     AddMsStructLayoutForRecord(Specialization);
8385   }
8386 
8387   if (ModulePrivateLoc.isValid())
8388     Diag(Specialization->getLocation(), diag::err_module_private_specialization)
8389       << (isPartialSpecialization? 1 : 0)
8390       << FixItHint::CreateRemoval(ModulePrivateLoc);
8391 
8392   // C++ [temp.expl.spec]p9:
8393   //   A template explicit specialization is in the scope of the
8394   //   namespace in which the template was defined.
8395   //
8396   // We actually implement this paragraph where we set the semantic
8397   // context (in the creation of the ClassTemplateSpecializationDecl),
8398   // but we also maintain the lexical context where the actual
8399   // definition occurs.
8400   Specialization->setLexicalDeclContext(CurContext);
8401 
8402   // We may be starting the definition of this specialization.
8403   if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip))
8404     Specialization->startDefinition();
8405 
8406   if (TUK == TagUseKind::Friend) {
8407     // Build the fully-sugared type for this class template
8408     // specialization as the user wrote in the specialization
8409     // itself. This means that we'll pretty-print the type retrieved
8410     // from the specialization's declaration the way that the user
8411     // actually wrote the specialization, rather than formatting the
8412     // name based on the "canonical" representation used to store the
8413     // template arguments in the specialization.
8414     TypeSourceInfo *WrittenTy = Context.getTemplateSpecializationTypeInfo(
8415         Name, TemplateNameLoc, TemplateArgs, CanonType);
8416     FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
8417                                             TemplateNameLoc,
8418                                             WrittenTy,
8419                                             /*FIXME:*/KWLoc);
8420     Friend->setAccess(AS_public);
8421     CurContext->addDecl(Friend);
8422   } else {
8423     // Add the specialization into its lexical context, so that it can
8424     // be seen when iterating through the list of declarations in that
8425     // context. However, specializations are not found by name lookup.
8426     CurContext->addDecl(Specialization);
8427   }
8428 
8429   if (SkipBody && SkipBody->ShouldSkip)
8430     return SkipBody->Previous;
8431 
8432   Specialization->setInvalidDecl(Invalid);
8433   return Specialization;
8434 }
8435 
ActOnTemplateDeclarator(Scope * S,MultiTemplateParamsArg TemplateParameterLists,Declarator & D)8436 Decl *Sema::ActOnTemplateDeclarator(Scope *S,
8437                               MultiTemplateParamsArg TemplateParameterLists,
8438                                     Declarator &D) {
8439   Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
8440   ActOnDocumentableDecl(NewDecl);
8441   return NewDecl;
8442 }
8443 
ActOnConceptDefinition(Scope * S,MultiTemplateParamsArg TemplateParameterLists,const IdentifierInfo * Name,SourceLocation NameLoc,Expr * ConstraintExpr,const ParsedAttributesView & Attrs)8444 Decl *Sema::ActOnConceptDefinition(
8445     Scope *S, MultiTemplateParamsArg TemplateParameterLists,
8446     const IdentifierInfo *Name, SourceLocation NameLoc, Expr *ConstraintExpr,
8447     const ParsedAttributesView &Attrs) {
8448   DeclContext *DC = CurContext;
8449 
8450   if (!DC->getRedeclContext()->isFileContext()) {
8451     Diag(NameLoc,
8452       diag::err_concept_decls_may_only_appear_in_global_namespace_scope);
8453     return nullptr;
8454   }
8455 
8456   if (TemplateParameterLists.size() > 1) {
8457     Diag(NameLoc, diag::err_concept_extra_headers);
8458     return nullptr;
8459   }
8460 
8461   TemplateParameterList *Params = TemplateParameterLists.front();
8462 
8463   if (Params->size() == 0) {
8464     Diag(NameLoc, diag::err_concept_no_parameters);
8465     return nullptr;
8466   }
8467 
8468   // Ensure that the parameter pack, if present, is the last parameter in the
8469   // template.
8470   for (TemplateParameterList::const_iterator ParamIt = Params->begin(),
8471                                              ParamEnd = Params->end();
8472        ParamIt != ParamEnd; ++ParamIt) {
8473     Decl const *Param = *ParamIt;
8474     if (Param->isParameterPack()) {
8475       if (++ParamIt == ParamEnd)
8476         break;
8477       Diag(Param->getLocation(),
8478            diag::err_template_param_pack_must_be_last_template_parameter);
8479       return nullptr;
8480     }
8481   }
8482 
8483   if (DiagnoseUnexpandedParameterPack(ConstraintExpr))
8484     return nullptr;
8485 
8486   ConceptDecl *NewDecl =
8487       ConceptDecl::Create(Context, DC, NameLoc, Name, Params, ConstraintExpr);
8488 
8489   if (NewDecl->hasAssociatedConstraints()) {
8490     // C++2a [temp.concept]p4:
8491     // A concept shall not have associated constraints.
8492     Diag(NameLoc, diag::err_concept_no_associated_constraints);
8493     NewDecl->setInvalidDecl();
8494   }
8495 
8496   // Check for conflicting previous declaration.
8497   DeclarationNameInfo NameInfo(NewDecl->getDeclName(), NameLoc);
8498   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
8499                         forRedeclarationInCurContext());
8500   LookupName(Previous, S);
8501   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage=*/false,
8502                        /*AllowInlineNamespace*/false);
8503   bool AddToScope = true;
8504   CheckConceptRedefinition(NewDecl, Previous, AddToScope);
8505 
8506   ActOnDocumentableDecl(NewDecl);
8507   if (AddToScope)
8508     PushOnScopeChains(NewDecl, S);
8509 
8510   ProcessDeclAttributeList(S, NewDecl, Attrs);
8511 
8512   return NewDecl;
8513 }
8514 
CheckConceptRedefinition(ConceptDecl * NewDecl,LookupResult & Previous,bool & AddToScope)8515 void Sema::CheckConceptRedefinition(ConceptDecl *NewDecl,
8516                                     LookupResult &Previous, bool &AddToScope) {
8517   AddToScope = true;
8518 
8519   if (Previous.empty())
8520     return;
8521 
8522   auto *OldConcept = dyn_cast<ConceptDecl>(Previous.getRepresentativeDecl()->getUnderlyingDecl());
8523   if (!OldConcept) {
8524     auto *Old = Previous.getRepresentativeDecl();
8525     Diag(NewDecl->getLocation(), diag::err_redefinition_different_kind)
8526         << NewDecl->getDeclName();
8527     notePreviousDefinition(Old, NewDecl->getLocation());
8528     AddToScope = false;
8529     return;
8530   }
8531   // Check if we can merge with a concept declaration.
8532   bool IsSame = Context.isSameEntity(NewDecl, OldConcept);
8533   if (!IsSame) {
8534     Diag(NewDecl->getLocation(), diag::err_redefinition_different_concept)
8535         << NewDecl->getDeclName();
8536     notePreviousDefinition(OldConcept, NewDecl->getLocation());
8537     AddToScope = false;
8538     return;
8539   }
8540   if (hasReachableDefinition(OldConcept) &&
8541       IsRedefinitionInModule(NewDecl, OldConcept)) {
8542     Diag(NewDecl->getLocation(), diag::err_redefinition)
8543         << NewDecl->getDeclName();
8544     notePreviousDefinition(OldConcept, NewDecl->getLocation());
8545     AddToScope = false;
8546     return;
8547   }
8548   if (!Previous.isSingleResult()) {
8549     // FIXME: we should produce an error in case of ambig and failed lookups.
8550     //        Other decls (e.g. namespaces) also have this shortcoming.
8551     return;
8552   }
8553   // We unwrap canonical decl late to check for module visibility.
8554   Context.setPrimaryMergedDecl(NewDecl, OldConcept->getCanonicalDecl());
8555 }
8556 
8557 /// \brief Strips various properties off an implicit instantiation
8558 /// that has just been explicitly specialized.
StripImplicitInstantiation(NamedDecl * D,bool MinGW)8559 static void StripImplicitInstantiation(NamedDecl *D, bool MinGW) {
8560   if (MinGW || (isa<FunctionDecl>(D) &&
8561                 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()))
8562     D->dropAttrs<DLLImportAttr, DLLExportAttr>();
8563 
8564   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
8565     FD->setInlineSpecified(false);
8566 }
8567 
8568 /// Compute the diagnostic location for an explicit instantiation
8569 //  declaration or definition.
DiagLocForExplicitInstantiation(NamedDecl * D,SourceLocation PointOfInstantiation)8570 static SourceLocation DiagLocForExplicitInstantiation(
8571     NamedDecl* D, SourceLocation PointOfInstantiation) {
8572   // Explicit instantiations following a specialization have no effect and
8573   // hence no PointOfInstantiation. In that case, walk decl backwards
8574   // until a valid name loc is found.
8575   SourceLocation PrevDiagLoc = PointOfInstantiation;
8576   for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
8577        Prev = Prev->getPreviousDecl()) {
8578     PrevDiagLoc = Prev->getLocation();
8579   }
8580   assert(PrevDiagLoc.isValid() &&
8581          "Explicit instantiation without point of instantiation?");
8582   return PrevDiagLoc;
8583 }
8584 
8585 bool
CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,TemplateSpecializationKind NewTSK,NamedDecl * PrevDecl,TemplateSpecializationKind PrevTSK,SourceLocation PrevPointOfInstantiation,bool & HasNoEffect)8586 Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
8587                                              TemplateSpecializationKind NewTSK,
8588                                              NamedDecl *PrevDecl,
8589                                              TemplateSpecializationKind PrevTSK,
8590                                         SourceLocation PrevPointOfInstantiation,
8591                                              bool &HasNoEffect) {
8592   HasNoEffect = false;
8593 
8594   switch (NewTSK) {
8595   case TSK_Undeclared:
8596   case TSK_ImplicitInstantiation:
8597     assert(
8598         (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
8599         "previous declaration must be implicit!");
8600     return false;
8601 
8602   case TSK_ExplicitSpecialization:
8603     switch (PrevTSK) {
8604     case TSK_Undeclared:
8605     case TSK_ExplicitSpecialization:
8606       // Okay, we're just specializing something that is either already
8607       // explicitly specialized or has merely been mentioned without any
8608       // instantiation.
8609       return false;
8610 
8611     case TSK_ImplicitInstantiation:
8612       if (PrevPointOfInstantiation.isInvalid()) {
8613         // The declaration itself has not actually been instantiated, so it is
8614         // still okay to specialize it.
8615         StripImplicitInstantiation(
8616             PrevDecl,
8617             Context.getTargetInfo().getTriple().isWindowsGNUEnvironment());
8618         return false;
8619       }
8620       // Fall through
8621       [[fallthrough]];
8622 
8623     case TSK_ExplicitInstantiationDeclaration:
8624     case TSK_ExplicitInstantiationDefinition:
8625       assert((PrevTSK == TSK_ImplicitInstantiation ||
8626               PrevPointOfInstantiation.isValid()) &&
8627              "Explicit instantiation without point of instantiation?");
8628 
8629       // C++ [temp.expl.spec]p6:
8630       //   If a template, a member template or the member of a class template
8631       //   is explicitly specialized then that specialization shall be declared
8632       //   before the first use of that specialization that would cause an
8633       //   implicit instantiation to take place, in every translation unit in
8634       //   which such a use occurs; no diagnostic is required.
8635       for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
8636         // Is there any previous explicit specialization declaration?
8637         if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
8638           return false;
8639       }
8640 
8641       Diag(NewLoc, diag::err_specialization_after_instantiation)
8642         << PrevDecl;
8643       Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
8644         << (PrevTSK != TSK_ImplicitInstantiation);
8645 
8646       return true;
8647     }
8648     llvm_unreachable("The switch over PrevTSK must be exhaustive.");
8649 
8650   case TSK_ExplicitInstantiationDeclaration:
8651     switch (PrevTSK) {
8652     case TSK_ExplicitInstantiationDeclaration:
8653       // This explicit instantiation declaration is redundant (that's okay).
8654       HasNoEffect = true;
8655       return false;
8656 
8657     case TSK_Undeclared:
8658     case TSK_ImplicitInstantiation:
8659       // We're explicitly instantiating something that may have already been
8660       // implicitly instantiated; that's fine.
8661       return false;
8662 
8663     case TSK_ExplicitSpecialization:
8664       // C++0x [temp.explicit]p4:
8665       //   For a given set of template parameters, if an explicit instantiation
8666       //   of a template appears after a declaration of an explicit
8667       //   specialization for that template, the explicit instantiation has no
8668       //   effect.
8669       HasNoEffect = true;
8670       return false;
8671 
8672     case TSK_ExplicitInstantiationDefinition:
8673       // C++0x [temp.explicit]p10:
8674       //   If an entity is the subject of both an explicit instantiation
8675       //   declaration and an explicit instantiation definition in the same
8676       //   translation unit, the definition shall follow the declaration.
8677       Diag(NewLoc,
8678            diag::err_explicit_instantiation_declaration_after_definition);
8679 
8680       // Explicit instantiations following a specialization have no effect and
8681       // hence no PrevPointOfInstantiation. In that case, walk decl backwards
8682       // until a valid name loc is found.
8683       Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
8684            diag::note_explicit_instantiation_definition_here);
8685       HasNoEffect = true;
8686       return false;
8687     }
8688     llvm_unreachable("Unexpected TemplateSpecializationKind!");
8689 
8690   case TSK_ExplicitInstantiationDefinition:
8691     switch (PrevTSK) {
8692     case TSK_Undeclared:
8693     case TSK_ImplicitInstantiation:
8694       // We're explicitly instantiating something that may have already been
8695       // implicitly instantiated; that's fine.
8696       return false;
8697 
8698     case TSK_ExplicitSpecialization:
8699       // C++ DR 259, C++0x [temp.explicit]p4:
8700       //   For a given set of template parameters, if an explicit
8701       //   instantiation of a template appears after a declaration of
8702       //   an explicit specialization for that template, the explicit
8703       //   instantiation has no effect.
8704       Diag(NewLoc, diag::warn_explicit_instantiation_after_specialization)
8705         << PrevDecl;
8706       Diag(PrevDecl->getLocation(),
8707            diag::note_previous_template_specialization);
8708       HasNoEffect = true;
8709       return false;
8710 
8711     case TSK_ExplicitInstantiationDeclaration:
8712       // We're explicitly instantiating a definition for something for which we
8713       // were previously asked to suppress instantiations. That's fine.
8714 
8715       // C++0x [temp.explicit]p4:
8716       //   For a given set of template parameters, if an explicit instantiation
8717       //   of a template appears after a declaration of an explicit
8718       //   specialization for that template, the explicit instantiation has no
8719       //   effect.
8720       for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
8721         // Is there any previous explicit specialization declaration?
8722         if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
8723           HasNoEffect = true;
8724           break;
8725         }
8726       }
8727 
8728       return false;
8729 
8730     case TSK_ExplicitInstantiationDefinition:
8731       // C++0x [temp.spec]p5:
8732       //   For a given template and a given set of template-arguments,
8733       //     - an explicit instantiation definition shall appear at most once
8734       //       in a program,
8735 
8736       // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
8737       Diag(NewLoc, (getLangOpts().MSVCCompat)
8738                        ? diag::ext_explicit_instantiation_duplicate
8739                        : diag::err_explicit_instantiation_duplicate)
8740           << PrevDecl;
8741       Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
8742            diag::note_previous_explicit_instantiation);
8743       HasNoEffect = true;
8744       return false;
8745     }
8746   }
8747 
8748   llvm_unreachable("Missing specialization/instantiation case?");
8749 }
8750 
CheckDependentFunctionTemplateSpecialization(FunctionDecl * FD,const TemplateArgumentListInfo * ExplicitTemplateArgs,LookupResult & Previous)8751 bool Sema::CheckDependentFunctionTemplateSpecialization(
8752     FunctionDecl *FD, const TemplateArgumentListInfo *ExplicitTemplateArgs,
8753     LookupResult &Previous) {
8754   // Remove anything from Previous that isn't a function template in
8755   // the correct context.
8756   DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
8757   LookupResult::Filter F = Previous.makeFilter();
8758   enum DiscardReason { NotAFunctionTemplate, NotAMemberOfEnclosing };
8759   SmallVector<std::pair<DiscardReason, Decl *>, 8> DiscardedCandidates;
8760   while (F.hasNext()) {
8761     NamedDecl *D = F.next()->getUnderlyingDecl();
8762     if (!isa<FunctionTemplateDecl>(D)) {
8763       F.erase();
8764       DiscardedCandidates.push_back(std::make_pair(NotAFunctionTemplate, D));
8765       continue;
8766     }
8767 
8768     if (!FDLookupContext->InEnclosingNamespaceSetOf(
8769             D->getDeclContext()->getRedeclContext())) {
8770       F.erase();
8771       DiscardedCandidates.push_back(std::make_pair(NotAMemberOfEnclosing, D));
8772       continue;
8773     }
8774   }
8775   F.done();
8776 
8777   bool IsFriend = FD->getFriendObjectKind() != Decl::FOK_None;
8778   if (Previous.empty()) {
8779     Diag(FD->getLocation(), diag::err_dependent_function_template_spec_no_match)
8780         << IsFriend;
8781     for (auto &P : DiscardedCandidates)
8782       Diag(P.second->getLocation(),
8783            diag::note_dependent_function_template_spec_discard_reason)
8784           << P.first << IsFriend;
8785     return true;
8786   }
8787 
8788   FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
8789                                          ExplicitTemplateArgs);
8790   return false;
8791 }
8792 
CheckFunctionTemplateSpecialization(FunctionDecl * FD,TemplateArgumentListInfo * ExplicitTemplateArgs,LookupResult & Previous,bool QualifiedFriend)8793 bool Sema::CheckFunctionTemplateSpecialization(
8794     FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
8795     LookupResult &Previous, bool QualifiedFriend) {
8796   // The set of function template specializations that could match this
8797   // explicit function template specialization.
8798   UnresolvedSet<8> Candidates;
8799   TemplateSpecCandidateSet FailedCandidates(FD->getLocation(),
8800                                             /*ForTakingAddress=*/false);
8801 
8802   llvm::SmallDenseMap<FunctionDecl *, TemplateArgumentListInfo, 8>
8803       ConvertedTemplateArgs;
8804 
8805   DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
8806   for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8807          I != E; ++I) {
8808     NamedDecl *Ovl = (*I)->getUnderlyingDecl();
8809     if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
8810       // Only consider templates found within the same semantic lookup scope as
8811       // FD.
8812       if (!FDLookupContext->InEnclosingNamespaceSetOf(
8813                                 Ovl->getDeclContext()->getRedeclContext()))
8814         continue;
8815 
8816       QualType FT = FD->getType();
8817       // C++11 [dcl.constexpr]p8:
8818       //   A constexpr specifier for a non-static member function that is not
8819       //   a constructor declares that member function to be const.
8820       //
8821       // When matching a constexpr member function template specialization
8822       // against the primary template, we don't yet know whether the
8823       // specialization has an implicit 'const' (because we don't know whether
8824       // it will be a static member function until we know which template it
8825       // specializes). This rule was removed in C++14.
8826       if (auto *NewMD = dyn_cast<CXXMethodDecl>(FD);
8827           !getLangOpts().CPlusPlus14 && NewMD && NewMD->isConstexpr() &&
8828           !isa<CXXConstructorDecl, CXXDestructorDecl>(NewMD)) {
8829         auto *OldMD = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
8830         if (OldMD && OldMD->isConst()) {
8831           const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
8832           FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8833           EPI.TypeQuals.addConst();
8834           FT = Context.getFunctionType(FPT->getReturnType(),
8835                                        FPT->getParamTypes(), EPI);
8836         }
8837       }
8838 
8839       TemplateArgumentListInfo Args;
8840       if (ExplicitTemplateArgs)
8841         Args = *ExplicitTemplateArgs;
8842 
8843       // C++ [temp.expl.spec]p11:
8844       //   A trailing template-argument can be left unspecified in the
8845       //   template-id naming an explicit function template specialization
8846       //   provided it can be deduced from the function argument type.
8847       // Perform template argument deduction to determine whether we may be
8848       // specializing this template.
8849       // FIXME: It is somewhat wasteful to build
8850       TemplateDeductionInfo Info(FailedCandidates.getLocation());
8851       FunctionDecl *Specialization = nullptr;
8852       if (TemplateDeductionResult TDK = DeduceTemplateArguments(
8853               cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()),
8854               ExplicitTemplateArgs ? &Args : nullptr, FT, Specialization, Info);
8855           TDK != TemplateDeductionResult::Success) {
8856         // Template argument deduction failed; record why it failed, so
8857         // that we can provide nifty diagnostics.
8858         FailedCandidates.addCandidate().set(
8859             I.getPair(), FunTmpl->getTemplatedDecl(),
8860             MakeDeductionFailureInfo(Context, TDK, Info));
8861         (void)TDK;
8862         continue;
8863       }
8864 
8865       // Target attributes are part of the cuda function signature, so
8866       // the deduced template's cuda target must match that of the
8867       // specialization.  Given that C++ template deduction does not
8868       // take target attributes into account, we reject candidates
8869       // here that have a different target.
8870       if (LangOpts.CUDA &&
8871           CUDA().IdentifyTarget(Specialization,
8872                                 /* IgnoreImplicitHDAttr = */ true) !=
8873               CUDA().IdentifyTarget(FD, /* IgnoreImplicitHDAttr = */ true)) {
8874         FailedCandidates.addCandidate().set(
8875             I.getPair(), FunTmpl->getTemplatedDecl(),
8876             MakeDeductionFailureInfo(
8877                 Context, TemplateDeductionResult::CUDATargetMismatch, Info));
8878         continue;
8879       }
8880 
8881       // Record this candidate.
8882       if (ExplicitTemplateArgs)
8883         ConvertedTemplateArgs[Specialization] = std::move(Args);
8884       Candidates.addDecl(Specialization, I.getAccess());
8885     }
8886   }
8887 
8888   // For a qualified friend declaration (with no explicit marker to indicate
8889   // that a template specialization was intended), note all (template and
8890   // non-template) candidates.
8891   if (QualifiedFriend && Candidates.empty()) {
8892     Diag(FD->getLocation(), diag::err_qualified_friend_no_match)
8893         << FD->getDeclName() << FDLookupContext;
8894     // FIXME: We should form a single candidate list and diagnose all
8895     // candidates at once, to get proper sorting and limiting.
8896     for (auto *OldND : Previous) {
8897       if (auto *OldFD = dyn_cast<FunctionDecl>(OldND->getUnderlyingDecl()))
8898         NoteOverloadCandidate(OldND, OldFD, CRK_None, FD->getType(), false);
8899     }
8900     FailedCandidates.NoteCandidates(*this, FD->getLocation());
8901     return true;
8902   }
8903 
8904   // Find the most specialized function template.
8905   UnresolvedSetIterator Result = getMostSpecialized(
8906       Candidates.begin(), Candidates.end(), FailedCandidates, FD->getLocation(),
8907       PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(),
8908       PDiag(diag::err_function_template_spec_ambiguous)
8909           << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
8910       PDiag(diag::note_function_template_spec_matched));
8911 
8912   if (Result == Candidates.end())
8913     return true;
8914 
8915   // Ignore access information;  it doesn't figure into redeclaration checking.
8916   FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
8917 
8918   // C++23 [except.spec]p13:
8919   //   An exception specification is considered to be needed when:
8920   //   - [...]
8921   //   - the exception specification is compared to that of another declaration
8922   //     (e.g., an explicit specialization or an overriding virtual function);
8923   //   - [...]
8924   //
8925   //  The exception specification of a defaulted function is evaluated as
8926   //  described above only when needed; similarly, the noexcept-specifier of a
8927   //  specialization of a function template or member function of a class
8928   //  template is instantiated only when needed.
8929   //
8930   // The standard doesn't specify what the "comparison with another declaration"
8931   // entails, nor the exact circumstances in which it occurs. Moreover, it does
8932   // not state which properties of an explicit specialization must match the
8933   // primary template.
8934   //
8935   // We assume that an explicit specialization must correspond with (per
8936   // [basic.scope.scope]p4) and declare the same entity as (per [basic.link]p8)
8937   // the declaration produced by substitution into the function template.
8938   //
8939   // Since the determination whether two function declarations correspond does
8940   // not consider exception specification, we only need to instantiate it once
8941   // we determine the primary template when comparing types per
8942   // [basic.link]p11.1.
8943   auto *SpecializationFPT =
8944       Specialization->getType()->castAs<FunctionProtoType>();
8945   // If the function has a dependent exception specification, resolve it after
8946   // we have selected the primary template so we can check whether it matches.
8947   if (getLangOpts().CPlusPlus17 &&
8948       isUnresolvedExceptionSpec(SpecializationFPT->getExceptionSpecType()) &&
8949       !ResolveExceptionSpec(FD->getLocation(), SpecializationFPT))
8950     return true;
8951 
8952   FunctionTemplateSpecializationInfo *SpecInfo
8953     = Specialization->getTemplateSpecializationInfo();
8954   assert(SpecInfo && "Function template specialization info missing?");
8955 
8956   // Note: do not overwrite location info if previous template
8957   // specialization kind was explicit.
8958   TemplateSpecializationKind TSK = SpecInfo->getTemplateSpecializationKind();
8959   if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
8960     Specialization->setLocation(FD->getLocation());
8961     Specialization->setLexicalDeclContext(FD->getLexicalDeclContext());
8962     // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
8963     // function can differ from the template declaration with respect to
8964     // the constexpr specifier.
8965     // FIXME: We need an update record for this AST mutation.
8966     // FIXME: What if there are multiple such prior declarations (for instance,
8967     // from different modules)?
8968     Specialization->setConstexprKind(FD->getConstexprKind());
8969   }
8970 
8971   // FIXME: Check if the prior specialization has a point of instantiation.
8972   // If so, we have run afoul of .
8973 
8974   // If this is a friend declaration, then we're not really declaring
8975   // an explicit specialization.
8976   bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
8977 
8978   // Check the scope of this explicit specialization.
8979   if (!isFriend &&
8980       CheckTemplateSpecializationScope(*this,
8981                                        Specialization->getPrimaryTemplate(),
8982                                        Specialization, FD->getLocation(),
8983                                        false))
8984     return true;
8985 
8986   // C++ [temp.expl.spec]p6:
8987   //   If a template, a member template or the member of a class template is
8988   //   explicitly specialized then that specialization shall be declared
8989   //   before the first use of that specialization that would cause an implicit
8990   //   instantiation to take place, in every translation unit in which such a
8991   //   use occurs; no diagnostic is required.
8992   bool HasNoEffect = false;
8993   if (!isFriend &&
8994       CheckSpecializationInstantiationRedecl(FD->getLocation(),
8995                                              TSK_ExplicitSpecialization,
8996                                              Specialization,
8997                                    SpecInfo->getTemplateSpecializationKind(),
8998                                          SpecInfo->getPointOfInstantiation(),
8999                                              HasNoEffect))
9000     return true;
9001 
9002   // Mark the prior declaration as an explicit specialization, so that later
9003   // clients know that this is an explicit specialization.
9004   if (!isFriend) {
9005     // Since explicit specializations do not inherit '=delete' from their
9006     // primary function template - check if the 'specialization' that was
9007     // implicitly generated (during template argument deduction for partial
9008     // ordering) from the most specialized of all the function templates that
9009     // 'FD' could have been specializing, has a 'deleted' definition.  If so,
9010     // first check that it was implicitly generated during template argument
9011     // deduction by making sure it wasn't referenced, and then reset the deleted
9012     // flag to not-deleted, so that we can inherit that information from 'FD'.
9013     if (Specialization->isDeleted() && !SpecInfo->isExplicitSpecialization() &&
9014         !Specialization->getCanonicalDecl()->isReferenced()) {
9015       // FIXME: This assert will not hold in the presence of modules.
9016       assert(
9017           Specialization->getCanonicalDecl() == Specialization &&
9018           "This must be the only existing declaration of this specialization");
9019       // FIXME: We need an update record for this AST mutation.
9020       Specialization->setDeletedAsWritten(false);
9021     }
9022     // FIXME: We need an update record for this AST mutation.
9023     SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
9024     MarkUnusedFileScopedDecl(Specialization);
9025   }
9026 
9027   // Turn the given function declaration into a function template
9028   // specialization, with the template arguments from the previous
9029   // specialization.
9030   // Take copies of (semantic and syntactic) template argument lists.
9031   TemplateArgumentList *TemplArgs = TemplateArgumentList::CreateCopy(
9032       Context, Specialization->getTemplateSpecializationArgs()->asArray());
9033   FD->setFunctionTemplateSpecialization(
9034       Specialization->getPrimaryTemplate(), TemplArgs, /*InsertPos=*/nullptr,
9035       SpecInfo->getTemplateSpecializationKind(),
9036       ExplicitTemplateArgs ? &ConvertedTemplateArgs[Specialization] : nullptr);
9037 
9038   // A function template specialization inherits the target attributes
9039   // of its template.  (We require the attributes explicitly in the
9040   // code to match, but a template may have implicit attributes by
9041   // virtue e.g. of being constexpr, and it passes these implicit
9042   // attributes on to its specializations.)
9043   if (LangOpts.CUDA)
9044     CUDA().inheritTargetAttrs(FD, *Specialization->getPrimaryTemplate());
9045 
9046   // The "previous declaration" for this function template specialization is
9047   // the prior function template specialization.
9048   Previous.clear();
9049   Previous.addDecl(Specialization);
9050   return false;
9051 }
9052 
9053 bool
CheckMemberSpecialization(NamedDecl * Member,LookupResult & Previous)9054 Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
9055   assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
9056 
9057   // Try to find the member we are instantiating.
9058   NamedDecl *FoundInstantiation = nullptr;
9059   NamedDecl *Instantiation = nullptr;
9060   NamedDecl *InstantiatedFrom = nullptr;
9061   MemberSpecializationInfo *MSInfo = nullptr;
9062 
9063   if (Previous.empty()) {
9064     // Nowhere to look anyway.
9065   } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
9066     SmallVector<FunctionDecl *> Candidates;
9067     bool Ambiguous = false;
9068     for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9069            I != E; ++I) {
9070       CXXMethodDecl *Method =
9071           dyn_cast<CXXMethodDecl>((*I)->getUnderlyingDecl());
9072       if (!Method)
9073         continue;
9074       QualType Adjusted = Function->getType();
9075       if (!hasExplicitCallingConv(Adjusted))
9076         Adjusted = adjustCCAndNoReturn(Adjusted, Method->getType());
9077       // This doesn't handle deduced return types, but both function
9078       // declarations should be undeduced at this point.
9079       if (!Context.hasSameType(Adjusted, Method->getType()))
9080         continue;
9081       if (ConstraintSatisfaction Satisfaction;
9082           Method->getTrailingRequiresClause() &&
9083           (CheckFunctionConstraints(Method, Satisfaction,
9084                                     /*UsageLoc=*/Member->getLocation(),
9085                                     /*ForOverloadResolution=*/true) ||
9086            !Satisfaction.IsSatisfied))
9087         continue;
9088       Candidates.push_back(Method);
9089       FunctionDecl *MoreConstrained =
9090           Instantiation ? getMoreConstrainedFunction(
9091                               Method, cast<FunctionDecl>(Instantiation))
9092                         : Method;
9093       if (!MoreConstrained) {
9094         Ambiguous = true;
9095         continue;
9096       }
9097       if (MoreConstrained == Method) {
9098         Ambiguous = false;
9099         FoundInstantiation = *I;
9100         Instantiation = Method;
9101         InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
9102         MSInfo = Method->getMemberSpecializationInfo();
9103       }
9104     }
9105     if (Ambiguous) {
9106       Diag(Member->getLocation(), diag::err_function_member_spec_ambiguous)
9107           << Member << (InstantiatedFrom ? InstantiatedFrom : Instantiation);
9108       for (FunctionDecl *Candidate : Candidates)
9109         Diag(Candidate->getLocation(), diag::note_function_member_spec_matched)
9110             << Candidate;
9111       return true;
9112     }
9113   } else if (isa<VarDecl>(Member)) {
9114     VarDecl *PrevVar;
9115     if (Previous.isSingleResult() &&
9116         (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
9117       if (PrevVar->isStaticDataMember()) {
9118         FoundInstantiation = Previous.getRepresentativeDecl();
9119         Instantiation = PrevVar;
9120         InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
9121         MSInfo = PrevVar->getMemberSpecializationInfo();
9122       }
9123   } else if (isa<RecordDecl>(Member)) {
9124     CXXRecordDecl *PrevRecord;
9125     if (Previous.isSingleResult() &&
9126         (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
9127       FoundInstantiation = Previous.getRepresentativeDecl();
9128       Instantiation = PrevRecord;
9129       InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
9130       MSInfo = PrevRecord->getMemberSpecializationInfo();
9131     }
9132   } else if (isa<EnumDecl>(Member)) {
9133     EnumDecl *PrevEnum;
9134     if (Previous.isSingleResult() &&
9135         (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) {
9136       FoundInstantiation = Previous.getRepresentativeDecl();
9137       Instantiation = PrevEnum;
9138       InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
9139       MSInfo = PrevEnum->getMemberSpecializationInfo();
9140     }
9141   }
9142 
9143   if (!Instantiation) {
9144     // There is no previous declaration that matches. Since member
9145     // specializations are always out-of-line, the caller will complain about
9146     // this mismatch later.
9147     return false;
9148   }
9149 
9150   // A member specialization in a friend declaration isn't really declaring
9151   // an explicit specialization, just identifying a specific (possibly implicit)
9152   // specialization. Don't change the template specialization kind.
9153   //
9154   // FIXME: Is this really valid? Other compilers reject.
9155   if (Member->getFriendObjectKind() != Decl::FOK_None) {
9156     // Preserve instantiation information.
9157     if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
9158       cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
9159                                       cast<CXXMethodDecl>(InstantiatedFrom),
9160         cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
9161     } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
9162       cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
9163                                       cast<CXXRecordDecl>(InstantiatedFrom),
9164         cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
9165     }
9166 
9167     Previous.clear();
9168     Previous.addDecl(FoundInstantiation);
9169     return false;
9170   }
9171 
9172   // Make sure that this is a specialization of a member.
9173   if (!InstantiatedFrom) {
9174     Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
9175       << Member;
9176     Diag(Instantiation->getLocation(), diag::note_specialized_decl);
9177     return true;
9178   }
9179 
9180   // C++ [temp.expl.spec]p6:
9181   //   If a template, a member template or the member of a class template is
9182   //   explicitly specialized then that specialization shall be declared
9183   //   before the first use of that specialization that would cause an implicit
9184   //   instantiation to take place, in every translation unit in which such a
9185   //   use occurs; no diagnostic is required.
9186   assert(MSInfo && "Member specialization info missing?");
9187 
9188   bool HasNoEffect = false;
9189   if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
9190                                              TSK_ExplicitSpecialization,
9191                                              Instantiation,
9192                                      MSInfo->getTemplateSpecializationKind(),
9193                                            MSInfo->getPointOfInstantiation(),
9194                                              HasNoEffect))
9195     return true;
9196 
9197   // Check the scope of this explicit specialization.
9198   if (CheckTemplateSpecializationScope(*this,
9199                                        InstantiatedFrom,
9200                                        Instantiation, Member->getLocation(),
9201                                        false))
9202     return true;
9203 
9204   // Note that this member specialization is an "instantiation of" the
9205   // corresponding member of the original template.
9206   if (auto *MemberFunction = dyn_cast<FunctionDecl>(Member)) {
9207     FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
9208     if (InstantiationFunction->getTemplateSpecializationKind() ==
9209           TSK_ImplicitInstantiation) {
9210       // Explicit specializations of member functions of class templates do not
9211       // inherit '=delete' from the member function they are specializing.
9212       if (InstantiationFunction->isDeleted()) {
9213         // FIXME: This assert will not hold in the presence of modules.
9214         assert(InstantiationFunction->getCanonicalDecl() ==
9215                InstantiationFunction);
9216         // FIXME: We need an update record for this AST mutation.
9217         InstantiationFunction->setDeletedAsWritten(false);
9218       }
9219     }
9220 
9221     MemberFunction->setInstantiationOfMemberFunction(
9222         cast<CXXMethodDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
9223   } else if (auto *MemberVar = dyn_cast<VarDecl>(Member)) {
9224     MemberVar->setInstantiationOfStaticDataMember(
9225         cast<VarDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
9226   } else if (auto *MemberClass = dyn_cast<CXXRecordDecl>(Member)) {
9227     MemberClass->setInstantiationOfMemberClass(
9228         cast<CXXRecordDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
9229   } else if (auto *MemberEnum = dyn_cast<EnumDecl>(Member)) {
9230     MemberEnum->setInstantiationOfMemberEnum(
9231         cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
9232   } else {
9233     llvm_unreachable("unknown member specialization kind");
9234   }
9235 
9236   // Save the caller the trouble of having to figure out which declaration
9237   // this specialization matches.
9238   Previous.clear();
9239   Previous.addDecl(FoundInstantiation);
9240   return false;
9241 }
9242 
9243 /// Complete the explicit specialization of a member of a class template by
9244 /// updating the instantiated member to be marked as an explicit specialization.
9245 ///
9246 /// \param OrigD The member declaration instantiated from the template.
9247 /// \param Loc The location of the explicit specialization of the member.
9248 template<typename DeclT>
completeMemberSpecializationImpl(Sema & S,DeclT * OrigD,SourceLocation Loc)9249 static void completeMemberSpecializationImpl(Sema &S, DeclT *OrigD,
9250                                              SourceLocation Loc) {
9251   if (OrigD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
9252     return;
9253 
9254   // FIXME: Inform AST mutation listeners of this AST mutation.
9255   // FIXME: If there are multiple in-class declarations of the member (from
9256   // multiple modules, or a declaration and later definition of a member type),
9257   // should we update all of them?
9258   OrigD->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
9259   OrigD->setLocation(Loc);
9260 }
9261 
CompleteMemberSpecialization(NamedDecl * Member,LookupResult & Previous)9262 void Sema::CompleteMemberSpecialization(NamedDecl *Member,
9263                                         LookupResult &Previous) {
9264   NamedDecl *Instantiation = cast<NamedDecl>(Member->getCanonicalDecl());
9265   if (Instantiation == Member)
9266     return;
9267 
9268   if (auto *Function = dyn_cast<CXXMethodDecl>(Instantiation))
9269     completeMemberSpecializationImpl(*this, Function, Member->getLocation());
9270   else if (auto *Var = dyn_cast<VarDecl>(Instantiation))
9271     completeMemberSpecializationImpl(*this, Var, Member->getLocation());
9272   else if (auto *Record = dyn_cast<CXXRecordDecl>(Instantiation))
9273     completeMemberSpecializationImpl(*this, Record, Member->getLocation());
9274   else if (auto *Enum = dyn_cast<EnumDecl>(Instantiation))
9275     completeMemberSpecializationImpl(*this, Enum, Member->getLocation());
9276   else
9277     llvm_unreachable("unknown member specialization kind");
9278 }
9279 
9280 /// Check the scope of an explicit instantiation.
9281 ///
9282 /// \returns true if a serious error occurs, false otherwise.
CheckExplicitInstantiationScope(Sema & S,NamedDecl * D,SourceLocation InstLoc,bool WasQualifiedName)9283 static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
9284                                             SourceLocation InstLoc,
9285                                             bool WasQualifiedName) {
9286   DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
9287   DeclContext *CurContext = S.CurContext->getRedeclContext();
9288 
9289   if (CurContext->isRecord()) {
9290     S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
9291       << D;
9292     return true;
9293   }
9294 
9295   // C++11 [temp.explicit]p3:
9296   //   An explicit instantiation shall appear in an enclosing namespace of its
9297   //   template. If the name declared in the explicit instantiation is an
9298   //   unqualified name, the explicit instantiation shall appear in the
9299   //   namespace where its template is declared or, if that namespace is inline
9300   //   (7.3.1), any namespace from its enclosing namespace set.
9301   //
9302   // This is DR275, which we do not retroactively apply to C++98/03.
9303   if (WasQualifiedName) {
9304     if (CurContext->Encloses(OrigContext))
9305       return false;
9306   } else {
9307     if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
9308       return false;
9309   }
9310 
9311   if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
9312     if (WasQualifiedName)
9313       S.Diag(InstLoc,
9314              S.getLangOpts().CPlusPlus11?
9315                diag::err_explicit_instantiation_out_of_scope :
9316                diag::warn_explicit_instantiation_out_of_scope_0x)
9317         << D << NS;
9318     else
9319       S.Diag(InstLoc,
9320              S.getLangOpts().CPlusPlus11?
9321                diag::err_explicit_instantiation_unqualified_wrong_namespace :
9322                diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
9323         << D << NS;
9324   } else
9325     S.Diag(InstLoc,
9326            S.getLangOpts().CPlusPlus11?
9327              diag::err_explicit_instantiation_must_be_global :
9328              diag::warn_explicit_instantiation_must_be_global_0x)
9329       << D;
9330   S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
9331   return false;
9332 }
9333 
9334 /// Common checks for whether an explicit instantiation of \p D is valid.
CheckExplicitInstantiation(Sema & S,NamedDecl * D,SourceLocation InstLoc,bool WasQualifiedName,TemplateSpecializationKind TSK)9335 static bool CheckExplicitInstantiation(Sema &S, NamedDecl *D,
9336                                        SourceLocation InstLoc,
9337                                        bool WasQualifiedName,
9338                                        TemplateSpecializationKind TSK) {
9339   // C++ [temp.explicit]p13:
9340   //   An explicit instantiation declaration shall not name a specialization of
9341   //   a template with internal linkage.
9342   if (TSK == TSK_ExplicitInstantiationDeclaration &&
9343       D->getFormalLinkage() == Linkage::Internal) {
9344     S.Diag(InstLoc, diag::err_explicit_instantiation_internal_linkage) << D;
9345     return true;
9346   }
9347 
9348   // C++11 [temp.explicit]p3: [DR 275]
9349   //   An explicit instantiation shall appear in an enclosing namespace of its
9350   //   template.
9351   if (CheckExplicitInstantiationScope(S, D, InstLoc, WasQualifiedName))
9352     return true;
9353 
9354   return false;
9355 }
9356 
9357 /// Determine whether the given scope specifier has a template-id in it.
ScopeSpecifierHasTemplateId(const CXXScopeSpec & SS)9358 static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
9359   if (!SS.isSet())
9360     return false;
9361 
9362   // C++11 [temp.explicit]p3:
9363   //   If the explicit instantiation is for a member function, a member class
9364   //   or a static data member of a class template specialization, the name of
9365   //   the class template specialization in the qualified-id for the member
9366   //   name shall be a simple-template-id.
9367   //
9368   // C++98 has the same restriction, just worded differently.
9369   for (NestedNameSpecifier *NNS = SS.getScopeRep(); NNS;
9370        NNS = NNS->getPrefix())
9371     if (const Type *T = NNS->getAsType())
9372       if (isa<TemplateSpecializationType>(T))
9373         return true;
9374 
9375   return false;
9376 }
9377 
9378 /// Make a dllexport or dllimport attr on a class template specialization take
9379 /// effect.
dllExportImportClassTemplateSpecialization(Sema & S,ClassTemplateSpecializationDecl * Def)9380 static void dllExportImportClassTemplateSpecialization(
9381     Sema &S, ClassTemplateSpecializationDecl *Def) {
9382   auto *A = cast_or_null<InheritableAttr>(getDLLAttr(Def));
9383   assert(A && "dllExportImportClassTemplateSpecialization called "
9384               "on Def without dllexport or dllimport");
9385 
9386   // We reject explicit instantiations in class scope, so there should
9387   // never be any delayed exported classes to worry about.
9388   assert(S.DelayedDllExportClasses.empty() &&
9389          "delayed exports present at explicit instantiation");
9390   S.checkClassLevelDLLAttribute(Def);
9391 
9392   // Propagate attribute to base class templates.
9393   for (auto &B : Def->bases()) {
9394     if (auto *BT = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
9395             B.getType()->getAsCXXRecordDecl()))
9396       S.propagateDLLAttrToBaseClassTemplate(Def, A, BT, B.getBeginLoc());
9397   }
9398 
9399   S.referenceDLLExportedClassMethods();
9400 }
9401 
ActOnExplicitInstantiation(Scope * S,SourceLocation ExternLoc,SourceLocation TemplateLoc,unsigned TagSpec,SourceLocation KWLoc,const CXXScopeSpec & SS,TemplateTy TemplateD,SourceLocation TemplateNameLoc,SourceLocation LAngleLoc,ASTTemplateArgsPtr TemplateArgsIn,SourceLocation RAngleLoc,const ParsedAttributesView & Attr)9402 DeclResult Sema::ActOnExplicitInstantiation(
9403     Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc,
9404     unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS,
9405     TemplateTy TemplateD, SourceLocation TemplateNameLoc,
9406     SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn,
9407     SourceLocation RAngleLoc, const ParsedAttributesView &Attr) {
9408   // Find the class template we're specializing
9409   TemplateName Name = TemplateD.get();
9410   TemplateDecl *TD = Name.getAsTemplateDecl();
9411   // Check that the specialization uses the same tag kind as the
9412   // original template.
9413   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
9414   assert(Kind != TagTypeKind::Enum &&
9415          "Invalid enum tag in class template explicit instantiation!");
9416 
9417   ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(TD);
9418 
9419   if (!ClassTemplate) {
9420     NonTagKind NTK = getNonTagTypeDeclKind(TD, Kind);
9421     Diag(TemplateNameLoc, diag::err_tag_reference_non_tag)
9422         << TD << NTK << llvm::to_underlying(Kind);
9423     Diag(TD->getLocation(), diag::note_previous_use);
9424     return true;
9425   }
9426 
9427   if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
9428                                     Kind, /*isDefinition*/false, KWLoc,
9429                                     ClassTemplate->getIdentifier())) {
9430     Diag(KWLoc, diag::err_use_with_wrong_tag)
9431       << ClassTemplate
9432       << FixItHint::CreateReplacement(KWLoc,
9433                             ClassTemplate->getTemplatedDecl()->getKindName());
9434     Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
9435          diag::note_previous_use);
9436     Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
9437   }
9438 
9439   // C++0x [temp.explicit]p2:
9440   //   There are two forms of explicit instantiation: an explicit instantiation
9441   //   definition and an explicit instantiation declaration. An explicit
9442   //   instantiation declaration begins with the extern keyword. [...]
9443   TemplateSpecializationKind TSK = ExternLoc.isInvalid()
9444                                        ? TSK_ExplicitInstantiationDefinition
9445                                        : TSK_ExplicitInstantiationDeclaration;
9446 
9447   if (TSK == TSK_ExplicitInstantiationDeclaration &&
9448       !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
9449     // Check for dllexport class template instantiation declarations,
9450     // except for MinGW mode.
9451     for (const ParsedAttr &AL : Attr) {
9452       if (AL.getKind() == ParsedAttr::AT_DLLExport) {
9453         Diag(ExternLoc,
9454              diag::warn_attribute_dllexport_explicit_instantiation_decl);
9455         Diag(AL.getLoc(), diag::note_attribute);
9456         break;
9457       }
9458     }
9459 
9460     if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) {
9461       Diag(ExternLoc,
9462            diag::warn_attribute_dllexport_explicit_instantiation_decl);
9463       Diag(A->getLocation(), diag::note_attribute);
9464     }
9465   }
9466 
9467   // In MSVC mode, dllimported explicit instantiation definitions are treated as
9468   // instantiation declarations for most purposes.
9469   bool DLLImportExplicitInstantiationDef = false;
9470   if (TSK == TSK_ExplicitInstantiationDefinition &&
9471       Context.getTargetInfo().getCXXABI().isMicrosoft()) {
9472     // Check for dllimport class template instantiation definitions.
9473     bool DLLImport =
9474         ClassTemplate->getTemplatedDecl()->getAttr<DLLImportAttr>();
9475     for (const ParsedAttr &AL : Attr) {
9476       if (AL.getKind() == ParsedAttr::AT_DLLImport)
9477         DLLImport = true;
9478       if (AL.getKind() == ParsedAttr::AT_DLLExport) {
9479         // dllexport trumps dllimport here.
9480         DLLImport = false;
9481         break;
9482       }
9483     }
9484     if (DLLImport) {
9485       TSK = TSK_ExplicitInstantiationDeclaration;
9486       DLLImportExplicitInstantiationDef = true;
9487     }
9488   }
9489 
9490   // Translate the parser's template argument list in our AST format.
9491   TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
9492   translateTemplateArguments(TemplateArgsIn, TemplateArgs);
9493 
9494   // Check that the template argument list is well-formed for this
9495   // template.
9496   SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
9497   if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, TemplateArgs,
9498                                 false, SugaredConverted, CanonicalConverted,
9499                                 /*UpdateArgsWithConversions=*/true))
9500     return true;
9501 
9502   // Find the class template specialization declaration that
9503   // corresponds to these arguments.
9504   void *InsertPos = nullptr;
9505   ClassTemplateSpecializationDecl *PrevDecl =
9506       ClassTemplate->findSpecialization(CanonicalConverted, InsertPos);
9507 
9508   TemplateSpecializationKind PrevDecl_TSK
9509     = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
9510 
9511   if (TSK == TSK_ExplicitInstantiationDefinition && PrevDecl != nullptr &&
9512       Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
9513     // Check for dllexport class template instantiation definitions in MinGW
9514     // mode, if a previous declaration of the instantiation was seen.
9515     for (const ParsedAttr &AL : Attr) {
9516       if (AL.getKind() == ParsedAttr::AT_DLLExport) {
9517         Diag(AL.getLoc(),
9518              diag::warn_attribute_dllexport_explicit_instantiation_def);
9519         break;
9520       }
9521     }
9522   }
9523 
9524   if (CheckExplicitInstantiation(*this, ClassTemplate, TemplateNameLoc,
9525                                  SS.isSet(), TSK))
9526     return true;
9527 
9528   ClassTemplateSpecializationDecl *Specialization = nullptr;
9529 
9530   bool HasNoEffect = false;
9531   if (PrevDecl) {
9532     if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
9533                                                PrevDecl, PrevDecl_TSK,
9534                                             PrevDecl->getPointOfInstantiation(),
9535                                                HasNoEffect))
9536       return PrevDecl;
9537 
9538     // Even though HasNoEffect == true means that this explicit instantiation
9539     // has no effect on semantics, we go on to put its syntax in the AST.
9540 
9541     if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
9542         PrevDecl_TSK == TSK_Undeclared) {
9543       // Since the only prior class template specialization with these
9544       // arguments was referenced but not declared, reuse that
9545       // declaration node as our own, updating the source location
9546       // for the template name to reflect our new declaration.
9547       // (Other source locations will be updated later.)
9548       Specialization = PrevDecl;
9549       Specialization->setLocation(TemplateNameLoc);
9550       PrevDecl = nullptr;
9551     }
9552 
9553     if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
9554         DLLImportExplicitInstantiationDef) {
9555       // The new specialization might add a dllimport attribute.
9556       HasNoEffect = false;
9557     }
9558   }
9559 
9560   if (!Specialization) {
9561     // Create a new class template specialization declaration node for
9562     // this explicit specialization.
9563     Specialization = ClassTemplateSpecializationDecl::Create(
9564         Context, Kind, ClassTemplate->getDeclContext(), KWLoc, TemplateNameLoc,
9565         ClassTemplate, CanonicalConverted, PrevDecl);
9566     SetNestedNameSpecifier(*this, Specialization, SS);
9567 
9568     // A MSInheritanceAttr attached to the previous declaration must be
9569     // propagated to the new node prior to instantiation.
9570     if (PrevDecl) {
9571       if (const auto *A = PrevDecl->getAttr<MSInheritanceAttr>()) {
9572         auto *Clone = A->clone(getASTContext());
9573         Clone->setInherited(true);
9574         Specialization->addAttr(Clone);
9575         Consumer.AssignInheritanceModel(Specialization);
9576       }
9577     }
9578 
9579     if (!HasNoEffect && !PrevDecl) {
9580       // Insert the new specialization.
9581       ClassTemplate->AddSpecialization(Specialization, InsertPos);
9582     }
9583   }
9584 
9585   Specialization->setTemplateArgsAsWritten(TemplateArgs);
9586 
9587   // Set source locations for keywords.
9588   Specialization->setExternKeywordLoc(ExternLoc);
9589   Specialization->setTemplateKeywordLoc(TemplateLoc);
9590   Specialization->setBraceRange(SourceRange());
9591 
9592   bool PreviouslyDLLExported = Specialization->hasAttr<DLLExportAttr>();
9593   ProcessDeclAttributeList(S, Specialization, Attr);
9594   ProcessAPINotes(Specialization);
9595 
9596   // Add the explicit instantiation into its lexical context. However,
9597   // since explicit instantiations are never found by name lookup, we
9598   // just put it into the declaration context directly.
9599   Specialization->setLexicalDeclContext(CurContext);
9600   CurContext->addDecl(Specialization);
9601 
9602   // Syntax is now OK, so return if it has no other effect on semantics.
9603   if (HasNoEffect) {
9604     // Set the template specialization kind.
9605     Specialization->setTemplateSpecializationKind(TSK);
9606     return Specialization;
9607   }
9608 
9609   // C++ [temp.explicit]p3:
9610   //   A definition of a class template or class member template
9611   //   shall be in scope at the point of the explicit instantiation of
9612   //   the class template or class member template.
9613   //
9614   // This check comes when we actually try to perform the
9615   // instantiation.
9616   ClassTemplateSpecializationDecl *Def
9617     = cast_or_null<ClassTemplateSpecializationDecl>(
9618                                               Specialization->getDefinition());
9619   if (!Def)
9620     InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
9621   else if (TSK == TSK_ExplicitInstantiationDefinition) {
9622     MarkVTableUsed(TemplateNameLoc, Specialization, true);
9623     Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
9624   }
9625 
9626   // Instantiate the members of this class template specialization.
9627   Def = cast_or_null<ClassTemplateSpecializationDecl>(
9628                                        Specialization->getDefinition());
9629   if (Def) {
9630     TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
9631     // Fix a TSK_ExplicitInstantiationDeclaration followed by a
9632     // TSK_ExplicitInstantiationDefinition
9633     if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
9634         (TSK == TSK_ExplicitInstantiationDefinition ||
9635          DLLImportExplicitInstantiationDef)) {
9636       // FIXME: Need to notify the ASTMutationListener that we did this.
9637       Def->setTemplateSpecializationKind(TSK);
9638 
9639       if (!getDLLAttr(Def) && getDLLAttr(Specialization) &&
9640           Context.getTargetInfo().shouldDLLImportComdatSymbols()) {
9641         // An explicit instantiation definition can add a dll attribute to a
9642         // template with a previous instantiation declaration. MinGW doesn't
9643         // allow this.
9644         auto *A = cast<InheritableAttr>(
9645             getDLLAttr(Specialization)->clone(getASTContext()));
9646         A->setInherited(true);
9647         Def->addAttr(A);
9648         dllExportImportClassTemplateSpecialization(*this, Def);
9649       }
9650     }
9651 
9652     // Fix a TSK_ImplicitInstantiation followed by a
9653     // TSK_ExplicitInstantiationDefinition
9654     bool NewlyDLLExported =
9655         !PreviouslyDLLExported && Specialization->hasAttr<DLLExportAttr>();
9656     if (Old_TSK == TSK_ImplicitInstantiation && NewlyDLLExported &&
9657         Context.getTargetInfo().shouldDLLImportComdatSymbols()) {
9658       // An explicit instantiation definition can add a dll attribute to a
9659       // template with a previous implicit instantiation. MinGW doesn't allow
9660       // this. We limit clang to only adding dllexport, to avoid potentially
9661       // strange codegen behavior. For example, if we extend this conditional
9662       // to dllimport, and we have a source file calling a method on an
9663       // implicitly instantiated template class instance and then declaring a
9664       // dllimport explicit instantiation definition for the same template
9665       // class, the codegen for the method call will not respect the dllimport,
9666       // while it will with cl. The Def will already have the DLL attribute,
9667       // since the Def and Specialization will be the same in the case of
9668       // Old_TSK == TSK_ImplicitInstantiation, and we already added the
9669       // attribute to the Specialization; we just need to make it take effect.
9670       assert(Def == Specialization &&
9671              "Def and Specialization should match for implicit instantiation");
9672       dllExportImportClassTemplateSpecialization(*this, Def);
9673     }
9674 
9675     // In MinGW mode, export the template instantiation if the declaration
9676     // was marked dllexport.
9677     if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
9678         Context.getTargetInfo().getTriple().isWindowsGNUEnvironment() &&
9679         PrevDecl->hasAttr<DLLExportAttr>()) {
9680       dllExportImportClassTemplateSpecialization(*this, Def);
9681     }
9682 
9683     // Set the template specialization kind. Make sure it is set before
9684     // instantiating the members which will trigger ASTConsumer callbacks.
9685     Specialization->setTemplateSpecializationKind(TSK);
9686     InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
9687   } else {
9688 
9689     // Set the template specialization kind.
9690     Specialization->setTemplateSpecializationKind(TSK);
9691   }
9692 
9693   return Specialization;
9694 }
9695 
9696 DeclResult
ActOnExplicitInstantiation(Scope * S,SourceLocation ExternLoc,SourceLocation TemplateLoc,unsigned TagSpec,SourceLocation KWLoc,CXXScopeSpec & SS,IdentifierInfo * Name,SourceLocation NameLoc,const ParsedAttributesView & Attr)9697 Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc,
9698                                  SourceLocation TemplateLoc, unsigned TagSpec,
9699                                  SourceLocation KWLoc, CXXScopeSpec &SS,
9700                                  IdentifierInfo *Name, SourceLocation NameLoc,
9701                                  const ParsedAttributesView &Attr) {
9702 
9703   bool Owned = false;
9704   bool IsDependent = false;
9705   Decl *TagD =
9706       ActOnTag(S, TagSpec, TagUseKind::Reference, KWLoc, SS, Name, NameLoc,
9707                Attr, AS_none, /*ModulePrivateLoc=*/SourceLocation(),
9708                MultiTemplateParamsArg(), Owned, IsDependent, SourceLocation(),
9709                false, TypeResult(), /*IsTypeSpecifier*/ false,
9710                /*IsTemplateParamOrArg*/ false, /*OOK=*/OOK_Outside)
9711           .get();
9712   assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
9713 
9714   if (!TagD)
9715     return true;
9716 
9717   TagDecl *Tag = cast<TagDecl>(TagD);
9718   assert(!Tag->isEnum() && "shouldn't see enumerations here");
9719 
9720   if (Tag->isInvalidDecl())
9721     return true;
9722 
9723   CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
9724   CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
9725   if (!Pattern) {
9726     Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
9727       << Context.getTypeDeclType(Record);
9728     Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
9729     return true;
9730   }
9731 
9732   // C++0x [temp.explicit]p2:
9733   //   If the explicit instantiation is for a class or member class, the
9734   //   elaborated-type-specifier in the declaration shall include a
9735   //   simple-template-id.
9736   //
9737   // C++98 has the same restriction, just worded differently.
9738   if (!ScopeSpecifierHasTemplateId(SS))
9739     Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
9740       << Record << SS.getRange();
9741 
9742   // C++0x [temp.explicit]p2:
9743   //   There are two forms of explicit instantiation: an explicit instantiation
9744   //   definition and an explicit instantiation declaration. An explicit
9745   //   instantiation declaration begins with the extern keyword. [...]
9746   TemplateSpecializationKind TSK
9747     = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
9748                            : TSK_ExplicitInstantiationDeclaration;
9749 
9750   CheckExplicitInstantiation(*this, Record, NameLoc, true, TSK);
9751 
9752   // Verify that it is okay to explicitly instantiate here.
9753   CXXRecordDecl *PrevDecl
9754     = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
9755   if (!PrevDecl && Record->getDefinition())
9756     PrevDecl = Record;
9757   if (PrevDecl) {
9758     MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
9759     bool HasNoEffect = false;
9760     assert(MSInfo && "No member specialization information?");
9761     if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
9762                                                PrevDecl,
9763                                         MSInfo->getTemplateSpecializationKind(),
9764                                              MSInfo->getPointOfInstantiation(),
9765                                                HasNoEffect))
9766       return true;
9767     if (HasNoEffect)
9768       return TagD;
9769   }
9770 
9771   CXXRecordDecl *RecordDef
9772     = cast_or_null<CXXRecordDecl>(Record->getDefinition());
9773   if (!RecordDef) {
9774     // C++ [temp.explicit]p3:
9775     //   A definition of a member class of a class template shall be in scope
9776     //   at the point of an explicit instantiation of the member class.
9777     CXXRecordDecl *Def
9778       = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
9779     if (!Def) {
9780       Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
9781         << 0 << Record->getDeclName() << Record->getDeclContext();
9782       Diag(Pattern->getLocation(), diag::note_forward_declaration)
9783         << Pattern;
9784       return true;
9785     } else {
9786       if (InstantiateClass(NameLoc, Record, Def,
9787                            getTemplateInstantiationArgs(Record),
9788                            TSK))
9789         return true;
9790 
9791       RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
9792       if (!RecordDef)
9793         return true;
9794     }
9795   }
9796 
9797   // Instantiate all of the members of the class.
9798   InstantiateClassMembers(NameLoc, RecordDef,
9799                           getTemplateInstantiationArgs(Record), TSK);
9800 
9801   if (TSK == TSK_ExplicitInstantiationDefinition)
9802     MarkVTableUsed(NameLoc, RecordDef, true);
9803 
9804   // FIXME: We don't have any representation for explicit instantiations of
9805   // member classes. Such a representation is not needed for compilation, but it
9806   // should be available for clients that want to see all of the declarations in
9807   // the source code.
9808   return TagD;
9809 }
9810 
ActOnExplicitInstantiation(Scope * S,SourceLocation ExternLoc,SourceLocation TemplateLoc,Declarator & D)9811 DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
9812                                             SourceLocation ExternLoc,
9813                                             SourceLocation TemplateLoc,
9814                                             Declarator &D) {
9815   // Explicit instantiations always require a name.
9816   // TODO: check if/when DNInfo should replace Name.
9817   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
9818   DeclarationName Name = NameInfo.getName();
9819   if (!Name) {
9820     if (!D.isInvalidType())
9821       Diag(D.getDeclSpec().getBeginLoc(),
9822            diag::err_explicit_instantiation_requires_name)
9823           << D.getDeclSpec().getSourceRange() << D.getSourceRange();
9824 
9825     return true;
9826   }
9827 
9828   // Get the innermost enclosing declaration scope.
9829   S = S->getDeclParent();
9830 
9831   // Determine the type of the declaration.
9832   TypeSourceInfo *T = GetTypeForDeclarator(D);
9833   QualType R = T->getType();
9834   if (R.isNull())
9835     return true;
9836 
9837   // C++ [dcl.stc]p1:
9838   //   A storage-class-specifier shall not be specified in [...] an explicit
9839   //   instantiation (14.7.2) directive.
9840   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
9841     Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
9842       << Name;
9843     return true;
9844   } else if (D.getDeclSpec().getStorageClassSpec()
9845                                                 != DeclSpec::SCS_unspecified) {
9846     // Complain about then remove the storage class specifier.
9847     Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
9848       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
9849 
9850     D.getMutableDeclSpec().ClearStorageClassSpecs();
9851   }
9852 
9853   // C++0x [temp.explicit]p1:
9854   //   [...] An explicit instantiation of a function template shall not use the
9855   //   inline or constexpr specifiers.
9856   // Presumably, this also applies to member functions of class templates as
9857   // well.
9858   if (D.getDeclSpec().isInlineSpecified())
9859     Diag(D.getDeclSpec().getInlineSpecLoc(),
9860          getLangOpts().CPlusPlus11 ?
9861            diag::err_explicit_instantiation_inline :
9862            diag::warn_explicit_instantiation_inline_0x)
9863       << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
9864   if (D.getDeclSpec().hasConstexprSpecifier() && R->isFunctionType())
9865     // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
9866     // not already specified.
9867     Diag(D.getDeclSpec().getConstexprSpecLoc(),
9868          diag::err_explicit_instantiation_constexpr);
9869 
9870   // A deduction guide is not on the list of entities that can be explicitly
9871   // instantiated.
9872   if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
9873     Diag(D.getDeclSpec().getBeginLoc(), diag::err_deduction_guide_specialized)
9874         << /*explicit instantiation*/ 0;
9875     return true;
9876   }
9877 
9878   // C++0x [temp.explicit]p2:
9879   //   There are two forms of explicit instantiation: an explicit instantiation
9880   //   definition and an explicit instantiation declaration. An explicit
9881   //   instantiation declaration begins with the extern keyword. [...]
9882   TemplateSpecializationKind TSK
9883     = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
9884                            : TSK_ExplicitInstantiationDeclaration;
9885 
9886   LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
9887   LookupParsedName(Previous, S, &D.getCXXScopeSpec(),
9888                    /*ObjectType=*/QualType());
9889 
9890   if (!R->isFunctionType()) {
9891     // C++ [temp.explicit]p1:
9892     //   A [...] static data member of a class template can be explicitly
9893     //   instantiated from the member definition associated with its class
9894     //   template.
9895     // C++1y [temp.explicit]p1:
9896     //   A [...] variable [...] template specialization can be explicitly
9897     //   instantiated from its template.
9898     if (Previous.isAmbiguous())
9899       return true;
9900 
9901     VarDecl *Prev = Previous.getAsSingle<VarDecl>();
9902     VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
9903 
9904     if (!PrevTemplate) {
9905       if (!Prev || !Prev->isStaticDataMember()) {
9906         // We expect to see a static data member here.
9907         Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
9908             << Name;
9909         for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
9910              P != PEnd; ++P)
9911           Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
9912         return true;
9913       }
9914 
9915       if (!Prev->getInstantiatedFromStaticDataMember()) {
9916         // FIXME: Check for explicit specialization?
9917         Diag(D.getIdentifierLoc(),
9918              diag::err_explicit_instantiation_data_member_not_instantiated)
9919             << Prev;
9920         Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
9921         // FIXME: Can we provide a note showing where this was declared?
9922         return true;
9923       }
9924     } else {
9925       // Explicitly instantiate a variable template.
9926 
9927       // C++1y [dcl.spec.auto]p6:
9928       //   ... A program that uses auto or decltype(auto) in a context not
9929       //   explicitly allowed in this section is ill-formed.
9930       //
9931       // This includes auto-typed variable template instantiations.
9932       if (R->isUndeducedType()) {
9933         Diag(T->getTypeLoc().getBeginLoc(),
9934              diag::err_auto_not_allowed_var_inst);
9935         return true;
9936       }
9937 
9938       if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
9939         // C++1y [temp.explicit]p3:
9940         //   If the explicit instantiation is for a variable, the unqualified-id
9941         //   in the declaration shall be a template-id.
9942         Diag(D.getIdentifierLoc(),
9943              diag::err_explicit_instantiation_without_template_id)
9944           << PrevTemplate;
9945         Diag(PrevTemplate->getLocation(),
9946              diag::note_explicit_instantiation_here);
9947         return true;
9948       }
9949 
9950       // Translate the parser's template argument list into our AST format.
9951       TemplateArgumentListInfo TemplateArgs =
9952           makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
9953 
9954       DeclResult Res = CheckVarTemplateId(PrevTemplate, TemplateLoc,
9955                                           D.getIdentifierLoc(), TemplateArgs);
9956       if (Res.isInvalid())
9957         return true;
9958 
9959       if (!Res.isUsable()) {
9960         // We somehow specified dependent template arguments in an explicit
9961         // instantiation. This should probably only happen during error
9962         // recovery.
9963         Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_dependent);
9964         return true;
9965       }
9966 
9967       // Ignore access control bits, we don't need them for redeclaration
9968       // checking.
9969       Prev = cast<VarDecl>(Res.get());
9970     }
9971 
9972     // C++0x [temp.explicit]p2:
9973     //   If the explicit instantiation is for a member function, a member class
9974     //   or a static data member of a class template specialization, the name of
9975     //   the class template specialization in the qualified-id for the member
9976     //   name shall be a simple-template-id.
9977     //
9978     // C++98 has the same restriction, just worded differently.
9979     //
9980     // This does not apply to variable template specializations, where the
9981     // template-id is in the unqualified-id instead.
9982     if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate)
9983       Diag(D.getIdentifierLoc(),
9984            diag::ext_explicit_instantiation_without_qualified_id)
9985         << Prev << D.getCXXScopeSpec().getRange();
9986 
9987     CheckExplicitInstantiation(*this, Prev, D.getIdentifierLoc(), true, TSK);
9988 
9989     // Verify that it is okay to explicitly instantiate here.
9990     TemplateSpecializationKind PrevTSK = Prev->getTemplateSpecializationKind();
9991     SourceLocation POI = Prev->getPointOfInstantiation();
9992     bool HasNoEffect = false;
9993     if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
9994                                                PrevTSK, POI, HasNoEffect))
9995       return true;
9996 
9997     if (!HasNoEffect) {
9998       // Instantiate static data member or variable template.
9999       Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
10000       if (auto *VTSD = dyn_cast<VarTemplatePartialSpecializationDecl>(Prev)) {
10001         VTSD->setExternKeywordLoc(ExternLoc);
10002         VTSD->setTemplateKeywordLoc(TemplateLoc);
10003       }
10004 
10005       // Merge attributes.
10006       ProcessDeclAttributeList(S, Prev, D.getDeclSpec().getAttributes());
10007       if (PrevTemplate)
10008         ProcessAPINotes(Prev);
10009 
10010       if (TSK == TSK_ExplicitInstantiationDefinition)
10011         InstantiateVariableDefinition(D.getIdentifierLoc(), Prev);
10012     }
10013 
10014     // Check the new variable specialization against the parsed input.
10015     if (PrevTemplate && !Context.hasSameType(Prev->getType(), R)) {
10016       Diag(T->getTypeLoc().getBeginLoc(),
10017            diag::err_invalid_var_template_spec_type)
10018           << 0 << PrevTemplate << R << Prev->getType();
10019       Diag(PrevTemplate->getLocation(), diag::note_template_declared_here)
10020           << 2 << PrevTemplate->getDeclName();
10021       return true;
10022     }
10023 
10024     // FIXME: Create an ExplicitInstantiation node?
10025     return (Decl*) nullptr;
10026   }
10027 
10028   // If the declarator is a template-id, translate the parser's template
10029   // argument list into our AST format.
10030   bool HasExplicitTemplateArgs = false;
10031   TemplateArgumentListInfo TemplateArgs;
10032   if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
10033     TemplateArgs = makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
10034     HasExplicitTemplateArgs = true;
10035   }
10036 
10037   // C++ [temp.explicit]p1:
10038   //   A [...] function [...] can be explicitly instantiated from its template.
10039   //   A member function [...] of a class template can be explicitly
10040   //  instantiated from the member definition associated with its class
10041   //  template.
10042   UnresolvedSet<8> TemplateMatches;
10043   FunctionDecl *NonTemplateMatch = nullptr;
10044   TemplateSpecCandidateSet FailedCandidates(D.getIdentifierLoc());
10045   for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
10046        P != PEnd; ++P) {
10047     NamedDecl *Prev = *P;
10048     if (!HasExplicitTemplateArgs) {
10049       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
10050         QualType Adjusted = adjustCCAndNoReturn(R, Method->getType(),
10051                                                 /*AdjustExceptionSpec*/true);
10052         if (Context.hasSameUnqualifiedType(Method->getType(), Adjusted)) {
10053           if (Method->getPrimaryTemplate()) {
10054             TemplateMatches.addDecl(Method, P.getAccess());
10055           } else {
10056             // FIXME: Can this assert ever happen?  Needs a test.
10057             assert(!NonTemplateMatch && "Multiple NonTemplateMatches");
10058             NonTemplateMatch = Method;
10059           }
10060         }
10061       }
10062     }
10063 
10064     FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
10065     if (!FunTmpl)
10066       continue;
10067 
10068     TemplateDeductionInfo Info(FailedCandidates.getLocation());
10069     FunctionDecl *Specialization = nullptr;
10070     if (TemplateDeductionResult TDK = DeduceTemplateArguments(
10071             FunTmpl, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr), R,
10072             Specialization, Info);
10073         TDK != TemplateDeductionResult::Success) {
10074       // Keep track of almost-matches.
10075       FailedCandidates.addCandidate()
10076           .set(P.getPair(), FunTmpl->getTemplatedDecl(),
10077                MakeDeductionFailureInfo(Context, TDK, Info));
10078       (void)TDK;
10079       continue;
10080     }
10081 
10082     // Target attributes are part of the cuda function signature, so
10083     // the cuda target of the instantiated function must match that of its
10084     // template.  Given that C++ template deduction does not take
10085     // target attributes into account, we reject candidates here that
10086     // have a different target.
10087     if (LangOpts.CUDA &&
10088         CUDA().IdentifyTarget(Specialization,
10089                               /* IgnoreImplicitHDAttr = */ true) !=
10090             CUDA().IdentifyTarget(D.getDeclSpec().getAttributes())) {
10091       FailedCandidates.addCandidate().set(
10092           P.getPair(), FunTmpl->getTemplatedDecl(),
10093           MakeDeductionFailureInfo(
10094               Context, TemplateDeductionResult::CUDATargetMismatch, Info));
10095       continue;
10096     }
10097 
10098     TemplateMatches.addDecl(Specialization, P.getAccess());
10099   }
10100 
10101   FunctionDecl *Specialization = NonTemplateMatch;
10102   if (!Specialization) {
10103     // Find the most specialized function template specialization.
10104     UnresolvedSetIterator Result = getMostSpecialized(
10105         TemplateMatches.begin(), TemplateMatches.end(), FailedCandidates,
10106         D.getIdentifierLoc(),
10107         PDiag(diag::err_explicit_instantiation_not_known) << Name,
10108         PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
10109         PDiag(diag::note_explicit_instantiation_candidate));
10110 
10111     if (Result == TemplateMatches.end())
10112       return true;
10113 
10114     // Ignore access control bits, we don't need them for redeclaration checking.
10115     Specialization = cast<FunctionDecl>(*Result);
10116   }
10117 
10118   // C++11 [except.spec]p4
10119   // In an explicit instantiation an exception-specification may be specified,
10120   // but is not required.
10121   // If an exception-specification is specified in an explicit instantiation
10122   // directive, it shall be compatible with the exception-specifications of
10123   // other declarations of that function.
10124   if (auto *FPT = R->getAs<FunctionProtoType>())
10125     if (FPT->hasExceptionSpec()) {
10126       unsigned DiagID =
10127           diag::err_mismatched_exception_spec_explicit_instantiation;
10128       if (getLangOpts().MicrosoftExt)
10129         DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
10130       bool Result = CheckEquivalentExceptionSpec(
10131           PDiag(DiagID) << Specialization->getType(),
10132           PDiag(diag::note_explicit_instantiation_here),
10133           Specialization->getType()->getAs<FunctionProtoType>(),
10134           Specialization->getLocation(), FPT, D.getBeginLoc());
10135       // In Microsoft mode, mismatching exception specifications just cause a
10136       // warning.
10137       if (!getLangOpts().MicrosoftExt && Result)
10138         return true;
10139     }
10140 
10141   if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
10142     Diag(D.getIdentifierLoc(),
10143          diag::err_explicit_instantiation_member_function_not_instantiated)
10144       << Specialization
10145       << (Specialization->getTemplateSpecializationKind() ==
10146           TSK_ExplicitSpecialization);
10147     Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
10148     return true;
10149   }
10150 
10151   FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
10152   if (!PrevDecl && Specialization->isThisDeclarationADefinition())
10153     PrevDecl = Specialization;
10154 
10155   if (PrevDecl) {
10156     bool HasNoEffect = false;
10157     if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
10158                                                PrevDecl,
10159                                      PrevDecl->getTemplateSpecializationKind(),
10160                                           PrevDecl->getPointOfInstantiation(),
10161                                                HasNoEffect))
10162       return true;
10163 
10164     // FIXME: We may still want to build some representation of this
10165     // explicit specialization.
10166     if (HasNoEffect)
10167       return (Decl*) nullptr;
10168   }
10169 
10170   // HACK: libc++ has a bug where it attempts to explicitly instantiate the
10171   // functions
10172   //     valarray<size_t>::valarray(size_t) and
10173   //     valarray<size_t>::~valarray()
10174   // that it declared to have internal linkage with the internal_linkage
10175   // attribute. Ignore the explicit instantiation declaration in this case.
10176   if (Specialization->hasAttr<InternalLinkageAttr>() &&
10177       TSK == TSK_ExplicitInstantiationDeclaration) {
10178     if (auto *RD = dyn_cast<CXXRecordDecl>(Specialization->getDeclContext()))
10179       if (RD->getIdentifier() && RD->getIdentifier()->isStr("valarray") &&
10180           RD->isInStdNamespace())
10181         return (Decl*) nullptr;
10182   }
10183 
10184   ProcessDeclAttributeList(S, Specialization, D.getDeclSpec().getAttributes());
10185   ProcessAPINotes(Specialization);
10186 
10187   // In MSVC mode, dllimported explicit instantiation definitions are treated as
10188   // instantiation declarations.
10189   if (TSK == TSK_ExplicitInstantiationDefinition &&
10190       Specialization->hasAttr<DLLImportAttr>() &&
10191       Context.getTargetInfo().getCXXABI().isMicrosoft())
10192     TSK = TSK_ExplicitInstantiationDeclaration;
10193 
10194   Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
10195 
10196   if (Specialization->isDefined()) {
10197     // Let the ASTConsumer know that this function has been explicitly
10198     // instantiated now, and its linkage might have changed.
10199     Consumer.HandleTopLevelDecl(DeclGroupRef(Specialization));
10200   } else if (TSK == TSK_ExplicitInstantiationDefinition)
10201     InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
10202 
10203   // C++0x [temp.explicit]p2:
10204   //   If the explicit instantiation is for a member function, a member class
10205   //   or a static data member of a class template specialization, the name of
10206   //   the class template specialization in the qualified-id for the member
10207   //   name shall be a simple-template-id.
10208   //
10209   // C++98 has the same restriction, just worded differently.
10210   FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
10211   if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId && !FunTmpl &&
10212       D.getCXXScopeSpec().isSet() &&
10213       !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
10214     Diag(D.getIdentifierLoc(),
10215          diag::ext_explicit_instantiation_without_qualified_id)
10216     << Specialization << D.getCXXScopeSpec().getRange();
10217 
10218   CheckExplicitInstantiation(
10219       *this,
10220       FunTmpl ? (NamedDecl *)FunTmpl
10221               : Specialization->getInstantiatedFromMemberFunction(),
10222       D.getIdentifierLoc(), D.getCXXScopeSpec().isSet(), TSK);
10223 
10224   // FIXME: Create some kind of ExplicitInstantiationDecl here.
10225   return (Decl*) nullptr;
10226 }
10227 
ActOnDependentTag(Scope * S,unsigned TagSpec,TagUseKind TUK,const CXXScopeSpec & SS,const IdentifierInfo * Name,SourceLocation TagLoc,SourceLocation NameLoc)10228 TypeResult Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
10229                                    const CXXScopeSpec &SS,
10230                                    const IdentifierInfo *Name,
10231                                    SourceLocation TagLoc,
10232                                    SourceLocation NameLoc) {
10233   // This has to hold, because SS is expected to be defined.
10234   assert(Name && "Expected a name in a dependent tag");
10235 
10236   NestedNameSpecifier *NNS = SS.getScopeRep();
10237   if (!NNS)
10238     return true;
10239 
10240   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
10241 
10242   if (TUK == TagUseKind::Declaration || TUK == TagUseKind::Definition) {
10243     Diag(NameLoc, diag::err_dependent_tag_decl)
10244         << (TUK == TagUseKind::Definition) << llvm::to_underlying(Kind)
10245         << SS.getRange();
10246     return true;
10247   }
10248 
10249   // Create the resulting type.
10250   ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
10251   QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
10252 
10253   // Create type-source location information for this type.
10254   TypeLocBuilder TLB;
10255   DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(Result);
10256   TL.setElaboratedKeywordLoc(TagLoc);
10257   TL.setQualifierLoc(SS.getWithLocInContext(Context));
10258   TL.setNameLoc(NameLoc);
10259   return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
10260 }
10261 
ActOnTypenameType(Scope * S,SourceLocation TypenameLoc,const CXXScopeSpec & SS,const IdentifierInfo & II,SourceLocation IdLoc,ImplicitTypenameContext IsImplicitTypename)10262 TypeResult Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
10263                                    const CXXScopeSpec &SS,
10264                                    const IdentifierInfo &II,
10265                                    SourceLocation IdLoc,
10266                                    ImplicitTypenameContext IsImplicitTypename) {
10267   if (SS.isInvalid())
10268     return true;
10269 
10270   if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
10271     Diag(TypenameLoc,
10272          getLangOpts().CPlusPlus11 ?
10273            diag::warn_cxx98_compat_typename_outside_of_template :
10274            diag::ext_typename_outside_of_template)
10275       << FixItHint::CreateRemoval(TypenameLoc);
10276 
10277   NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
10278   TypeSourceInfo *TSI = nullptr;
10279   QualType T =
10280       CheckTypenameType((TypenameLoc.isValid() ||
10281                          IsImplicitTypename == ImplicitTypenameContext::Yes)
10282                             ? ElaboratedTypeKeyword::Typename
10283                             : ElaboratedTypeKeyword::None,
10284                         TypenameLoc, QualifierLoc, II, IdLoc, &TSI,
10285                         /*DeducedTSTContext=*/true);
10286   if (T.isNull())
10287     return true;
10288   return CreateParsedType(T, TSI);
10289 }
10290 
10291 TypeResult
ActOnTypenameType(Scope * S,SourceLocation TypenameLoc,const CXXScopeSpec & SS,SourceLocation TemplateKWLoc,TemplateTy TemplateIn,const IdentifierInfo * TemplateII,SourceLocation TemplateIILoc,SourceLocation LAngleLoc,ASTTemplateArgsPtr TemplateArgsIn,SourceLocation RAngleLoc)10292 Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
10293                         const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
10294                         TemplateTy TemplateIn, const IdentifierInfo *TemplateII,
10295                         SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
10296                         ASTTemplateArgsPtr TemplateArgsIn,
10297                         SourceLocation RAngleLoc) {
10298   if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
10299     Diag(TypenameLoc,
10300          getLangOpts().CPlusPlus11 ?
10301            diag::warn_cxx98_compat_typename_outside_of_template :
10302            diag::ext_typename_outside_of_template)
10303       << FixItHint::CreateRemoval(TypenameLoc);
10304 
10305   // Strangely, non-type results are not ignored by this lookup, so the
10306   // program is ill-formed if it finds an injected-class-name.
10307   if (TypenameLoc.isValid()) {
10308     auto *LookupRD =
10309         dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, false));
10310     if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
10311       Diag(TemplateIILoc,
10312            diag::ext_out_of_line_qualified_id_type_names_constructor)
10313         << TemplateII << 0 /*injected-class-name used as template name*/
10314         << (TemplateKWLoc.isValid() ? 1 : 0 /*'template'/'typename' keyword*/);
10315     }
10316   }
10317 
10318   // Translate the parser's template argument list in our AST format.
10319   TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
10320   translateTemplateArguments(TemplateArgsIn, TemplateArgs);
10321 
10322   TemplateName Template = TemplateIn.get();
10323   if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
10324     // Construct a dependent template specialization type.
10325     assert(DTN && "dependent template has non-dependent name?");
10326     assert(DTN->getQualifier() == SS.getScopeRep());
10327 
10328     if (!DTN->isIdentifier()) {
10329       Diag(TemplateIILoc, diag::err_template_id_not_a_type) << Template;
10330       NoteAllFoundTemplates(Template);
10331       return true;
10332     }
10333 
10334     QualType T = Context.getDependentTemplateSpecializationType(
10335         ElaboratedTypeKeyword::Typename, DTN->getQualifier(),
10336         DTN->getIdentifier(), TemplateArgs.arguments());
10337 
10338     // Create source-location information for this type.
10339     TypeLocBuilder Builder;
10340     DependentTemplateSpecializationTypeLoc SpecTL
10341     = Builder.push<DependentTemplateSpecializationTypeLoc>(T);
10342     SpecTL.setElaboratedKeywordLoc(TypenameLoc);
10343     SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
10344     SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
10345     SpecTL.setTemplateNameLoc(TemplateIILoc);
10346     SpecTL.setLAngleLoc(LAngleLoc);
10347     SpecTL.setRAngleLoc(RAngleLoc);
10348     for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
10349       SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
10350     return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
10351   }
10352 
10353   QualType T = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
10354   if (T.isNull())
10355     return true;
10356 
10357   // Provide source-location information for the template specialization type.
10358   TypeLocBuilder Builder;
10359   TemplateSpecializationTypeLoc SpecTL
10360     = Builder.push<TemplateSpecializationTypeLoc>(T);
10361   SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
10362   SpecTL.setTemplateNameLoc(TemplateIILoc);
10363   SpecTL.setLAngleLoc(LAngleLoc);
10364   SpecTL.setRAngleLoc(RAngleLoc);
10365   for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
10366     SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
10367 
10368   T = Context.getElaboratedType(ElaboratedTypeKeyword::Typename,
10369                                 SS.getScopeRep(), T);
10370   ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
10371   TL.setElaboratedKeywordLoc(TypenameLoc);
10372   TL.setQualifierLoc(SS.getWithLocInContext(Context));
10373 
10374   TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
10375   return CreateParsedType(T, TSI);
10376 }
10377 
10378 /// Determine whether this failed name lookup should be treated as being
10379 /// disabled by a usage of std::enable_if.
isEnableIf(NestedNameSpecifierLoc NNS,const IdentifierInfo & II,SourceRange & CondRange,Expr * & Cond)10380 static bool isEnableIf(NestedNameSpecifierLoc NNS, const IdentifierInfo &II,
10381                        SourceRange &CondRange, Expr *&Cond) {
10382   // We must be looking for a ::type...
10383   if (!II.isStr("type"))
10384     return false;
10385 
10386   // ... within an explicitly-written template specialization...
10387   if (!NNS || !NNS.getNestedNameSpecifier()->getAsType())
10388     return false;
10389   TypeLoc EnableIfTy = NNS.getTypeLoc();
10390   TemplateSpecializationTypeLoc EnableIfTSTLoc =
10391       EnableIfTy.getAs<TemplateSpecializationTypeLoc>();
10392   if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
10393     return false;
10394   const TemplateSpecializationType *EnableIfTST = EnableIfTSTLoc.getTypePtr();
10395 
10396   // ... which names a complete class template declaration...
10397   const TemplateDecl *EnableIfDecl =
10398     EnableIfTST->getTemplateName().getAsTemplateDecl();
10399   if (!EnableIfDecl || EnableIfTST->isIncompleteType())
10400     return false;
10401 
10402   // ... called "enable_if".
10403   const IdentifierInfo *EnableIfII =
10404     EnableIfDecl->getDeclName().getAsIdentifierInfo();
10405   if (!EnableIfII || !EnableIfII->isStr("enable_if"))
10406     return false;
10407 
10408   // Assume the first template argument is the condition.
10409   CondRange = EnableIfTSTLoc.getArgLoc(0).getSourceRange();
10410 
10411   // Dig out the condition.
10412   Cond = nullptr;
10413   if (EnableIfTSTLoc.getArgLoc(0).getArgument().getKind()
10414         != TemplateArgument::Expression)
10415     return true;
10416 
10417   Cond = EnableIfTSTLoc.getArgLoc(0).getSourceExpression();
10418 
10419   // Ignore Boolean literals; they add no value.
10420   if (isa<CXXBoolLiteralExpr>(Cond->IgnoreParenCasts()))
10421     Cond = nullptr;
10422 
10423   return true;
10424 }
10425 
10426 QualType
CheckTypenameType(ElaboratedTypeKeyword Keyword,SourceLocation KeywordLoc,NestedNameSpecifierLoc QualifierLoc,const IdentifierInfo & II,SourceLocation IILoc,TypeSourceInfo ** TSI,bool DeducedTSTContext)10427 Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
10428                         SourceLocation KeywordLoc,
10429                         NestedNameSpecifierLoc QualifierLoc,
10430                         const IdentifierInfo &II,
10431                         SourceLocation IILoc,
10432                         TypeSourceInfo **TSI,
10433                         bool DeducedTSTContext) {
10434   QualType T = CheckTypenameType(Keyword, KeywordLoc, QualifierLoc, II, IILoc,
10435                                  DeducedTSTContext);
10436   if (T.isNull())
10437     return QualType();
10438 
10439   *TSI = Context.CreateTypeSourceInfo(T);
10440   if (isa<DependentNameType>(T)) {
10441     DependentNameTypeLoc TL =
10442         (*TSI)->getTypeLoc().castAs<DependentNameTypeLoc>();
10443     TL.setElaboratedKeywordLoc(KeywordLoc);
10444     TL.setQualifierLoc(QualifierLoc);
10445     TL.setNameLoc(IILoc);
10446   } else {
10447     ElaboratedTypeLoc TL = (*TSI)->getTypeLoc().castAs<ElaboratedTypeLoc>();
10448     TL.setElaboratedKeywordLoc(KeywordLoc);
10449     TL.setQualifierLoc(QualifierLoc);
10450     TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IILoc);
10451   }
10452   return T;
10453 }
10454 
10455 /// Build the type that describes a C++ typename specifier,
10456 /// e.g., "typename T::type".
10457 QualType
CheckTypenameType(ElaboratedTypeKeyword Keyword,SourceLocation KeywordLoc,NestedNameSpecifierLoc QualifierLoc,const IdentifierInfo & II,SourceLocation IILoc,bool DeducedTSTContext)10458 Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
10459                         SourceLocation KeywordLoc,
10460                         NestedNameSpecifierLoc QualifierLoc,
10461                         const IdentifierInfo &II,
10462                         SourceLocation IILoc, bool DeducedTSTContext) {
10463   CXXScopeSpec SS;
10464   SS.Adopt(QualifierLoc);
10465 
10466   DeclContext *Ctx = nullptr;
10467   if (QualifierLoc) {
10468     Ctx = computeDeclContext(SS);
10469     if (!Ctx) {
10470       // If the nested-name-specifier is dependent and couldn't be
10471       // resolved to a type, build a typename type.
10472       assert(QualifierLoc.getNestedNameSpecifier()->isDependent());
10473       return Context.getDependentNameType(Keyword,
10474                                           QualifierLoc.getNestedNameSpecifier(),
10475                                           &II);
10476     }
10477 
10478     // If the nested-name-specifier refers to the current instantiation,
10479     // the "typename" keyword itself is superfluous. In C++03, the
10480     // program is actually ill-formed. However, DR 382 (in C++0x CD1)
10481     // allows such extraneous "typename" keywords, and we retroactively
10482     // apply this DR to C++03 code with only a warning. In any case we continue.
10483 
10484     if (RequireCompleteDeclContext(SS, Ctx))
10485       return QualType();
10486   }
10487 
10488   DeclarationName Name(&II);
10489   LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
10490   if (Ctx)
10491     LookupQualifiedName(Result, Ctx, SS);
10492   else
10493     LookupName(Result, CurScope);
10494   unsigned DiagID = 0;
10495   Decl *Referenced = nullptr;
10496   switch (Result.getResultKind()) {
10497   case LookupResult::NotFound: {
10498     // If we're looking up 'type' within a template named 'enable_if', produce
10499     // a more specific diagnostic.
10500     SourceRange CondRange;
10501     Expr *Cond = nullptr;
10502     if (Ctx && isEnableIf(QualifierLoc, II, CondRange, Cond)) {
10503       // If we have a condition, narrow it down to the specific failed
10504       // condition.
10505       if (Cond) {
10506         Expr *FailedCond;
10507         std::string FailedDescription;
10508         std::tie(FailedCond, FailedDescription) =
10509           findFailedBooleanCondition(Cond);
10510 
10511         Diag(FailedCond->getExprLoc(),
10512              diag::err_typename_nested_not_found_requirement)
10513           << FailedDescription
10514           << FailedCond->getSourceRange();
10515         return QualType();
10516       }
10517 
10518       Diag(CondRange.getBegin(),
10519            diag::err_typename_nested_not_found_enable_if)
10520           << Ctx << CondRange;
10521       return QualType();
10522     }
10523 
10524     DiagID = Ctx ? diag::err_typename_nested_not_found
10525                  : diag::err_unknown_typename;
10526     break;
10527   }
10528 
10529   case LookupResult::FoundUnresolvedValue: {
10530     // We found a using declaration that is a value. Most likely, the using
10531     // declaration itself is meant to have the 'typename' keyword.
10532     SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
10533                           IILoc);
10534     Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
10535       << Name << Ctx << FullRange;
10536     if (UnresolvedUsingValueDecl *Using
10537           = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
10538       SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
10539       Diag(Loc, diag::note_using_value_decl_missing_typename)
10540         << FixItHint::CreateInsertion(Loc, "typename ");
10541     }
10542   }
10543   // Fall through to create a dependent typename type, from which we can recover
10544   // better.
10545   [[fallthrough]];
10546 
10547   case LookupResult::NotFoundInCurrentInstantiation:
10548     // Okay, it's a member of an unknown instantiation.
10549     return Context.getDependentNameType(Keyword,
10550                                         QualifierLoc.getNestedNameSpecifier(),
10551                                         &II);
10552 
10553   case LookupResult::Found:
10554     if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
10555       // C++ [class.qual]p2:
10556       //   In a lookup in which function names are not ignored and the
10557       //   nested-name-specifier nominates a class C, if the name specified
10558       //   after the nested-name-specifier, when looked up in C, is the
10559       //   injected-class-name of C [...] then the name is instead considered
10560       //   to name the constructor of class C.
10561       //
10562       // Unlike in an elaborated-type-specifier, function names are not ignored
10563       // in typename-specifier lookup. However, they are ignored in all the
10564       // contexts where we form a typename type with no keyword (that is, in
10565       // mem-initializer-ids, base-specifiers, and elaborated-type-specifiers).
10566       //
10567       // FIXME: That's not strictly true: mem-initializer-id lookup does not
10568       // ignore functions, but that appears to be an oversight.
10569       auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(Ctx);
10570       auto *FoundRD = dyn_cast<CXXRecordDecl>(Type);
10571       if (Keyword == ElaboratedTypeKeyword::Typename && LookupRD && FoundRD &&
10572           FoundRD->isInjectedClassName() &&
10573           declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
10574         Diag(IILoc, diag::ext_out_of_line_qualified_id_type_names_constructor)
10575             << &II << 1 << 0 /*'typename' keyword used*/;
10576 
10577       // We found a type. Build an ElaboratedType, since the
10578       // typename-specifier was just sugar.
10579       MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
10580       return Context.getElaboratedType(Keyword,
10581                                        QualifierLoc.getNestedNameSpecifier(),
10582                                        Context.getTypeDeclType(Type));
10583     }
10584 
10585     // C++ [dcl.type.simple]p2:
10586     //   A type-specifier of the form
10587     //     typename[opt] nested-name-specifier[opt] template-name
10588     //   is a placeholder for a deduced class type [...].
10589     if (getLangOpts().CPlusPlus17) {
10590       if (auto *TD = getAsTypeTemplateDecl(Result.getFoundDecl())) {
10591         if (!DeducedTSTContext) {
10592           QualType T(QualifierLoc
10593                          ? QualifierLoc.getNestedNameSpecifier()->getAsType()
10594                          : nullptr, 0);
10595           if (!T.isNull())
10596             Diag(IILoc, diag::err_dependent_deduced_tst)
10597               << (int)getTemplateNameKindForDiagnostics(TemplateName(TD)) << T;
10598           else
10599             Diag(IILoc, diag::err_deduced_tst)
10600               << (int)getTemplateNameKindForDiagnostics(TemplateName(TD));
10601           NoteTemplateLocation(*TD);
10602           return QualType();
10603         }
10604         return Context.getElaboratedType(
10605             Keyword, QualifierLoc.getNestedNameSpecifier(),
10606             Context.getDeducedTemplateSpecializationType(TemplateName(TD),
10607                                                          QualType(), false));
10608       }
10609     }
10610 
10611     DiagID = Ctx ? diag::err_typename_nested_not_type
10612                  : diag::err_typename_not_type;
10613     Referenced = Result.getFoundDecl();
10614     break;
10615 
10616   case LookupResult::FoundOverloaded:
10617     DiagID = Ctx ? diag::err_typename_nested_not_type
10618                  : diag::err_typename_not_type;
10619     Referenced = *Result.begin();
10620     break;
10621 
10622   case LookupResult::Ambiguous:
10623     return QualType();
10624   }
10625 
10626   // If we get here, it's because name lookup did not find a
10627   // type. Emit an appropriate diagnostic and return an error.
10628   SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
10629                         IILoc);
10630   if (Ctx)
10631     Diag(IILoc, DiagID) << FullRange << Name << Ctx;
10632   else
10633     Diag(IILoc, DiagID) << FullRange << Name;
10634   if (Referenced)
10635     Diag(Referenced->getLocation(),
10636          Ctx ? diag::note_typename_member_refers_here
10637              : diag::note_typename_refers_here)
10638       << Name;
10639   return QualType();
10640 }
10641 
10642 namespace {
10643   // See Sema::RebuildTypeInCurrentInstantiation
10644   class CurrentInstantiationRebuilder
10645     : public TreeTransform<CurrentInstantiationRebuilder> {
10646     SourceLocation Loc;
10647     DeclarationName Entity;
10648 
10649   public:
10650     typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
10651 
CurrentInstantiationRebuilder(Sema & SemaRef,SourceLocation Loc,DeclarationName Entity)10652     CurrentInstantiationRebuilder(Sema &SemaRef,
10653                                   SourceLocation Loc,
10654                                   DeclarationName Entity)
10655     : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
10656       Loc(Loc), Entity(Entity) { }
10657 
10658     /// Determine whether the given type \p T has already been
10659     /// transformed.
10660     ///
10661     /// For the purposes of type reconstruction, a type has already been
10662     /// transformed if it is NULL or if it is not dependent.
AlreadyTransformed(QualType T)10663     bool AlreadyTransformed(QualType T) {
10664       return T.isNull() || !T->isInstantiationDependentType();
10665     }
10666 
10667     /// Returns the location of the entity whose type is being
10668     /// rebuilt.
getBaseLocation()10669     SourceLocation getBaseLocation() { return Loc; }
10670 
10671     /// Returns the name of the entity whose type is being rebuilt.
getBaseEntity()10672     DeclarationName getBaseEntity() { return Entity; }
10673 
10674     /// Sets the "base" location and entity when that
10675     /// information is known based on another transformation.
setBase(SourceLocation Loc,DeclarationName Entity)10676     void setBase(SourceLocation Loc, DeclarationName Entity) {
10677       this->Loc = Loc;
10678       this->Entity = Entity;
10679     }
10680 
TransformLambdaExpr(LambdaExpr * E)10681     ExprResult TransformLambdaExpr(LambdaExpr *E) {
10682       // Lambdas never need to be transformed.
10683       return E;
10684     }
10685   };
10686 } // end anonymous namespace
10687 
RebuildTypeInCurrentInstantiation(TypeSourceInfo * T,SourceLocation Loc,DeclarationName Name)10688 TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
10689                                                         SourceLocation Loc,
10690                                                         DeclarationName Name) {
10691   if (!T || !T->getType()->isInstantiationDependentType())
10692     return T;
10693 
10694   CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
10695   return Rebuilder.TransformType(T);
10696 }
10697 
RebuildExprInCurrentInstantiation(Expr * E)10698 ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
10699   CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
10700                                           DeclarationName());
10701   return Rebuilder.TransformExpr(E);
10702 }
10703 
RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec & SS)10704 bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
10705   if (SS.isInvalid())
10706     return true;
10707 
10708   NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
10709   CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
10710                                           DeclarationName());
10711   NestedNameSpecifierLoc Rebuilt
10712     = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
10713   if (!Rebuilt)
10714     return true;
10715 
10716   SS.Adopt(Rebuilt);
10717   return false;
10718 }
10719 
RebuildTemplateParamsInCurrentInstantiation(TemplateParameterList * Params)10720 bool Sema::RebuildTemplateParamsInCurrentInstantiation(
10721                                                TemplateParameterList *Params) {
10722   for (unsigned I = 0, N = Params->size(); I != N; ++I) {
10723     Decl *Param = Params->getParam(I);
10724 
10725     // There is nothing to rebuild in a type parameter.
10726     if (isa<TemplateTypeParmDecl>(Param))
10727       continue;
10728 
10729     // Rebuild the template parameter list of a template template parameter.
10730     if (TemplateTemplateParmDecl *TTP
10731         = dyn_cast<TemplateTemplateParmDecl>(Param)) {
10732       if (RebuildTemplateParamsInCurrentInstantiation(
10733             TTP->getTemplateParameters()))
10734         return true;
10735 
10736       continue;
10737     }
10738 
10739     // Rebuild the type of a non-type template parameter.
10740     NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Param);
10741     TypeSourceInfo *NewTSI
10742       = RebuildTypeInCurrentInstantiation(NTTP->getTypeSourceInfo(),
10743                                           NTTP->getLocation(),
10744                                           NTTP->getDeclName());
10745     if (!NewTSI)
10746       return true;
10747 
10748     if (NewTSI->getType()->isUndeducedType()) {
10749       // C++17 [temp.dep.expr]p3:
10750       //   An id-expression is type-dependent if it contains
10751       //    - an identifier associated by name lookup with a non-type
10752       //      template-parameter declared with a type that contains a
10753       //      placeholder type (7.1.7.4),
10754       NewTSI = SubstAutoTypeSourceInfoDependent(NewTSI);
10755     }
10756 
10757     if (NewTSI != NTTP->getTypeSourceInfo()) {
10758       NTTP->setTypeSourceInfo(NewTSI);
10759       NTTP->setType(NewTSI->getType());
10760     }
10761   }
10762 
10763   return false;
10764 }
10765 
10766 std::string
getTemplateArgumentBindingsText(const TemplateParameterList * Params,const TemplateArgumentList & Args)10767 Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
10768                                       const TemplateArgumentList &Args) {
10769   return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
10770 }
10771 
10772 std::string
getTemplateArgumentBindingsText(const TemplateParameterList * Params,const TemplateArgument * Args,unsigned NumArgs)10773 Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
10774                                       const TemplateArgument *Args,
10775                                       unsigned NumArgs) {
10776   SmallString<128> Str;
10777   llvm::raw_svector_ostream Out(Str);
10778 
10779   if (!Params || Params->size() == 0 || NumArgs == 0)
10780     return std::string();
10781 
10782   for (unsigned I = 0, N = Params->size(); I != N; ++I) {
10783     if (I >= NumArgs)
10784       break;
10785 
10786     if (I == 0)
10787       Out << "[with ";
10788     else
10789       Out << ", ";
10790 
10791     if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
10792       Out << Id->getName();
10793     } else {
10794       Out << '$' << I;
10795     }
10796 
10797     Out << " = ";
10798     Args[I].print(getPrintingPolicy(), Out,
10799                   TemplateParameterList::shouldIncludeTypeForArgument(
10800                       getPrintingPolicy(), Params, I));
10801   }
10802 
10803   Out << ']';
10804   return std::string(Out.str());
10805 }
10806 
MarkAsLateParsedTemplate(FunctionDecl * FD,Decl * FnD,CachedTokens & Toks)10807 void Sema::MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
10808                                     CachedTokens &Toks) {
10809   if (!FD)
10810     return;
10811 
10812   auto LPT = std::make_unique<LateParsedTemplate>();
10813 
10814   // Take tokens to avoid allocations
10815   LPT->Toks.swap(Toks);
10816   LPT->D = FnD;
10817   LPT->FPO = getCurFPFeatures();
10818   LateParsedTemplateMap.insert(std::make_pair(FD, std::move(LPT)));
10819 
10820   FD->setLateTemplateParsed(true);
10821 }
10822 
UnmarkAsLateParsedTemplate(FunctionDecl * FD)10823 void Sema::UnmarkAsLateParsedTemplate(FunctionDecl *FD) {
10824   if (!FD)
10825     return;
10826   FD->setLateTemplateParsed(false);
10827 }
10828 
IsInsideALocalClassWithinATemplateFunction()10829 bool Sema::IsInsideALocalClassWithinATemplateFunction() {
10830   DeclContext *DC = CurContext;
10831 
10832   while (DC) {
10833     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
10834       const FunctionDecl *FD = RD->isLocalClass();
10835       return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
10836     } else if (DC->isTranslationUnit() || DC->isNamespace())
10837       return false;
10838 
10839     DC = DC->getParent();
10840   }
10841   return false;
10842 }
10843 
10844 namespace {
10845 /// Walk the path from which a declaration was instantiated, and check
10846 /// that every explicit specialization along that path is visible. This enforces
10847 /// C++ [temp.expl.spec]/6:
10848 ///
10849 ///   If a template, a member template or a member of a class template is
10850 ///   explicitly specialized then that specialization shall be declared before
10851 ///   the first use of that specialization that would cause an implicit
10852 ///   instantiation to take place, in every translation unit in which such a
10853 ///   use occurs; no diagnostic is required.
10854 ///
10855 /// and also C++ [temp.class.spec]/1:
10856 ///
10857 ///   A partial specialization shall be declared before the first use of a
10858 ///   class template specialization that would make use of the partial
10859 ///   specialization as the result of an implicit or explicit instantiation
10860 ///   in every translation unit in which such a use occurs; no diagnostic is
10861 ///   required.
10862 class ExplicitSpecializationVisibilityChecker {
10863   Sema &S;
10864   SourceLocation Loc;
10865   llvm::SmallVector<Module *, 8> Modules;
10866   Sema::AcceptableKind Kind;
10867 
10868 public:
ExplicitSpecializationVisibilityChecker(Sema & S,SourceLocation Loc,Sema::AcceptableKind Kind)10869   ExplicitSpecializationVisibilityChecker(Sema &S, SourceLocation Loc,
10870                                           Sema::AcceptableKind Kind)
10871       : S(S), Loc(Loc), Kind(Kind) {}
10872 
check(NamedDecl * ND)10873   void check(NamedDecl *ND) {
10874     if (auto *FD = dyn_cast<FunctionDecl>(ND))
10875       return checkImpl(FD);
10876     if (auto *RD = dyn_cast<CXXRecordDecl>(ND))
10877       return checkImpl(RD);
10878     if (auto *VD = dyn_cast<VarDecl>(ND))
10879       return checkImpl(VD);
10880     if (auto *ED = dyn_cast<EnumDecl>(ND))
10881       return checkImpl(ED);
10882   }
10883 
10884 private:
diagnose(NamedDecl * D,bool IsPartialSpec)10885   void diagnose(NamedDecl *D, bool IsPartialSpec) {
10886     auto Kind = IsPartialSpec ? Sema::MissingImportKind::PartialSpecialization
10887                               : Sema::MissingImportKind::ExplicitSpecialization;
10888     const bool Recover = true;
10889 
10890     // If we got a custom set of modules (because only a subset of the
10891     // declarations are interesting), use them, otherwise let
10892     // diagnoseMissingImport intelligently pick some.
10893     if (Modules.empty())
10894       S.diagnoseMissingImport(Loc, D, Kind, Recover);
10895     else
10896       S.diagnoseMissingImport(Loc, D, D->getLocation(), Modules, Kind, Recover);
10897   }
10898 
CheckMemberSpecialization(const NamedDecl * D)10899   bool CheckMemberSpecialization(const NamedDecl *D) {
10900     return Kind == Sema::AcceptableKind::Visible
10901                ? S.hasVisibleMemberSpecialization(D)
10902                : S.hasReachableMemberSpecialization(D);
10903   }
10904 
CheckExplicitSpecialization(const NamedDecl * D)10905   bool CheckExplicitSpecialization(const NamedDecl *D) {
10906     return Kind == Sema::AcceptableKind::Visible
10907                ? S.hasVisibleExplicitSpecialization(D)
10908                : S.hasReachableExplicitSpecialization(D);
10909   }
10910 
CheckDeclaration(const NamedDecl * D)10911   bool CheckDeclaration(const NamedDecl *D) {
10912     return Kind == Sema::AcceptableKind::Visible ? S.hasVisibleDeclaration(D)
10913                                                  : S.hasReachableDeclaration(D);
10914   }
10915 
10916   // Check a specific declaration. There are three problematic cases:
10917   //
10918   //  1) The declaration is an explicit specialization of a template
10919   //     specialization.
10920   //  2) The declaration is an explicit specialization of a member of an
10921   //     templated class.
10922   //  3) The declaration is an instantiation of a template, and that template
10923   //     is an explicit specialization of a member of a templated class.
10924   //
10925   // We don't need to go any deeper than that, as the instantiation of the
10926   // surrounding class / etc is not triggered by whatever triggered this
10927   // instantiation, and thus should be checked elsewhere.
10928   template<typename SpecDecl>
checkImpl(SpecDecl * Spec)10929   void checkImpl(SpecDecl *Spec) {
10930     bool IsHiddenExplicitSpecialization = false;
10931     if (Spec->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) {
10932       IsHiddenExplicitSpecialization = Spec->getMemberSpecializationInfo()
10933                                            ? !CheckMemberSpecialization(Spec)
10934                                            : !CheckExplicitSpecialization(Spec);
10935     } else {
10936       checkInstantiated(Spec);
10937     }
10938 
10939     if (IsHiddenExplicitSpecialization)
10940       diagnose(Spec->getMostRecentDecl(), false);
10941   }
10942 
checkInstantiated(FunctionDecl * FD)10943   void checkInstantiated(FunctionDecl *FD) {
10944     if (auto *TD = FD->getPrimaryTemplate())
10945       checkTemplate(TD);
10946   }
10947 
checkInstantiated(CXXRecordDecl * RD)10948   void checkInstantiated(CXXRecordDecl *RD) {
10949     auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD);
10950     if (!SD)
10951       return;
10952 
10953     auto From = SD->getSpecializedTemplateOrPartial();
10954     if (auto *TD = From.dyn_cast<ClassTemplateDecl *>())
10955       checkTemplate(TD);
10956     else if (auto *TD =
10957                  From.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
10958       if (!CheckDeclaration(TD))
10959         diagnose(TD, true);
10960       checkTemplate(TD);
10961     }
10962   }
10963 
checkInstantiated(VarDecl * RD)10964   void checkInstantiated(VarDecl *RD) {
10965     auto *SD = dyn_cast<VarTemplateSpecializationDecl>(RD);
10966     if (!SD)
10967       return;
10968 
10969     auto From = SD->getSpecializedTemplateOrPartial();
10970     if (auto *TD = From.dyn_cast<VarTemplateDecl *>())
10971       checkTemplate(TD);
10972     else if (auto *TD =
10973                  From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
10974       if (!CheckDeclaration(TD))
10975         diagnose(TD, true);
10976       checkTemplate(TD);
10977     }
10978   }
10979 
checkInstantiated(EnumDecl * FD)10980   void checkInstantiated(EnumDecl *FD) {}
10981 
10982   template<typename TemplDecl>
checkTemplate(TemplDecl * TD)10983   void checkTemplate(TemplDecl *TD) {
10984     if (TD->isMemberSpecialization()) {
10985       if (!CheckMemberSpecialization(TD))
10986         diagnose(TD->getMostRecentDecl(), false);
10987     }
10988   }
10989 };
10990 } // end anonymous namespace
10991 
checkSpecializationVisibility(SourceLocation Loc,NamedDecl * Spec)10992 void Sema::checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec) {
10993   if (!getLangOpts().Modules)
10994     return;
10995 
10996   ExplicitSpecializationVisibilityChecker(*this, Loc,
10997                                           Sema::AcceptableKind::Visible)
10998       .check(Spec);
10999 }
11000 
checkSpecializationReachability(SourceLocation Loc,NamedDecl * Spec)11001 void Sema::checkSpecializationReachability(SourceLocation Loc,
11002                                            NamedDecl *Spec) {
11003   if (!getLangOpts().CPlusPlusModules)
11004     return checkSpecializationVisibility(Loc, Spec);
11005 
11006   ExplicitSpecializationVisibilityChecker(*this, Loc,
11007                                           Sema::AcceptableKind::Reachable)
11008       .check(Spec);
11009 }
11010 
getTopMostPointOfInstantiation(const NamedDecl * N) const11011 SourceLocation Sema::getTopMostPointOfInstantiation(const NamedDecl *N) const {
11012   if (!getLangOpts().CPlusPlus || CodeSynthesisContexts.empty())
11013     return N->getLocation();
11014   if (const auto *FD = dyn_cast<FunctionDecl>(N)) {
11015     if (!FD->isFunctionTemplateSpecialization())
11016       return FD->getLocation();
11017   } else if (!isa<ClassTemplateSpecializationDecl,
11018                   VarTemplateSpecializationDecl>(N)) {
11019     return N->getLocation();
11020   }
11021   for (const CodeSynthesisContext &CSC : CodeSynthesisContexts) {
11022     if (!CSC.isInstantiationRecord() || CSC.PointOfInstantiation.isInvalid())
11023       continue;
11024     return CSC.PointOfInstantiation;
11025   }
11026   return N->getLocation();
11027 }
11028