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