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