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