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