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