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