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