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