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