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