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