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