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