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