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