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