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