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