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