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