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