clang  16.0.0git
SemaTemplate.cpp
Go to the documentation of this file.
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/Decl.h"
15 #include "clang/AST/DeclFriend.h"
16 #include "clang/AST/DeclTemplate.h"
17 #include "clang/AST/Expr.h"
18 #include "clang/AST/ExprCXX.h"
20 #include "clang/AST/TemplateName.h"
21 #include "clang/AST/TypeVisitor.h"
22 #include "clang/Basic/Builtins.h"
26 #include "clang/Basic/Stack.h"
27 #include "clang/Basic/TargetInfo.h"
28 #include "clang/Sema/DeclSpec.h"
30 #include "clang/Sema/Lookup.h"
31 #include "clang/Sema/Overload.h"
33 #include "clang/Sema/Scope.h"
35 #include "clang/Sema/Template.h"
37 #include "llvm/ADT/SmallBitVector.h"
38 #include "llvm/ADT/SmallString.h"
39 #include "llvm/ADT/StringExtras.h"
40 
41 #include <iterator>
42 using namespace clang;
43 using namespace sema;
44 
45 // Exported for use by Parser.
48  unsigned N) {
49  if (!N) return SourceRange();
50  return SourceRange(Ps[0]->getTemplateLoc(), Ps[N-1]->getRAngleLoc());
51 }
52 
53 unsigned Sema::getTemplateDepth(Scope *S) const {
54  unsigned Depth = 0;
55 
56  // Each template parameter scope represents one level of template parameter
57  // depth.
58  for (Scope *TempParamScope = S->getTemplateParamParent(); TempParamScope;
59  TempParamScope = TempParamScope->getParent()->getTemplateParamParent()) {
60  ++Depth;
61  }
62 
63  // Note that there are template parameters with the given depth.
64  auto ParamsAtDepth = [&](unsigned D) { Depth = std::max(Depth, D + 1); };
65 
66  // Look for parameters of an enclosing generic lambda. We don't create a
67  // template parameter scope for these.
68  for (FunctionScopeInfo *FSI : getFunctionScopes()) {
69  if (auto *LSI = dyn_cast<LambdaScopeInfo>(FSI)) {
70  if (!LSI->TemplateParams.empty()) {
71  ParamsAtDepth(LSI->AutoTemplateParameterDepth);
72  break;
73  }
74  if (LSI->GLTemplateParameterList) {
75  ParamsAtDepth(LSI->GLTemplateParameterList->getDepth());
76  break;
77  }
78  }
79  }
80 
81  // Look for parameters of an enclosing terse function template. We don't
82  // create a template parameter scope for these either.
83  for (const InventedTemplateParameterInfo &Info :
84  getInventedParameterInfos()) {
85  if (!Info.TemplateParams.empty()) {
86  ParamsAtDepth(Info.AutoTemplateParameterDepth);
87  break;
88  }
89  }
90 
91  return Depth;
92 }
93 
94 /// \brief Determine whether the declaration found is acceptable as the name
95 /// of a template and, if so, return that template declaration. Otherwise,
96 /// returns null.
97 ///
98 /// Note that this may return an UnresolvedUsingValueDecl if AllowDependent
99 /// is true. In all other cases it will return a TemplateDecl (or null).
101  bool AllowFunctionTemplates,
102  bool AllowDependent) {
103  D = D->getUnderlyingDecl();
104 
105  if (isa<TemplateDecl>(D)) {
106  if (!AllowFunctionTemplates && isa<FunctionTemplateDecl>(D))
107  return nullptr;
108 
109  return D;
110  }
111 
112  if (const auto *Record = dyn_cast<CXXRecordDecl>(D)) {
113  // C++ [temp.local]p1:
114  // Like normal (non-template) classes, class templates have an
115  // injected-class-name (Clause 9). The injected-class-name
116  // can be used with or without a template-argument-list. When
117  // it is used without a template-argument-list, it is
118  // equivalent to the injected-class-name followed by the
119  // template-parameters of the class template enclosed in
120  // <>. When it is used with a template-argument-list, it
121  // refers to the specified class template specialization,
122  // which could be the current specialization or another
123  // specialization.
124  if (Record->isInjectedClassName()) {
125  Record = cast<CXXRecordDecl>(Record->getDeclContext());
126  if (Record->getDescribedClassTemplate())
127  return Record->getDescribedClassTemplate();
128 
129  if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(Record))
130  return Spec->getSpecializedTemplate();
131  }
132 
133  return nullptr;
134  }
135 
136  // 'using Dependent::foo;' can resolve to a template name.
137  // 'using typename Dependent::foo;' cannot (not even if 'foo' is an
138  // injected-class-name).
139  if (AllowDependent && isa<UnresolvedUsingValueDecl>(D))
140  return D;
141 
142  return nullptr;
143 }
144 
146  bool AllowFunctionTemplates,
147  bool AllowDependent) {
148  LookupResult::Filter filter = R.makeFilter();
149  while (filter.hasNext()) {
150  NamedDecl *Orig = filter.next();
151  if (!getAsTemplateNameDecl(Orig, AllowFunctionTemplates, AllowDependent))
152  filter.erase();
153  }
154  filter.done();
155 }
156 
158  bool AllowFunctionTemplates,
159  bool AllowDependent,
160  bool AllowNonTemplateFunctions) {
161  for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
162  if (getAsTemplateNameDecl(*I, AllowFunctionTemplates, AllowDependent))
163  return true;
164  if (AllowNonTemplateFunctions &&
165  isa<FunctionDecl>((*I)->getUnderlyingDecl()))
166  return true;
167  }
168 
169  return false;
170 }
171 
173  CXXScopeSpec &SS,
174  bool hasTemplateKeyword,
175  const UnqualifiedId &Name,
176  ParsedType ObjectTypePtr,
177  bool EnteringContext,
178  TemplateTy &TemplateResult,
179  bool &MemberOfUnknownSpecialization,
180  bool Disambiguation) {
181  assert(getLangOpts().CPlusPlus && "No template names in C!");
182 
183  DeclarationName TName;
184  MemberOfUnknownSpecialization = false;
185 
186  switch (Name.getKind()) {
188  TName = DeclarationName(Name.Identifier);
189  break;
190 
192  TName = Context.DeclarationNames.getCXXOperatorName(
193  Name.OperatorFunctionId.Operator);
194  break;
195 
197  TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
198  break;
199 
200  default:
201  return TNK_Non_template;
202  }
203 
204  QualType ObjectType = ObjectTypePtr.get();
205 
206  AssumedTemplateKind AssumedTemplate;
207  LookupResult R(*this, TName, Name.getBeginLoc(), LookupOrdinaryName);
208  if (LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
209  MemberOfUnknownSpecialization, SourceLocation(),
210  &AssumedTemplate,
211  /*AllowTypoCorrection=*/!Disambiguation))
212  return TNK_Non_template;
213 
214  if (AssumedTemplate != AssumedTemplateKind::None) {
215  TemplateResult = TemplateTy::make(Context.getAssumedTemplateName(TName));
216  // Let the parser know whether we found nothing or found functions; if we
217  // found nothing, we want to more carefully check whether this is actually
218  // a function template name versus some other kind of undeclared identifier.
219  return AssumedTemplate == AssumedTemplateKind::FoundNothing
222  }
223 
224  if (R.empty())
225  return TNK_Non_template;
226 
227  NamedDecl *D = nullptr;
228  UsingShadowDecl *FoundUsingShadow = dyn_cast<UsingShadowDecl>(*R.begin());
229  if (R.isAmbiguous()) {
230  // If we got an ambiguity involving a non-function template, treat this
231  // as a template name, and pick an arbitrary template for error recovery.
232  bool AnyFunctionTemplates = false;
233  for (NamedDecl *FoundD : R) {
234  if (NamedDecl *FoundTemplate = getAsTemplateNameDecl(FoundD)) {
235  if (isa<FunctionTemplateDecl>(FoundTemplate))
236  AnyFunctionTemplates = true;
237  else {
238  D = FoundTemplate;
239  FoundUsingShadow = dyn_cast<UsingShadowDecl>(FoundD);
240  break;
241  }
242  }
243  }
244 
245  // If we didn't find any templates at all, this isn't a template name.
246  // Leave the ambiguity for a later lookup to diagnose.
247  if (!D && !AnyFunctionTemplates) {
248  R.suppressDiagnostics();
249  return TNK_Non_template;
250  }
251 
252  // If the only templates were function templates, filter out the rest.
253  // We'll diagnose the ambiguity later.
254  if (!D)
255  FilterAcceptableTemplateNames(R);
256  }
257 
258  // At this point, we have either picked a single template name declaration D
259  // or we have a non-empty set of results R containing either one template name
260  // declaration or a set of function templates.
261 
262  TemplateName Template;
263  TemplateNameKind TemplateKind;
264 
265  unsigned ResultCount = R.end() - R.begin();
266  if (!D && ResultCount > 1) {
267  // We assume that we'll preserve the qualifier from a function
268  // template name in other ways.
269  Template = Context.getOverloadedTemplateName(R.begin(), R.end());
270  TemplateKind = TNK_Function_template;
271 
272  // We'll do this lookup again later.
274  } else {
275  if (!D) {
276  D = getAsTemplateNameDecl(*R.begin());
277  assert(D && "unambiguous result is not a template name");
278  }
279 
280  if (isa<UnresolvedUsingValueDecl>(D)) {
281  // We don't yet know whether this is a template-name or not.
282  MemberOfUnknownSpecialization = true;
283  return TNK_Non_template;
284  }
285 
286  TemplateDecl *TD = cast<TemplateDecl>(D);
287  Template =
288  FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD);
289  assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD);
290  if (SS.isSet() && !SS.isInvalid()) {
291  NestedNameSpecifier *Qualifier = SS.getScopeRep();
292  Template = Context.getQualifiedTemplateName(Qualifier, hasTemplateKeyword,
293  Template);
294  }
295 
296  if (isa<FunctionTemplateDecl>(TD)) {
297  TemplateKind = TNK_Function_template;
298 
299  // We'll do this lookup again later.
301  } else {
302  assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) ||
303  isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD) ||
304  isa<BuiltinTemplateDecl>(TD) || isa<ConceptDecl>(TD));
305  TemplateKind =
306  isa<VarTemplateDecl>(TD) ? TNK_Var_template :
307  isa<ConceptDecl>(TD) ? TNK_Concept_template :
309  }
310  }
311 
312  TemplateResult = TemplateTy::make(Template);
313  return TemplateKind;
314 }
315 
317  SourceLocation NameLoc,
318  ParsedTemplateTy *Template) {
319  CXXScopeSpec SS;
320  bool MemberOfUnknownSpecialization = false;
321 
322  // We could use redeclaration lookup here, but we don't need to: the
323  // syntactic form of a deduction guide is enough to identify it even
324  // if we can't look up the template name at all.
325  LookupResult R(*this, DeclarationName(&Name), NameLoc, LookupOrdinaryName);
326  if (LookupTemplateName(R, S, SS, /*ObjectType*/ QualType(),
327  /*EnteringContext*/ false,
328  MemberOfUnknownSpecialization))
329  return false;
330 
331  if (R.empty()) return false;
332  if (R.isAmbiguous()) {
333  // FIXME: Diagnose an ambiguity if we find at least one template.
335  return false;
336  }
337 
338  // We only treat template-names that name type templates as valid deduction
339  // guide names.
341  if (!TD || !getAsTypeTemplateDecl(TD))
342  return false;
343 
344  if (Template)
345  *Template = TemplateTy::make(TemplateName(TD));
346  return true;
347 }
348 
350  SourceLocation IILoc,
351  Scope *S,
352  const CXXScopeSpec *SS,
353  TemplateTy &SuggestedTemplate,
354  TemplateNameKind &SuggestedKind) {
355  // We can't recover unless there's a dependent scope specifier preceding the
356  // template name.
357  // FIXME: Typo correction?
358  if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
359  computeDeclContext(*SS))
360  return false;
361 
362  // The code is missing a 'template' keyword prior to the dependent template
363  // name.
365  Diag(IILoc, diag::err_template_kw_missing)
366  << Qualifier << II.getName()
367  << FixItHint::CreateInsertion(IILoc, "template ");
368  SuggestedTemplate
369  = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II));
370  SuggestedKind = TNK_Dependent_template_name;
371  return true;
372 }
373 
375  Scope *S, CXXScopeSpec &SS,
376  QualType ObjectType,
377  bool EnteringContext,
378  bool &MemberOfUnknownSpecialization,
379  RequiredTemplateKind RequiredTemplate,
380  AssumedTemplateKind *ATK,
381  bool AllowTypoCorrection) {
382  if (ATK)
384 
385  if (SS.isInvalid())
386  return true;
387 
388  Found.setTemplateNameLookup(true);
389 
390  // Determine where to perform name lookup
391  MemberOfUnknownSpecialization = false;
392  DeclContext *LookupCtx = nullptr;
393  bool IsDependent = false;
394  if (!ObjectType.isNull()) {
395  // This nested-name-specifier occurs in a member access expression, e.g.,
396  // x->B::f, and we are looking into the type of the object.
397  assert(SS.isEmpty() && "ObjectType and scope specifier cannot coexist");
398  LookupCtx = computeDeclContext(ObjectType);
399  IsDependent = !LookupCtx && ObjectType->isDependentType();
400  assert((IsDependent || !ObjectType->isIncompleteType() ||
401  !ObjectType->getAs<TagType>() ||
402  ObjectType->castAs<TagType>()->isBeingDefined()) &&
403  "Caller should have completed object type");
404 
405  // Template names cannot appear inside an Objective-C class or object type
406  // or a vector type.
407  //
408  // FIXME: This is wrong. For example:
409  //
410  // template<typename T> using Vec = T __attribute__((ext_vector_type(4)));
411  // Vec<int> vi;
412  // vi.Vec<int>::~Vec<int>();
413  //
414  // ... should be accepted but we will not treat 'Vec' as a template name
415  // here. The right thing to do would be to check if the name is a valid
416  // vector component name, and look up a template name if not. And similarly
417  // for lookups into Objective-C class and object types, where the same
418  // problem can arise.
419  if (ObjectType->isObjCObjectOrInterfaceType() ||
420  ObjectType->isVectorType()) {
421  Found.clear();
422  return false;
423  }
424  } else if (SS.isNotEmpty()) {
425  // This nested-name-specifier occurs after another nested-name-specifier,
426  // so long into the context associated with the prior nested-name-specifier.
427  LookupCtx = computeDeclContext(SS, EnteringContext);
428  IsDependent = !LookupCtx && isDependentScopeSpecifier(SS);
429 
430  // The declaration context must be complete.
431  if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
432  return true;
433  }
434 
435  bool ObjectTypeSearchedInScope = false;
436  bool AllowFunctionTemplatesInLookup = true;
437  if (LookupCtx) {
438  // Perform "qualified" name lookup into the declaration context we
439  // computed, which is either the type of the base of a member access
440  // expression or the declaration context associated with a prior
441  // nested-name-specifier.
442  LookupQualifiedName(Found, LookupCtx);
443 
444  // FIXME: The C++ standard does not clearly specify what happens in the
445  // case where the object type is dependent, and implementations vary. In
446  // Clang, we treat a name after a . or -> as a template-name if lookup
447  // finds a non-dependent member or member of the current instantiation that
448  // is a type template, or finds no such members and lookup in the context
449  // of the postfix-expression finds a type template. In the latter case, the
450  // name is nonetheless dependent, and we may resolve it to a member of an
451  // unknown specialization when we come to instantiate the template.
452  IsDependent |= Found.wasNotFoundInCurrentInstantiation();
453  }
454 
455  if (SS.isEmpty() && (ObjectType.isNull() || Found.empty())) {
456  // C++ [basic.lookup.classref]p1:
457  // In a class member access expression (5.2.5), if the . or -> token is
458  // immediately followed by an identifier followed by a <, the
459  // identifier must be looked up to determine whether the < is the
460  // beginning of a template argument list (14.2) or a less-than operator.
461  // The identifier is first looked up in the class of the object
462  // expression. If the identifier is not found, it is then looked up in
463  // the context of the entire postfix-expression and shall name a class
464  // template.
465  if (S)
466  LookupName(Found, S);
467 
468  if (!ObjectType.isNull()) {
469  // FIXME: We should filter out all non-type templates here, particularly
470  // variable templates and concepts. But the exclusion of alias templates
471  // and template template parameters is a wording defect.
472  AllowFunctionTemplatesInLookup = false;
473  ObjectTypeSearchedInScope = true;
474  }
475 
476  IsDependent |= Found.wasNotFoundInCurrentInstantiation();
477  }
478 
479  if (Found.isAmbiguous())
480  return false;
481 
482  if (ATK && SS.isEmpty() && ObjectType.isNull() &&
483  !RequiredTemplate.hasTemplateKeyword()) {
484  // C++2a [temp.names]p2:
485  // A name is also considered to refer to a template if it is an
486  // unqualified-id followed by a < and name lookup finds either one or more
487  // functions or finds nothing.
488  //
489  // To keep our behavior consistent, we apply the "finds nothing" part in
490  // all language modes, and diagnose the empty lookup in ActOnCallExpr if we
491  // successfully form a call to an undeclared template-id.
492  bool AllFunctions =
493  getLangOpts().CPlusPlus20 && llvm::all_of(Found, [](NamedDecl *ND) {
494  return isa<FunctionDecl>(ND->getUnderlyingDecl());
495  });
496  if (AllFunctions || (Found.empty() && !IsDependent)) {
497  // If lookup found any functions, or if this is a name that can only be
498  // used for a function, then strongly assume this is a function
499  // template-id.
500  *ATK = (Found.empty() && Found.getLookupName().isIdentifier())
501  ? AssumedTemplateKind::FoundNothing
502  : AssumedTemplateKind::FoundFunctions;
503  Found.clear();
504  return false;
505  }
506  }
507 
508  if (Found.empty() && !IsDependent && AllowTypoCorrection) {
509  // If we did not find any names, and this is not a disambiguation, attempt
510  // to correct any typos.
511  DeclarationName Name = Found.getLookupName();
512  Found.clear();
513  // Simple filter callback that, for keywords, only accepts the C++ *_cast
514  DefaultFilterCCC FilterCCC{};
515  FilterCCC.WantTypeSpecifiers = false;
516  FilterCCC.WantExpressionKeywords = false;
517  FilterCCC.WantRemainingKeywords = false;
518  FilterCCC.WantCXXNamedCasts = true;
519  if (TypoCorrection Corrected =
520  CorrectTypo(Found.getLookupNameInfo(), Found.getLookupKind(), S,
521  &SS, FilterCCC, CTK_ErrorRecovery, LookupCtx)) {
522  if (auto *ND = Corrected.getFoundDecl())
523  Found.addDecl(ND);
524  FilterAcceptableTemplateNames(Found);
525  if (Found.isAmbiguous()) {
526  Found.clear();
527  } else if (!Found.empty()) {
528  Found.setLookupName(Corrected.getCorrection());
529  if (LookupCtx) {
530  std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
531  bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
532  Name.getAsString() == CorrectedStr;
533  diagnoseTypo(Corrected, PDiag(diag::err_no_member_template_suggest)
534  << Name << LookupCtx << DroppedSpecifier
535  << SS.getRange());
536  } else {
537  diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest) << Name);
538  }
539  }
540  }
541  }
542 
543  NamedDecl *ExampleLookupResult =
544  Found.empty() ? nullptr : Found.getRepresentativeDecl();
545  FilterAcceptableTemplateNames(Found, AllowFunctionTemplatesInLookup);
546  if (Found.empty()) {
547  if (IsDependent) {
548  MemberOfUnknownSpecialization = true;
549  return false;
550  }
551 
552  // If a 'template' keyword was used, a lookup that finds only non-template
553  // names is an error.
554  if (ExampleLookupResult && RequiredTemplate) {
555  Diag(Found.getNameLoc(), diag::err_template_kw_refers_to_non_template)
556  << Found.getLookupName() << SS.getRange()
557  << RequiredTemplate.hasTemplateKeyword()
558  << RequiredTemplate.getTemplateKeywordLoc();
559  Diag(ExampleLookupResult->getUnderlyingDecl()->getLocation(),
560  diag::note_template_kw_refers_to_non_template)
561  << Found.getLookupName();
562  return true;
563  }
564 
565  return false;
566  }
567 
568  if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope &&
569  !getLangOpts().CPlusPlus11) {
570  // C++03 [basic.lookup.classref]p1:
571  // [...] If the lookup in the class of the object expression finds a
572  // template, the name is also looked up in the context of the entire
573  // postfix-expression and [...]
574  //
575  // Note: C++11 does not perform this second lookup.
576  LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
577  LookupOrdinaryName);
578  FoundOuter.setTemplateNameLookup(true);
579  LookupName(FoundOuter, S);
580  // FIXME: We silently accept an ambiguous lookup here, in violation of
581  // [basic.lookup]/1.
582  FilterAcceptableTemplateNames(FoundOuter, /*AllowFunctionTemplates=*/false);
583 
584  NamedDecl *OuterTemplate;
585  if (FoundOuter.empty()) {
586  // - if the name is not found, the name found in the class of the
587  // object expression is used, otherwise
588  } else if (FoundOuter.isAmbiguous() || !FoundOuter.isSingleResult() ||
589  !(OuterTemplate =
590  getAsTemplateNameDecl(FoundOuter.getFoundDecl()))) {
591  // - if the name is found in the context of the entire
592  // postfix-expression and does not name a class template, the name
593  // found in the class of the object expression is used, otherwise
594  FoundOuter.clear();
595  } else if (!Found.isSuppressingDiagnostics()) {
596  // - if the name found is a class template, it must refer to the same
597  // entity as the one found in the class of the object expression,
598  // otherwise the program is ill-formed.
599  if (!Found.isSingleResult() ||
600  getAsTemplateNameDecl(Found.getFoundDecl())->getCanonicalDecl() !=
601  OuterTemplate->getCanonicalDecl()) {
602  Diag(Found.getNameLoc(),
603  diag::ext_nested_name_member_ref_lookup_ambiguous)
604  << Found.getLookupName()
605  << ObjectType;
607  diag::note_ambig_member_ref_object_type)
608  << ObjectType;
609  Diag(FoundOuter.getFoundDecl()->getLocation(),
610  diag::note_ambig_member_ref_scope);
611 
612  // Recover by taking the template that we found in the object
613  // expression's type.
614  }
615  }
616  }
617 
618  return false;
619 }
620 
622  SourceLocation Less,
623  SourceLocation Greater) {
624  if (TemplateName.isInvalid())
625  return;
626 
627  DeclarationNameInfo NameInfo;
628  CXXScopeSpec SS;
629  LookupNameKind LookupKind;
630 
631  DeclContext *LookupCtx = nullptr;
632  NamedDecl *Found = nullptr;
633  bool MissingTemplateKeyword = false;
634 
635  // Figure out what name we looked up.
636  if (auto *DRE = dyn_cast<DeclRefExpr>(TemplateName.get())) {
637  NameInfo = DRE->getNameInfo();
638  SS.Adopt(DRE->getQualifierLoc());
639  LookupKind = LookupOrdinaryName;
640  Found = DRE->getFoundDecl();
641  } else if (auto *ME = dyn_cast<MemberExpr>(TemplateName.get())) {
642  NameInfo = ME->getMemberNameInfo();
643  SS.Adopt(ME->getQualifierLoc());
644  LookupKind = LookupMemberName;
645  LookupCtx = ME->getBase()->getType()->getAsCXXRecordDecl();
646  Found = ME->getMemberDecl();
647  } else if (auto *DSDRE =
648  dyn_cast<DependentScopeDeclRefExpr>(TemplateName.get())) {
649  NameInfo = DSDRE->getNameInfo();
650  SS.Adopt(DSDRE->getQualifierLoc());
651  MissingTemplateKeyword = true;
652  } else if (auto *DSME =
653  dyn_cast<CXXDependentScopeMemberExpr>(TemplateName.get())) {
654  NameInfo = DSME->getMemberNameInfo();
655  SS.Adopt(DSME->getQualifierLoc());
656  MissingTemplateKeyword = true;
657  } else {
658  llvm_unreachable("unexpected kind of potential template name");
659  }
660 
661  // If this is a dependent-scope lookup, diagnose that the 'template' keyword
662  // was missing.
663  if (MissingTemplateKeyword) {
664  Diag(NameInfo.getBeginLoc(), diag::err_template_kw_missing)
665  << "" << NameInfo.getName().getAsString() << SourceRange(Less, Greater);
666  return;
667  }
668 
669  // Try to correct the name by looking for templates and C++ named casts.
670  struct TemplateCandidateFilter : CorrectionCandidateCallback {
671  Sema &S;
672  TemplateCandidateFilter(Sema &S) : S(S) {
673  WantTypeSpecifiers = false;
674  WantExpressionKeywords = false;
675  WantRemainingKeywords = false;
676  WantCXXNamedCasts = true;
677  };
678  bool ValidateCandidate(const TypoCorrection &Candidate) override {
679  if (auto *ND = Candidate.getCorrectionDecl())
680  return S.getAsTemplateNameDecl(ND);
681  return Candidate.isKeyword();
682  }
683 
684  std::unique_ptr<CorrectionCandidateCallback> clone() override {
685  return std::make_unique<TemplateCandidateFilter>(*this);
686  }
687  };
688 
689  DeclarationName Name = NameInfo.getName();
690  TemplateCandidateFilter CCC(*this);
691  if (TypoCorrection Corrected = CorrectTypo(NameInfo, LookupKind, S, &SS, CCC,
692  CTK_ErrorRecovery, LookupCtx)) {
693  auto *ND = Corrected.getFoundDecl();
694  if (ND)
695  ND = getAsTemplateNameDecl(ND);
696  if (ND || Corrected.isKeyword()) {
697  if (LookupCtx) {
698  std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
699  bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
700  Name.getAsString() == CorrectedStr;
701  diagnoseTypo(Corrected,
702  PDiag(diag::err_non_template_in_member_template_id_suggest)
703  << Name << LookupCtx << DroppedSpecifier
704  << SS.getRange(), false);
705  } else {
706  diagnoseTypo(Corrected,
707  PDiag(diag::err_non_template_in_template_id_suggest)
708  << Name, false);
709  }
710  if (Found)
711  Diag(Found->getLocation(),
712  diag::note_non_template_in_template_id_found);
713  return;
714  }
715  }
716 
717  Diag(NameInfo.getLoc(), diag::err_non_template_in_template_id)
718  << Name << SourceRange(Less, Greater);
719  if (Found)
720  Diag(Found->getLocation(), diag::note_non_template_in_template_id_found);
721 }
722 
723 /// ActOnDependentIdExpression - Handle a dependent id-expression that
724 /// was just parsed. This is only possible with an explicit scope
725 /// specifier naming a dependent type.
728  SourceLocation TemplateKWLoc,
729  const DeclarationNameInfo &NameInfo,
730  bool isAddressOfOperand,
731  const TemplateArgumentListInfo *TemplateArgs) {
732  DeclContext *DC = getFunctionLevelDeclContext();
733 
734  // C++11 [expr.prim.general]p12:
735  // An id-expression that denotes a non-static data member or non-static
736  // member function of a class can only be used:
737  // (...)
738  // - if that id-expression denotes a non-static data member and it
739  // appears in an unevaluated operand.
740  //
741  // If this might be the case, form a DependentScopeDeclRefExpr instead of a
742  // CXXDependentScopeMemberExpr. The former can instantiate to either
743  // DeclRefExpr or MemberExpr depending on lookup results, while the latter is
744  // always a MemberExpr.
745  bool MightBeCxx11UnevalField =
746  getLangOpts().CPlusPlus11 && isUnevaluatedContext();
747 
748  // Check if the nested name specifier is an enum type.
749  bool IsEnum = false;
750  if (NestedNameSpecifier *NNS = SS.getScopeRep())
751  IsEnum = isa_and_nonnull<EnumType>(NNS->getAsType());
752 
753  if (!MightBeCxx11UnevalField && !isAddressOfOperand && !IsEnum &&
754  isa<CXXMethodDecl>(DC) && cast<CXXMethodDecl>(DC)->isInstance()) {
755  QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType();
756 
757  // Since the 'this' expression is synthesized, we don't need to
758  // perform the double-lookup check.
759  NamedDecl *FirstQualifierInScope = nullptr;
760 
762  Context, /*This*/ nullptr, ThisType, /*IsArrow*/ true,
763  /*Op*/ SourceLocation(), SS.getWithLocInContext(Context), TemplateKWLoc,
764  FirstQualifierInScope, NameInfo, TemplateArgs);
765  }
766 
767  return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
768 }
769 
772  SourceLocation TemplateKWLoc,
773  const DeclarationNameInfo &NameInfo,
774  const TemplateArgumentListInfo *TemplateArgs) {
775  // DependentScopeDeclRefExpr::Create requires a valid QualifierLoc
776  NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
777  if (!QualifierLoc)
778  return ExprError();
779 
781  Context, QualifierLoc, TemplateKWLoc, NameInfo, TemplateArgs);
782 }
783 
784 
785 /// Determine whether we would be unable to instantiate this template (because
786 /// it either has no definition, or is in the process of being instantiated).
788  NamedDecl *Instantiation,
789  bool InstantiatedFromMember,
790  const NamedDecl *Pattern,
791  const NamedDecl *PatternDef,
793  bool Complain /*= true*/) {
794  assert(isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) ||
795  isa<VarDecl>(Instantiation));
796 
797  bool IsEntityBeingDefined = false;
798  if (const TagDecl *TD = dyn_cast_or_null<TagDecl>(PatternDef))
799  IsEntityBeingDefined = TD->isBeingDefined();
800 
801  if (PatternDef && !IsEntityBeingDefined) {
802  NamedDecl *SuggestedDef = nullptr;
803  if (!hasReachableDefinition(const_cast<NamedDecl *>(PatternDef),
804  &SuggestedDef,
805  /*OnlyNeedComplete*/ false)) {
806  // If we're allowed to diagnose this and recover, do so.
807  bool Recover = Complain && !isSFINAEContext();
808  if (Complain)
809  diagnoseMissingImport(PointOfInstantiation, SuggestedDef,
811  return !Recover;
812  }
813  return false;
814  }
815 
816  if (!Complain || (PatternDef && PatternDef->isInvalidDecl()))
817  return true;
818 
820  QualType InstantiationTy;
821  if (TagDecl *TD = dyn_cast<TagDecl>(Instantiation))
822  InstantiationTy = Context.getTypeDeclType(TD);
823  if (PatternDef) {
824  Diag(PointOfInstantiation,
825  diag::err_template_instantiate_within_definition)
826  << /*implicit|explicit*/(TSK != TSK_ImplicitInstantiation)
827  << InstantiationTy;
828  // Not much point in noting the template declaration here, since
829  // we're lexically inside it.
830  Instantiation->setInvalidDecl();
831  } else if (InstantiatedFromMember) {
832  if (isa<FunctionDecl>(Instantiation)) {
833  Diag(PointOfInstantiation,
834  diag::err_explicit_instantiation_undefined_member)
835  << /*member function*/ 1 << Instantiation->getDeclName()
836  << Instantiation->getDeclContext();
837  Note = diag::note_explicit_instantiation_here;
838  } else {
839  assert(isa<TagDecl>(Instantiation) && "Must be a TagDecl!");
840  Diag(PointOfInstantiation,
841  diag::err_implicit_instantiate_member_undefined)
842  << InstantiationTy;
843  Note = diag::note_member_declared_at;
844  }
845  } else {
846  if (isa<FunctionDecl>(Instantiation)) {
847  Diag(PointOfInstantiation,
848  diag::err_explicit_instantiation_undefined_func_template)
849  << Pattern;
850  Note = diag::note_explicit_instantiation_here;
851  } else if (isa<TagDecl>(Instantiation)) {
852  Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
853  << (TSK != TSK_ImplicitInstantiation)
854  << InstantiationTy;
855  Note = diag::note_template_decl_here;
856  } else {
857  assert(isa<VarDecl>(Instantiation) && "Must be a VarDecl!");
858  if (isa<VarTemplateSpecializationDecl>(Instantiation)) {
859  Diag(PointOfInstantiation,
860  diag::err_explicit_instantiation_undefined_var_template)
861  << Instantiation;
862  Instantiation->setInvalidDecl();
863  } else
864  Diag(PointOfInstantiation,
865  diag::err_explicit_instantiation_undefined_member)
866  << /*static data member*/ 2 << Instantiation->getDeclName()
867  << Instantiation->getDeclContext();
868  Note = diag::note_explicit_instantiation_here;
869  }
870  }
871  if (Note) // Diagnostics were emitted.
872  Diag(Pattern->getLocation(), *Note);
873 
874  // In general, Instantiation isn't marked invalid to get more than one
875  // error for multiple undefined instantiations. But the code that does
876  // explicit declaration -> explicit definition conversion can't handle
877  // invalid declarations, so mark as invalid in that case.
879  Instantiation->setInvalidDecl();
880  return true;
881 }
882 
883 /// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
884 /// that the template parameter 'PrevDecl' is being shadowed by a new
885 /// declaration at location Loc. Returns true to indicate that this is
886 /// an error, and false otherwise.
888  assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
889 
890  // C++ [temp.local]p4:
891  // A template-parameter shall not be redeclared within its
892  // scope (including nested scopes).
893  //
894  // Make this a warning when MSVC compatibility is requested.
895  unsigned DiagId = getLangOpts().MSVCCompat ? diag::ext_template_param_shadow
896  : diag::err_template_param_shadow;
897  Diag(Loc, DiagId) << cast<NamedDecl>(PrevDecl)->getDeclName();
898  Diag(PrevDecl->getLocation(), diag::note_template_param_here);
899 }
900 
901 /// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
902 /// the parameter D to reference the templated declaration and return a pointer
903 /// to the template declaration. Otherwise, do nothing to D and return null.
905  if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
906  D = Temp->getTemplatedDecl();
907  return Temp;
908  }
909  return nullptr;
910 }
911 
913  SourceLocation EllipsisLoc) const {
914  assert(Kind == Template &&
915  "Only template template arguments can be pack expansions here");
916  assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
917  "Template template argument pack expansion without packs");
918  ParsedTemplateArgument Result(*this);
919  Result.EllipsisLoc = EllipsisLoc;
920  return Result;
921 }
922 
924  const ParsedTemplateArgument &Arg) {
925 
926  switch (Arg.getKind()) {
928  TypeSourceInfo *DI;
929  QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
930  if (!DI)
931  DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
932  return TemplateArgumentLoc(TemplateArgument(T), DI);
933  }
934 
936  Expr *E = static_cast<Expr *>(Arg.getAsExpr());
938  }
939 
941  TemplateName Template = Arg.getAsTemplate().get();
942  TemplateArgument TArg;
943  if (Arg.getEllipsisLoc().isValid())
944  TArg = TemplateArgument(Template, Optional<unsigned int>());
945  else
946  TArg = Template;
947  return TemplateArgumentLoc(
948  SemaRef.Context, TArg,
950  Arg.getLocation(), Arg.getEllipsisLoc());
951  }
952  }
953 
954  llvm_unreachable("Unhandled parsed template argument");
955 }
956 
957 /// Translates template arguments as provided by the parser
958 /// into template arguments used by semantic analysis.
960  TemplateArgumentListInfo &TemplateArgs) {
961  for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
962  TemplateArgs.addArgument(translateTemplateArgument(*this,
963  TemplateArgsIn[I]));
964 }
965 
967  SourceLocation Loc,
968  IdentifierInfo *Name) {
969  NamedDecl *PrevDecl = SemaRef.LookupSingleName(
971  if (PrevDecl && PrevDecl->isTemplateParameter())
972  SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
973 }
974 
975 /// Convert a parsed type into a parsed template argument. This is mostly
976 /// trivial, except that we may have parsed a C++17 deduced class template
977 /// specialization type, in which case we should form a template template
978 /// argument instead of a type template argument.
980  TypeSourceInfo *TInfo;
981  QualType T = GetTypeFromParser(ParsedType.get(), &TInfo);
982  if (T.isNull())
983  return ParsedTemplateArgument();
984  assert(TInfo && "template argument with no location");
985 
986  // If we might have formed a deduced template specialization type, convert
987  // it to a template template argument.
988  if (getLangOpts().CPlusPlus17) {
989  TypeLoc TL = TInfo->getTypeLoc();
990  SourceLocation EllipsisLoc;
991  if (auto PET = TL.getAs<PackExpansionTypeLoc>()) {
992  EllipsisLoc = PET.getEllipsisLoc();
993  TL = PET.getPatternLoc();
994  }
995 
996  CXXScopeSpec SS;
997  if (auto ET = TL.getAs<ElaboratedTypeLoc>()) {
998  SS.Adopt(ET.getQualifierLoc());
999  TL = ET.getNamedTypeLoc();
1000  }
1001 
1002  if (auto DTST = TL.getAs<DeducedTemplateSpecializationTypeLoc>()) {
1003  TemplateName Name = DTST.getTypePtr()->getTemplateName();
1004  if (SS.isSet())
1005  Name = Context.getQualifiedTemplateName(SS.getScopeRep(),
1006  /*HasTemplateKeyword=*/false,
1007  Name);
1008  ParsedTemplateArgument Result(SS, TemplateTy::make(Name),
1009  DTST.getTemplateNameLoc());
1010  if (EllipsisLoc.isValid())
1011  Result = Result.getTemplatePackExpansion(EllipsisLoc);
1012  return Result;
1013  }
1014  }
1015 
1016  // This is a normal type template argument. Note, if the type template
1017  // argument is an injected-class-name for a template, it has a dual nature
1018  // and can be used as either a type or a template. We handle that in
1019  // convertTypeTemplateArgumentToTemplate.
1022  TInfo->getTypeLoc().getBeginLoc());
1023 }
1024 
1025 /// ActOnTypeParameter - Called when a C++ template type parameter
1026 /// (e.g., "typename T") has been parsed. Typename specifies whether
1027 /// the keyword "typename" was used to declare the type parameter
1028 /// (otherwise, "class" was used), and KeyLoc is the location of the
1029 /// "class" or "typename" keyword. ParamName is the name of the
1030 /// parameter (NULL indicates an unnamed template parameter) and
1031 /// ParamNameLoc is the location of the parameter name (if any).
1032 /// If the type parameter has a default argument, it will be added
1033 /// later via ActOnTypeParameterDefault.
1035  SourceLocation EllipsisLoc,
1036  SourceLocation KeyLoc,
1037  IdentifierInfo *ParamName,
1038  SourceLocation ParamNameLoc,
1039  unsigned Depth, unsigned Position,
1040  SourceLocation EqualLoc,
1041  ParsedType DefaultArg,
1042  bool HasTypeConstraint) {
1043  assert(S->isTemplateParamScope() &&
1044  "Template type parameter not in template parameter scope!");
1045 
1046  bool IsParameterPack = EllipsisLoc.isValid();
1047  TemplateTypeParmDecl *Param
1049  KeyLoc, ParamNameLoc, Depth, Position,
1050  ParamName, Typename, IsParameterPack,
1051  HasTypeConstraint);
1052  Param->setAccess(AS_public);
1053 
1054  if (Param->isParameterPack())
1055  if (auto *LSI = getEnclosingLambda())
1056  LSI->LocalPacks.push_back(Param);
1057 
1058  if (ParamName) {
1059  maybeDiagnoseTemplateParameterShadow(*this, S, ParamNameLoc, ParamName);
1060 
1061  // Add the template parameter into the current scope.
1062  S->AddDecl(Param);
1063  IdResolver.AddDecl(Param);
1064  }
1065 
1066  // C++0x [temp.param]p9:
1067  // A default template-argument may be specified for any kind of
1068  // template-parameter that is not a template parameter pack.
1069  if (DefaultArg && IsParameterPack) {
1070  Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1071  DefaultArg = nullptr;
1072  }
1073 
1074  // Handle the default argument, if provided.
1075  if (DefaultArg) {
1076  TypeSourceInfo *DefaultTInfo;
1077  GetTypeFromParser(DefaultArg, &DefaultTInfo);
1078 
1079  assert(DefaultTInfo && "expected source information for type");
1080 
1081  // Check for unexpanded parameter packs.
1082  if (DiagnoseUnexpandedParameterPack(ParamNameLoc, DefaultTInfo,
1083  UPPC_DefaultArgument))
1084  return Param;
1085 
1086  // Check the template argument itself.
1087  if (CheckTemplateArgument(DefaultTInfo)) {
1088  Param->setInvalidDecl();
1089  return Param;
1090  }
1091 
1092  Param->setDefaultArgument(DefaultTInfo);
1093  }
1094 
1095  return Param;
1096 }
1097 
1098 /// Convert the parser's template argument list representation into our form.
1101  TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
1102  TemplateId.RAngleLoc);
1103  ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
1104  TemplateId.NumArgs);
1105  S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
1106  return TemplateArgs;
1107 }
1108 
1110  TemplateIdAnnotation *TypeConstr,
1111  TemplateTypeParmDecl *ConstrainedParameter,
1112  SourceLocation EllipsisLoc) {
1113  return BuildTypeConstraint(SS, TypeConstr, ConstrainedParameter, EllipsisLoc,
1114  false);
1115 }
1116 
1118  TemplateIdAnnotation *TypeConstr,
1119  TemplateTypeParmDecl *ConstrainedParameter,
1120  SourceLocation EllipsisLoc,
1121  bool AllowUnexpandedPack) {
1122  TemplateName TN = TypeConstr->Template.get();
1123  ConceptDecl *CD = cast<ConceptDecl>(TN.getAsTemplateDecl());
1124 
1125  // C++2a [temp.param]p4:
1126  // [...] The concept designated by a type-constraint shall be a type
1127  // concept ([temp.concept]).
1128  if (!CD->isTypeConcept()) {
1129  Diag(TypeConstr->TemplateNameLoc,
1130  diag::err_type_constraint_non_type_concept);
1131  return true;
1132  }
1133 
1134  bool WereArgsSpecified = TypeConstr->LAngleLoc.isValid();
1135 
1136  if (!WereArgsSpecified &&
1138  Diag(TypeConstr->TemplateNameLoc,
1139  diag::err_type_constraint_missing_arguments) << CD;
1140  return true;
1141  }
1142 
1143  DeclarationNameInfo ConceptName(DeclarationName(TypeConstr->Name),
1144  TypeConstr->TemplateNameLoc);
1145 
1146  TemplateArgumentListInfo TemplateArgs;
1147  if (TypeConstr->LAngleLoc.isValid()) {
1148  TemplateArgs =
1149  makeTemplateArgumentListInfo(*this, *TypeConstr);
1150 
1151  if (EllipsisLoc.isInvalid() && !AllowUnexpandedPack) {
1152  for (TemplateArgumentLoc Arg : TemplateArgs.arguments()) {
1153  if (DiagnoseUnexpandedParameterPack(Arg, UPPC_TypeConstraint))
1154  return true;
1155  }
1156  }
1157  }
1158  return AttachTypeConstraint(
1159  SS.isSet() ? SS.getWithLocInContext(Context) : NestedNameSpecifierLoc(),
1160  ConceptName, CD,
1161  TypeConstr->LAngleLoc.isValid() ? &TemplateArgs : nullptr,
1162  ConstrainedParameter, EllipsisLoc);
1163 }
1164 
1165 template<typename ArgumentLocAppender>
1168  ConceptDecl *NamedConcept, SourceLocation LAngleLoc,
1169  SourceLocation RAngleLoc, QualType ConstrainedType,
1170  SourceLocation ParamNameLoc, ArgumentLocAppender Appender,
1171  SourceLocation EllipsisLoc) {
1172 
1173  TemplateArgumentListInfo ConstraintArgs;
1174  ConstraintArgs.addArgument(
1176  /*NTTPType=*/QualType(), ParamNameLoc));
1177 
1178  ConstraintArgs.setRAngleLoc(RAngleLoc);
1179  ConstraintArgs.setLAngleLoc(LAngleLoc);
1180  Appender(ConstraintArgs);
1181 
1182  // C++2a [temp.param]p4:
1183  // [...] This constraint-expression E is called the immediately-declared
1184  // constraint of T. [...]
1185  CXXScopeSpec SS;
1186  SS.Adopt(NS);
1187  ExprResult ImmediatelyDeclaredConstraint = S.CheckConceptTemplateId(
1188  SS, /*TemplateKWLoc=*/SourceLocation(), NameInfo,
1189  /*FoundDecl=*/NamedConcept, NamedConcept, &ConstraintArgs);
1190  if (ImmediatelyDeclaredConstraint.isInvalid() || !EllipsisLoc.isValid())
1191  return ImmediatelyDeclaredConstraint;
1192 
1193  // C++2a [temp.param]p4:
1194  // [...] If T is not a pack, then E is E', otherwise E is (E' && ...).
1195  //
1196  // We have the following case:
1197  //
1198  // template<typename T> concept C1 = true;
1199  // template<C1... T> struct s1;
1200  //
1201  // The constraint: (C1<T> && ...)
1202  //
1203  // Note that the type of C1<T> is known to be 'bool', so we don't need to do
1204  // any unqualified lookups for 'operator&&' here.
1205  return S.BuildCXXFoldExpr(/*UnqualifiedLookup=*/nullptr,
1206  /*LParenLoc=*/SourceLocation(),
1207  ImmediatelyDeclaredConstraint.get(), BO_LAnd,
1208  EllipsisLoc, /*RHS=*/nullptr,
1209  /*RParenLoc=*/SourceLocation(),
1210  /*NumExpansions=*/std::nullopt);
1211 }
1212 
1213 /// Attach a type-constraint to a template parameter.
1214 /// \returns true if an error occurred. This can happen if the
1215 /// immediately-declared constraint could not be formed (e.g. incorrect number
1216 /// of arguments for the named concept).
1218  DeclarationNameInfo NameInfo,
1219  ConceptDecl *NamedConcept,
1220  const TemplateArgumentListInfo *TemplateArgs,
1221  TemplateTypeParmDecl *ConstrainedParameter,
1222  SourceLocation EllipsisLoc) {
1223  // C++2a [temp.param]p4:
1224  // [...] If Q is of the form C<A1, ..., An>, then let E' be
1225  // C<T, A1, ..., An>. Otherwise, let E' be C<T>. [...]
1226  const ASTTemplateArgumentListInfo *ArgsAsWritten =
1227  TemplateArgs ? ASTTemplateArgumentListInfo::Create(Context,
1228  *TemplateArgs) : nullptr;
1229 
1230  QualType ParamAsArgument(ConstrainedParameter->getTypeForDecl(), 0);
1231 
1232  ExprResult ImmediatelyDeclaredConstraint =
1234  *this, NS, NameInfo, NamedConcept,
1235  TemplateArgs ? TemplateArgs->getLAngleLoc() : SourceLocation(),
1236  TemplateArgs ? TemplateArgs->getRAngleLoc() : SourceLocation(),
1237  ParamAsArgument, ConstrainedParameter->getLocation(),
1238  [&] (TemplateArgumentListInfo &ConstraintArgs) {
1239  if (TemplateArgs)
1240  for (const auto &ArgLoc : TemplateArgs->arguments())
1241  ConstraintArgs.addArgument(ArgLoc);
1242  }, EllipsisLoc);
1243  if (ImmediatelyDeclaredConstraint.isInvalid())
1244  return true;
1245 
1246  ConstrainedParameter->setTypeConstraint(NS, NameInfo,
1247  /*FoundDecl=*/NamedConcept,
1248  NamedConcept, ArgsAsWritten,
1249  ImmediatelyDeclaredConstraint.get());
1250  return false;
1251 }
1252 
1254  SourceLocation EllipsisLoc) {
1255  if (NTTP->getType() != TL.getType() ||
1258  diag::err_unsupported_placeholder_constraint)
1260  return true;
1261  }
1262  // FIXME: Concepts: This should be the type of the placeholder, but this is
1263  // unclear in the wording right now.
1264  DeclRefExpr *Ref =
1265  BuildDeclRefExpr(NTTP, NTTP->getType(), VK_PRValue, NTTP->getLocation());
1266  if (!Ref)
1267  return true;
1268  ExprResult ImmediatelyDeclaredConstraint = formImmediatelyDeclaredConstraint(
1270  TL.getNamedConcept(), TL.getLAngleLoc(), TL.getRAngleLoc(),
1271  BuildDecltypeType(Ref), NTTP->getLocation(),
1272  [&](TemplateArgumentListInfo &ConstraintArgs) {
1273  for (unsigned I = 0, C = TL.getNumArgs(); I != C; ++I)
1274  ConstraintArgs.addArgument(TL.getArgLoc(I));
1275  },
1276  EllipsisLoc);
1277  if (ImmediatelyDeclaredConstraint.isInvalid() ||
1278  !ImmediatelyDeclaredConstraint.isUsable())
1279  return true;
1280 
1281  NTTP->setPlaceholderTypeConstraint(ImmediatelyDeclaredConstraint.get());
1282  return false;
1283 }
1284 
1285 /// Check that the type of a non-type template parameter is
1286 /// well-formed.
1287 ///
1288 /// \returns the (possibly-promoted) parameter type if valid;
1289 /// otherwise, produces a diagnostic and returns a NULL type.
1291  SourceLocation Loc) {
1292  if (TSI->getType()->isUndeducedType()) {
1293  // C++17 [temp.dep.expr]p3:
1294  // An id-expression is type-dependent if it contains
1295  // - an identifier associated by name lookup with a non-type
1296  // template-parameter declared with a type that contains a
1297  // placeholder type (7.1.7.4),
1298  TSI = SubstAutoTypeSourceInfoDependent(TSI);
1299  }
1300 
1301  return CheckNonTypeTemplateParameterType(TSI->getType(), Loc);
1302 }
1303 
1304 /// Require the given type to be a structural type, and diagnose if it is not.
1305 ///
1306 /// \return \c true if an error was produced.
1308  if (T->isDependentType())
1309  return false;
1310 
1311  if (RequireCompleteType(Loc, T, diag::err_template_nontype_parm_incomplete))
1312  return true;
1313 
1314  if (T->isStructuralType())
1315  return false;
1316 
1317  // Structural types are required to be object types or lvalue references.
1318  if (T->isRValueReferenceType()) {
1319  Diag(Loc, diag::err_template_nontype_parm_rvalue_ref) << T;
1320  return true;
1321  }
1322 
1323  // Don't mention structural types in our diagnostic prior to C++20. Also,
1324  // there's not much more we can say about non-scalar non-class types --
1325  // because we can't see functions or arrays here, those can only be language
1326  // extensions.
1327  if (!getLangOpts().CPlusPlus20 ||
1328  (!T->isScalarType() && !T->isRecordType())) {
1329  Diag(Loc, diag::err_template_nontype_parm_bad_type) << T;
1330  return true;
1331  }
1332 
1333  // Structural types are required to be literal types.
1334  if (RequireLiteralType(Loc, T, diag::err_template_nontype_parm_not_literal))
1335  return true;
1336 
1337  Diag(Loc, diag::err_template_nontype_parm_not_structural) << T;
1338 
1339  // Drill down into the reason why the class is non-structural.
1340  while (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
1341  // All members are required to be public and non-mutable, and can't be of
1342  // rvalue reference type. Check these conditions first to prefer a "local"
1343  // reason over a more distant one.
1344  for (const FieldDecl *FD : RD->fields()) {
1345  if (FD->getAccess() != AS_public) {
1346  Diag(FD->getLocation(), diag::note_not_structural_non_public) << T << 0;
1347  return true;
1348  }
1349  if (FD->isMutable()) {
1350  Diag(FD->getLocation(), diag::note_not_structural_mutable_field) << T;
1351  return true;
1352  }
1353  if (FD->getType()->isRValueReferenceType()) {
1354  Diag(FD->getLocation(), diag::note_not_structural_rvalue_ref_field)
1355  << T;
1356  return true;
1357  }
1358  }
1359 
1360  // All bases are required to be public.
1361  for (const auto &BaseSpec : RD->bases()) {
1362  if (BaseSpec.getAccessSpecifier() != AS_public) {
1363  Diag(BaseSpec.getBaseTypeLoc(), diag::note_not_structural_non_public)
1364  << T << 1;
1365  return true;
1366  }
1367  }
1368 
1369  // All subobjects are required to be of structural types.
1370  SourceLocation SubLoc;
1371  QualType SubType;
1372  int Kind = -1;
1373 
1374  for (const FieldDecl *FD : RD->fields()) {
1375  QualType T = Context.getBaseElementType(FD->getType());
1376  if (!T->isStructuralType()) {
1377  SubLoc = FD->getLocation();
1378  SubType = T;
1379  Kind = 0;
1380  break;
1381  }
1382  }
1383 
1384  if (Kind == -1) {
1385  for (const auto &BaseSpec : RD->bases()) {
1386  QualType T = BaseSpec.getType();
1387  if (!T->isStructuralType()) {
1388  SubLoc = BaseSpec.getBaseTypeLoc();
1389  SubType = T;
1390  Kind = 1;
1391  break;
1392  }
1393  }
1394  }
1395 
1396  assert(Kind != -1 && "couldn't find reason why type is not structural");
1397  Diag(SubLoc, diag::note_not_structural_subobject)
1398  << T << Kind << SubType;
1399  T = SubType;
1400  RD = T->getAsCXXRecordDecl();
1401  }
1402 
1403  return true;
1404 }
1405 
1407  SourceLocation Loc) {
1408  // We don't allow variably-modified types as the type of non-type template
1409  // parameters.
1410  if (T->isVariablyModifiedType()) {
1411  Diag(Loc, diag::err_variably_modified_nontype_template_param)
1412  << T;
1413  return QualType();
1414  }
1415 
1416  // C++ [temp.param]p4:
1417  //
1418  // A non-type template-parameter shall have one of the following
1419  // (optionally cv-qualified) types:
1420  //
1421  // -- integral or enumeration type,
1422  if (T->isIntegralOrEnumerationType() ||
1423  // -- pointer to object or pointer to function,
1424  T->isPointerType() ||
1425  // -- lvalue reference to object or lvalue reference to function,
1426  T->isLValueReferenceType() ||
1427  // -- pointer to member,
1428  T->isMemberPointerType() ||
1429  // -- std::nullptr_t, or
1430  T->isNullPtrType() ||
1431  // -- a type that contains a placeholder type.
1432  T->isUndeducedType()) {
1433  // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
1434  // are ignored when determining its type.
1435  return T.getUnqualifiedType();
1436  }
1437 
1438  // C++ [temp.param]p8:
1439  //
1440  // A non-type template-parameter of type "array of T" or
1441  // "function returning T" is adjusted to be of type "pointer to
1442  // T" or "pointer to function returning T", respectively.
1443  if (T->isArrayType() || T->isFunctionType())
1444  return Context.getDecayedType(T);
1445 
1446  // If T is a dependent type, we can't do the check now, so we
1447  // assume that it is well-formed. Note that stripping off the
1448  // qualifiers here is not really correct if T turns out to be
1449  // an array type, but we'll recompute the type everywhere it's
1450  // used during instantiation, so that should be OK. (Using the
1451  // qualified type is equally wrong.)
1452  if (T->isDependentType())
1453  return T.getUnqualifiedType();
1454 
1455  // C++20 [temp.param]p6:
1456  // -- a structural type
1457  if (RequireStructuralType(T, Loc))
1458  return QualType();
1459 
1460  if (!getLangOpts().CPlusPlus20) {
1461  // FIXME: Consider allowing structural types as an extension in C++17. (In
1462  // earlier language modes, the template argument evaluation rules are too
1463  // inflexible.)
1464  Diag(Loc, diag::err_template_nontype_parm_bad_structural_type) << T;
1465  return QualType();
1466  }
1467 
1468  Diag(Loc, diag::warn_cxx17_compat_template_nontype_parm_type) << T;
1469  return T.getUnqualifiedType();
1470 }
1471 
1473  unsigned Depth,
1474  unsigned Position,
1475  SourceLocation EqualLoc,
1476  Expr *Default) {
1477  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
1478 
1479  // Check that we have valid decl-specifiers specified.
1480  auto CheckValidDeclSpecifiers = [this, &D] {
1481  // C++ [temp.param]
1482  // p1
1483  // template-parameter:
1484  // ...
1485  // parameter-declaration
1486  // p2
1487  // ... A storage class shall not be specified in a template-parameter
1488  // declaration.
1489  // [dcl.typedef]p1:
1490  // The typedef specifier [...] shall not be used in the decl-specifier-seq
1491  // of a parameter-declaration
1492  const DeclSpec &DS = D.getDeclSpec();
1493  auto EmitDiag = [this](SourceLocation Loc) {
1494  Diag(Loc, diag::err_invalid_decl_specifier_in_nontype_parm)
1495  << FixItHint::CreateRemoval(Loc);
1496  };
1498  EmitDiag(DS.getStorageClassSpecLoc());
1499 
1501  EmitDiag(DS.getThreadStorageClassSpecLoc());
1502 
1503  // [dcl.inline]p1:
1504  // The inline specifier can be applied only to the declaration or
1505  // definition of a variable or function.
1506 
1507  if (DS.isInlineSpecified())
1508  EmitDiag(DS.getInlineSpecLoc());
1509 
1510  // [dcl.constexpr]p1:
1511  // The constexpr specifier shall be applied only to the definition of a
1512  // variable or variable template or the declaration of a function or
1513  // function template.
1514 
1515  if (DS.hasConstexprSpecifier())
1516  EmitDiag(DS.getConstexprSpecLoc());
1517 
1518  // [dcl.fct.spec]p1:
1519  // Function-specifiers can be used only in function declarations.
1520 
1521  if (DS.isVirtualSpecified())
1522  EmitDiag(DS.getVirtualSpecLoc());
1523 
1524  if (DS.hasExplicitSpecifier())
1525  EmitDiag(DS.getExplicitSpecLoc());
1526 
1527  if (DS.isNoreturnSpecified())
1528  EmitDiag(DS.getNoreturnSpecLoc());
1529  };
1530 
1531  CheckValidDeclSpecifiers();
1532 
1533  if (const auto *T = TInfo->getType()->getContainedDeducedType())
1534  if (isa<AutoType>(T))
1535  Diag(D.getIdentifierLoc(),
1536  diag::warn_cxx14_compat_template_nontype_parm_auto_type)
1537  << QualType(TInfo->getType()->getContainedAutoType(), 0);
1538 
1539  assert(S->isTemplateParamScope() &&
1540  "Non-type template parameter not in template parameter scope!");
1541  bool Invalid = false;
1542 
1543  QualType T = CheckNonTypeTemplateParameterType(TInfo, D.getIdentifierLoc());
1544  if (T.isNull()) {
1545  T = Context.IntTy; // Recover with an 'int' type.
1546  Invalid = true;
1547  }
1548 
1549  CheckFunctionOrTemplateParamDeclarator(S, D);
1550 
1551  IdentifierInfo *ParamName = D.getIdentifier();
1552  bool IsParameterPack = D.hasEllipsis();
1554  Context, Context.getTranslationUnitDecl(), D.getBeginLoc(),
1555  D.getIdentifierLoc(), Depth, Position, ParamName, T, IsParameterPack,
1556  TInfo);
1557  Param->setAccess(AS_public);
1558 
1559  if (AutoTypeLoc TL = TInfo->getTypeLoc().getContainedAutoTypeLoc())
1560  if (TL.isConstrained())
1561  if (AttachTypeConstraint(TL, Param, D.getEllipsisLoc()))
1562  Invalid = true;
1563 
1564  if (Invalid)
1565  Param->setInvalidDecl();
1566 
1567  if (Param->isParameterPack())
1568  if (auto *LSI = getEnclosingLambda())
1569  LSI->LocalPacks.push_back(Param);
1570 
1571  if (ParamName) {
1573  ParamName);
1574 
1575  // Add the template parameter into the current scope.
1576  S->AddDecl(Param);
1577  IdResolver.AddDecl(Param);
1578  }
1579 
1580  // C++0x [temp.param]p9:
1581  // A default template-argument may be specified for any kind of
1582  // template-parameter that is not a template parameter pack.
1583  if (Default && IsParameterPack) {
1584  Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1585  Default = nullptr;
1586  }
1587 
1588  // Check the well-formedness of the default template argument, if provided.
1589  if (Default) {
1590  // Check for unexpanded parameter packs.
1591  if (DiagnoseUnexpandedParameterPack(Default, UPPC_DefaultArgument))
1592  return Param;
1593 
1594  TemplateArgument SugaredConverted, CanonicalConverted;
1595  ExprResult DefaultRes = CheckTemplateArgument(
1596  Param, Param->getType(), Default, SugaredConverted, CanonicalConverted,
1597  CTAK_Specified);
1598  if (DefaultRes.isInvalid()) {
1599  Param->setInvalidDecl();
1600  return Param;
1601  }
1602  Default = DefaultRes.get();
1603 
1604  Param->setDefaultArgument(Default);
1605  }
1606 
1607  return Param;
1608 }
1609 
1610 /// ActOnTemplateTemplateParameter - Called when a C++ template template
1611 /// parameter (e.g. T in template <template <typename> class T> class array)
1612 /// has been parsed. S is the current scope.
1614  SourceLocation TmpLoc,
1615  TemplateParameterList *Params,
1616  SourceLocation EllipsisLoc,
1617  IdentifierInfo *Name,
1618  SourceLocation NameLoc,
1619  unsigned Depth,
1620  unsigned Position,
1621  SourceLocation EqualLoc,
1622  ParsedTemplateArgument Default) {
1623  assert(S->isTemplateParamScope() &&
1624  "Template template parameter not in template parameter scope!");
1625 
1626  // Construct the parameter object.
1627  bool IsParameterPack = EllipsisLoc.isValid();
1628  TemplateTemplateParmDecl *Param =
1630  NameLoc.isInvalid()? TmpLoc : NameLoc,
1631  Depth, Position, IsParameterPack,
1632  Name, Params);
1633  Param->setAccess(AS_public);
1634 
1635  if (Param->isParameterPack())
1636  if (auto *LSI = getEnclosingLambda())
1637  LSI->LocalPacks.push_back(Param);
1638 
1639  // If the template template parameter has a name, then link the identifier
1640  // into the scope and lookup mechanisms.
1641  if (Name) {
1642  maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name);
1643 
1644  S->AddDecl(Param);
1645  IdResolver.AddDecl(Param);
1646  }
1647 
1648  if (Params->size() == 0) {
1649  Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
1650  << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
1651  Param->setInvalidDecl();
1652  }
1653 
1654  // C++0x [temp.param]p9:
1655  // A default template-argument may be specified for any kind of
1656  // template-parameter that is not a template parameter pack.
1657  if (IsParameterPack && !Default.isInvalid()) {
1658  Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1660  }
1661 
1662  if (!Default.isInvalid()) {
1663  // Check only that we have a template template argument. We don't want to
1664  // try to check well-formedness now, because our template template parameter
1665  // might have dependent types in its template parameters, which we wouldn't
1666  // be able to match now.
1667  //
1668  // If none of the template template parameter's template arguments mention
1669  // other template parameters, we could actually perform more checking here.
1670  // However, it isn't worth doing.
1672  if (DefaultArg.getArgument().getAsTemplate().isNull()) {
1673  Diag(DefaultArg.getLocation(), diag::err_template_arg_not_valid_template)
1674  << DefaultArg.getSourceRange();
1675  return Param;
1676  }
1677 
1678  // Check for unexpanded parameter packs.
1679  if (DiagnoseUnexpandedParameterPack(DefaultArg.getLocation(),
1680  DefaultArg.getArgument().getAsTemplate(),
1681  UPPC_DefaultArgument))
1682  return Param;
1683 
1684  Param->setDefaultArgument(Context, DefaultArg);
1685  }
1686 
1687  return Param;
1688 }
1689 
1690 namespace {
1691 class ConstraintRefersToContainingTemplateChecker
1692  : public TreeTransform<ConstraintRefersToContainingTemplateChecker> {
1693  bool Result = false;
1694  const FunctionDecl *Friend = nullptr;
1695  unsigned TemplateDepth = 0;
1696 
1697  // Check a record-decl that we've seen to see if it is a lexical parent of the
1698  // Friend, likely because it was referred to without its template arguments.
1699  void CheckIfContainingRecord(const CXXRecordDecl *CheckingRD) {
1700  CheckingRD = CheckingRD->getMostRecentDecl();
1701 
1702  for (const DeclContext *DC = Friend->getLexicalDeclContext();
1703  DC && !DC->isFileContext(); DC = DC->getParent())
1704  if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
1705  if (CheckingRD == RD->getMostRecentDecl())
1706  Result = true;
1707  }
1708 
1709  void CheckNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
1710  assert(D->getDepth() <= TemplateDepth &&
1711  "Nothing should reference a value below the actual template depth, "
1712  "depth is likely wrong");
1713  if (D->getDepth() != TemplateDepth)
1714  Result = true;
1715 
1716  // Necessary because the type of the NTTP might be what refers to the parent
1717  // constriant.
1718  TransformType(D->getType());
1719  }
1720 
1721 public:
1723 
1724  ConstraintRefersToContainingTemplateChecker(Sema &SemaRef,
1725  const FunctionDecl *Friend,
1726  unsigned TemplateDepth)
1727  : inherited(SemaRef), Friend(Friend), TemplateDepth(TemplateDepth) {}
1728  bool getResult() const { return Result; }
1729 
1730  // This should be the only template parm type that we have to deal with.
1731  // SubstTempalteTypeParmPack, SubstNonTypeTemplateParmPack, and
1732  // FunctionParmPackExpr are all partially substituted, which cannot happen
1733  // with concepts at this point in translation.
1734  using inherited::TransformTemplateTypeParmType;
1735  QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
1736  TemplateTypeParmTypeLoc TL, bool) {
1737  assert(TL.getDecl()->getDepth() <= TemplateDepth &&
1738  "Nothing should reference a value below the actual template depth, "
1739  "depth is likely wrong");
1740  if (TL.getDecl()->getDepth() != TemplateDepth)
1741  Result = true;
1742  return inherited::TransformTemplateTypeParmType(
1743  TLB, TL,
1744  /*SuppressObjCLifetime=*/false);
1745  }
1746 
1747  Decl *TransformDecl(SourceLocation Loc, Decl *D) {
1748  if (!D)
1749  return D;
1750  // FIXME : This is possibly an incomplete list, but it is unclear what other
1751  // Decl kinds could be used to refer to the template parameters. This is a
1752  // best guess so far based on examples currently available, but the
1753  // unreachable should catch future instances/cases.
1754  if (auto *TD = dyn_cast<TypedefNameDecl>(D))
1755  TransformType(TD->getUnderlyingType());
1756  else if (auto *NTTPD = dyn_cast<NonTypeTemplateParmDecl>(D))
1757  CheckNonTypeTemplateParmDecl(NTTPD);
1758  else if (auto *VD = dyn_cast<ValueDecl>(D))
1759  TransformType(VD->getType());
1760  else if (auto *TD = dyn_cast<TemplateDecl>(D))
1761  TransformTemplateParameterList(TD->getTemplateParameters());
1762  else if (auto *RD = dyn_cast<CXXRecordDecl>(D))
1763  CheckIfContainingRecord(RD);
1764  else if (isa<NamedDecl>(D)) {
1765  // No direct types to visit here I believe.
1766  } else
1767  llvm_unreachable("Don't know how to handle this declaration type yet");
1768  return D;
1769  }
1770 };
1771 } // namespace
1772 
1774  const FunctionDecl *Friend, unsigned TemplateDepth,
1775  const Expr *Constraint) {
1776  assert(Friend->getFriendObjectKind() && "Only works on a friend");
1777  ConstraintRefersToContainingTemplateChecker Checker(*this, Friend,
1778  TemplateDepth);
1779  Checker.TransformExpr(const_cast<Expr *>(Constraint));
1780  return Checker.getResult();
1781 }
1782 
1783 /// ActOnTemplateParameterList - Builds a TemplateParameterList, optionally
1784 /// constrained by RequiresClause, that contains the template parameters in
1785 /// Params.
1788  SourceLocation ExportLoc,
1789  SourceLocation TemplateLoc,
1790  SourceLocation LAngleLoc,
1791  ArrayRef<NamedDecl *> Params,
1792  SourceLocation RAngleLoc,
1793  Expr *RequiresClause) {
1794  if (ExportLoc.isValid())
1795  Diag(ExportLoc, diag::warn_template_export_unsupported);
1796 
1797  for (NamedDecl *P : Params)
1798  warnOnReservedIdentifier(P);
1799 
1801  Context, TemplateLoc, LAngleLoc,
1802  llvm::makeArrayRef(Params.data(), Params.size()),
1803  RAngleLoc, RequiresClause);
1804 }
1805 
1807  const CXXScopeSpec &SS) {
1808  if (SS.isSet())
1810 }
1811 
1813  Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
1814  CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
1815  const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams,
1816  AccessSpecifier AS, SourceLocation ModulePrivateLoc,
1817  SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists,
1818  TemplateParameterList **OuterTemplateParamLists, SkipBodyInfo *SkipBody) {
1819  assert(TemplateParams && TemplateParams->size() > 0 &&
1820  "No template parameters");
1821  assert(TUK != TUK_Reference && "Can only declare or define class templates");
1822  bool Invalid = false;
1823 
1824  // Check that we can declare a template here.
1825  if (CheckTemplateDeclScope(S, TemplateParams))
1826  return true;
1827 
1829  assert(Kind != TTK_Enum && "can't build template of enumerated type");
1830 
1831  // There is no such thing as an unnamed class template.
1832  if (!Name) {
1833  Diag(KWLoc, diag::err_template_unnamed_class);
1834  return true;
1835  }
1836 
1837  // Find any previous declaration with this name. For a friend with no
1838  // scope explicitly specified, we only look for tag declarations (per
1839  // C++11 [basic.lookup.elab]p2).
1840  DeclContext *SemanticContext;
1841  LookupResult Previous(*this, Name, NameLoc,
1842  (SS.isEmpty() && TUK == TUK_Friend)
1843  ? LookupTagName : LookupOrdinaryName,
1844  forRedeclarationInCurContext());
1845  if (SS.isNotEmpty() && !SS.isInvalid()) {
1846  SemanticContext = computeDeclContext(SS, true);
1847  if (!SemanticContext) {
1848  // FIXME: Horrible, horrible hack! We can't currently represent this
1849  // in the AST, and historically we have just ignored such friend
1850  // class templates, so don't complain here.
1851  Diag(NameLoc, TUK == TUK_Friend
1852  ? diag::warn_template_qualified_friend_ignored
1853  : diag::err_template_qualified_declarator_no_match)
1854  << SS.getScopeRep() << SS.getRange();
1855  return TUK != TUK_Friend;
1856  }
1857 
1858  if (RequireCompleteDeclContext(SS, SemanticContext))
1859  return true;
1860 
1861  // If we're adding a template to a dependent context, we may need to
1862  // rebuilding some of the types used within the template parameter list,
1863  // now that we know what the current instantiation is.
1864  if (SemanticContext->isDependentContext()) {
1865  ContextRAII SavedContext(*this, SemanticContext);
1866  if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
1867  Invalid = true;
1868  } else if (TUK != TUK_Friend && TUK != TUK_Reference)
1869  diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc, false);
1870 
1871  LookupQualifiedName(Previous, SemanticContext);
1872  } else {
1873  SemanticContext = CurContext;
1874 
1875  // C++14 [class.mem]p14:
1876  // If T is the name of a class, then each of the following shall have a
1877  // name different from T:
1878  // -- every member template of class T
1879  if (TUK != TUK_Friend &&
1880  DiagnoseClassNameShadow(SemanticContext,
1881  DeclarationNameInfo(Name, NameLoc)))
1882  return true;
1883 
1884  LookupName(Previous, S);
1885  }
1886 
1887  if (Previous.isAmbiguous())
1888  return true;
1889 
1890  NamedDecl *PrevDecl = nullptr;
1891  if (Previous.begin() != Previous.end())
1892  PrevDecl = (*Previous.begin())->getUnderlyingDecl();
1893 
1894  if (PrevDecl && PrevDecl->isTemplateParameter()) {
1895  // Maybe we will complain about the shadowed template parameter.
1896  DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
1897  // Just pretend that we didn't see the previous declaration.
1898  PrevDecl = nullptr;
1899  }
1900 
1901  // If there is a previous declaration with the same name, check
1902  // whether this is a valid redeclaration.
1903  ClassTemplateDecl *PrevClassTemplate =
1904  dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
1905 
1906  // We may have found the injected-class-name of a class template,
1907  // class template partial specialization, or class template specialization.
1908  // In these cases, grab the template that is being defined or specialized.
1909  if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
1910  cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
1911  PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
1912  PrevClassTemplate
1913  = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
1914  if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
1915  PrevClassTemplate
1916  = cast<ClassTemplateSpecializationDecl>(PrevDecl)
1917  ->getSpecializedTemplate();
1918  }
1919  }
1920 
1921  if (TUK == TUK_Friend) {
1922  // C++ [namespace.memdef]p3:
1923  // [...] When looking for a prior declaration of a class or a function
1924  // declared as a friend, and when the name of the friend class or
1925  // function is neither a qualified name nor a template-id, scopes outside
1926  // the innermost enclosing namespace scope are not considered.
1927  if (!SS.isSet()) {
1928  DeclContext *OutermostContext = CurContext;
1929  while (!OutermostContext->isFileContext())
1930  OutermostContext = OutermostContext->getLookupParent();
1931 
1932  if (PrevDecl &&
1933  (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
1934  OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
1935  SemanticContext = PrevDecl->getDeclContext();
1936  } else {
1937  // Declarations in outer scopes don't matter. However, the outermost
1938  // context we computed is the semantic context for our new
1939  // declaration.
1940  PrevDecl = PrevClassTemplate = nullptr;
1941  SemanticContext = OutermostContext;
1942 
1943  // Check that the chosen semantic context doesn't already contain a
1944  // declaration of this name as a non-tag type.
1945  Previous.clear(LookupOrdinaryName);
1946  DeclContext *LookupContext = SemanticContext;
1947  while (LookupContext->isTransparentContext())
1948  LookupContext = LookupContext->getLookupParent();
1949  LookupQualifiedName(Previous, LookupContext);
1950 
1951  if (Previous.isAmbiguous())
1952  return true;
1953 
1954  if (Previous.begin() != Previous.end())
1955  PrevDecl = (*Previous.begin())->getUnderlyingDecl();
1956  }
1957  }
1958  } else if (PrevDecl &&
1959  !isDeclInScope(Previous.getRepresentativeDecl(), SemanticContext,
1960  S, SS.isValid()))
1961  PrevDecl = PrevClassTemplate = nullptr;
1962 
1963  if (auto *Shadow = dyn_cast_or_null<UsingShadowDecl>(
1964  PrevDecl ? Previous.getRepresentativeDecl() : nullptr)) {
1965  if (SS.isEmpty() &&
1966  !(PrevClassTemplate &&
1967  PrevClassTemplate->getDeclContext()->getRedeclContext()->Equals(
1968  SemanticContext->getRedeclContext()))) {
1969  Diag(KWLoc, diag::err_using_decl_conflict_reverse);
1970  Diag(Shadow->getTargetDecl()->getLocation(),
1971  diag::note_using_decl_target);
1972  Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
1973  // Recover by ignoring the old declaration.
1974  PrevDecl = PrevClassTemplate = nullptr;
1975  }
1976  }
1977 
1978  if (PrevClassTemplate) {
1979  // Ensure that the template parameter lists are compatible. Skip this check
1980  // for a friend in a dependent context: the template parameter list itself
1981  // could be dependent.
1982  if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
1983  !TemplateParameterListsAreEqual(TemplateParams,
1984  PrevClassTemplate->getTemplateParameters(),
1985  /*Complain=*/true,
1986  TPL_TemplateMatch))
1987  return true;
1988 
1989  // C++ [temp.class]p4:
1990  // In a redeclaration, partial specialization, explicit
1991  // specialization or explicit instantiation of a class template,
1992  // the class-key shall agree in kind with the original class
1993  // template declaration (7.1.5.3).
1994  RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
1995  if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind,
1996  TUK == TUK_Definition, KWLoc, Name)) {
1997  Diag(KWLoc, diag::err_use_with_wrong_tag)
1998  << Name
1999  << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
2000  Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
2001  Kind = PrevRecordDecl->getTagKind();
2002  }
2003 
2004  // Check for redefinition of this class template.
2005  if (TUK == TUK_Definition) {
2006  if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
2007  // If we have a prior definition that is not visible, treat this as
2008  // simply making that previous definition visible.
2009  NamedDecl *Hidden = nullptr;
2010  if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
2011  SkipBody->ShouldSkip = true;
2012  SkipBody->Previous = Def;
2013  auto *Tmpl = cast<CXXRecordDecl>(Hidden)->getDescribedClassTemplate();
2014  assert(Tmpl && "original definition of a class template is not a "
2015  "class template?");
2016  makeMergedDefinitionVisible(Hidden);
2017  makeMergedDefinitionVisible(Tmpl);
2018  } else {
2019  Diag(NameLoc, diag::err_redefinition) << Name;
2020  Diag(Def->getLocation(), diag::note_previous_definition);
2021  // FIXME: Would it make sense to try to "forget" the previous
2022  // definition, as part of error recovery?
2023  return true;
2024  }
2025  }
2026  }
2027  } else if (PrevDecl) {
2028  // C++ [temp]p5:
2029  // A class template shall not have the same name as any other
2030  // template, class, function, object, enumeration, enumerator,
2031  // namespace, or type in the same scope (3.3), except as specified
2032  // in (14.5.4).
2033  Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
2034  Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2035  return true;
2036  }
2037 
2038  // Check the template parameter list of this declaration, possibly
2039  // merging in the template parameter list from the previous class
2040  // template declaration. Skip this check for a friend in a dependent
2041  // context, because the template parameter list might be dependent.
2042  if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
2043  CheckTemplateParameterList(
2044  TemplateParams,
2045  PrevClassTemplate
2046  ? PrevClassTemplate->getMostRecentDecl()->getTemplateParameters()
2047  : nullptr,
2048  (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
2049  SemanticContext->isDependentContext())
2050  ? TPC_ClassTemplateMember
2051  : TUK == TUK_Friend ? TPC_FriendClassTemplate : TPC_ClassTemplate,
2052  SkipBody))
2053  Invalid = true;
2054 
2055  if (SS.isSet()) {
2056  // If the name of the template was qualified, we must be defining the
2057  // template out-of-line.
2058  if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
2059  Diag(NameLoc, TUK == TUK_Friend ? diag::err_friend_decl_does_not_match
2060  : diag::err_member_decl_does_not_match)
2061  << Name << SemanticContext << /*IsDefinition*/true << SS.getRange();
2062  Invalid = true;
2063  }
2064  }
2065 
2066  // If this is a templated friend in a dependent context we should not put it
2067  // on the redecl chain. In some cases, the templated friend can be the most
2068  // recent declaration tricking the template instantiator to make substitutions
2069  // there.
2070  // FIXME: Figure out how to combine with shouldLinkDependentDeclWithPrevious
2071  bool ShouldAddRedecl
2072  = !(TUK == TUK_Friend && CurContext->isDependentContext());
2073 
2074  CXXRecordDecl *NewClass =
2075  CXXRecordDecl::Create(Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
2076  PrevClassTemplate && ShouldAddRedecl ?
2077  PrevClassTemplate->getTemplatedDecl() : nullptr,
2078  /*DelayTypeCreation=*/true);
2079  SetNestedNameSpecifier(*this, NewClass, SS);
2080  if (NumOuterTemplateParamLists > 0)
2082  Context, llvm::makeArrayRef(OuterTemplateParamLists,
2083  NumOuterTemplateParamLists));
2084 
2085  // Add alignment attributes if necessary; these attributes are checked when
2086  // the ASTContext lays out the structure.
2087  if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
2088  AddAlignmentAttributesForRecord(NewClass);
2089  AddMsStructLayoutForRecord(NewClass);
2090  }
2091 
2092  ClassTemplateDecl *NewTemplate
2093  = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
2094  DeclarationName(Name), TemplateParams,
2095  NewClass);
2096 
2097  if (ShouldAddRedecl)
2098  NewTemplate->setPreviousDecl(PrevClassTemplate);
2099 
2100  NewClass->setDescribedClassTemplate(NewTemplate);
2101 
2102  if (ModulePrivateLoc.isValid())
2103  NewTemplate->setModulePrivate();
2104 
2105  // Build the type for the class template declaration now.
2106  QualType T = NewTemplate->getInjectedClassNameSpecialization();
2107  T = Context.getInjectedClassNameType(NewClass, T);
2108  assert(T->isDependentType() && "Class template type is not dependent?");
2109  (void)T;
2110 
2111  // If we are providing an explicit specialization of a member that is a
2112  // class template, make a note of that.
2113  if (PrevClassTemplate &&
2114  PrevClassTemplate->getInstantiatedFromMemberTemplate())
2115  PrevClassTemplate->setMemberSpecialization();
2116 
2117  // Set the access specifier.
2118  if (!Invalid && TUK != TUK_Friend && NewTemplate->getDeclContext()->isRecord())
2119  SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
2120 
2121  // Set the lexical context of these templates
2122  NewClass->setLexicalDeclContext(CurContext);
2123  NewTemplate->setLexicalDeclContext(CurContext);
2124 
2125  if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
2126  NewClass->startDefinition();
2127 
2128  ProcessDeclAttributeList(S, NewClass, Attr);
2129 
2130  if (PrevClassTemplate)
2131  mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
2132 
2133  AddPushedVisibilityAttribute(NewClass);
2134  inferGslOwnerPointerAttribute(NewClass);
2135 
2136  if (TUK != TUK_Friend) {
2137  // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
2138  Scope *Outer = S;
2139  while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
2140  Outer = Outer->getParent();
2141  PushOnScopeChains(NewTemplate, Outer);
2142  } else {
2143  if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
2144  NewTemplate->setAccess(PrevClassTemplate->getAccess());
2145  NewClass->setAccess(PrevClassTemplate->getAccess());
2146  }
2147 
2148  NewTemplate->setObjectOfFriendDecl();
2149 
2150  // Friend templates are visible in fairly strange ways.
2151  if (!CurContext->isDependentContext()) {
2152  DeclContext *DC = SemanticContext->getRedeclContext();
2153  DC->makeDeclVisibleInContext(NewTemplate);
2154  if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
2155  PushOnScopeChains(NewTemplate, EnclosingScope,
2156  /* AddToContext = */ false);
2157  }
2158 
2159  FriendDecl *Friend = FriendDecl::Create(
2160  Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc);
2161  Friend->setAccess(AS_public);
2162  CurContext->addDecl(Friend);
2163  }
2164 
2165  if (PrevClassTemplate)
2166  CheckRedeclarationInModule(NewTemplate, PrevClassTemplate);
2167 
2168  if (Invalid) {
2169  NewTemplate->setInvalidDecl();
2170  NewClass->setInvalidDecl();
2171  }
2172 
2173  ActOnDocumentableDecl(NewTemplate);
2174 
2175  if (SkipBody && SkipBody->ShouldSkip)
2176  return SkipBody->Previous;
2177 
2178  return NewTemplate;
2179 }
2180 
2181 namespace {
2182 /// Tree transform to "extract" a transformed type from a class template's
2183 /// constructor to a deduction guide.
2184 class ExtractTypeForDeductionGuide
2185  : public TreeTransform<ExtractTypeForDeductionGuide> {
2186  llvm::SmallVectorImpl<TypedefNameDecl *> &MaterializedTypedefs;
2187 
2188 public:
2190  ExtractTypeForDeductionGuide(
2191  Sema &SemaRef,
2192  llvm::SmallVectorImpl<TypedefNameDecl *> &MaterializedTypedefs)
2193  : Base(SemaRef), MaterializedTypedefs(MaterializedTypedefs) {}
2194 
2195  TypeSourceInfo *transform(TypeSourceInfo *TSI) { return TransformType(TSI); }
2196 
2197  QualType TransformTypedefType(TypeLocBuilder &TLB, TypedefTypeLoc TL) {
2198  ASTContext &Context = SemaRef.getASTContext();
2199  TypedefNameDecl *OrigDecl = TL.getTypedefNameDecl();
2200  TypedefNameDecl *Decl = OrigDecl;
2201  // Transform the underlying type of the typedef and clone the Decl only if
2202  // the typedef has a dependent context.
2203  if (OrigDecl->getDeclContext()->isDependentContext()) {
2204  TypeLocBuilder InnerTLB;
2205  QualType Transformed =
2206  TransformType(InnerTLB, OrigDecl->getTypeSourceInfo()->getTypeLoc());
2207  TypeSourceInfo *TSI = InnerTLB.getTypeSourceInfo(Context, Transformed);
2208  if (isa<TypeAliasDecl>(OrigDecl))
2210  Context, Context.getTranslationUnitDecl(), OrigDecl->getBeginLoc(),
2211  OrigDecl->getLocation(), OrigDecl->getIdentifier(), TSI);
2212  else {
2213  assert(isa<TypedefDecl>(OrigDecl) && "Not a Type alias or typedef");
2215  Context, Context.getTranslationUnitDecl(), OrigDecl->getBeginLoc(),
2216  OrigDecl->getLocation(), OrigDecl->getIdentifier(), TSI);
2217  }
2218  MaterializedTypedefs.push_back(Decl);
2219  }
2220 
2221  QualType TDTy = Context.getTypedefType(Decl);
2222  TypedefTypeLoc TypedefTL = TLB.push<TypedefTypeLoc>(TDTy);
2223  TypedefTL.setNameLoc(TL.getNameLoc());
2224 
2225  return TDTy;
2226  }
2227 };
2228 
2229 /// Transform to convert portions of a constructor declaration into the
2230 /// corresponding deduction guide, per C++1z [over.match.class.deduct]p1.
2231 struct ConvertConstructorToDeductionGuideTransform {
2232  ConvertConstructorToDeductionGuideTransform(Sema &S,
2233  ClassTemplateDecl *Template)
2234  : SemaRef(S), Template(Template) {}
2235 
2236  Sema &SemaRef;
2237  ClassTemplateDecl *Template;
2238 
2239  DeclContext *DC = Template->getDeclContext();
2240  CXXRecordDecl *Primary = Template->getTemplatedDecl();
2241  DeclarationName DeductionGuideName =
2243 
2244  QualType DeducedType = SemaRef.Context.getTypeDeclType(Primary);
2245 
2246  // Index adjustment to apply to convert depth-1 template parameters into
2247  // depth-0 template parameters.
2248  unsigned Depth1IndexAdjustment = Template->getTemplateParameters()->size();
2249 
2250  /// Transform a constructor declaration into a deduction guide.
2251  NamedDecl *transformConstructor(FunctionTemplateDecl *FTD,
2252  CXXConstructorDecl *CD) {
2254 
2255  LocalInstantiationScope Scope(SemaRef);
2256 
2257  // C++ [over.match.class.deduct]p1:
2258  // -- For each constructor of the class template designated by the
2259  // template-name, a function template with the following properties:
2260 
2261  // -- The template parameters are the template parameters of the class
2262  // template followed by the template parameters (including default
2263  // template arguments) of the constructor, if any.
2264  TemplateParameterList *TemplateParams = Template->getTemplateParameters();
2265  if (FTD) {
2266  TemplateParameterList *InnerParams = FTD->getTemplateParameters();
2267  SmallVector<NamedDecl *, 16> AllParams;
2268  AllParams.reserve(TemplateParams->size() + InnerParams->size());
2269  AllParams.insert(AllParams.begin(),
2270  TemplateParams->begin(), TemplateParams->end());
2271  SubstArgs.reserve(InnerParams->size());
2272 
2273  // Later template parameters could refer to earlier ones, so build up
2274  // a list of substituted template arguments as we go.
2275  for (NamedDecl *Param : *InnerParams) {
2278  Args.addOuterTemplateArguments(SubstArgs);
2279  Args.addOuterRetainedLevel();
2280  NamedDecl *NewParam = transformTemplateParameter(Param, Args);
2281  if (!NewParam)
2282  return nullptr;
2283  AllParams.push_back(NewParam);
2284  SubstArgs.push_back(SemaRef.Context.getCanonicalTemplateArgument(
2285  SemaRef.Context.getInjectedTemplateArg(NewParam)));
2286  }
2287 
2288  // Substitute new template parameters into requires-clause if present.
2289  Expr *RequiresClause = nullptr;
2290  if (Expr *InnerRC = InnerParams->getRequiresClause()) {
2293  Args.addOuterTemplateArguments(SubstArgs);
2294  Args.addOuterRetainedLevel();
2295  ExprResult E = SemaRef.SubstExpr(InnerRC, Args);
2296  if (E.isInvalid())
2297  return nullptr;
2298  RequiresClause = E.getAs<Expr>();
2299  }
2300 
2301  TemplateParams = TemplateParameterList::Create(
2302  SemaRef.Context, InnerParams->getTemplateLoc(),
2303  InnerParams->getLAngleLoc(), AllParams, InnerParams->getRAngleLoc(),
2304  RequiresClause);
2305  }
2306 
2307  // If we built a new template-parameter-list, track that we need to
2308  // substitute references to the old parameters into references to the
2309  // new ones.
2312  if (FTD) {
2313  Args.addOuterTemplateArguments(SubstArgs);
2314  Args.addOuterRetainedLevel();
2315  }
2316 
2319  assert(FPTL && "no prototype for constructor declaration");
2320 
2321  // Transform the type of the function, adjusting the return type and
2322  // replacing references to the old parameters with references to the
2323  // new ones.
2324  TypeLocBuilder TLB;
2326  SmallVector<TypedefNameDecl *, 4> MaterializedTypedefs;
2327  QualType NewType = transformFunctionProtoType(TLB, FPTL, Params, Args,
2328  MaterializedTypedefs);
2329  if (NewType.isNull())
2330  return nullptr;
2331  TypeSourceInfo *NewTInfo = TLB.getTypeSourceInfo(SemaRef.Context, NewType);
2332 
2333  return buildDeductionGuide(TemplateParams, CD, CD->getExplicitSpecifier(),
2334  NewTInfo, CD->getBeginLoc(), CD->getLocation(),
2335  CD->getEndLoc(), MaterializedTypedefs);
2336  }
2337 
2338  /// Build a deduction guide with the specified parameter types.
2339  NamedDecl *buildSimpleDeductionGuide(MutableArrayRef<QualType> ParamTypes) {
2340  SourceLocation Loc = Template->getLocation();
2341 
2342  // Build the requested type.
2344  EPI.HasTrailingReturn = true;
2345  QualType Result = SemaRef.BuildFunctionType(DeducedType, ParamTypes, Loc,
2346  DeductionGuideName, EPI);
2347  TypeSourceInfo *TSI = SemaRef.Context.getTrivialTypeSourceInfo(Result, Loc);
2348 
2349  FunctionProtoTypeLoc FPTL =
2351 
2352  // Build the parameters, needed during deduction / substitution.
2354  for (auto T : ParamTypes) {
2355  ParmVarDecl *NewParam = ParmVarDecl::Create(
2356  SemaRef.Context, DC, Loc, Loc, nullptr, T,
2357  SemaRef.Context.getTrivialTypeSourceInfo(T, Loc), SC_None, nullptr);
2358  NewParam->setScopeInfo(0, Params.size());
2359  FPTL.setParam(Params.size(), NewParam);
2360  Params.push_back(NewParam);
2361  }
2362 
2363  return buildDeductionGuide(Template->getTemplateParameters(), nullptr,
2364  ExplicitSpecifier(), TSI, Loc, Loc, Loc);
2365  }
2366 
2367 private:
2368  /// Transform a constructor template parameter into a deduction guide template
2369  /// parameter, rebuilding any internal references to earlier parameters and
2370  /// renumbering as we go.
2371  NamedDecl *transformTemplateParameter(NamedDecl *TemplateParam,
2373  if (auto *TTP = dyn_cast<TemplateTypeParmDecl>(TemplateParam)) {
2374  // TemplateTypeParmDecl's index cannot be changed after creation, so
2375  // substitute it directly.
2376  auto *NewTTP = TemplateTypeParmDecl::Create(
2377  SemaRef.Context, DC, TTP->getBeginLoc(), TTP->getLocation(),
2378  /*Depth*/ 0, Depth1IndexAdjustment + TTP->getIndex(),
2379  TTP->getIdentifier(), TTP->wasDeclaredWithTypename(),
2380  TTP->isParameterPack(), TTP->hasTypeConstraint(),
2381  TTP->isExpandedParameterPack()
2382  ? llvm::Optional<unsigned>(TTP->getNumExpansionParameters())
2383  : std::nullopt);
2384  if (const auto *TC = TTP->getTypeConstraint())
2385  SemaRef.SubstTypeConstraint(NewTTP, TC, Args,
2386  /*EvaluateConstraint*/ true);
2387  if (TTP->hasDefaultArgument()) {
2388  TypeSourceInfo *InstantiatedDefaultArg =
2389  SemaRef.SubstType(TTP->getDefaultArgumentInfo(), Args,
2390  TTP->getDefaultArgumentLoc(), TTP->getDeclName());
2391  if (InstantiatedDefaultArg)
2392  NewTTP->setDefaultArgument(InstantiatedDefaultArg);
2393  }
2394  SemaRef.CurrentInstantiationScope->InstantiatedLocal(TemplateParam,
2395  NewTTP);
2396  return NewTTP;
2397  }
2398 
2399  if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(TemplateParam))
2400  return transformTemplateParameterImpl(TTP, Args);
2401 
2402  return transformTemplateParameterImpl(
2403  cast<NonTypeTemplateParmDecl>(TemplateParam), Args);
2404  }
2405  template<typename TemplateParmDecl>
2406  TemplateParmDecl *
2407  transformTemplateParameterImpl(TemplateParmDecl *OldParam,
2409  // Ask the template instantiator to do the heavy lifting for us, then adjust
2410  // the index of the parameter once it's done.
2411  auto *NewParam =
2412  cast<TemplateParmDecl>(SemaRef.SubstDecl(OldParam, DC, Args));
2413  assert(NewParam->getDepth() == 0 && "unexpected template param depth");
2414  NewParam->setPosition(NewParam->getPosition() + Depth1IndexAdjustment);
2415  return NewParam;
2416  }
2417 
2418  QualType transformFunctionProtoType(
2422  SmallVectorImpl<TypedefNameDecl *> &MaterializedTypedefs) {
2423  SmallVector<QualType, 4> ParamTypes;
2424  const FunctionProtoType *T = TL.getTypePtr();
2425 
2426  // -- The types of the function parameters are those of the constructor.
2427  for (auto *OldParam : TL.getParams()) {
2428  ParmVarDecl *NewParam =
2429  transformFunctionTypeParam(OldParam, Args, MaterializedTypedefs);
2430  if (!NewParam)
2431  return QualType();
2432  ParamTypes.push_back(NewParam->getType());
2433  Params.push_back(NewParam);
2434  }
2435 
2436  // -- The return type is the class template specialization designated by
2437  // the template-name and template arguments corresponding to the
2438  // template parameters obtained from the class template.
2439  //
2440  // We use the injected-class-name type of the primary template instead.
2441  // This has the convenient property that it is different from any type that
2442  // the user can write in a deduction-guide (because they cannot enter the
2443  // context of the template), so implicit deduction guides can never collide
2444  // with explicit ones.
2445  QualType ReturnType = DeducedType;
2446  TLB.pushTypeSpec(ReturnType).setNameLoc(Primary->getLocation());
2447 
2448  // Resolving a wording defect, we also inherit the variadicness of the
2449  // constructor.
2451  EPI.Variadic = T->isVariadic();
2452  EPI.HasTrailingReturn = true;
2453 
2454  QualType Result = SemaRef.BuildFunctionType(
2455  ReturnType, ParamTypes, TL.getBeginLoc(), DeductionGuideName, EPI);
2456  if (Result.isNull())
2457  return QualType();
2458 
2459  FunctionProtoTypeLoc NewTL = TLB.push<FunctionProtoTypeLoc>(Result);
2461  NewTL.setLParenLoc(TL.getLParenLoc());
2462  NewTL.setRParenLoc(TL.getRParenLoc());
2464  NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
2465  for (unsigned I = 0, E = NewTL.getNumParams(); I != E; ++I)
2466  NewTL.setParam(I, Params[I]);
2467 
2468  return Result;
2469  }
2470 
2471  ParmVarDecl *transformFunctionTypeParam(
2473  llvm::SmallVectorImpl<TypedefNameDecl *> &MaterializedTypedefs) {
2474  TypeSourceInfo *OldDI = OldParam->getTypeSourceInfo();
2475  TypeSourceInfo *NewDI;
2476  if (auto PackTL = OldDI->getTypeLoc().getAs<PackExpansionTypeLoc>()) {
2477  // Expand out the one and only element in each inner pack.
2478  Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, 0);
2479  NewDI =
2480  SemaRef.SubstType(PackTL.getPatternLoc(), Args,
2481  OldParam->getLocation(), OldParam->getDeclName());
2482  if (!NewDI) return nullptr;
2483  NewDI =
2484  SemaRef.CheckPackExpansion(NewDI, PackTL.getEllipsisLoc(),
2485  PackTL.getTypePtr()->getNumExpansions());
2486  } else
2487  NewDI = SemaRef.SubstType(OldDI, Args, OldParam->getLocation(),
2488  OldParam->getDeclName());
2489  if (!NewDI)
2490  return nullptr;
2491 
2492  // Extract the type. This (for instance) replaces references to typedef
2493  // members of the current instantiations with the definitions of those
2494  // typedefs, avoiding triggering instantiation of the deduced type during
2495  // deduction.
2496  NewDI = ExtractTypeForDeductionGuide(SemaRef, MaterializedTypedefs)
2497  .transform(NewDI);
2498 
2499  // Resolving a wording defect, we also inherit default arguments from the
2500  // constructor.
2501  ExprResult NewDefArg;
2502  if (OldParam->hasDefaultArg()) {
2503  // We don't care what the value is (we won't use it); just create a
2504  // placeholder to indicate there is a default argument.
2505  QualType ParamTy = NewDI->getType();
2506  NewDefArg = new (SemaRef.Context)
2507  OpaqueValueExpr(OldParam->getDefaultArg()->getBeginLoc(),
2508  ParamTy.getNonLValueExprType(SemaRef.Context),
2509  ParamTy->isLValueReferenceType() ? VK_LValue
2510  : ParamTy->isRValueReferenceType() ? VK_XValue
2511  : VK_PRValue);
2512  }
2513 
2514  ParmVarDecl *NewParam = ParmVarDecl::Create(SemaRef.Context, DC,
2515  OldParam->getInnerLocStart(),
2516  OldParam->getLocation(),
2517  OldParam->getIdentifier(),
2518  NewDI->getType(),
2519  NewDI,
2520  OldParam->getStorageClass(),
2521  NewDefArg.get());
2522  NewParam->setScopeInfo(OldParam->getFunctionScopeDepth(),
2523  OldParam->getFunctionScopeIndex());
2524  SemaRef.CurrentInstantiationScope->InstantiatedLocal(OldParam, NewParam);
2525  return NewParam;
2526  }
2527 
2528  FunctionTemplateDecl *buildDeductionGuide(
2529  TemplateParameterList *TemplateParams, CXXConstructorDecl *Ctor,
2530  ExplicitSpecifier ES, TypeSourceInfo *TInfo, SourceLocation LocStart,
2531  SourceLocation Loc, SourceLocation LocEnd,
2532  llvm::ArrayRef<TypedefNameDecl *> MaterializedTypedefs = {}) {
2533  DeclarationNameInfo Name(DeductionGuideName, Loc);
2534  ArrayRef<ParmVarDecl *> Params =
2535  TInfo->getTypeLoc().castAs<FunctionProtoTypeLoc>().getParams();
2536 
2537  // Build the implicit deduction guide template.
2538  auto *Guide =
2539  CXXDeductionGuideDecl::Create(SemaRef.Context, DC, LocStart, ES, Name,
2540  TInfo->getType(), TInfo, LocEnd, Ctor);
2541  Guide->setImplicit();
2542  Guide->setParams(Params);
2543  if (Ctor && Ctor->getTrailingRequiresClause())
2544  Guide->setTrailingRequiresClause(Ctor->getTrailingRequiresClause());
2545 
2546  for (auto *Param : Params)
2547  Param->setDeclContext(Guide);
2548  for (auto *TD : MaterializedTypedefs)
2549  TD->setDeclContext(Guide);
2550 
2551  auto *GuideTemplate = FunctionTemplateDecl::Create(
2552  SemaRef.Context, DC, Loc, DeductionGuideName, TemplateParams, Guide);
2553  GuideTemplate->setImplicit();
2554  Guide->setDescribedFunctionTemplate(GuideTemplate);
2555 
2556  if (isa<CXXRecordDecl>(DC)) {
2557  Guide->setAccess(AS_public);
2558  GuideTemplate->setAccess(AS_public);
2559  }
2560 
2561  DC->addDecl(GuideTemplate);
2562  return GuideTemplate;
2563  }
2564 };
2565 }
2566 
2568  SourceLocation Loc) {
2569  if (CXXRecordDecl *DefRecord =
2570  cast<CXXRecordDecl>(Template->getTemplatedDecl())->getDefinition()) {
2571  TemplateDecl *DescribedTemplate = DefRecord->getDescribedClassTemplate();
2572  Template = DescribedTemplate ? DescribedTemplate : Template;
2573  }
2574 
2575  DeclContext *DC = Template->getDeclContext();
2576  if (DC->isDependentContext())
2577  return;
2578 
2579  ConvertConstructorToDeductionGuideTransform Transform(
2580  *this, cast<ClassTemplateDecl>(Template));
2581  if (!isCompleteType(Loc, Transform.DeducedType))
2582  return;
2583 
2584  // Check whether we've already declared deduction guides for this template.
2585  // FIXME: Consider storing a flag on the template to indicate this.
2586  auto Existing = DC->lookup(Transform.DeductionGuideName);
2587  for (auto *D : Existing)
2588  if (D->isImplicit())
2589  return;
2590 
2591  // In case we were expanding a pack when we attempted to declare deduction
2592  // guides, turn off pack expansion for everything we're about to do.
2593  ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
2594  // Create a template instantiation record to track the "instantiation" of
2595  // constructors into deduction guides.
2596  // FIXME: Add a kind for this to give more meaningful diagnostics. But can
2597  // this substitution process actually fail?
2598  InstantiatingTemplate BuildingDeductionGuides(*this, Loc, Template);
2599  if (BuildingDeductionGuides.isInvalid())
2600  return;
2601 
2602  // Convert declared constructors into deduction guide templates.
2603  // FIXME: Skip constructors for which deduction must necessarily fail (those
2604  // for which some class template parameter without a default argument never
2605  // appears in a deduced context).
2606  bool AddedAny = false;
2607  for (NamedDecl *D : LookupConstructors(Transform.Primary)) {
2608  D = D->getUnderlyingDecl();
2609  if (D->isInvalidDecl() || D->isImplicit())
2610  continue;
2611  D = cast<NamedDecl>(D->getCanonicalDecl());
2612 
2613  auto *FTD = dyn_cast<FunctionTemplateDecl>(D);
2614  auto *CD =
2615  dyn_cast_or_null<CXXConstructorDecl>(FTD ? FTD->getTemplatedDecl() : D);
2616  // Class-scope explicit specializations (MS extension) do not result in
2617  // deduction guides.
2618  if (!CD || (!FTD && CD->isFunctionTemplateSpecialization()))
2619  continue;
2620 
2621  // Cannot make a deduction guide when unparsed arguments are present.
2622  if (llvm::any_of(CD->parameters(), [](ParmVarDecl *P) {
2623  return !P || P->hasUnparsedDefaultArg();
2624  }))
2625  continue;
2626 
2627  Transform.transformConstructor(FTD, CD);
2628  AddedAny = true;
2629  }
2630 
2631  // C++17 [over.match.class.deduct]
2632  // -- If C is not defined or does not declare any constructors, an
2633  // additional function template derived as above from a hypothetical
2634  // constructor C().
2635  if (!AddedAny)
2636  Transform.buildSimpleDeductionGuide(std::nullopt);
2637 
2638  // -- An additional function template derived as above from a hypothetical
2639  // constructor C(C), called the copy deduction candidate.
2640  cast<CXXDeductionGuideDecl>(
2641  cast<FunctionTemplateDecl>(
2642  Transform.buildSimpleDeductionGuide(Transform.DeducedType))
2643  ->getTemplatedDecl())
2644  ->setIsCopyDeductionCandidate();
2645 }
2646 
2647 /// Diagnose the presence of a default template argument on a
2648 /// template parameter, which is ill-formed in certain contexts.
2649 ///
2650 /// \returns true if the default template argument should be dropped.
2653  SourceLocation ParamLoc,
2654  SourceRange DefArgRange) {
2655  switch (TPC) {
2657  case Sema::TPC_VarTemplate:
2659  return false;
2660 
2663  // C++ [temp.param]p9:
2664  // A default template-argument shall not be specified in a
2665  // function template declaration or a function template
2666  // definition [...]
2667  // If a friend function template declaration specifies a default
2668  // template-argument, that declaration shall be a definition and shall be
2669  // the only declaration of the function template in the translation unit.
2670  // (C++98/03 doesn't have this wording; see DR226).
2671  S.Diag(ParamLoc, S.getLangOpts().CPlusPlus11 ?
2672  diag::warn_cxx98_compat_template_parameter_default_in_function_template
2673  : diag::ext_template_parameter_default_in_function_template)
2674  << DefArgRange;
2675  return false;
2676 
2678  // C++0x [temp.param]p9:
2679  // A default template-argument shall not be specified in the
2680  // template-parameter-lists of the definition of a member of a
2681  // class template that appears outside of the member's class.
2682  S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
2683  << DefArgRange;
2684  return true;
2685 
2688  // C++ [temp.param]p9:
2689  // A default template-argument shall not be specified in a
2690  // friend template declaration.
2691  S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
2692  << DefArgRange;
2693  return true;
2694 
2695  // FIXME: C++0x [temp.param]p9 allows default template-arguments
2696  // for friend function templates if there is only a single
2697  // declaration (and it is a definition). Strange!
2698  }
2699 
2700  llvm_unreachable("Invalid TemplateParamListContext!");
2701 }
2702 
2703 /// Check for unexpanded parameter packs within the template parameters
2704 /// of a template template parameter, recursively.
2706  TemplateTemplateParmDecl *TTP) {
2707  // A template template parameter which is a parameter pack is also a pack
2708  // expansion.
2709  if (TTP->isParameterPack())
2710  return false;
2711 
2713  for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2714  NamedDecl *P = Params->getParam(I);
2715  if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(P)) {
2716  if (!TTP->isParameterPack())
2717  if (const TypeConstraint *TC = TTP->getTypeConstraint())
2718  if (TC->hasExplicitTemplateArgs())
2719  for (auto &ArgLoc : TC->getTemplateArgsAsWritten()->arguments())
2720  if (S.DiagnoseUnexpandedParameterPack(ArgLoc,
2722  return true;
2723  continue;
2724  }
2725 
2726  if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
2727  if (!NTTP->isParameterPack() &&
2728  S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
2729  NTTP->getTypeSourceInfo(),
2731  return true;
2732 
2733  continue;
2734  }
2735 
2736  if (TemplateTemplateParmDecl *InnerTTP
2737  = dyn_cast<TemplateTemplateParmDecl>(P))
2738  if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
2739  return true;
2740  }
2741 
2742  return false;
2743 }
2744 
2745 /// Checks the validity of a template parameter list, possibly
2746 /// considering the template parameter list from a previous
2747 /// declaration.
2748 ///
2749 /// If an "old" template parameter list is provided, it must be
2750 /// equivalent (per TemplateParameterListsAreEqual) to the "new"
2751 /// template parameter list.
2752 ///
2753 /// \param NewParams Template parameter list for a new template
2754 /// declaration. This template parameter list will be updated with any
2755 /// default arguments that are carried through from the previous
2756 /// template parameter list.
2757 ///
2758 /// \param OldParams If provided, template parameter list from a
2759 /// previous declaration of the same template. Default template
2760 /// arguments will be merged from the old template parameter list to
2761 /// the new template parameter list.
2762 ///
2763 /// \param TPC Describes the context in which we are checking the given
2764 /// template parameter list.
2765 ///
2766 /// \param SkipBody If we might have already made a prior merged definition
2767 /// of this template visible, the corresponding body-skipping information.
2768 /// Default argument redefinition is not an error when skipping such a body,
2769 /// because (under the ODR) we can assume the default arguments are the same
2770 /// as the prior merged definition.
2771 ///
2772 /// \returns true if an error occurred, false otherwise.
2774  TemplateParameterList *OldParams,
2776  SkipBodyInfo *SkipBody) {
2777  bool Invalid = false;
2778 
2779  // C++ [temp.param]p10:
2780  // The set of default template-arguments available for use with a
2781  // template declaration or definition is obtained by merging the
2782  // default arguments from the definition (if in scope) and all
2783  // declarations in scope in the same way default function
2784  // arguments are (8.3.6).
2785  bool SawDefaultArgument = false;
2786  SourceLocation PreviousDefaultArgLoc;
2787 
2788  // Dummy initialization to avoid warnings.
2789  TemplateParameterList::iterator OldParam = NewParams->end();
2790  if (OldParams)
2791  OldParam = OldParams->begin();
2792 
2793  bool RemoveDefaultArguments = false;
2794  for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2795  NewParamEnd = NewParams->end();
2796  NewParam != NewParamEnd; ++NewParam) {
2797  // Whether we've seen a duplicate default argument in the same translation
2798  // unit.
2799  bool RedundantDefaultArg = false;
2800  // Whether we've found inconsis inconsitent default arguments in different
2801  // translation unit.
2802  bool InconsistentDefaultArg = false;
2803  // The name of the module which contains the inconsistent default argument.
2804  std::string PrevModuleName;
2805 
2806  SourceLocation OldDefaultLoc;
2807  SourceLocation NewDefaultLoc;
2808 
2809  // Variable used to diagnose missing default arguments
2810  bool MissingDefaultArg = false;
2811 
2812  // Variable used to diagnose non-final parameter packs
2813  bool SawParameterPack = false;
2814 
2815  if (TemplateTypeParmDecl *NewTypeParm
2816  = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
2817  // Check the presence of a default argument here.
2818  if (NewTypeParm->hasDefaultArgument() &&
2820  NewTypeParm->getLocation(),
2821  NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
2822  .getSourceRange()))
2823  NewTypeParm->removeDefaultArgument();
2824 
2825  // Merge default arguments for template type parameters.
2826  TemplateTypeParmDecl *OldTypeParm
2827  = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr;
2828  if (NewTypeParm->isParameterPack()) {
2829  assert(!NewTypeParm->hasDefaultArgument() &&
2830  "Parameter packs can't have a default argument!");
2831  SawParameterPack = true;
2832  } else if (OldTypeParm && hasVisibleDefaultArgument(OldTypeParm) &&
2833  NewTypeParm->hasDefaultArgument() &&
2834  (!SkipBody || !SkipBody->ShouldSkip)) {
2835  OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
2836  NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
2837  SawDefaultArgument = true;
2838 
2839  if (!OldTypeParm->getOwningModule() ||
2840  isModuleUnitOfCurrentTU(OldTypeParm->getOwningModule()))
2841  RedundantDefaultArg = true;
2842  else if (!getASTContext().isSameDefaultTemplateArgument(OldTypeParm,
2843  NewTypeParm)) {
2844  InconsistentDefaultArg = true;
2845  PrevModuleName =
2846  OldTypeParm->getImportedOwningModule()->getFullModuleName();
2847  }
2848  PreviousDefaultArgLoc = NewDefaultLoc;
2849  } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
2850  // Merge the default argument from the old declaration to the
2851  // new declaration.
2852  NewTypeParm->setInheritedDefaultArgument(Context, OldTypeParm);
2853  PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
2854  } else if (NewTypeParm->hasDefaultArgument()) {
2855  SawDefaultArgument = true;
2856  PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
2857  } else if (SawDefaultArgument)
2858  MissingDefaultArg = true;
2859  } else if (NonTypeTemplateParmDecl *NewNonTypeParm
2860  = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
2861  // Check for unexpanded parameter packs.
2862  if (!NewNonTypeParm->isParameterPack() &&
2863  DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
2864  NewNonTypeParm->getTypeSourceInfo(),
2865  UPPC_NonTypeTemplateParameterType)) {
2866  Invalid = true;
2867  continue;
2868  }
2869 
2870  // Check the presence of a default argument here.
2871  if (NewNonTypeParm->hasDefaultArgument() &&
2873  NewNonTypeParm->getLocation(),
2874  NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
2875  NewNonTypeParm->removeDefaultArgument();
2876  }
2877 
2878  // Merge default arguments for non-type template parameters
2879  NonTypeTemplateParmDecl *OldNonTypeParm
2880  = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr;
2881  if (NewNonTypeParm->isParameterPack()) {
2882  assert(!NewNonTypeParm->hasDefaultArgument() &&
2883  "Parameter packs can't have a default argument!");
2884  if (!NewNonTypeParm->isPackExpansion())
2885  SawParameterPack = true;
2886  } else if (OldNonTypeParm && hasVisibleDefaultArgument(OldNonTypeParm) &&
2887  NewNonTypeParm->hasDefaultArgument() &&
2888  (!SkipBody || !SkipBody->ShouldSkip)) {
2889  OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
2890  NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
2891  SawDefaultArgument = true;
2892  if (!OldNonTypeParm->getOwningModule() ||
2893  isModuleUnitOfCurrentTU(OldNonTypeParm->getOwningModule()))
2894  RedundantDefaultArg = true;
2895  else if (!getASTContext().isSameDefaultTemplateArgument(
2896  OldNonTypeParm, NewNonTypeParm)) {
2897  InconsistentDefaultArg = true;
2898  PrevModuleName =
2899  OldNonTypeParm->getImportedOwningModule()->getFullModuleName();
2900  }
2901  PreviousDefaultArgLoc = NewDefaultLoc;
2902  } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
2903  // Merge the default argument from the old declaration to the
2904  // new declaration.
2905  NewNonTypeParm->setInheritedDefaultArgument(Context, OldNonTypeParm);
2906  PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
2907  } else if (NewNonTypeParm->hasDefaultArgument()) {
2908  SawDefaultArgument = true;
2909  PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
2910  } else if (SawDefaultArgument)
2911  MissingDefaultArg = true;
2912  } else {
2913  TemplateTemplateParmDecl *NewTemplateParm
2914  = cast<TemplateTemplateParmDecl>(*NewParam);
2915 
2916  // Check for unexpanded parameter packs, recursively.
2917  if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
2918  Invalid = true;
2919  continue;
2920  }
2921 
2922  // Check the presence of a default argument here.
2923  if (NewTemplateParm->hasDefaultArgument() &&
2925  NewTemplateParm->getLocation(),
2926  NewTemplateParm->getDefaultArgument().getSourceRange()))
2927  NewTemplateParm->removeDefaultArgument();
2928 
2929  // Merge default arguments for template template parameters
2930  TemplateTemplateParmDecl *OldTemplateParm
2931  = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr;
2932  if (NewTemplateParm->isParameterPack()) {
2933  assert(!NewTemplateParm->hasDefaultArgument() &&
2934  "Parameter packs can't have a default argument!");
2935  if (!NewTemplateParm->isPackExpansion())
2936  SawParameterPack = true;
2937  } else if (OldTemplateParm &&
2938  hasVisibleDefaultArgument(OldTemplateParm) &&
2939  NewTemplateParm->hasDefaultArgument() &&
2940  (!SkipBody || !SkipBody->ShouldSkip)) {
2941  OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
2942  NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
2943  SawDefaultArgument = true;
2944  if (!OldTemplateParm->getOwningModule() ||
2945  isModuleUnitOfCurrentTU(OldTemplateParm->getOwningModule()))
2946  RedundantDefaultArg = true;
2947  else if (!getASTContext().isSameDefaultTemplateArgument(
2948  OldTemplateParm, NewTemplateParm)) {
2949  InconsistentDefaultArg = true;
2950  PrevModuleName =
2951  OldTemplateParm->getImportedOwningModule()->getFullModuleName();
2952  }
2953  PreviousDefaultArgLoc = NewDefaultLoc;
2954  } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
2955  // Merge the default argument from the old declaration to the
2956  // new declaration.
2957  NewTemplateParm->setInheritedDefaultArgument(Context, OldTemplateParm);
2958  PreviousDefaultArgLoc
2959  = OldTemplateParm->getDefaultArgument().getLocation();
2960  } else if (NewTemplateParm->hasDefaultArgument()) {
2961  SawDefaultArgument = true;
2962  PreviousDefaultArgLoc
2963  = NewTemplateParm->getDefaultArgument().getLocation();
2964  } else if (SawDefaultArgument)
2965  MissingDefaultArg = true;
2966  }
2967 
2968  // C++11 [temp.param]p11:
2969  // If a template parameter of a primary class template or alias template
2970  // is a template parameter pack, it shall be the last template parameter.
2971  if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
2972  (TPC == TPC_ClassTemplate || TPC == TPC_VarTemplate ||
2973  TPC == TPC_TypeAliasTemplate)) {
2974  Diag((*NewParam)->getLocation(),
2975  diag::err_template_param_pack_must_be_last_template_parameter);
2976  Invalid = true;
2977  }
2978 
2979  // [basic.def.odr]/13:
2980  // There can be more than one definition of a
2981  // ...
2982  // default template argument
2983  // ...
2984  // in a program provided that each definition appears in a different
2985  // translation unit and the definitions satisfy the [same-meaning
2986  // criteria of the ODR].
2987  //
2988  // Simply, the design of modules allows the definition of template default
2989  // argument to be repeated across translation unit. Note that the ODR is
2990  // checked elsewhere. But it is still not allowed to repeat template default
2991  // argument in the same translation unit.
2992  if (RedundantDefaultArg) {
2993  Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
2994  Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
2995  Invalid = true;
2996  } else if (InconsistentDefaultArg) {
2997  // We could only diagnose about the case that the OldParam is imported.
2998  // The case NewParam is imported should be handled in ASTReader.
2999  Diag(NewDefaultLoc,
3000  diag::err_template_param_default_arg_inconsistent_redefinition);
3001  Diag(OldDefaultLoc,
3002  diag::note_template_param_prev_default_arg_in_other_module)
3003  << PrevModuleName;
3004  Invalid = true;
3005  } else if (MissingDefaultArg && TPC != TPC_FunctionTemplate) {
3006  // C++ [temp.param]p11:
3007  // If a template-parameter of a class template has a default
3008  // template-argument, each subsequent template-parameter shall either
3009  // have a default template-argument supplied or be a template parameter
3010  // pack.
3011  Diag((*NewParam)->getLocation(),
3012  diag::err_template_param_default_arg_missing);
3013  Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
3014  Invalid = true;
3015  RemoveDefaultArguments = true;
3016  }
3017 
3018  // If we have an old template parameter list that we're merging
3019  // in, move on to the next parameter.
3020  if (OldParams)
3021  ++OldParam;
3022  }
3023 
3024  // We were missing some default arguments at the end of the list, so remove
3025  // all of the default arguments.
3026  if (RemoveDefaultArguments) {
3027  for (TemplateParameterList::iterator NewParam = NewParams->begin(),
3028  NewParamEnd = NewParams->end();
3029  NewParam != NewParamEnd; ++NewParam) {
3030  if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
3031  TTP->removeDefaultArgument();
3032  else if (NonTypeTemplateParmDecl *NTTP
3033  = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
3034  NTTP->removeDefaultArgument();
3035  else
3036  cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
3037  }
3038  }
3039 
3040  return Invalid;
3041 }
3042 
3043 namespace {
3044 
3045 /// A class which looks for a use of a certain level of template
3046 /// parameter.
3047 struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
3049 
3050  unsigned Depth;
3051 
3052  // Whether we're looking for a use of a template parameter that makes the
3053  // overall construct type-dependent / a dependent type. This is strictly
3054  // best-effort for now; we may fail to match at all for a dependent type
3055  // in some cases if this is set.
3056  bool IgnoreNonTypeDependent;
3057 
3058  bool Match;
3059  SourceLocation MatchLoc;
3060 
3061  DependencyChecker(unsigned Depth, bool IgnoreNonTypeDependent)
3062  : Depth(Depth), IgnoreNonTypeDependent(IgnoreNonTypeDependent),
3063  Match(false) {}
3064 
3065  DependencyChecker(TemplateParameterList *Params, bool IgnoreNonTypeDependent)
3066  : IgnoreNonTypeDependent(IgnoreNonTypeDependent), Match(false) {
3067  NamedDecl *ND = Params->getParam(0);
3068  if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
3069  Depth = PD->getDepth();
3070  } else if (NonTypeTemplateParmDecl *PD =
3071  dyn_cast<NonTypeTemplateParmDecl>(ND)) {
3072  Depth = PD->getDepth();
3073  } else {
3074  Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
3075  }
3076  }
3077 
3078  bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
3079  if (ParmDepth >= Depth) {
3080  Match = true;
3081  MatchLoc = Loc;
3082  return true;
3083  }
3084  return false;
3085  }
3086 
3087  bool TraverseStmt(Stmt *S, DataRecursionQueue *Q = nullptr) {
3088  // Prune out non-type-dependent expressions if requested. This can
3089  // sometimes result in us failing to find a template parameter reference
3090  // (if a value-dependent expression creates a dependent type), but this
3091  // mode is best-effort only.
3092  if (auto *E = dyn_cast_or_null<Expr>(S))
3093  if (IgnoreNonTypeDependent && !E->isTypeDependent())
3094  return true;
3095  return super::TraverseStmt(S, Q);
3096  }
3097 
3098  bool TraverseTypeLoc(TypeLoc TL) {
3099  if (IgnoreNonTypeDependent && !TL.isNull() &&
3100  !TL.getType()->isDependentType())
3101  return true;
3102  return super::TraverseTypeLoc(TL);
3103  }
3104 
3105  bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
3106  return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());
3107  }
3108 
3109  bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
3110  // For a best-effort search, keep looking until we find a location.
3111  return IgnoreNonTypeDependent || !Matches(T->getDepth());
3112  }
3113 
3114  bool TraverseTemplateName(TemplateName N) {
3115  if (TemplateTemplateParmDecl *PD =
3116  dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
3117  if (Matches(PD->getDepth()))
3118  return false;
3119  return super::TraverseTemplateName(N);
3120  }
3121 
3122  bool VisitDeclRefExpr(DeclRefExpr *E) {
3123  if (NonTypeTemplateParmDecl *PD =
3124  dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
3125  if (Matches(PD->getDepth(), E->getExprLoc()))
3126  return false;
3127  return super::VisitDeclRefExpr(E);
3128  }
3129 
3130  bool VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
3131  return TraverseType(T->getReplacementType());
3132  }
3133 
3134  bool
3135  VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *T) {
3136  return TraverseTemplateArgument(T->getArgumentPack());
3137  }
3138 
3139  bool TraverseInjectedClassNameType(const InjectedClassNameType *T) {
3140  return TraverseType(T->getInjectedSpecializationType());
3141  }
3142 };
3143 } // end anonymous namespace
3144 
3145 /// Determines whether a given type depends on the given parameter
3146 /// list.
3147 static bool
3149  if (!Params->size())
3150  return false;
3151 
3152  DependencyChecker Checker(Params, /*IgnoreNonTypeDependent*/false);
3153  Checker.TraverseType(T);
3154  return Checker.Match;
3155 }
3156 
3157 // Find the source range corresponding to the named type in the given
3158 // nested-name-specifier, if any.
3160  QualType T,
3161  const CXXScopeSpec &SS) {
3163  while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) {
3164  if (const Type *CurType = NNS->getAsType()) {
3165  if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0)))
3166  return NNSLoc.getTypeLoc().getSourceRange();
3167  } else
3168  break;
3169 
3170  NNSLoc = NNSLoc.getPrefix();
3171  }
3172 
3173  return SourceRange();
3174 }
3175 
3176 /// Match the given template parameter lists to the given scope
3177 /// specifier, returning the template parameter list that applies to the
3178 /// name.
3179 ///
3180 /// \param DeclStartLoc the start of the declaration that has a scope
3181 /// specifier or a template parameter list.
3182 ///
3183 /// \param DeclLoc The location of the declaration itself.
3184 ///
3185 /// \param SS the scope specifier that will be matched to the given template
3186 /// parameter lists. This scope specifier precedes a qualified name that is
3187 /// being declared.
3188 ///
3189 /// \param TemplateId The template-id following the scope specifier, if there
3190 /// is one. Used to check for a missing 'template<>'.
3191 ///
3192 /// \param ParamLists the template parameter lists, from the outermost to the
3193 /// innermost template parameter lists.
3194 ///
3195 /// \param IsFriend Whether to apply the slightly different rules for
3196 /// matching template parameters to scope specifiers in friend
3197 /// declarations.
3198 ///
3199 /// \param IsMemberSpecialization will be set true if the scope specifier
3200 /// denotes a fully-specialized type, and therefore this is a declaration of
3201 /// a member specialization.
3202 ///
3203 /// \returns the template parameter list, if any, that corresponds to the
3204 /// name that is preceded by the scope specifier @p SS. This template
3205 /// parameter list may have template parameters (if we're declaring a
3206 /// template) or may have no template parameters (if we're declaring a
3207 /// template specialization), or may be NULL (if what we're declaring isn't
3208 /// itself a template).
3210  SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
3211  TemplateIdAnnotation *TemplateId,
3212  ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
3213  bool &IsMemberSpecialization, bool &Invalid, bool SuppressDiagnostic) {
3214  IsMemberSpecialization = false;
3215  Invalid = false;
3216 
3217  // The sequence of nested types to which we will match up the template
3218  // parameter lists. We first build this list by starting with the type named
3219  // by the nested-name-specifier and walking out until we run out of types.
3220  SmallVector<QualType, 4> NestedTypes;
3221  QualType T;
3222  if (SS.getScopeRep()) {
3223  if (CXXRecordDecl *Record
3224  = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
3225  T = Context.getTypeDeclType(Record);
3226  else
3227  T = QualType(SS.getScopeRep()->getAsType(), 0);
3228  }
3229 
3230  // If we found an explicit specialization that prevents us from needing
3231  // 'template<>' headers, this will be set to the location of that
3232  // explicit specialization.
3233  SourceLocation ExplicitSpecLoc;
3234 
3235  while (!T.isNull()) {
3236  NestedTypes.push_back(T);
3237 
3238  // Retrieve the parent of a record type.
3239  if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
3240  // If this type is an explicit specialization, we're done.
3242  = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
3243  if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) &&
3244  Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
3245  ExplicitSpecLoc = Spec->getLocation();
3246  break;
3247  }
3248  } else if (Record->getTemplateSpecializationKind()
3250  ExplicitSpecLoc = Record->getLocation();
3251  break;
3252  }
3253 
3254  if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
3255  T = Context.getTypeDeclType(Parent);
3256  else
3257  T = QualType();
3258  continue;
3259  }
3260 
3261  if (const TemplateSpecializationType *TST
3263  if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
3264  if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
3265  T = Context.getTypeDeclType(Parent);
3266  else
3267  T = QualType();
3268  continue;
3269  }
3270  }
3271 
3272  // Look one step prior in a dependent template specialization type.
3273  if (const DependentTemplateSpecializationType *DependentTST
3275  if (NestedNameSpecifier *NNS = DependentTST->getQualifier())
3276  T = QualType(NNS->getAsType(), 0);
3277  else
3278  T = QualType();
3279  continue;
3280  }
3281 
3282  // Look one step prior in a dependent name type.
3283  if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
3284  if (NestedNameSpecifier *NNS = DependentName->getQualifier())
3285  T = QualType(NNS->getAsType(), 0);
3286  else
3287  T = QualType();
3288  continue;
3289  }
3290 
3291  // Retrieve the parent of an enumeration type.
3292  if (const EnumType *EnumT = T->getAs<EnumType>()) {
3293  // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
3294  // check here.
3295  EnumDecl *Enum = EnumT->getDecl();
3296 
3297  // Get to the parent type.
3298  if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
3299  T = Context.getTypeDeclType(Parent);
3300  else
3301  T = QualType();
3302  continue;
3303  }
3304 
3305  T = QualType();
3306  }
3307  // Reverse the nested types list, since we want to traverse from the outermost
3308  // to the innermost while checking template-parameter-lists.
3309  std::reverse(NestedTypes.begin(), NestedTypes.end());
3310 
3311  // C++0x [temp.expl.spec]p17:
3312  // A member or a member template may be nested within many
3313  // enclosing class templates. In an explicit specialization for
3314  // such a member, the member declaration shall be preceded by a
3315  // template<> for each enclosing class template that is
3316  // explicitly specialized.
3317  bool SawNonEmptyTemplateParameterList = false;
3318 
3319  auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
3320  if (SawNonEmptyTemplateParameterList) {
3321  if (!SuppressDiagnostic)
3322  Diag(DeclLoc, diag::err_specialize_member_of_template)
3323  << !Recovery << Range;
3324  Invalid = true;
3325  IsMemberSpecialization = false;
3326  return true;
3327  }
3328 
3329  return false;
3330  };
3331 
3332  auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
3333  // Check that we can have an explicit specialization here.
3334  if (CheckExplicitSpecialization(Range, true))
3335  return true;
3336 
3337  // We don't have a template header, but we should.
3338  SourceLocation ExpectedTemplateLoc;
3339  if (!ParamLists.empty())
3340  ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
3341  else
3342  ExpectedTemplateLoc = DeclStartLoc;
3343 
3344  if (!SuppressDiagnostic)
3345  Diag(DeclLoc, diag::err_template_spec_needs_header)
3346  << Range
3347  << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
3348  return false;
3349  };
3350 
3351  unsigned ParamIdx = 0;
3352  for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
3353  ++TypeIdx) {
3354  T = NestedTypes[TypeIdx];
3355 
3356  // Whether we expect a 'template<>' header.
3357  bool NeedEmptyTemplateHeader = false;
3358 
3359  // Whether we expect a template header with parameters.
3360  bool NeedNonemptyTemplateHeader = false;
3361 
3362  // For a dependent type, the set of template parameters that we
3363  // expect to see.
3364  TemplateParameterList *ExpectedTemplateParams = nullptr;
3365 
3366  // C++0x [temp.expl.spec]p15:
3367  // A member or a member template may be nested within many enclosing
3368  // class templates. In an explicit specialization for such a member, the
3369  // member declaration shall be preceded by a template<> for each
3370  // enclosing class template that is explicitly specialized.
3371  if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
3373  = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
3374  ExpectedTemplateParams = Partial->getTemplateParameters();
3375  NeedNonemptyTemplateHeader = true;
3376  } else if (Record->isDependentType()) {
3377  if (Record->getDescribedClassTemplate()) {
3378  ExpectedTemplateParams = Record->getDescribedClassTemplate()
3379  ->getTemplateParameters();
3380  NeedNonemptyTemplateHeader = true;
3381  }
3382  } else if (ClassTemplateSpecializationDecl *Spec
3383  = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
3384  // C++0x [temp.expl.spec]p4:
3385  // Members of an explicitly specialized class template are defined
3386  // in the same manner as members of normal classes, and not using
3387  // the template<> syntax.
3388  if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
3389  NeedEmptyTemplateHeader = true;
3390  else
3391  continue;
3392  } else if (Record->getTemplateSpecializationKind()) {
3393  if (Record->getTemplateSpecializationKind()
3395  TypeIdx == NumTypes - 1)
3396  IsMemberSpecialization = true;
3397 
3398  continue;
3399  }
3400  } else if (const TemplateSpecializationType *TST
3402  if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
3403  ExpectedTemplateParams = Template->getTemplateParameters();
3404  NeedNonemptyTemplateHeader = true;
3405  }
3406  } else if (T->getAs<DependentTemplateSpecializationType>()) {
3407  // FIXME: We actually could/should check the template arguments here
3408  // against the corresponding template parameter list.
3409  NeedNonemptyTemplateHeader = false;
3410  }
3411 
3412  // C++ [temp.expl.spec]p16:
3413  // In an explicit specialization declaration for a member of a class
3414  // template or a member template that ap- pears in namespace scope, the
3415  // member template and some of its enclosing class templates may remain
3416  // unspecialized, except that the declaration shall not explicitly
3417  // specialize a class member template if its en- closing class templates
3418  // are not explicitly specialized as well.
3419  if (ParamIdx < ParamLists.size()) {
3420  if (ParamLists[ParamIdx]->size() == 0) {
3421  if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
3422  false))
3423  return nullptr;
3424  } else
3425  SawNonEmptyTemplateParameterList = true;
3426  }
3427 
3428  if (NeedEmptyTemplateHeader) {
3429  // If we're on the last of the types, and we need a 'template<>' header
3430  // here, then it's a member specialization.
3431  if (TypeIdx == NumTypes - 1)
3432  IsMemberSpecialization = true;
3433 
3434  if (ParamIdx < ParamLists.size()) {
3435  if (ParamLists[ParamIdx]->size() > 0) {
3436  // The header has template parameters when it shouldn't. Complain.
3437  if (!SuppressDiagnostic)
3438  Diag(ParamLists[ParamIdx]->getTemplateLoc(),
3439  diag::err_template_param_list_matches_nontemplate)
3440  << T
3441  << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
3442  ParamLists[ParamIdx]->getRAngleLoc())
3443  << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
3444  Invalid = true;
3445  return nullptr;
3446  }
3447 
3448  // Consume this template header.
3449  ++ParamIdx;
3450  continue;
3451  }
3452 
3453  if (!IsFriend)
3454  if (DiagnoseMissingExplicitSpecialization(
3455  getRangeOfTypeInNestedNameSpecifier(Context, T, SS)))
3456  return nullptr;
3457 
3458  continue;
3459  }
3460 
3461  if (NeedNonemptyTemplateHeader) {
3462  // In friend declarations we can have template-ids which don't
3463  // depend on the corresponding template parameter lists. But
3464  // assume that empty parameter lists are supposed to match this
3465  // template-id.
3466  if (IsFriend && T->isDependentType()) {
3467  if (ParamIdx < ParamLists.size() &&
3468  DependsOnTemplateParameters(T, ParamLists[ParamIdx]))
3469  ExpectedTemplateParams = nullptr;
3470  else
3471  continue;
3472  }
3473 
3474  if (ParamIdx < ParamLists.size()) {
3475  // Check the template parameter list, if we can.
3476  if (ExpectedTemplateParams &&
3477  !TemplateParameterListsAreEqual(ParamLists[ParamIdx],
3478  ExpectedTemplateParams,
3479  !SuppressDiagnostic, TPL_TemplateMatch))
3480  Invalid = true;
3481 
3482  if (!Invalid &&
3483  CheckTemplateParameterList(ParamLists[ParamIdx], nullptr,
3484  TPC_ClassTemplateMember))
3485  Invalid = true;
3486 
3487  ++ParamIdx;
3488  continue;
3489  }
3490 
3491  if (!SuppressDiagnostic)
3492  Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
3493  << T
3494  << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
3495  Invalid = true;
3496  continue;
3497  }
3498  }
3499 
3500  // If there were at least as many template-ids as there were template
3501  // parameter lists, then there are no template parameter lists remaining for
3502  // the declaration itself.
3503  if (ParamIdx >= ParamLists.size()) {
3504  if (TemplateId && !IsFriend) {
3505  // We don't have a template header for the declaration itself, but we
3506  // should.
3507  DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
3508  TemplateId->RAngleLoc));
3509 
3510  // Fabricate an empty template parameter list for the invented header.
3512  SourceLocation(), std::nullopt,
3513  SourceLocation(), nullptr);
3514  }
3515 
3516  return nullptr;
3517  }
3518 
3519  // If there were too many template parameter lists, complain about that now.
3520  if (ParamIdx < ParamLists.size() - 1) {
3521  bool HasAnyExplicitSpecHeader = false;
3522  bool AllExplicitSpecHeaders = true;
3523  for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
3524  if (ParamLists[I]->size() == 0)
3525  HasAnyExplicitSpecHeader = true;
3526  else
3527  AllExplicitSpecHeaders = false;
3528  }
3529 
3530  if (!SuppressDiagnostic)
3531  Diag(ParamLists[ParamIdx]->getTemplateLoc(),
3532  AllExplicitSpecHeaders ? diag::warn_template_spec_extra_headers
3533  : diag::err_template_spec_extra_headers)
3534  << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
3535  ParamLists[ParamLists.size() - 2]->getRAngleLoc());
3536 
3537  // If there was a specialization somewhere, such that 'template<>' is
3538  // not required, and there were any 'template<>' headers, note where the
3539  // specialization occurred.
3540  if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader &&
3541  !SuppressDiagnostic)
3542  Diag(ExplicitSpecLoc,
3543  diag::note_explicit_template_spec_does_not_need_header)
3544  << NestedTypes.back();
3545 
3546  // We have a template parameter list with no corresponding scope, which
3547  // means that the resulting template declaration can't be instantiated
3548  // properly (we'll end up with dependent nodes when we shouldn't).
3549  if (!AllExplicitSpecHeaders)
3550  Invalid = true;
3551  }
3552 
3553  // C++ [temp.expl.spec]p16:
3554  // In an explicit specialization declaration for a member of a class
3555  // template or a member template that ap- pears in namespace scope, the
3556  // member template and some of its enclosing class templates may remain
3557  // unspecialized, except that the declaration shall not explicitly
3558  // specialize a class member template if its en- closing class templates
3559  // are not explicitly specialized as well.
3560  if (ParamLists.back()->size() == 0 &&
3561  CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
3562  false))
3563  return nullptr;
3564 
3565  // Return the last template parameter list, which corresponds to the
3566  // entity being declared.
3567  return ParamLists.back();
3568 }
3569 
3571  if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3572  Diag(Template->getLocation(), diag::note_template_declared_here)
3573  << (isa<FunctionTemplateDecl>(Template)
3574  ? 0
3575  : isa<ClassTemplateDecl>(Template)
3576  ? 1
3577  : isa<VarTemplateDecl>(Template)
3578  ? 2
3579  : isa<TypeAliasTemplateDecl>(Template) ? 3 : 4)
3580  << Template->getDeclName();
3581  return;
3582  }
3583 
3584  if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
3585  for (OverloadedTemplateStorage::iterator I = OST->begin(),
3586  IEnd = OST->end();
3587  I != IEnd; ++I)
3588  Diag((*I)->getLocation(), diag::note_template_declared_here)
3589  << 0 << (*I)->getDeclName();
3590 
3591  return;
3592  }
3593 }
3594 
3595 static QualType
3597  ArrayRef<TemplateArgument> Converted,
3598  SourceLocation TemplateLoc,
3599  TemplateArgumentListInfo &TemplateArgs) {
3600  ASTContext &Context = SemaRef.getASTContext();
3601 
3602  switch (BTD->getBuiltinTemplateKind()) {
3603  case BTK__make_integer_seq: {
3604  // Specializations of __make_integer_seq<S, T, N> are treated like
3605  // S<T, 0, ..., N-1>.
3606 
3607  QualType OrigType = Converted[1].getAsType();
3608  // C++14 [inteseq.intseq]p1:
3609  // T shall be an integer type.
3610  if (!OrigType->isDependentType() && !OrigType->isIntegralType(Context)) {
3611  SemaRef.Diag(TemplateArgs[1].getLocation(),
3612  diag::err_integer_sequence_integral_element_type);
3613  return QualType();
3614  }
3615 
3616  TemplateArgument NumArgsArg = Converted[2];
3617  if (NumArgsArg.isDependent())
3619  Converted);
3620 
3621  TemplateArgumentListInfo SyntheticTemplateArgs;
3622  // The type argument, wrapped in substitution sugar, gets reused as the
3623  // first template argument in the synthetic template argument list.
3624  SyntheticTemplateArgs.addArgument(
3627  OrigType, TemplateArgs[1].getLocation())));
3628 
3629  if (llvm::APSInt NumArgs = NumArgsArg.getAsIntegral(); NumArgs >= 0) {
3630  // Expand N into 0 ... N-1.
3631  for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned());
3632  I < NumArgs; ++I) {
3633  TemplateArgument TA(Context, I, OrigType);
3634  SyntheticTemplateArgs.addArgument(SemaRef.getTrivialTemplateArgumentLoc(
3635  TA, OrigType, TemplateArgs[2].getLocation()));
3636  }
3637  } else {
3638  // C++14 [inteseq.make]p1:
3639  // If N is negative the program is ill-formed.
3640  SemaRef.Diag(TemplateArgs[2].getLocation(),
3641  diag::err_integer_sequence_negative_length);
3642  return QualType();
3643  }
3644 
3645  // The first template argument will be reused as the template decl that
3646  // our synthetic template arguments will be applied to.
3647  return SemaRef.CheckTemplateIdType(Converted[0].getAsTemplate(),
3648  TemplateLoc, SyntheticTemplateArgs);
3649  }
3650 
3652  // Specializations of
3653  // __type_pack_element<Index, T_1, ..., T_N>
3654  // are treated like T_Index.
3655  assert(Converted.size() == 2 &&
3656  "__type_pack_element should be given an index and a parameter pack");
3657 
3658  TemplateArgument IndexArg = Converted[0], Ts = Converted[1];
3659  if (IndexArg.isDependent() || Ts.isDependent())
3661  Converted);
3662 
3663  llvm::APSInt Index = IndexArg.getAsIntegral();
3664  assert(Index >= 0 && "the index used with __type_pack_element should be of "
3665  "type std::size_t, and hence be non-negative");
3666  // If the Index is out of bounds, the program is ill-formed.
3667  if (Index >= Ts.pack_size()) {
3668  SemaRef.Diag(TemplateArgs[0].getLocation(),
3669  diag::err_type_pack_element_out_of_bounds);
3670  return QualType();
3671  }
3672 
3673  // We simply return the type at index `Index`.
3674  int64_t N = Index.getExtValue();
3675  return Ts.getPackAsArray()[N].getAsType();
3676  }
3677  llvm_unreachable("unexpected BuiltinTemplateDecl!");
3678 }
3679 
3680 /// Determine whether this alias template is "enable_if_t".
3681 /// libc++ >=14 uses "__enable_if_t" in C++11 mode.
3682 static bool isEnableIfAliasTemplate(TypeAliasTemplateDecl *AliasTemplate) {
3683  return AliasTemplate->getName().equals("enable_if_t") ||
3684  AliasTemplate->getName().equals("__enable_if_t");
3685 }
3686 
3687 /// Collect all of the separable terms in the given condition, which
3688 /// might be a conjunction.
3689 ///
3690 /// FIXME: The right answer is to convert the logical expression into
3691 /// disjunctive normal form, so we can find the first failed term
3692 /// within each possible clause.
3693 static void collectConjunctionTerms(Expr *Clause,
3694  SmallVectorImpl<Expr *> &Terms) {
3695  if (auto BinOp = dyn_cast<BinaryOperator>(Clause->IgnoreParenImpCasts())) {
3696  if (BinOp->getOpcode() == BO_LAnd) {
3697  collectConjunctionTerms(BinOp->getLHS(), Terms);
3698  collectConjunctionTerms(BinOp->getRHS(), Terms);
3699  return;
3700  }
3701  }
3702 
3703  Terms.push_back(Clause);
3704 }
3705 
3706 // The ranges-v3 library uses an odd pattern of a top-level "||" with
3707 // a left-hand side that is value-dependent but never true. Identify
3708 // the idiom and ignore that term.
3710  // Top-level '||'.
3711  auto *BinOp = dyn_cast<BinaryOperator>(Cond->IgnoreParenImpCasts());
3712  if (!BinOp) return Cond;
3713 
3714  if (BinOp->getOpcode() != BO_LOr) return Cond;
3715 
3716  // With an inner '==' that has a literal on the right-hand side.
3717  Expr *LHS = BinOp->getLHS();
3718  auto *InnerBinOp = dyn_cast<BinaryOperator>(LHS->IgnoreParenImpCasts());
3719  if (!InnerBinOp) return Cond;
3720 
3721  if (InnerBinOp->getOpcode() != BO_EQ ||
3722  !isa<IntegerLiteral>(InnerBinOp->getRHS()))
3723  return Cond;
3724 
3725  // If the inner binary operation came from a macro expansion named
3726  // CONCEPT_REQUIRES or CONCEPT_REQUIRES_, return the right-hand side
3727  // of the '||', which is the real, user-provided condition.
3728  SourceLocation Loc = InnerBinOp->getExprLoc();
3729  if (!Loc.isMacroID()) return Cond;
3730 
3731  StringRef MacroName = PP.getImmediateMacroName(Loc);
3732  if (MacroName == "CONCEPT_REQUIRES" || MacroName == "CONCEPT_REQUIRES_")
3733  return BinOp->getRHS();
3734 
3735  return Cond;
3736 }
3737 
3738 namespace {
3739 
3740 // A PrinterHelper that prints more helpful diagnostics for some sub-expressions
3741 // within failing boolean expression, such as substituting template parameters
3742 // for actual types.
3743 class FailedBooleanConditionPrinterHelper : public PrinterHelper {
3744 public:
3745  explicit FailedBooleanConditionPrinterHelper(const PrintingPolicy &P)
3746  : Policy(P) {}
3747 
3748  bool handledStmt(Stmt *E, raw_ostream &OS) override {
3749  const auto *DR = dyn_cast<DeclRefExpr>(E);
3750  if (DR && DR->getQualifier()) {
3751  // If this is a qualified name, expand the template arguments in nested
3752  // qualifiers.
3753  DR->getQualifier()->print(OS, Policy, true);
3754  // Then print the decl itself.
3755  const ValueDecl *VD = DR->getDecl();
3756  OS << VD->getName();
3757  if (const auto *IV = dyn_cast<VarTemplateSpecializationDecl>(VD)) {
3758  // This is a template variable, print the expanded template arguments.
3760  OS, IV->getTemplateArgs().asArray(), Policy,
3761  IV->getSpecializedTemplate()->getTemplateParameters());
3762  }
3763  return true;
3764  }
3765  return false;
3766  }
3767 
3768 private:
3769  const PrintingPolicy Policy;
3770 };
3771 
3772 } // end anonymous namespace
3773 
3774 std::pair<Expr *, std::string>
3776  Cond = lookThroughRangesV3Condition(PP, Cond);
3777 
3778  // Separate out all of the terms in a conjunction.
3779  SmallVector<Expr *, 4> Terms;
3780  collectConjunctionTerms(Cond, Terms);
3781 
3782  // Determine which term failed.
3783  Expr *FailedCond = nullptr;
3784  for (Expr *Term : Terms) {
3785  Expr *TermAsWritten = Term->IgnoreParenImpCasts();
3786 
3787  // Literals are uninteresting.
3788  if (isa<CXXBoolLiteralExpr>(TermAsWritten) ||
3789  isa<IntegerLiteral>(TermAsWritten))
3790  continue;
3791 
3792  // The initialization of the parameter from the argument is
3793  // a constant-evaluated context.
3794  EnterExpressionEvaluationContext ConstantEvaluated(
3796 
3797  bool Succeeded;
3798  if (Term->EvaluateAsBooleanCondition(Succeeded, Context) &&
3799  !Succeeded) {
3800  FailedCond = TermAsWritten;
3801  break;
3802  }
3803  }
3804  if (!FailedCond)
3805  FailedCond = Cond->IgnoreParenImpCasts();
3806 
3807  std::string Description;
3808  {
3809  llvm::raw_string_ostream Out(Description);
3810  PrintingPolicy Policy = getPrintingPolicy();
3811  Policy.PrintCanonicalTypes = true;
3812  FailedBooleanConditionPrinterHelper Helper(Policy);
3813  FailedCond->printPretty(Out, &Helper, Policy, 0, "\n", nullptr);
3814  }
3815  return { FailedCond, Description };
3816 }
3817 
3819  SourceLocation TemplateLoc,
3820  TemplateArgumentListInfo &TemplateArgs) {
3822  = Name.getUnderlying().getAsDependentTemplateName();
3823  if (DTN && DTN->isIdentifier())
3824  // When building a template-id where the template-name is dependent,
3825  // assume the template is a type template. Either our assumption is
3826  // correct, or the code is ill-formed and will be diagnosed when the
3827  // dependent name is substituted.
3829  ETK_None, DTN->getQualifier(), DTN->getIdentifier(),
3830  TemplateArgs.arguments());
3831 
3832  if (Name.getAsAssumedTemplateName() &&
3833  resolveAssumedTemplateNameAsType(/*Scope*/nullptr, Name, TemplateLoc))
3834  return QualType();
3835 
3836  TemplateDecl *Template = Name.getAsTemplateDecl();
3837  if (!Template || isa<FunctionTemplateDecl>(Template) ||
3838  isa<VarTemplateDecl>(Template) || isa<ConceptDecl>(Template)) {
3839  // We might have a substituted template template parameter pack. If so,
3840  // build a template specialization type for it.
3841  if (Name.getAsSubstTemplateTemplateParmPack())
3842  return Context.getTemplateSpecializationType(Name,
3843  TemplateArgs.arguments());
3844 
3845  Diag(TemplateLoc, diag::err_template_id_not_a_type)
3846  << Name;
3847  NoteAllFoundTemplates(Name);
3848  return QualType();
3849  }
3850 
3851  // Check that the template argument list is well-formed for this
3852  // template.
3853  SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
3854  if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs, false,
3855  SugaredConverted, CanonicalConverted,
3856  /*UpdateArgsWithConversions=*/true))
3857  return QualType();
3858 
3859  QualType CanonType;
3860 
3862  dyn_cast<TypeAliasTemplateDecl>(Template)) {
3863 
3864  // Find the canonical type for this type alias template specialization.
3865  TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
3866  if (Pattern->isInvalidDecl())
3867  return QualType();
3868 
3869  // Only substitute for the innermost template argument list.
3870  MultiLevelTemplateArgumentList TemplateArgLists;
3871  TemplateArgLists.addOuterTemplateArguments(Template, CanonicalConverted,
3872  /*Final=*/false);
3873  TemplateArgLists.addOuterRetainedLevels(
3874  AliasTemplate->getTemplateParameters()->getDepth());
3875 
3877  InstantiatingTemplate Inst(*this, TemplateLoc, Template);
3878  if (Inst.isInvalid())
3879  return QualType();
3880 
3881  CanonType = SubstType(Pattern->getUnderlyingType(),
3882  TemplateArgLists, AliasTemplate->getLocation(),
3883  AliasTemplate->getDeclName());
3884  if (CanonType.isNull()) {
3885  // If this was enable_if and we failed to find the nested type
3886  // within enable_if in a SFINAE context, dig out the specific
3887  // enable_if condition that failed and present that instead.
3889  if (auto DeductionInfo = isSFINAEContext()) {
3890  if (*DeductionInfo &&
3891  (*DeductionInfo)->hasSFINAEDiagnostic() &&
3892  (*DeductionInfo)->peekSFINAEDiagnostic().second.getDiagID() ==
3893  diag::err_typename_nested_not_found_enable_if &&
3894  TemplateArgs[0].getArgument().getKind()
3896  Expr *FailedCond;
3897  std::string FailedDescription;
3898  std::tie(FailedCond, FailedDescription) =
3899  findFailedBooleanCondition(TemplateArgs[0].getSourceExpression());
3900 
3901  // Remove the old SFINAE diagnostic.
3902  PartialDiagnosticAt OldDiag =
3904  (*DeductionInfo)->takeSFINAEDiagnostic(OldDiag);
3905 
3906  // Add a new SFINAE diagnostic specifying which condition
3907  // failed.
3908  (*DeductionInfo)->addSFINAEDiagnostic(
3909  OldDiag.first,
3910  PDiag(diag::err_typename_nested_not_found_requirement)
3911  << FailedDescription
3912  << FailedCond->getSourceRange());
3913  }
3914  }
3915  }
3916 
3917  return QualType();
3918  }
3919  } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Template)) {
3920  CanonType = checkBuiltinTemplateIdType(*this, BTD, SugaredConverted,
3921  TemplateLoc, TemplateArgs);
3922  } else if (Name.isDependent() ||
3924  TemplateArgs, CanonicalConverted)) {
3925  // This class template specialization is a dependent
3926  // type. Therefore, its canonical type is another class template
3927  // specialization type that contains all of the converted
3928  // arguments in canonical form. This ensures that, e.g., A<T> and
3929  // A<T, T> have identical types when A is declared as:
3930  //
3931  // template<typename T, typename U = T> struct A;
3932  CanonType = Context.getCanonicalTemplateSpecializationType(
3933  Name, CanonicalConverted);
3934 
3935  // This might work out to be a current instantiation, in which
3936  // case the canonical type needs to be the InjectedClassNameType.
3937  //
3938  // TODO: in theory this could be a simple hashtable lookup; most
3939  // changes to CurContext don't change the set of current
3940  // instantiations.
3941  if (isa<ClassTemplateDecl>(Template)) {
3942  for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
3943  // If we get out to a namespace, we're done.
3944  if (Ctx->isFileContext()) break;
3945 
3946  // If this isn't a record, keep looking.
3947  CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
3948  if (!Record) continue;
3949 
3950  // Look for one of the two cases with InjectedClassNameTypes
3951  // and check whether it's the same template.
3952  if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
3953  !Record->getDescribedClassTemplate())
3954  continue;
3955 
3956  // Fetch the injected class name type and check whether its
3957  // injected type is equal to the type we just built.
3958  QualType ICNT = Context.getTypeDeclType(Record);
3959  QualType Injected = cast<InjectedClassNameType>(ICNT)
3960  ->getInjectedSpecializationType();
3961 
3962  if (CanonType != Injected->getCanonicalTypeInternal())
3963  continue;
3964 
3965  // If so, the canonical type of this TST is the injected
3966  // class name type of the record we just found.
3967  assert(ICNT.isCanonical());
3968  CanonType = ICNT;
3969  break;
3970  }
3971  }
3972  } else if (ClassTemplateDecl *ClassTemplate =
3973  dyn_cast<ClassTemplateDecl>(Template)) {
3974  // Find the class template specialization declaration that
3975  // corresponds to these arguments.
3976  void *InsertPos = nullptr;
3978  ClassTemplate->findSpecialization(CanonicalConverted, InsertPos);
3979  if (!Decl) {
3980  // This is the first time we have referenced this class template
3981  // specialization. Create the canonical declaration and add it to
3982  // the set of specializations.
3984  Context, ClassTemplate->getTemplatedDecl()->getTagKind(),
3985  ClassTemplate->getDeclContext(),
3986  ClassTemplate->getTemplatedDecl()->getBeginLoc(),
3987  ClassTemplate->getLocation(), ClassTemplate, CanonicalConverted,
3988  nullptr);
3989  ClassTemplate->AddSpecialization(Decl, InsertPos);
3990  if (ClassTemplate->isOutOfLine())
3991  Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
3992  }
3993 
3994  if (Decl->getSpecializationKind() == TSK_Undeclared &&
3995  ClassTemplate->getTemplatedDecl()->hasAttrs()) {
3996  InstantiatingTemplate Inst(*this, TemplateLoc, Decl);
3997  if (!Inst.isInvalid()) {
3998  MultiLevelTemplateArgumentList TemplateArgLists(Template,
3999  CanonicalConverted,
4000  /*Final=*/false);
4001  InstantiateAttrsForDecl(TemplateArgLists,
4002  ClassTemplate->getTemplatedDecl(), Decl);
4003  }
4004  }
4005 
4006  // Diagnose uses of this specialization.
4007  (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
4008 
4009  CanonType = Context.getTypeDeclType(Decl);
4010  assert(isa<RecordType>(CanonType) &&
4011  "type of non-dependent specialization is not a RecordType");
4012  } else {
4013  llvm_unreachable("Unhandled template kind");
4014  }
4015 
4016  // Build the fully-sugared type for this class template
4017  // specialization, which refers back to the class template
4018  // specialization we created or found.
4019  return Context.getTemplateSpecializationType(Name, TemplateArgs.arguments(),
4020  CanonType);
4021 }
4022 
4024  TemplateNameKind &TNK,
4025  SourceLocation NameLoc,
4026  IdentifierInfo *&II) {
4027  assert(TNK == TNK_Undeclared_template && "not an undeclared template name");
4028 
4029  TemplateName Name = ParsedName.get();
4030  auto *ATN = Name.getAsAssumedTemplateName();
4031  assert(ATN && "not an assumed template name");
4032  II = ATN->getDeclName().getAsIdentifierInfo();
4033 
4034  if (!resolveAssumedTemplateNameAsType(S, Name, NameLoc, /*Diagnose*/false)) {
4035  // Resolved to a type template name.
4036  ParsedName = TemplateTy::make(Name);
4037  TNK = TNK_Type_template;
4038  }
4039 }
4040 
4042  SourceLocation NameLoc,
4043  bool Diagnose) {
4044  // We assumed this undeclared identifier to be an (ADL-only) function
4045  // template name, but it was used in a context where a type was required.
4046  // Try to typo-correct it now.
4047  AssumedTemplateStorage *ATN = Name.getAsAssumedTemplateName();
4048  assert(ATN && "not an assumed template name");
4049 
4050  LookupResult R(*this, ATN->getDeclName(), NameLoc, LookupOrdinaryName);
4051  struct CandidateCallback : CorrectionCandidateCallback {
4052  bool ValidateCandidate(const TypoCorrection &TC) override {
4053  return TC.getCorrectionDecl() &&
4055  }
4056  std::unique_ptr<CorrectionCandidateCallback> clone() override {
4057  return std::make_unique<CandidateCallback>(*this);
4058  }
4059  } FilterCCC;
4060 
4061  TypoCorrection Corrected =
4062  CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, nullptr,
4063  FilterCCC, CTK_ErrorRecovery);
4064  if (Corrected && Corrected.getFoundDecl()) {
4065  diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest)
4066  << ATN->getDeclName());
4067  Name = TemplateName(Corrected.getCorrectionDeclAs<TemplateDecl>());
4068  return false;
4069  }
4070 
4071  if (Diagnose)
4072  Diag(R.getNameLoc(), diag::err_no_template) << R.getLookupName();
4073  return true;
4074 }
4075 
4077  Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
4078  TemplateTy TemplateD, IdentifierInfo *TemplateII,
4079  SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
4080  ASTTemplateArgsPtr TemplateArgsIn, SourceLocation RAngleLoc,
4081  bool IsCtorOrDtorName, bool IsClassName,
4082  ImplicitTypenameContext AllowImplicitTypename) {
4083  if (SS.isInvalid())
4084  return true;
4085 
4086  if (!IsCtorOrDtorName && !IsClassName && SS.isSet()) {
4087  DeclContext *LookupCtx = computeDeclContext(SS, /*EnteringContext*/false);
4088 
4089  // C++ [temp.res]p3:
4090  // A qualified-id that refers to a type and in which the
4091  // nested-name-specifier depends on a template-parameter (14.6.2)
4092  // shall be prefixed by the keyword typename to indicate that the
4093  // qualified-id denotes a type, forming an
4094  // elaborated-type-specifier (7.1.5.3).
4095  if (!LookupCtx && isDependentScopeSpecifier(SS)) {
4096  // C++2a relaxes some of those restrictions in [temp.res]p5.
4097  if (AllowImplicitTypename == ImplicitTypenameContext::Yes) {
4098  if (getLangOpts().CPlusPlus20)
4099  Diag(SS.getBeginLoc(), diag::warn_cxx17_compat_implicit_typename);
4100  else
4101  Diag(SS.getBeginLoc(), diag::ext_implicit_typename)
4102  << SS.getScopeRep() << TemplateII->getName()
4103  << FixItHint::CreateInsertion(SS.getBeginLoc(), "typename ");
4104  } else
4105  Diag(SS.getBeginLoc(), diag::err_typename_missing_template)
4106  << SS.getScopeRep() << TemplateII->getName();
4107 
4108  // FIXME: This is not quite correct recovery as we don't transform SS
4109  // into the corresponding dependent form (and we don't diagnose missing
4110  // 'template' keywords within SS as a result).
4111  return ActOnTypenameType(nullptr, SourceLocation(), SS, TemplateKWLoc,
4112  TemplateD, TemplateII, TemplateIILoc, LAngleLoc,
4113  TemplateArgsIn, RAngleLoc);
4114  }
4115 
4116  // Per C++ [class.qual]p2, if the template-id was an injected-class-name,
4117  // it's not actually allowed to be used as a type in most cases. Because
4118  // we annotate it before we know whether it's valid, we have to check for
4119  // this case here.
4120  auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
4121  if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
4122  Diag(TemplateIILoc,
4123  TemplateKWLoc.isInvalid()
4124  ? diag::err_out_of_line_qualified_id_type_names_constructor
4125  : diag::ext_out_of_line_qualified_id_type_names_constructor)
4126  << TemplateII << 0 /*injected-class-name used as template name*/
4127  << 1 /*if any keyword was present, it was 'template'*/;
4128  }
4129  }
4130 
4131  TemplateName Template = TemplateD.get();
4132  if (Template.getAsAssumedTemplateName() &&
4133  resolveAssumedTemplateNameAsType(S, Template, TemplateIILoc))
4134  return true;
4135 
4136  // Translate the parser's template argument list in our AST format.
4137  TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
4138  translateTemplateArguments(TemplateArgsIn, TemplateArgs);
4139 
4140  if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
4141  assert(SS.getScopeRep() == DTN->getQualifier());
4143  ETK_None, DTN->getQualifier(), DTN->getIdentifier(),
4144  TemplateArgs.arguments());
4145  // Build type-source information.
4146  TypeLocBuilder TLB;
4150  SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
4151  SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
4152  SpecTL.setTemplateNameLoc(TemplateIILoc);
4153  SpecTL.setLAngleLoc(LAngleLoc);
4154  SpecTL.setRAngleLoc(RAngleLoc);
4155  for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
4156  SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
4157  return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
4158  }
4159 
4160  QualType SpecTy = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
4161  if (SpecTy.isNull())
4162  return true;
4163 
4164  // Build type-source information.
4165  TypeLocBuilder TLB;
4167  TLB.push<TemplateSpecializationTypeLoc>(SpecTy);
4168  SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
4169  SpecTL.setTemplateNameLoc(TemplateIILoc);
4170  SpecTL.setLAngleLoc(LAngleLoc);
4171  SpecTL.setRAngleLoc(RAngleLoc);
4172  for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
4173  SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
4174 
4175  // Create an elaborated-type-specifier containing the nested-name-specifier.
4176  QualType ElTy = getElaboratedType(
4177  ETK_None, !IsCtorOrDtorName ? SS : CXXScopeSpec(), SpecTy);
4178  ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(ElTy);
4180  if (!ElabTL.isEmpty())
4181  ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
4182  return CreateParsedType(ElTy, TLB.getTypeSourceInfo(Context, ElTy));
4183 }
4184 
4186  TypeSpecifierType TagSpec,
4187  SourceLocation TagLoc,
4188  CXXScopeSpec &SS,
4189  SourceLocation TemplateKWLoc,
4190  TemplateTy TemplateD,
4191  SourceLocation TemplateLoc,
4192  SourceLocation LAngleLoc,
4193  ASTTemplateArgsPtr TemplateArgsIn,
4194  SourceLocation RAngleLoc) {
4195  if (SS.isInvalid())
4196  return TypeResult(true);
4197 
4198  TemplateName Template = TemplateD.get();
4199 
4200  // Translate the parser's template argument list in our AST format.
4201  TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
4202  translateTemplateArguments(TemplateArgsIn, TemplateArgs);
4203 
4204  // Determine the tag kind
4206  ElaboratedTypeKeyword Keyword
4208 
4209  if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
4210  assert(SS.getScopeRep() == DTN->getQualifier());
4212  Keyword, DTN->getQualifier(), DTN->getIdentifier(),
4213  TemplateArgs.arguments());
4214 
4215  // Build type-source information.
4216  TypeLocBuilder TLB;
4219  SpecTL.setElaboratedKeywordLoc(TagLoc);
4220  SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
4221  SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
4222  SpecTL.setTemplateNameLoc(TemplateLoc);
4223  SpecTL.setLAngleLoc(LAngleLoc);
4224  SpecTL.setRAngleLoc(RAngleLoc);
4225  for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
4226  SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
4227  return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
4228  }
4229 
4230  if (TypeAliasTemplateDecl *TAT =
4231  dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) {
4232  // C++0x [dcl.type.elab]p2:
4233  // If the identifier resolves to a typedef-name or the simple-template-id
4234  // resolves to an alias template specialization, the
4235  // elaborated-type-specifier is ill-formed.
4236  Diag(TemplateLoc, diag::err_tag_reference_non_tag)
4237  << TAT << NTK_TypeAliasTemplate << TagKind;
4238  Diag(TAT->getLocation(), diag::note_declared_at);
4239  }
4240 
4241  QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
4242  if (Result.isNull())
4243  return TypeResult(true);
4244 
4245  // Check the tag kind
4246  if (const RecordType *RT = Result->getAs<RecordType>()) {
4247  RecordDecl *D = RT->getDecl();
4248 
4250  assert(Id && "templated class must have an identifier");
4251 
4252  if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TUK_Definition,
4253  TagLoc, Id)) {
4254  Diag(TagLoc, diag::err_use_with_wrong_tag)
4255  << Result
4257  Diag(D->getLocation(), diag::note_previous_use);
4258  }
4259  }
4260 
4261  // Provide source-location information for the template specialization.
4262  TypeLocBuilder TLB;
4264  = TLB.push<TemplateSpecializationTypeLoc>(Result);
4265  SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
4266  SpecTL.setTemplateNameLoc(TemplateLoc);
4267  SpecTL.setLAngleLoc(LAngleLoc);
4268  SpecTL.setRAngleLoc(RAngleLoc);
4269  for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
4270  SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
4271 
4272  // Construct an elaborated type containing the nested-name-specifier (if any)
4273  // and tag keyword.
4274  Result = Context.getElaboratedType(Keyword, SS.getScopeRep(), Result);
4275  ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
4276  ElabTL.setElaboratedKeywordLoc(TagLoc);
4277  ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
4278  return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
4279 }
4280 
4281 static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
4282  NamedDecl *PrevDecl,
4283  SourceLocation Loc,
4285 
4287 
4289  const TemplateArgument &Arg, unsigned Depth, unsigned Index) {
4290  switch (Arg.getKind()) {
4297  return false;
4298 
4299  case TemplateArgument::Type: {
4300  QualType Type = Arg.getAsType();
4301  const TemplateTypeParmType *TPT =
4303  return TPT && !Type.hasQualifiers() &&
4304  TPT->getDepth() == Depth && TPT->getIndex() == Index;
4305  }
4306 
4308  DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
4309  if (!DRE || !DRE->getDecl())
4310  return false;
4311  const NonTypeTemplateParmDecl *NTTP =
4312  dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
4313  return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
4314  }
4315 
4317  const TemplateTemplateParmDecl *TTP =
4318  dyn_cast_or_null<TemplateTemplateParmDecl>(
4320  return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
4321  }
4322  llvm_unreachable("unexpected kind of template argument");
4323 }
4324 
4327  if (Params->size() != Args.size())
4328  return false;
4329 
4330  unsigned Depth = Params->getDepth();
4331 
4332  for (unsigned I = 0, N = Args.size(); I != N; ++I) {
4333  TemplateArgument Arg = Args[I];
4334 
4335  // If the parameter is a pack expansion, the argument must be a pack
4336  // whose only element is a pack expansion.
4337  if (Params->getParam(I)->isParameterPack()) {
4338  if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
4339  !Arg.pack_begin()->isPackExpansion())
4340  return false;
4341  Arg = Arg.pack_begin()->getPackExpansionPattern();
4342  }
4343 
4345  return false;
4346  }
4347 
4348  return true;
4349 }
4350 
4351 template<typename PartialSpecDecl>
4352 static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial) {
4353  if (Partial->getDeclContext()->isDependentContext())
4354  return;
4355 
4356  // FIXME: Get the TDK from deduction in order to provide better diagnostics
4357  // for non-substitution-failure issues?
4358  TemplateDeductionInfo Info(Partial->getLocation());
4359  if (S.isMoreSpecializedThanPrimary(Partial, Info))
4360  return;
4361 
4362  auto *Template = Partial->getSpecializedTemplate();
4363  S.Diag(Partial->getLocation(),
4364  diag::ext_partial_spec_not_more_specialized_than_primary)
4365  << isa<VarTemplateDecl>(Template);
4366 
4367  if (Info.hasSFINAEDiagnostic()) {
4370  Info.takeSFINAEDiagnostic(Diag);
4371  SmallString<128> SFINAEArgString;
4372  Diag.second.EmitToString(S.getDiagnostics(), SFINAEArgString);
4373  S.Diag(Diag.first,
4374  diag::note_partial_spec_not_more_specialized_than_primary)
4375  << SFINAEArgString;
4376  }
4377 
4378  S.Diag(Template->getLocation(), diag::note_template_decl_here);
4379  SmallVector<const Expr *, 3> PartialAC, TemplateAC;
4380  Template->getAssociatedConstraints(TemplateAC);
4381  Partial->getAssociatedConstraints(PartialAC);
4382  S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(Partial, PartialAC, Template,
4383  TemplateAC);
4384 }
4385 
4386 static void
4388  const llvm::SmallBitVector &DeducibleParams) {
4389  for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
4390  if (!DeducibleParams[I]) {
4391  NamedDecl *Param = TemplateParams->getParam(I);
4392  if (Param->getDeclName())
4393  S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
4394  << Param->getDeclName();
4395  else
4396  S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
4397  << "(anonymous)";
4398  }
4399  }
4400 }
4401 
4402 
4403 template<typename PartialSpecDecl>
4405  PartialSpecDecl *Partial) {
4406  // C++1z [temp.class.spec]p8: (DR1495)
4407  // - The specialization shall be more specialized than the primary
4408  // template (14.5.5.2).
4409  checkMoreSpecializedThanPrimary(S, Partial);
4410 
4411  // C++ [temp.class.spec]p8: (DR1315)
4412  // - Each template-parameter shall appear at least once in the
4413  // template-id outside a non-deduced context.
4414  // C++1z [temp.class.spec.match]p3 (P0127R2)
4415  // If the template arguments of a partial specialization cannot be
4416  // deduced because of the structure of its template-parameter-list
4417  // and the template-id, the program is ill-formed.
4418  auto *TemplateParams = Partial->getTemplateParameters();
4419  llvm::SmallBitVector DeducibleParams(TemplateParams->size());
4420  S.MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
4421  TemplateParams->getDepth(), DeducibleParams);
4422 
4423  if (!DeducibleParams.all()) {
4424  unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
4425  S.Diag(Partial->getLocation(), diag::ext_partial_specs_not_deducible)
4426  << isa<VarTemplatePartialSpecializationDecl>(Partial)
4427  << (NumNonDeducible > 1)
4428  << SourceRange(Partial->getLocation(),
4429  Partial->getTemplateArgsAsWritten()->RAngleLoc);
4430  noteNonDeducibleParameters(S, TemplateParams, DeducibleParams);
4431  }
4432 }
4433 
4436  checkTemplatePartialSpecialization(*this, Partial);
4437 }
4438 
4441  checkTemplatePartialSpecialization(*this, Partial);
4442 }
4443 
4445  // C++1z [temp.param]p11:
4446  // A template parameter of a deduction guide template that does not have a
4447  // default-argument shall be deducible from the parameter-type-list of the
4448  // deduction guide template.
4449  auto *TemplateParams = TD->getTemplateParameters();
4450  llvm::SmallBitVector DeducibleParams(TemplateParams->size());
4451  MarkDeducedTemplateParameters(TD, DeducibleParams);
4452  for (unsigned I = 0; I != TemplateParams->size(); ++I) {
4453  // A parameter pack is deducible (to an empty pack).
4454  auto *Param = TemplateParams->getParam(I);
4455  if (Param->isParameterPack() || hasVisibleDefaultArgument(Param))
4456  DeducibleParams[I] = true;
4457  }
4458 
4459  if (!DeducibleParams.all()) {
4460  unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
4461  Diag(TD->getLocation(), diag::err_deduction_guide_template_not_deducible)
4462  << (NumNonDeducible > 1);
4463  noteNonDeducibleParameters(*this, TemplateParams, DeducibleParams);
4464  }
4465 }
4466 
4468  Scope *S, Declarator &D, TypeSourceInfo *DI, SourceLocation TemplateKWLoc,
4469  TemplateParameterList *TemplateParams, StorageClass SC,
4470  bool IsPartialSpecialization) {
4471  // D must be variable template id.
4473  "Variable template specialization is declared with a template id.");
4474 
4475  TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
4476  TemplateArgumentListInfo TemplateArgs =
4477  makeTemplateArgumentListInfo(*this, *TemplateId);
4478  SourceLocation TemplateNameLoc = D.getIdentifierLoc();
4479  SourceLocation LAngleLoc = TemplateId->LAngleLoc;
4480  SourceLocation RAngleLoc = TemplateId->RAngleLoc;
4481 
4482  TemplateName Name = TemplateId->Template.get();
4483 
4484  // The template-id must name a variable template.
4485  VarTemplateDecl *VarTemplate =
4486  dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
4487  if (!VarTemplate) {
4488  NamedDecl *FnTemplate;
4489  if (auto *OTS = Name.getAsOverloadedTemplate())
4490  FnTemplate = *OTS->begin();
4491  else
4492  FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
4493  if (FnTemplate)
4494  return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
4495  << FnTemplate->getDeclName();
4496  return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
4498  }
4499 
4500  // Check for unexpanded parameter packs in any of the template arguments.
4501  for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
4502  if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
4503  UPPC_PartialSpecialization))
4504  return true;
4505 
4506  // Check that the template argument list is well-formed for this
4507  // template.
4508  SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
4509  if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
4510  false, SugaredConverted, CanonicalConverted,
4511  /*UpdateArgsWithConversions=*/true))
4512  return true;
4513 
4514  // Find the variable template (partial) specialization declaration that
4515  // corresponds to these arguments.
4517  if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, VarTemplate,
4518  TemplateArgs.size(),
4519  CanonicalConverted))
4520  return true;
4521 
4522  // FIXME: Move these checks to CheckTemplatePartialSpecializationArgs so we
4523  // also do them during instantiation.
4524  if (!Name.isDependent() &&
4526  TemplateArgs, CanonicalConverted)) {
4527  Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
4528  << VarTemplate->getDeclName();
4529  IsPartialSpecialization = false;
4530  }
4531 
4533  CanonicalConverted) &&
4534  (!Context.getLangOpts().CPlusPlus20 ||
4535  !TemplateParams->hasAssociatedConstraints())) {
4536  // C++ [temp.class.spec]p9b3:
4537  //
4538  // -- The argument list of the specialization shall not be identical
4539  // to the implicit argument list of the primary template.
4540  Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
4541  << /*variable template*/ 1
4542  << /*is definition*/(SC != SC_Extern && !CurContext->isRecord())
4543  << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
4544  // FIXME: Recover from this by treating the declaration as a redeclaration
4545  // of the primary template.
4546  return true;
4547  }
4548  }
4549 
4550  void *InsertPos = nullptr;
4551  VarTemplateSpecializationDecl *PrevDecl = nullptr;
4552 
4554  PrevDecl = VarTemplate->findPartialSpecialization(
4555  CanonicalConverted, TemplateParams, InsertPos);
4556  else
4557  PrevDecl = VarTemplate->findSpecialization(CanonicalConverted, InsertPos);
4558 
4560 
4561  // Check whether we can declare a variable template specialization in
4562  // the current scope.
4563  if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
4564  TemplateNameLoc,
4566  return true;
4567 
4568  if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
4569  // Since the only prior variable template specialization with these
4570  // arguments was referenced but not declared, reuse that
4571  // declaration node as our own, updating its source location and
4572  // the list of outer template parameters to reflect our new declaration.
4573  Specialization = PrevDecl;
4574  Specialization->setLocation(TemplateNameLoc);
4575  PrevDecl = nullptr;
4576  } else if (IsPartialSpecialization) {
4577  // Create a new class template partial specialization declaration node.
4579  cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
4582  Context, VarTemplate->getDeclContext(), TemplateKWLoc,
4583  TemplateNameLoc, TemplateParams, VarTemplate, DI->getType(), DI, SC,
4584  CanonicalConverted, TemplateArgs);
4585 
4586  if (!PrevPartial)
4587  VarTemplate->AddPartialSpecialization(Partial, InsertPos);
4588  Specialization = Partial;
4589 
4590  // If we are providing an explicit specialization of a member variable
4591  // template specialization, make a note of that.
4592  if (PrevPartial && PrevPartial->getInstantiatedFromMember())
4593  PrevPartial->setMemberSpecialization();
4594 
4595  CheckTemplatePartialSpecialization(Partial);
4596  } else {
4597  // Create a new class template specialization declaration node for
4598  // this explicit specialization or friend declaration.
4600  Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
4601  VarTemplate, DI->getType(), DI, SC, CanonicalConverted);
4602  Specialization->setTemplateArgsInfo(TemplateArgs);
4603 
4604  if (!PrevDecl)
4605  VarTemplate->AddSpecialization(Specialization, InsertPos);
4606  }
4607 
4608  // C++ [temp.expl.spec]p6:
4609  // If a template, a member template or the member of a class template is
4610  // explicitly specialized then that specialization shall be declared
4611  // before the first use of that specialization that would cause an implicit
4612  // instantiation to take place, in every translation unit in which such a
4613  // use occurs; no diagnostic is required.
4614  if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
4615  bool Okay = false;
4616  for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
4617  // Is there any previous explicit specialization declaration?
4619  Okay = true;
4620  break;
4621  }
4622  }
4623 
4624  if (!Okay) {
4625  SourceRange Range(TemplateNameLoc, RAngleLoc);
4626  Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
4627  << Name << Range;
4628 
4629  Diag(PrevDecl->getPointOfInstantiation(),
4630  diag::note_instantiation_required_here)
4631  << (PrevDecl->getTemplateSpecializationKind() !=
4633  return true;
4634  }
4635  }
4636 
4637  Specialization->setTemplateKeywordLoc(TemplateKWLoc);
4638  Specialization->setLexicalDeclContext(CurContext);
4639 
4640  // Add the specialization into its lexical context, so that it can
4641  // be seen when iterating through the list of declarations in that
4642  // context. However, specializations are not found by name lookup.
4643  CurContext->addDecl(Specialization);
4644 
4645  // Note that this is an explicit specialization.
4646  Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
4647 
4648  if (PrevDecl) {
4649  // Check that this isn't a redefinition of this specialization,
4650  // merging with previous declarations.
4651  LookupResult PrevSpec(*this, GetNameForDeclarator(D), LookupOrdinaryName,
4652  forRedeclarationInCurContext());
4653  PrevSpec.addDecl(PrevDecl);
4654  D.setRedeclaration(CheckVariableDeclaration(Specialization, PrevSpec));
4655  } else if (Specialization->isStaticDataMember() &&
4656  Specialization->isOutOfLine()) {
4657  Specialization->setAccess(VarTemplate->getAccess());
4658  }
4659 
4660  return Specialization;
4661 }
4662 
4663 namespace {
4664 /// A partial specialization whose template arguments have matched
4665 /// a given template-id.
4666 struct PartialSpecMatchResult {
4668  TemplateArgumentList *Args;
4669 };
4670 } // end anonymous namespace
4671 
4672 DeclResult
4674  SourceLocation TemplateNameLoc,
4675  const TemplateArgumentListInfo &TemplateArgs) {
4676  assert(Template && "A variable template id without template?");
4677 
4678  // Check that the template argument list is well-formed for this template.
4679  SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
4680  if (CheckTemplateArgumentList(
4681  Template, TemplateNameLoc,
4682  const_cast<TemplateArgumentListInfo &>(TemplateArgs), false,
4683  SugaredConverted, CanonicalConverted,
4684  /*UpdateArgsWithConversions=*/true))
4685  return true;
4686 
4687  // Produce a placeholder value if the specialization is dependent.
4688  if (Template->getDeclContext()->isDependentContext() ||
4690  TemplateArgs, CanonicalConverted))
4691  return DeclResult();
4692 
4693  // Find the variable template specialization declaration that
4694  // corresponds to these arguments.
4695  void *InsertPos = nullptr;
4696  if (VarTemplateSpecializationDecl *Spec =
4697  Template->findSpecialization(CanonicalConverted, InsertPos)) {
4698  checkSpecializationReachability(TemplateNameLoc, Spec);
4699  // If we already have a variable template specialization, return it.
4700  return Spec;
4701  }
4702 
4703  // This is the first time we have referenced this variable template
4704  // specialization. Create the canonical declaration and add it to
4705  // the set of specializations, based on the closest partial specialization
4706  // that it represents. That is,
4707  VarDecl *InstantiationPattern = Template->getTemplatedDecl();
4709  CanonicalConverted);
4710  TemplateArgumentList *InstantiationArgs = &TemplateArgList;
4711  bool AmbiguousPartialSpec = false;
4712  typedef PartialSpecMatchResult MatchResult;
4714  SourceLocation PointOfInstantiation = TemplateNameLoc;
4715  TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation,
4716  /*ForTakingAddress=*/false);
4717 
4718  // 1. Attempt to find the closest partial specialization that this
4719  // specializes, if any.
4720  // TODO: Unify with InstantiateClassTemplateSpecialization()?
4721  // Perhaps better after unification of DeduceTemplateArguments() and
4722  // getMoreSpecializedPartialSpecialization().
4724  Template->getPartialSpecializations(PartialSpecs);
4725 
4726  for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
4727  VarTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
4728  TemplateDeductionInfo Info(FailedCandidates.getLocation());
4729 
4730  if (TemplateDeductionResult Result =
4731  DeduceTemplateArguments(Partial, TemplateArgList, Info)) {
4732  // Store the failed-deduction information for use in diagnostics, later.
4733  // TODO: Actually use the failed-deduction info?
4734  FailedCandidates.addCandidate().set(
4735  DeclAccessPair::make(Template, AS_public), Partial,
4736  MakeDeductionFailureInfo(Context, Result, Info));
4737  (void)Result;
4738  } else {
4739  Matched.push_back(PartialSpecMatchResult());
4740  Matched.back().Partial = Partial;
4741  Matched.back().Args = Info.takeCanonical();
4742  }
4743  }
4744 
4745  if (Matched.size() >= 1) {
4746  SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
4747  if (Matched.size() == 1) {
4748  // -- If exactly one matching specialization is found, the
4749  // instantiation is generated from that specialization.
4750  // We don't need to do anything for this.
4751  } else {
4752  // -- If more than one matching specialization is found, the
4753  // partial order rules (14.5.4.2) are used to determine
4754  // whether one of the specializations is more specialized
4755  // than the others. If none of the specializations is more
4756  // specialized than all of the other matching
4757  // specializations, then the use of the variable template is
4758  // ambiguous and the program is ill-formed.
4759  for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
4760  PEnd = Matched.end();
4761  P != PEnd; ++P) {
4762  if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
4763  PointOfInstantiation) ==
4764  P->Partial)
4765  Best = P;
4766  }
4767 
4768  // Determine if the best partial specialization is more specialized than
4769  // the others.
4770  for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
4771  PEnd = Matched.end();
4772  P != PEnd; ++P) {
4773  if (P != Best && getMoreSpecializedPartialSpecialization(
4774  P->Partial, Best->Partial,
4775  PointOfInstantiation) != Best->Partial) {
4776  AmbiguousPartialSpec = true;
4777  break;
4778  }
4779  }
4780  }
4781 
4782  // Instantiate using the best variable template partial specialization.
4783  InstantiationPattern = Best->Partial;
4784  InstantiationArgs = Best->Args;
4785  } else {
4786  // -- If no match is found, the instantiation is generated
4787  // from the primary template.
4788  // InstantiationPattern = Template->getTemplatedDecl();
4789  }
4790 
4791  // 2. Create the canonical declaration.
4792  // Note that we do not instantiate a definition until we see an odr-use
4793  // in DoMarkVarDeclReferenced().
4794  // FIXME: LateAttrs et al.?
4795  VarTemplateSpecializationDecl *Decl = BuildVarTemplateInstantiation(
4796  Template, InstantiationPattern, *InstantiationArgs, TemplateArgs,
4797  CanonicalConverted, TemplateNameLoc /*, LateAttrs, StartingScope*/);
4798  if (!Decl)
4799  return true;
4800 
4801  if (AmbiguousPartialSpec) {
4802  // Partial ordering did not produce a clear winner. Complain.
4803  Decl->setInvalidDecl();
4804  Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
4805  << Decl;
4806 
4807  // Print the matching partial specializations.
4808  for (MatchResult P : Matched)
4809  Diag(P.Partial->getLocation(), diag::note_partial_spec_match)
4810  << getTemplateArgumentBindingsText(P.Partial->getTemplateParameters(),
4811  *P.Args);
4812  return true;
4813  }
4814 
4816  dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
4817  Decl->setInstantiationOf(D, InstantiationArgs);
4818 
4819  checkSpecializationReachability(TemplateNameLoc, Decl);
4820 
4821  assert(Decl && "No variable template specialization?");
4822  return Decl;
4823 }
4824 
4825 ExprResult
4827  const DeclarationNameInfo &NameInfo,
4828  VarTemplateDecl *Template, SourceLocation TemplateLoc,
4829  const TemplateArgumentListInfo *TemplateArgs) {
4830 
4831  DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
4832  *TemplateArgs);
4833  if (Decl.isInvalid())
4834  return ExprError();
4835 
4836  if (!Decl.get())
4837  return ExprResult();
4838 
4839  VarDecl *Var = cast<VarDecl>(Decl.get());
4840  if (!Var->getTemplateSpecializationKind())
4842  NameInfo.getLoc());
4843 
4844  // Build an ordinary singleton decl ref.
4845  return BuildDeclarationNameExpr(SS, NameInfo, Var,
4846  /*FoundD=*/nullptr, TemplateArgs);
4847 }
4848 
4850  SourceLocation Loc) {
4851  Diag(Loc, diag::err_template_missing_args)
4852  << (int)getTemplateNameKindForDiagnostics(Name) << Name;
4853  if (TemplateDecl *TD = Name.getAsTemplateDecl()) {
4854  Diag(TD->getLocation(), diag::note_template_decl_here)
4855  << TD->getTemplateParameters()->getSourceRange();
4856  }
4857 }
4858 
4859 ExprResult
4861  SourceLocation TemplateKWLoc,
4862  const DeclarationNameInfo &ConceptNameInfo,
4863  NamedDecl *FoundDecl,
4864  ConceptDecl *NamedConcept,
4865  const TemplateArgumentListInfo *TemplateArgs) {
4866  assert(NamedConcept && "A concept template id without a template?");
4867 
4868  llvm::SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
4869  if (CheckTemplateArgumentList(
4870  NamedConcept, ConceptNameInfo.getLoc(),
4871  const_cast<TemplateArgumentListInfo &>(*TemplateArgs),
4872  /*PartialTemplateArgs=*/false, SugaredConverted, CanonicalConverted,
4873  /*UpdateArgsWithConversions=*/false))
4874  return ExprError();
4875 
4877  Context, NamedConcept->getDeclContext(), NamedConcept->getLocation(),
4878  SugaredConverted);
4879  ConstraintSatisfaction Satisfaction;
4880  bool AreArgsDependent =
4882  *TemplateArgs, SugaredConverted);
4883  MultiLevelTemplateArgumentList MLTAL(NamedConcept, SugaredConverted,
4884  /*Final=*/true);
4886 
4888  *this, ExpressionEvaluationContext::ConstantEvaluated, CSD};
4889 
4890  if (!AreArgsDependent &&
4892  NamedConcept, {NamedConcept->getConstraintExpr()}, MLTAL,
4893  SourceRange(SS.isSet() ? SS.getBeginLoc() : ConceptNameInfo.getLoc(),
4894  TemplateArgs->getRAngleLoc()),
4895  Satisfaction))
4896  return ExprError();
4897 
4899  Context,
4900  SS.isSet() ? SS.getWithLocInContext(Context) : NestedNameSpecifierLoc{},
4901  TemplateKWLoc, ConceptNameInfo, FoundDecl, NamedConcept,
4902  ASTTemplateArgumentListInfo::Create(Context, *TemplateArgs), CSD,
4903  AreArgsDependent ? nullptr : &Satisfaction);
4904 }
4905 
4907  SourceLocation TemplateKWLoc,
4908  LookupResult &R,
4909  bool RequiresADL,
4910  const TemplateArgumentListInfo *TemplateArgs) {
4911  // FIXME: Can we do any checking at this point? I guess we could check the
4912  // template arguments that we have against the template name, if the template
4913  // name refers to a single template. That's not a terribly common case,
4914  // though.
4915  // foo<int> could identify a single function unambiguously
4916  // This approach does NOT work, since f<int>(1);
4917  // gets resolved prior to resorting to overload resolution
4918  // i.e., template<class T> void f(double);
4919  // vs template<class T, class U> void f(U);
4920 
4921  // These should be filtered out by our callers.
4922  assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
4923 
4924  // Non-function templates require a template argument list.
4925  if (auto *TD = R.getAsSingle<TemplateDecl>()) {
4926  if (!TemplateArgs && !isa<FunctionTemplateDecl>(TD)) {
4927  diagnoseMissingTemplateArguments(TemplateName(TD), R.getNameLoc());
4928  return ExprError();
4929  }
4930  }
4931 
4932  // In C++1y, check variable template ids.
4933  if (R.getAsSingle<VarTemplateDecl>()) {
4934  ExprResult Res = CheckVarTemplateId(SS, R.getLookupNameInfo(),
4936  TemplateKWLoc, TemplateArgs);
4937  if (Res.isInvalid() || Res.isUsable())
4938  return Res;
4939  // Result is dependent. Carry on to build an UnresolvedLookupEpxr.
4940  }
4941 
4942  if (R.getAsSingle<ConceptDecl>()) {
4943  return CheckConceptTemplateId(SS, TemplateKWLoc, R.getLookupNameInfo(),
4944  R.getFoundDecl(),
4945  R.getAsSingle<ConceptDecl>(), TemplateArgs);
4946  }
4947 
4948  // We don't want lookup warnings at this point.
4949  R.suppressDiagnostics();
4950 
4953  SS.getWithLocInContext(Context),
4954  TemplateKWLoc,
4955  R.getLookupNameInfo(),
4956  RequiresADL, TemplateArgs,
4957  R.begin(), R.end());
4958 
4959  return ULE;
4960 }
4961 
4962 // We actually only call this from template instantiation.
4963 ExprResult
4965  SourceLocation TemplateKWLoc,
4966  const DeclarationNameInfo &NameInfo,
4967  const TemplateArgumentListInfo *TemplateArgs) {
4968 
4969  assert(TemplateArgs || TemplateKWLoc.isValid());
4970  DeclContext *DC;
4971  if (!(DC = computeDeclContext(SS, false)) ||
4972  DC->isDependentContext() ||
4973  RequireCompleteDeclContext(SS, DC))
4974  return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
4975 
4976  bool MemberOfUnknownSpecialization;
4977  LookupResult R(*this, NameInfo, LookupOrdinaryName);
4978  if (LookupTemplateName(R, (Scope *)nullptr, SS, QualType(),
4979  /*Entering*/false, MemberOfUnknownSpecialization,
4980  TemplateKWLoc))
4981  return ExprError();
4982 
4983  if (R.isAmbiguous())
4984  return ExprError();
4985 
4986  if (R.empty()) {
4987  Diag(NameInfo.getLoc(), diag::err_no_member)
4988  << NameInfo.getName() << DC << SS.getRange();
4989  return ExprError();
4990  }
4991 
4992  if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
4993  Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
4994  << SS.getScopeRep()
4995  << NameInfo.getName().getAsString() << SS.getRange();
4996  Diag(Temp->getLocation(), diag::note_referenced_class_template);
4997  return ExprError();
4998  }
4999 
5000  return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL*/ false, TemplateArgs);
5001 }
5002 
5003 /// Form a template name from a name that is syntactically required to name a
5004 /// template, either due to use of the 'template' keyword or because a name in
5005 /// this syntactic context is assumed to name a template (C++ [temp.names]p2-4).
5006 ///
5007 /// This action forms a template name given the name of the template and its
5008 /// optional scope specifier. This is used when the 'template' keyword is used
5009 /// or when the parsing context unambiguously treats a following '<' as
5010 /// introducing a template argument list. Note that this may produce a
5011 /// non-dependent template name if we can perform the lookup now and identify
5012 /// the named template.
5013 ///
5014 /// For example, given "x.MetaFun::template apply", the scope specifier
5015 /// \p SS will be "MetaFun::", \p TemplateKWLoc contains the location
5016 /// of the "template" keyword, and "apply" is the \p Name.
5018  CXXScopeSpec &SS,
5019  SourceLocation TemplateKWLoc,
5020  const UnqualifiedId &Name,
5021  ParsedType ObjectType,
5022  bool EnteringContext,
5023  TemplateTy &Result,
5024  bool AllowInjectedClassName) {
5025  if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
5026  Diag(TemplateKWLoc,
5027  getLangOpts().CPlusPlus11 ?
5028  diag::warn_cxx98_compat_template_outside_of_template :
5029  diag::ext_template_outside_of_template)
5030  << FixItHint::CreateRemoval(TemplateKWLoc);
5031 
5032  if (SS.isInvalid())
5033  return TNK_Non_template;
5034 
5035  // Figure out where isTemplateName is going to look.
5036  DeclContext *LookupCtx = nullptr;
5037  if (SS.isNotEmpty())
5038  LookupCtx = computeDeclContext(SS, EnteringContext);
5039  else if (ObjectType)
5040  LookupCtx = computeDeclContext(GetTypeFromParser(ObjectType));
5041 
5042  // C++0x [temp.names]p5:
5043  // If a name prefixed by the keyword template is not the name of
5044  // a template, the program is ill-formed. [Note: the keyword
5045  // template may not be applied to non-template members of class
5046  // templates. -end note ] [ Note: as is the case with the
5047  // typename prefix, the template prefix is allowed in cases
5048  // where it is not strictly necessary; i.e., when the
5049  // nested-name-specifier or the expression on the left of the ->
5050  // or . is not dependent on a template-parameter, or the use
5051  // does not appear in the scope of a template. -end note]
5052  //
5053  // Note: C++03 was more strict here, because it banned the use of
5054  // the "template" keyword prior to a template-name that was not a
5055  // dependent name. C++ DR468 relaxed this requirement (the
5056  // "template" keyword is now permitted). We follow the C++0x
5057  // rules, even in C++03 mode with a warning, retroactively applying the DR.
5058  bool MemberOfUnknownSpecialization;
5059  TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
5060  ObjectType, EnteringContext, Result,
5061  MemberOfUnknownSpecialization);
5062  if (TNK != TNK_Non_template) {
5063  // We resolved this to a (non-dependent) template name. Return it.
5064  auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
5065  if (!AllowInjectedClassName && SS.isNotEmpty() && LookupRD &&
5066  Name.getKind() == UnqualifiedIdKind::IK_Identifier &&
5067  Name.Identifier && LookupRD->getIdentifier() == Name.Identifier) {
5068  // C++14 [class.qual]p2:
5069  // In a lookup in which function names are not ignored and the
5070  // nested-name-specifier nominates a class C, if the name specified
5071  // [...] is the injected-class-name of C, [...] the name is instead
5072  // considered to name the constructor
5073  //
5074  // We don't get here if naming the constructor would be valid, so we
5075  // just reject immediately and recover by treating the
5076  // injected-class-name as naming the template.
5077  Diag(Name.getBeginLoc(),
5078  diag::ext_out_of_line_qualified_id_type_names_constructor)
5079  << Name.Identifier
5080  << 0 /*injected-class-name used as template name*/
5081  << TemplateKWLoc.isValid();
5082  }
5083  return TNK;
5084  }
5085 
5086  if (!MemberOfUnknownSpecialization) {
5087  // Didn't find a template name, and the lookup wasn't dependent.
5088  // Do the lookup again to determine if this is a "nothing found" case or
5089  // a "not a template" case. FIXME: Refactor isTemplateName so we don't
5090  // need to do this.
5091  DeclarationNameInfo DNI = GetNameFromUnqualifiedId(Name);
5092  LookupResult R(*this, DNI.getName(), Name.getBeginLoc(),
5093  LookupOrdinaryName);
5094  bool MOUS;
5095  // Tell LookupTemplateName that we require a template so that it diagnoses
5096  // cases where it finds a non-template.
5097  RequiredTemplateKind RTK = TemplateKWLoc.isValid()
5098  ? RequiredTemplateKind(TemplateKWLoc)
5099  : TemplateNameIsRequired;
5100  if (!LookupTemplateName(R, S, SS, ObjectType.get(), EnteringContext, MOUS,
5101  RTK, nullptr, /*AllowTypoCorrection=*/false) &&
5102  !R.isAmbiguous()) {
5103  if (LookupCtx)
5104  Diag(Name.getBeginLoc(), diag::err_no_member)
5105  << DNI.getName() << LookupCtx << SS.getRange();
5106  else
5107  Diag(Name.getBeginLoc(), diag::err_undeclared_use)
5108  << DNI.getName() << SS.getRange();
5109  }
5110  return TNK_Non_template;
5111  }
5112 
5113  NestedNameSpecifier *Qualifier = SS.getScopeRep();
5114 
5115  switch (Name.getKind()) {
5117  Result = TemplateTy::make(
5118  Context.getDependentTemplateName(Qualifier, Name.Identifier));
5120 
5122  Result = TemplateTy::make(Context.getDependentTemplateName(
5123  Qualifier, Name.OperatorFunctionId.Operator));
5124  return TNK_Function_template;
5125 
5127  // This is a kind of template name, but can never occur in a dependent
5128  // scope (literal operators can only be declared at namespace scope).
5129  break;
5130 
5131  default:
5132  break;
5133  }
5134 
5135  // This name cannot possibly name a dependent template. Diagnose this now
5136  // rather than building a dependent template name that can never be valid.
5137  Diag(Name.getBeginLoc(),
5138  diag::err_template_kw_refers_to_dependent_non_template)
5139  << GetNameFromUnqualifiedId(Name).getName() << Name.getSourceRange()
5140  << TemplateKWLoc.isValid() << TemplateKWLoc;
5141  return TNK_Non_template;
5142 }
5143 
5146  SmallVectorImpl<TemplateArgument> &SugaredConverted,
5147  SmallVectorImpl<TemplateArgument> &CanonicalConverted) {
5148  const TemplateArgument &Arg = AL.getArgument();
5149  QualType ArgType;
5150  TypeSourceInfo *TSI = nullptr;
5151 
5152  // Check template type parameter.
5153  switch(Arg.getKind()) {
5155  // C++ [temp.arg.type]p1:
5156  // A template-argument for a template-parameter which is a
5157  // type shall be a type-id.
5158  ArgType = Arg.getAsType();
5159  TSI = AL.getTypeSourceInfo();
5160  break;
5163  // We have a template type parameter but the template argument
5164  // is a template without any arguments.
5165  SourceRange SR = AL.getSourceRange();
5167  diagnoseMissingTemplateArguments(Name, SR.getEnd());
5168  return true;
5169  }
5171  // We have a template type parameter but the template argument is an
5172  // expression; see if maybe it is missing the "typename" keyword.
5173  CXXScopeSpec SS;
5174  DeclarationNameInfo NameInfo;
5175 
5176  if (DependentScopeDeclRefExpr *ArgExpr =
5177  dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
5178  SS.Adopt(ArgExpr->getQualifierLoc());
5179  NameInfo = ArgExpr->getNameInfo();
5180  } else if (CXXDependentScopeMemberExpr *ArgExpr =
5181  dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
5182  if (ArgExpr->isImplicitAccess()) {
5183  SS.Adopt(ArgExpr->getQualifierLoc());
5184  NameInfo = ArgExpr->getMemberNameInfo();
5185  }
5186  }
5187 
5188  if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
5189  LookupResult Result(*this, NameInfo, LookupOrdinaryName);
5190  LookupParsedName(Result, CurScope, &SS);
5191 
5192  if (Result.getAsSingle<TypeDecl>() ||
5193  Result.getResultKind() ==
5195  assert(SS.getScopeRep() && "dependent scope expr must has a scope!");
5196  // Suggest that the user add 'typename' before the NNS.
5197  SourceLocation Loc = AL.getSourceRange().getBegin();
5198  Diag(Loc, getLangOpts().MSVCCompat
5199  ? diag::ext_ms_template_type_arg_missing_typename
5200  : diag::err_template_arg_must_be_type_suggest)
5201  << FixItHint::CreateInsertion(Loc, "typename ");
5202  Diag(Param->getLocation(), diag::note_template_param_here);
5203 
5204  // Recover by synthesizing a type using the location information that we
5205  // already have.
5206  ArgType =
5207  Context.getDependentNameType(ETK_Typename, SS.getScopeRep(), II);
5208  TypeLocBuilder TLB;
5209  DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(ArgType);
5210  TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
5211  TL.setQualifierLoc(SS.getWithLocInContext(Context));
5212  TL.setNameLoc(NameInfo.getLoc());
5213  TSI = TLB.getTypeSourceInfo(Context, ArgType);
5214 
5215  // Overwrite our input TemplateArgumentLoc so that we can recover
5216  // properly.
5217  AL = TemplateArgumentLoc(TemplateArgument(ArgType),
5219 
5220  break;
5221  }
5222  }
5223  // fallthrough
5224  [[fallthrough]];
5225  }
5226  default: {
5227  // We have a template type parameter but the template argument
5228  // is not a type.
5229  SourceRange SR = AL.getSourceRange();
5230  Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
5231  Diag(Param->getLocation(), diag::note_template_param_here);
5232 
5233  return true;
5234  }
5235  }
5236 
5237  if (CheckTemplateArgument(TSI))
5238  return true;
5239 
5240  // Objective-C ARC:
5241  // If an explicitly-specified template argument type is a lifetime type
5242  // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
5243  if (getLangOpts().ObjCAutoRefCount &&
5244  ArgType->isObjCLifetimeType() &&
5245  !ArgType.getObjCLifetime()) {
5246  Qualifiers Qs;
5248  ArgType = Context.getQualifiedType(ArgType, Qs);
5249  }
5250 
5251  SugaredConverted.push_back(TemplateArgument(ArgType));
5252  CanonicalConverted.push_back(
5253  TemplateArgument(Context.getCanonicalType(ArgType)));
5254  return false;
5255 }
5256 
5257 /// Substitute template arguments into the default template argument for
5258 /// the given template type parameter.
5259 ///
5260 /// \param SemaRef the semantic analysis object for which we are performing
5261 /// the substitution.
5262 ///
5263 /// \param Template the template that we are synthesizing template arguments
5264 /// for.
5265 ///
5266 /// \param TemplateLoc the location of the template name that started the
5267 /// template-id we are checking.
5268 ///
5269 /// \param RAngleLoc the location of the right angle bracket ('>') that
5270 /// terminates the template-id.
5271 ///
5272 /// \param Param the template template parameter whose default we are
5273 /// substituting into.
5274 ///
5275 /// \param Converted the list of template arguments provided for template
5276 /// parameters that precede \p Param in the template parameter list.
5277 /// \returns the substituted template argument, or NULL if an error occurred.
5279  Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
5280  SourceLocation RAngleLoc, TemplateTypeParmDecl *Param,
5281  ArrayRef<TemplateArgument> SugaredConverted,
5282  ArrayRef<TemplateArgument> CanonicalConverted) {
5283  TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
5284 
5285  // If the argument type is dependent, instantiate it now based
5286  // on the previously-computed template arguments.
5287  if (ArgType->getType()->isInstantiationDependentType()) {
5288  Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Param, Template,
5289  SugaredConverted,
5290  SourceRange(TemplateLoc, RAngleLoc));
5291  if (Inst.isInvalid())
5292  return nullptr;
5293 
5294  // Only substitute for the innermost template argument list.
5295  MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5296  /*Final=*/true);
5297  for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5298  TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5299 
5300  bool ForLambdaCallOperator = false;
5301  if (const auto *Rec = dyn_cast<CXXRecordDecl>(Template->getDeclContext()))
5302  ForLambdaCallOperator = Rec->isLambda();
5303  Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext(),
5304  !ForLambdaCallOperator);
5305  ArgType =
5306  SemaRef.SubstType(ArgType, TemplateArgLists,
5307  Param->getDefaultArgumentLoc(), Param->getDeclName());
5308  }
5309 
5310  return ArgType;
5311 }
5312 
5313 /// Substitute template arguments into the default template argument for
5314 /// the given non-type template parameter.
5315 ///
5316 /// \param SemaRef the semantic analysis object for which we are performing
5317 /// the substitution.
5318 ///
5319 /// \param Template the template that we are synthesizing template arguments
5320 /// for.
5321 ///
5322 /// \param TemplateLoc the location of the template name that started the
5323 /// template-id we are checking.
5324 ///
5325 /// \param RAngleLoc the location of the right angle bracket ('>') that
5326 /// terminates the template-id.
5327 ///
5328 /// \param Param the non-type template parameter whose default we are
5329 /// substituting into.
5330 ///
5331 /// \param Converted the list of template arguments provided for template
5332 /// parameters that precede \p Param in the template parameter list.
5333 ///
5334 /// \returns the substituted template argument, or NULL if an error occurred.
5336  Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
5337  SourceLocation RAngleLoc, NonTypeTemplateParmDecl *Param,
5338  ArrayRef<TemplateArgument> SugaredConverted,
5339  ArrayRef<TemplateArgument> CanonicalConverted) {
5340  Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Param, Template,
5341  SugaredConverted,
5342  SourceRange(TemplateLoc, RAngleLoc));
5343  if (Inst.isInvalid())
5344  return ExprError();
5345 
5346  // Only substitute for the innermost template argument list.
5347  MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5348  /*Final=*/true);
5349  for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5350  TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5351 
5352  Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
5353  EnterExpressionEvaluationContext ConstantEvaluated(
5355  return SemaRef.SubstExpr(Param->getDefaultArgument(), TemplateArgLists);
5356 }
5357 
5358 /// Substitute template arguments into the default template argument for
5359 /// the given template template parameter.
5360 ///
5361 /// \param SemaRef the semantic analysis object for which we are performing
5362 /// the substitution.
5363 ///
5364 /// \param Template the template that we are synthesizing template arguments
5365 /// for.
5366 ///
5367 /// \param TemplateLoc the location of the template name that started the
5368 /// template-id we are checking.
5369 ///
5370 /// \param RAngleLoc the location of the right angle bracket ('>') that
5371 /// terminates the template-id.
5372 ///
5373 /// \param Param the template template parameter whose default we are
5374 /// substituting into.
5375 ///
5376 /// \param Converted the list of template arguments provided for template
5377 /// parameters that precede \p Param in the template parameter list.
5378 ///
5379 /// \param QualifierLoc Will be set to the nested-name-specifier (with
5380 /// source-location information) that precedes the template name.
5381 ///
5382 /// \returns the substituted template argument, or NULL if an error occurred.
5384  Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
5385  SourceLocation RAngleLoc, TemplateTemplateParmDecl *Param,
5386  ArrayRef<TemplateArgument> SugaredConverted,
5387  ArrayRef<TemplateArgument> CanonicalConverted,
5388  NestedNameSpecifierLoc &QualifierLoc) {
5390  SemaRef, TemplateLoc, TemplateParameter(Param), Template,
5391  SugaredConverted, SourceRange(TemplateLoc, RAngleLoc));
5392  if (Inst.isInvalid())
5393  return TemplateName();
5394 
5395  // Only substitute for the innermost template argument list.
5396  MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5397  /*Final=*/true);
5398  for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5399  TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5400 
5401  Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
5402  // Substitute into the nested-name-specifier first,
5403  QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc();
5404  if (QualifierLoc) {
5405  QualifierLoc =
5406  SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgLists);
5407  if (!QualifierLoc)
5408  return TemplateName();
5409  }
5410 
5411  return SemaRef.SubstTemplateName(
5412  QualifierLoc,
5415  TemplateArgLists);
5416 }
5417 
5418 /// If the given template parameter has a default template
5419 /// argument, substitute into that default template argument and
5420 /// return the corresponding template argument.
5422  TemplateDecl *Template, SourceLocation TemplateLoc,
5423  SourceLocation RAngleLoc, Decl *Param,
5424  ArrayRef<TemplateArgument> SugaredConverted,
5425  ArrayRef<TemplateArgument> CanonicalConverted, bool &HasDefaultArg) {
5426  HasDefaultArg = false;
5427 
5428  if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
5429  if (!hasReachableDefaultArgument(TypeParm))
5430  return TemplateArgumentLoc();
5431 
5432  HasDefaultArg = true;
5434  *this, Template, TemplateLoc, RAngleLoc, TypeParm, SugaredConverted,
5435  CanonicalConverted);
5436  if (DI)
5437  return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
5438 
5439  return TemplateArgumentLoc();
5440  }
5441 
5442  if (NonTypeTemplateParmDecl *NonTypeParm
5443  = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
5444  if (!hasReachableDefaultArgument(NonTypeParm))
5445  return TemplateArgumentLoc();
5446 
5447  HasDefaultArg = true;
5449  *this, Template, TemplateLoc, RAngleLoc, NonTypeParm, SugaredConverted,
5450  CanonicalConverted);
5451  if (Arg.isInvalid())
5452  return TemplateArgumentLoc();
5453 
5454  Expr *ArgE = Arg.getAs<Expr>();
5455  return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
5456  }
5457 
5458  TemplateTemplateParmDecl *TempTempParm
5459  = cast<TemplateTemplateParmDecl>(Param);
5460  if (!hasReachableDefaultArgument(TempTempParm))
5461  return TemplateArgumentLoc();
5462 
5463  HasDefaultArg = true;
5464  NestedNameSpecifierLoc QualifierLoc;
5466  *this, Template, TemplateLoc, RAngleLoc, TempTempParm, SugaredConverted,
5467  CanonicalConverted, QualifierLoc);
5468  if (TName.isNull())
5469  return TemplateArgumentLoc();
5470 
5471  return TemplateArgumentLoc(
5472  Context, TemplateArgument(TName),
5473  TempTempParm->getDefaultArgument().getTemplateQualifierLoc(),
5474  TempTempParm->getDefaultArgument().getTemplateNameLoc());
5475 }
5476 
5477 /// Convert a template-argument that we parsed as a type into a template, if
5478 /// possible. C++ permits injected-class-names to perform dual service as
5479 /// template template arguments and as template type arguments.
5480 static TemplateArgumentLoc
5482  // Extract and step over any surrounding nested-name-specifier.
5483  NestedNameSpecifierLoc QualLoc;
5484  if (auto ETLoc = TLoc.getAs<ElaboratedTypeLoc>()) {
5485  if (ETLoc.getTypePtr()->getKeyword() != ETK_None)
5486  return TemplateArgumentLoc();
5487 
5488  QualLoc = ETLoc.getQualifierLoc();
5489  TLoc = ETLoc.getNamedTypeLoc();
5490  }
5491  // If this type was written as an injected-class-name, it can be used as a
5492  // template template argument.
5493  if (auto InjLoc = TLoc.getAs<InjectedClassNameTypeLoc>())
5494  return TemplateArgumentLoc(Context, InjLoc.getTypePtr()->getTemplateName(),
5495  QualLoc, InjLoc.getNameLoc());
5496 
5497  // If this type was written as an injected-class-name, it may have been
5498  // converted to a RecordType during instantiation. If the RecordType is
5499  // *not* wrapped in a TemplateSpecializationType and denotes a class
5500  // template specialization, it must have come from an injected-class-name.
5501  if (auto RecLoc = TLoc.getAs<RecordTypeLoc>())
5502  if (auto *CTSD =
5503  dyn_cast<ClassTemplateSpecializationDecl>(RecLoc.getDecl()))
5504  return TemplateArgumentLoc(Context,
5505  TemplateName(CTSD->getSpecializedTemplate()),
5506  QualLoc, RecLoc.getNameLoc());
5507 
5508  return TemplateArgumentLoc();
5509 }
5510 
5511 /// Check that the given template argument corresponds to the given
5512 /// template parameter.
5513 ///
5514 /// \param Param The template parameter against which the argument will be
5515 /// checked.
5516 ///
5517 /// \param Arg The template argument, which may be updated due to conversions.
5518 ///
5519 /// \param Template The template in which the template argument resides.
5520 ///
5521 /// \param TemplateLoc The location of the template name for the template
5522 /// whose argument list we're matching.
5523 ///
5524 /// \param RAngleLoc The location of the right angle bracket ('>') that closes
5525 /// the template argument list.
5526 ///
5527 /// \param ArgumentPackIndex The index into the argument pack where this
5528 /// argument will be placed. Only valid if the parameter is a parameter pack.
5529 ///
5530 /// \param Converted The checked, converted argument will be added to the
5531 /// end of this small vector.
5532 ///
5533 /// \param CTAK Describes how we arrived at this particular template argument:
5534 /// explicitly written, deduced, etc.
5535 ///
5536 /// \returns true on error, false otherwise.
5538  NamedDecl *Param, TemplateArgumentLoc &Arg, NamedDecl *Template,
5539  SourceLocation TemplateLoc, SourceLocation RAngleLoc,
5540  unsigned ArgumentPackIndex,
5541  SmallVectorImpl<TemplateArgument> &SugaredConverted,
5542  SmallVectorImpl<TemplateArgument> &CanonicalConverted,
5544  // Check template type parameters.
5545  if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
5546  return CheckTemplateTypeArgument(TTP, Arg, SugaredConverted,
5547  CanonicalConverted);
5548 
5549  // Check non-type template parameters.
5550  if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
5551  // Do substitution on the type of the non-type template parameter
5552  // with the template arguments we've seen thus far. But if the
5553  // template has a dependent context then we cannot substitute yet.
5554  QualType NTTPType = NTTP->getType();
5555  if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
5556  NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
5557 
5558  if (NTTPType->isInstantiationDependentType() &&
5559  !isa<TemplateTemplateParmDecl>(Template) &&
5560  !Template->getDeclContext()->isDependentContext()) {
5561  // Do substitution on the type of the non-type template parameter.
5562  InstantiatingTemplate Inst(*this, TemplateLoc, Template, NTTP,
5563  SugaredConverted,
5564  SourceRange(TemplateLoc, RAngleLoc));
5565  if (Inst.isInvalid())
5566  return true;
5567 
5568  MultiLevelTemplateArgumentList MLTAL(Template, SugaredConverted,
5569  /*Final=*/true);
5570  // If the parameter is a pack expansion, expand this slice of the pack.
5571  if (auto *PET = NTTPType->getAs<PackExpansionType>()) {
5572  Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this,
5573  ArgumentPackIndex);
5574  NTTPType = SubstType(PET->getPattern(), MLTAL, NTTP->getLocation(),
5575  NTTP->getDeclName());
5576  } else {
5577  NTTPType = SubstType(NTTPType, MLTAL, NTTP->getLocation(),
5578  NTTP->getDeclName());
5579  }
5580 
5581  // If that worked, check the non-type template parameter type
5582  // for validity.
5583  if (!NTTPType.isNull())
5584  NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
5585  NTTP->getLocation());
5586  if (NTTPType.isNull())
5587  return true;
5588  }
5589 
5590  switch (Arg.getArgument().getKind()) {
5592  llvm_unreachable("Should never see a NULL template argument here");
5593 
5595  Expr *E = Arg.getArgument().getAsExpr();
5596  TemplateArgument SugaredResult, CanonicalResult;
5597  unsigned CurSFINAEErrors = NumSFINAEErrors;
5598  ExprResult Res = CheckTemplateArgument(NTTP, NTTPType, E, SugaredResult,
5599  CanonicalResult, CTAK);
5600  if (Res.isInvalid())
5601  return true;
5602  // If the current template argument causes an error, give up now.
5603  if (CurSFINAEErrors < NumSFINAEErrors)
5604  return true;
5605 
5606  // If the resulting expression is new, then use it in place of the
5607  // old expression in the template argument.
5608  if (Res.get() != E) {
5609  TemplateArgument TA(Res.get());
5610  Arg = TemplateArgumentLoc(TA, Res.get());
5611  }
5612 
5613  SugaredConverted.push_back(SugaredResult);
5614  CanonicalConverted.push_back(CanonicalResult);
5615  break;
5616  }
5617 
5621  // We've already checked this template argument, so just copy
5622  // it to the list of converted arguments.
5623  SugaredConverted.push_back(Arg.getArgument());
5624  CanonicalConverted.push_back(
5625  Context.getCanonicalTemplateArgument(Arg.getArgument()));
5626  break;
5627