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