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