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