clang  5.0.0
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 /// \brief [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 /// \brief 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  return nullptr;
109 }
110 
112  bool AllowFunctionTemplates) {
113  // The set of class templates we've already seen.
114  llvm::SmallPtrSet<ClassTemplateDecl *, 8> ClassTemplates;
115  LookupResult::Filter filter = R.makeFilter();
116  while (filter.hasNext()) {
117  NamedDecl *Orig = filter.next();
119  AllowFunctionTemplates);
120  if (!Repl)
121  filter.erase();
122  else if (Repl != Orig) {
123 
124  // C++ [temp.local]p3:
125  // A lookup that finds an injected-class-name (10.2) can result in an
126  // ambiguity in certain cases (for example, if it is found in more than
127  // one base class). If all of the injected-class-names that are found
128  // refer to specializations of the same class template, and if the name
129  // is used as a template-name, the reference refers to the class
130  // template itself and not a specialization thereof, and is not
131  // ambiguous.
132  if (ClassTemplateDecl *ClassTmpl = dyn_cast<ClassTemplateDecl>(Repl))
133  if (!ClassTemplates.insert(ClassTmpl).second) {
134  filter.erase();
135  continue;
136  }
137 
138  // FIXME: we promote access to public here as a workaround to
139  // the fact that LookupResult doesn't let us remember that we
140  // found this template through a particular injected class name,
141  // which means we end up doing nasty things to the invariants.
142  // Pretending that access is public is *much* safer.
143  filter.replace(Repl, AS_public);
144  }
145  }
146  filter.done();
147 }
148 
150  bool AllowFunctionTemplates) {
151  for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I)
152  if (isAcceptableTemplateName(Context, *I, AllowFunctionTemplates))
153  return true;
154 
155  return false;
156 }
157 
159  CXXScopeSpec &SS,
160  bool hasTemplateKeyword,
162  ParsedType ObjectTypePtr,
163  bool EnteringContext,
164  TemplateTy &TemplateResult,
165  bool &MemberOfUnknownSpecialization) {
166  assert(getLangOpts().CPlusPlus && "No template names in C!");
167 
168  DeclarationName TName;
169  MemberOfUnknownSpecialization = false;
170 
171  switch (Name.getKind()) {
173  TName = DeclarationName(Name.Identifier);
174  break;
175 
179  break;
180 
183  break;
184 
185  default:
186  return TNK_Non_template;
187  }
188 
189  QualType ObjectType = ObjectTypePtr.get();
190 
191  LookupResult R(*this, TName, Name.getLocStart(), LookupOrdinaryName);
192  LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
193  MemberOfUnknownSpecialization);
194  if (R.empty()) return TNK_Non_template;
195  if (R.isAmbiguous()) {
196  // Suppress diagnostics; we'll redo this lookup later.
197  R.suppressDiagnostics();
198 
199  // FIXME: we might have ambiguous templates, in which case we
200  // should at least parse them properly!
201  return TNK_Non_template;
202  }
203 
204  TemplateName Template;
205  TemplateNameKind TemplateKind;
206 
207  unsigned ResultCount = R.end() - R.begin();
208  if (ResultCount > 1) {
209  // We assume that we'll preserve the qualifier from a function
210  // template name in other ways.
211  Template = Context.getOverloadedTemplateName(R.begin(), R.end());
212  TemplateKind = TNK_Function_template;
213 
214  // We'll do this lookup again later.
215  R.suppressDiagnostics();
216  } else {
217  TemplateDecl *TD = cast<TemplateDecl>((*R.begin())->getUnderlyingDecl());
218 
219  if (SS.isSet() && !SS.isInvalid()) {
220  NestedNameSpecifier *Qualifier = SS.getScopeRep();
221  Template = Context.getQualifiedTemplateName(Qualifier,
222  hasTemplateKeyword, TD);
223  } else {
224  Template = TemplateName(TD);
225  }
226 
227  if (isa<FunctionTemplateDecl>(TD)) {
228  TemplateKind = TNK_Function_template;
229 
230  // We'll do this lookup again later.
231  R.suppressDiagnostics();
232  } else {
233  assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) ||
234  isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD) ||
235  isa<BuiltinTemplateDecl>(TD));
236  TemplateKind =
237  isa<VarTemplateDecl>(TD) ? TNK_Var_template : TNK_Type_template;
238  }
239  }
240 
241  TemplateResult = TemplateTy::make(Template);
242  return TemplateKind;
243 }
244 
246  SourceLocation NameLoc,
247  ParsedTemplateTy *Template) {
248  CXXScopeSpec SS;
249  bool MemberOfUnknownSpecialization = false;
250 
251  // We could use redeclaration lookup here, but we don't need to: the
252  // syntactic form of a deduction guide is enough to identify it even
253  // if we can't look up the template name at all.
254  LookupResult R(*this, DeclarationName(&Name), NameLoc, LookupOrdinaryName);
255  LookupTemplateName(R, S, SS, /*ObjectType*/QualType(),
256  /*EnteringContext*/false, MemberOfUnknownSpecialization);
257 
258  if (R.empty()) return false;
259  if (R.isAmbiguous()) {
260  // FIXME: Diagnose an ambiguity if we find at least one template.
262  return false;
263  }
264 
265  // We only treat template-names that name type templates as valid deduction
266  // guide names.
268  if (!TD || !getAsTypeTemplateDecl(TD))
269  return false;
270 
271  if (Template)
272  *Template = TemplateTy::make(TemplateName(TD));
273  return true;
274 }
275 
277  SourceLocation IILoc,
278  Scope *S,
279  const CXXScopeSpec *SS,
280  TemplateTy &SuggestedTemplate,
281  TemplateNameKind &SuggestedKind) {
282  // We can't recover unless there's a dependent scope specifier preceding the
283  // template name.
284  // FIXME: Typo correction?
285  if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
286  computeDeclContext(*SS))
287  return false;
288 
289  // The code is missing a 'template' keyword prior to the dependent template
290  // name.
292  Diag(IILoc, diag::err_template_kw_missing)
293  << Qualifier << II.getName()
294  << FixItHint::CreateInsertion(IILoc, "template ");
295  SuggestedTemplate
296  = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II));
297  SuggestedKind = TNK_Dependent_template_name;
298  return true;
299 }
300 
302  Scope *S, CXXScopeSpec &SS,
303  QualType ObjectType,
304  bool EnteringContext,
305  bool &MemberOfUnknownSpecialization) {
306  // Determine where to perform name lookup
307  MemberOfUnknownSpecialization = false;
308  DeclContext *LookupCtx = nullptr;
309  bool isDependent = false;
310  if (!ObjectType.isNull()) {
311  // This nested-name-specifier occurs in a member access expression, e.g.,
312  // x->B::f, and we are looking into the type of the object.
313  assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
314  LookupCtx = computeDeclContext(ObjectType);
315  isDependent = ObjectType->isDependentType();
316  assert((isDependent || !ObjectType->isIncompleteType() ||
317  ObjectType->castAs<TagType>()->isBeingDefined()) &&
318  "Caller should have completed object type");
319 
320  // Template names cannot appear inside an Objective-C class or object type.
321  if (ObjectType->isObjCObjectOrInterfaceType()) {
322  Found.clear();
323  return;
324  }
325  } else if (SS.isSet()) {
326  // This nested-name-specifier occurs after another nested-name-specifier,
327  // so long into the context associated with the prior nested-name-specifier.
328  LookupCtx = computeDeclContext(SS, EnteringContext);
329  isDependent = isDependentScopeSpecifier(SS);
330 
331  // The declaration context must be complete.
332  if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
333  return;
334  }
335 
336  bool ObjectTypeSearchedInScope = false;
337  bool AllowFunctionTemplatesInLookup = true;
338  if (LookupCtx) {
339  // Perform "qualified" name lookup into the declaration context we
340  // computed, which is either the type of the base of a member access
341  // expression or the declaration context associated with a prior
342  // nested-name-specifier.
343  LookupQualifiedName(Found, LookupCtx);
344  if (!ObjectType.isNull() && Found.empty()) {
345  // C++ [basic.lookup.classref]p1:
346  // In a class member access expression (5.2.5), if the . or -> token is
347  // immediately followed by an identifier followed by a <, the
348  // identifier must be looked up to determine whether the < is the
349  // beginning of a template argument list (14.2) or a less-than operator.
350  // The identifier is first looked up in the class of the object
351  // expression. If the identifier is not found, it is then looked up in
352  // the context of the entire postfix-expression and shall name a class
353  // or function template.
354  if (S) LookupName(Found, S);
355  ObjectTypeSearchedInScope = true;
356  AllowFunctionTemplatesInLookup = false;
357  }
358  } else if (isDependent && (!S || ObjectType.isNull())) {
359  // We cannot look into a dependent object type or nested nme
360  // specifier.
361  MemberOfUnknownSpecialization = true;
362  return;
363  } else {
364  // Perform unqualified name lookup in the current scope.
365  LookupName(Found, S);
366 
367  if (!ObjectType.isNull())
368  AllowFunctionTemplatesInLookup = false;
369  }
370 
371  if (Found.empty() && !isDependent) {
372  // If we did not find any names, attempt to correct any typos.
374  Found.clear();
375  // Simple filter callback that, for keywords, only accepts the C++ *_cast
376  auto FilterCCC = llvm::make_unique<CorrectionCandidateCallback>();
377  FilterCCC->WantTypeSpecifiers = false;
378  FilterCCC->WantExpressionKeywords = false;
379  FilterCCC->WantRemainingKeywords = false;
380  FilterCCC->WantCXXNamedCasts = true;
381  if (TypoCorrection Corrected = CorrectTypo(
382  Found.getLookupNameInfo(), Found.getLookupKind(), S, &SS,
383  std::move(FilterCCC), CTK_ErrorRecovery, LookupCtx)) {
384  Found.setLookupName(Corrected.getCorrection());
385  if (auto *ND = Corrected.getFoundDecl())
386  Found.addDecl(ND);
387  FilterAcceptableTemplateNames(Found);
388  if (!Found.empty()) {
389  if (LookupCtx) {
390  std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
391  bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
392  Name.getAsString() == CorrectedStr;
393  diagnoseTypo(Corrected, PDiag(diag::err_no_member_template_suggest)
394  << Name << LookupCtx << DroppedSpecifier
395  << SS.getRange());
396  } else {
397  diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest) << Name);
398  }
399  }
400  } else {
401  Found.setLookupName(Name);
402  }
403  }
404 
405  FilterAcceptableTemplateNames(Found, AllowFunctionTemplatesInLookup);
406  if (Found.empty()) {
407  if (isDependent)
408  MemberOfUnknownSpecialization = true;
409  return;
410  }
411 
412  if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope &&
413  !getLangOpts().CPlusPlus11) {
414  // C++03 [basic.lookup.classref]p1:
415  // [...] If the lookup in the class of the object expression finds a
416  // template, the name is also looked up in the context of the entire
417  // postfix-expression and [...]
418  //
419  // Note: C++11 does not perform this second lookup.
420  LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
421  LookupOrdinaryName);
422  LookupName(FoundOuter, S);
423  FilterAcceptableTemplateNames(FoundOuter, /*AllowFunctionTemplates=*/false);
424 
425  if (FoundOuter.empty()) {
426  // - if the name is not found, the name found in the class of the
427  // object expression is used, otherwise
428  } else if (!FoundOuter.getAsSingle<ClassTemplateDecl>() ||
429  FoundOuter.isAmbiguous()) {
430  // - if the name is found in the context of the entire
431  // postfix-expression and does not name a class template, the name
432  // found in the class of the object expression is used, otherwise
433  FoundOuter.clear();
434  } else if (!Found.isSuppressingDiagnostics()) {
435  // - if the name found is a class template, it must refer to the same
436  // entity as the one found in the class of the object expression,
437  // otherwise the program is ill-formed.
438  if (!Found.isSingleResult() ||
439  Found.getFoundDecl()->getCanonicalDecl()
440  != FoundOuter.getFoundDecl()->getCanonicalDecl()) {
441  Diag(Found.getNameLoc(),
442  diag::ext_nested_name_member_ref_lookup_ambiguous)
443  << Found.getLookupName()
444  << ObjectType;
446  diag::note_ambig_member_ref_object_type)
447  << ObjectType;
448  Diag(FoundOuter.getFoundDecl()->getLocation(),
449  diag::note_ambig_member_ref_scope);
450 
451  // Recover by taking the template that we found in the object
452  // expression's type.
453  }
454  }
455  }
456 }
457 
459  SourceLocation Less,
460  SourceLocation Greater) {
461  if (TemplateName.isInvalid())
462  return;
463 
464  DeclarationNameInfo NameInfo;
465  CXXScopeSpec SS;
466  LookupNameKind LookupKind;
467 
468  DeclContext *LookupCtx = nullptr;
469  NamedDecl *Found = nullptr;
470 
471  // Figure out what name we looked up.
472  if (auto *ME = dyn_cast<MemberExpr>(TemplateName.get())) {
473  NameInfo = ME->getMemberNameInfo();
474  SS.Adopt(ME->getQualifierLoc());
475  LookupKind = LookupMemberName;
476  LookupCtx = ME->getBase()->getType()->getAsCXXRecordDecl();
477  Found = ME->getMemberDecl();
478  } else {
479  auto *DRE = cast<DeclRefExpr>(TemplateName.get());
480  NameInfo = DRE->getNameInfo();
481  SS.Adopt(DRE->getQualifierLoc());
482  LookupKind = LookupOrdinaryName;
483  Found = DRE->getFoundDecl();
484  }
485 
486  // Try to correct the name by looking for templates and C++ named casts.
487  struct TemplateCandidateFilter : CorrectionCandidateCallback {
488  TemplateCandidateFilter() {
489  WantTypeSpecifiers = false;
490  WantExpressionKeywords = false;
491  WantRemainingKeywords = false;
492  WantCXXNamedCasts = true;
493  };
494  bool ValidateCandidate(const TypoCorrection &Candidate) override {
495  if (auto *ND = Candidate.getCorrectionDecl())
496  return isAcceptableTemplateName(ND->getASTContext(), ND, true);
497  return Candidate.isKeyword();
498  }
499  };
500 
501  DeclarationName Name = NameInfo.getName();
502  if (TypoCorrection Corrected =
503  CorrectTypo(NameInfo, LookupKind, S, &SS,
504  llvm::make_unique<TemplateCandidateFilter>(),
505  CTK_ErrorRecovery, LookupCtx)) {
506  auto *ND = Corrected.getFoundDecl();
507  if (ND)
509  /*AllowFunctionTemplates*/ true);
510  if (ND || Corrected.isKeyword()) {
511  if (LookupCtx) {
512  std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
513  bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
514  Name.getAsString() == CorrectedStr;
515  diagnoseTypo(Corrected,
516  PDiag(diag::err_non_template_in_member_template_id_suggest)
517  << Name << LookupCtx << DroppedSpecifier
518  << SS.getRange(), false);
519  } else {
520  diagnoseTypo(Corrected,
521  PDiag(diag::err_non_template_in_template_id_suggest)
522  << Name, false);
523  }
524  if (Found)
525  Diag(Found->getLocation(),
526  diag::note_non_template_in_template_id_found);
527  return;
528  }
529  }
530 
531  Diag(NameInfo.getLoc(), diag::err_non_template_in_template_id)
532  << Name << SourceRange(Less, Greater);
533  if (Found)
534  Diag(Found->getLocation(), diag::note_non_template_in_template_id_found);
535 }
536 
537 /// ActOnDependentIdExpression - Handle a dependent id-expression that
538 /// was just parsed. This is only possible with an explicit scope
539 /// specifier naming a dependent type.
542  SourceLocation TemplateKWLoc,
543  const DeclarationNameInfo &NameInfo,
544  bool isAddressOfOperand,
545  const TemplateArgumentListInfo *TemplateArgs) {
546  DeclContext *DC = getFunctionLevelDeclContext();
547 
548  // C++11 [expr.prim.general]p12:
549  // An id-expression that denotes a non-static data member or non-static
550  // member function of a class can only be used:
551  // (...)
552  // - if that id-expression denotes a non-static data member and it
553  // appears in an unevaluated operand.
554  //
555  // If this might be the case, form a DependentScopeDeclRefExpr instead of a
556  // CXXDependentScopeMemberExpr. The former can instantiate to either
557  // DeclRefExpr or MemberExpr depending on lookup results, while the latter is
558  // always a MemberExpr.
559  bool MightBeCxx11UnevalField =
560  getLangOpts().CPlusPlus11 && isUnevaluatedContext();
561 
562  // Check if the nested name specifier is an enum type.
563  bool IsEnum = false;
564  if (NestedNameSpecifier *NNS = SS.getScopeRep())
565  IsEnum = dyn_cast_or_null<EnumType>(NNS->getAsType());
566 
567  if (!MightBeCxx11UnevalField && !isAddressOfOperand && !IsEnum &&
568  isa<CXXMethodDecl>(DC) && cast<CXXMethodDecl>(DC)->isInstance()) {
569  QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(Context);
570 
571  // Since the 'this' expression is synthesized, we don't need to
572  // perform the double-lookup check.
573  NamedDecl *FirstQualifierInScope = nullptr;
574 
576  Context, /*This*/ nullptr, ThisType, /*IsArrow*/ true,
577  /*Op*/ SourceLocation(), SS.getWithLocInContext(Context), TemplateKWLoc,
578  FirstQualifierInScope, NameInfo, TemplateArgs);
579  }
580 
581  return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
582 }
583 
586  SourceLocation TemplateKWLoc,
587  const DeclarationNameInfo &NameInfo,
588  const TemplateArgumentListInfo *TemplateArgs) {
590  Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
591  TemplateArgs);
592 }
593 
594 
595 /// Determine whether we would be unable to instantiate this template (because
596 /// it either has no definition, or is in the process of being instantiated).
598  NamedDecl *Instantiation,
599  bool InstantiatedFromMember,
600  const NamedDecl *Pattern,
601  const NamedDecl *PatternDef,
603  bool Complain /*= true*/) {
604  assert(isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) ||
605  isa<VarDecl>(Instantiation));
606 
607  bool IsEntityBeingDefined = false;
608  if (const TagDecl *TD = dyn_cast_or_null<TagDecl>(PatternDef))
609  IsEntityBeingDefined = TD->isBeingDefined();
610 
611  if (PatternDef && !IsEntityBeingDefined) {
612  NamedDecl *SuggestedDef = nullptr;
613  if (!hasVisibleDefinition(const_cast<NamedDecl*>(PatternDef), &SuggestedDef,
614  /*OnlyNeedComplete*/false)) {
615  // If we're allowed to diagnose this and recover, do so.
616  bool Recover = Complain && !isSFINAEContext();
617  if (Complain)
618  diagnoseMissingImport(PointOfInstantiation, SuggestedDef,
620  return !Recover;
621  }
622  return false;
623  }
624 
625  if (!Complain || (PatternDef && PatternDef->isInvalidDecl()))
626  return true;
627 
629  QualType InstantiationTy;
630  if (TagDecl *TD = dyn_cast<TagDecl>(Instantiation))
631  InstantiationTy = Context.getTypeDeclType(TD);
632  if (PatternDef) {
633  Diag(PointOfInstantiation,
634  diag::err_template_instantiate_within_definition)
635  << /*implicit|explicit*/(TSK != TSK_ImplicitInstantiation)
636  << InstantiationTy;
637  // Not much point in noting the template declaration here, since
638  // we're lexically inside it.
639  Instantiation->setInvalidDecl();
640  } else if (InstantiatedFromMember) {
641  if (isa<FunctionDecl>(Instantiation)) {
642  Diag(PointOfInstantiation,
643  diag::err_explicit_instantiation_undefined_member)
644  << /*member function*/ 1 << Instantiation->getDeclName()
645  << Instantiation->getDeclContext();
646  Note = diag::note_explicit_instantiation_here;
647  } else {
648  assert(isa<TagDecl>(Instantiation) && "Must be a TagDecl!");
649  Diag(PointOfInstantiation,
650  diag::err_implicit_instantiate_member_undefined)
651  << InstantiationTy;
652  Note = diag::note_member_declared_at;
653  }
654  } else {
655  if (isa<FunctionDecl>(Instantiation)) {
656  Diag(PointOfInstantiation,
657  diag::err_explicit_instantiation_undefined_func_template)
658  << Pattern;
659  Note = diag::note_explicit_instantiation_here;
660  } else if (isa<TagDecl>(Instantiation)) {
661  Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
662  << (TSK != TSK_ImplicitInstantiation)
663  << InstantiationTy;
664  Note = diag::note_template_decl_here;
665  } else {
666  assert(isa<VarDecl>(Instantiation) && "Must be a VarDecl!");
667  if (isa<VarTemplateSpecializationDecl>(Instantiation)) {
668  Diag(PointOfInstantiation,
669  diag::err_explicit_instantiation_undefined_var_template)
670  << Instantiation;
671  Instantiation->setInvalidDecl();
672  } else
673  Diag(PointOfInstantiation,
674  diag::err_explicit_instantiation_undefined_member)
675  << /*static data member*/ 2 << Instantiation->getDeclName()
676  << Instantiation->getDeclContext();
677  Note = diag::note_explicit_instantiation_here;
678  }
679  }
680  if (Note) // Diagnostics were emitted.
681  Diag(Pattern->getLocation(), Note.getValue());
682 
683  // In general, Instantiation isn't marked invalid to get more than one
684  // error for multiple undefined instantiations. But the code that does
685  // explicit declaration -> explicit definition conversion can't handle
686  // invalid declarations, so mark as invalid in that case.
688  Instantiation->setInvalidDecl();
689  return true;
690 }
691 
692 /// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
693 /// that the template parameter 'PrevDecl' is being shadowed by a new
694 /// declaration at location Loc. Returns true to indicate that this is
695 /// an error, and false otherwise.
697  assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
698 
699  // Microsoft Visual C++ permits template parameters to be shadowed.
700  if (getLangOpts().MicrosoftExt)
701  return;
702 
703  // C++ [temp.local]p4:
704  // A template-parameter shall not be redeclared within its
705  // scope (including nested scopes).
706  Diag(Loc, diag::err_template_param_shadow)
707  << cast<NamedDecl>(PrevDecl)->getDeclName();
708  Diag(PrevDecl->getLocation(), diag::note_template_param_here);
709 }
710 
711 /// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
712 /// the parameter D to reference the templated declaration and return a pointer
713 /// to the template declaration. Otherwise, do nothing to D and return null.
715  if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
716  D = Temp->getTemplatedDecl();
717  return Temp;
718  }
719  return nullptr;
720 }
721 
723  SourceLocation EllipsisLoc) const {
724  assert(Kind == Template &&
725  "Only template template arguments can be pack expansions here");
726  assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
727  "Template template argument pack expansion without packs");
729  Result.EllipsisLoc = EllipsisLoc;
730  return Result;
731 }
732 
734  const ParsedTemplateArgument &Arg) {
735 
736  switch (Arg.getKind()) {
738  TypeSourceInfo *DI;
739  QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
740  if (!DI)
741  DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
742  return TemplateArgumentLoc(TemplateArgument(T), DI);
743  }
744 
746  Expr *E = static_cast<Expr *>(Arg.getAsExpr());
748  }
749 
751  TemplateName Template = Arg.getAsTemplate().get();
752  TemplateArgument TArg;
753  if (Arg.getEllipsisLoc().isValid())
754  TArg = TemplateArgument(Template, Optional<unsigned int>());
755  else
756  TArg = Template;
757  return TemplateArgumentLoc(TArg,
759  SemaRef.Context),
760  Arg.getLocation(),
761  Arg.getEllipsisLoc());
762  }
763  }
764 
765  llvm_unreachable("Unhandled parsed template argument");
766 }
767 
768 /// \brief Translates template arguments as provided by the parser
769 /// into template arguments used by semantic analysis.
771  TemplateArgumentListInfo &TemplateArgs) {
772  for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
773  TemplateArgs.addArgument(translateTemplateArgument(*this,
774  TemplateArgsIn[I]));
775 }
776 
778  SourceLocation Loc,
779  IdentifierInfo *Name) {
780  NamedDecl *PrevDecl = SemaRef.LookupSingleName(
782  if (PrevDecl && PrevDecl->isTemplateParameter())
783  SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
784 }
785 
786 /// ActOnTypeParameter - Called when a C++ template type parameter
787 /// (e.g., "typename T") has been parsed. Typename specifies whether
788 /// the keyword "typename" was used to declare the type parameter
789 /// (otherwise, "class" was used), and KeyLoc is the location of the
790 /// "class" or "typename" keyword. ParamName is the name of the
791 /// parameter (NULL indicates an unnamed template parameter) and
792 /// ParamNameLoc is the location of the parameter name (if any).
793 /// If the type parameter has a default argument, it will be added
794 /// later via ActOnTypeParameterDefault.
796  SourceLocation EllipsisLoc,
797  SourceLocation KeyLoc,
798  IdentifierInfo *ParamName,
799  SourceLocation ParamNameLoc,
800  unsigned Depth, unsigned Position,
801  SourceLocation EqualLoc,
802  ParsedType DefaultArg) {
803  assert(S->isTemplateParamScope() &&
804  "Template type parameter not in template parameter scope!");
805 
806  SourceLocation Loc = ParamNameLoc;
807  if (!ParamName)
808  Loc = KeyLoc;
809 
810  bool IsParameterPack = EllipsisLoc.isValid();
811  TemplateTypeParmDecl *Param
813  KeyLoc, Loc, Depth, Position, ParamName,
814  Typename, IsParameterPack);
815  Param->setAccess(AS_public);
816 
817  if (ParamName) {
818  maybeDiagnoseTemplateParameterShadow(*this, S, ParamNameLoc, ParamName);
819 
820  // Add the template parameter into the current scope.
821  S->AddDecl(Param);
822  IdResolver.AddDecl(Param);
823  }
824 
825  // C++0x [temp.param]p9:
826  // A default template-argument may be specified for any kind of
827  // template-parameter that is not a template parameter pack.
828  if (DefaultArg && IsParameterPack) {
829  Diag(EqualLoc, diag::err_template_param_pack_default_arg);
830  DefaultArg = nullptr;
831  }
832 
833  // Handle the default argument, if provided.
834  if (DefaultArg) {
835  TypeSourceInfo *DefaultTInfo;
836  GetTypeFromParser(DefaultArg, &DefaultTInfo);
837 
838  assert(DefaultTInfo && "expected source information for type");
839 
840  // Check for unexpanded parameter packs.
841  if (DiagnoseUnexpandedParameterPack(Loc, DefaultTInfo,
842  UPPC_DefaultArgument))
843  return Param;
844 
845  // Check the template argument itself.
846  if (CheckTemplateArgument(Param, DefaultTInfo)) {
847  Param->setInvalidDecl();
848  return Param;
849  }
850 
851  Param->setDefaultArgument(DefaultTInfo);
852  }
853 
854  return Param;
855 }
856 
857 /// \brief Check that the type of a non-type template parameter is
858 /// well-formed.
859 ///
860 /// \returns the (possibly-promoted) parameter type if valid;
861 /// otherwise, produces a diagnostic and returns a NULL type.
863  SourceLocation Loc) {
864  if (TSI->getType()->isUndeducedType()) {
865  // C++1z [temp.dep.expr]p3:
866  // An id-expression is type-dependent if it contains
867  // - an identifier associated by name lookup with a non-type
868  // template-parameter declared with a type that contains a
869  // placeholder type (7.1.7.4),
870  TSI = SubstAutoTypeSourceInfo(TSI, Context.DependentTy);
871  }
872 
873  return CheckNonTypeTemplateParameterType(TSI->getType(), Loc);
874 }
875 
877  SourceLocation Loc) {
878  // We don't allow variably-modified types as the type of non-type template
879  // parameters.
880  if (T->isVariablyModifiedType()) {
881  Diag(Loc, diag::err_variably_modified_nontype_template_param)
882  << T;
883  return QualType();
884  }
885 
886  // C++ [temp.param]p4:
887  //
888  // A non-type template-parameter shall have one of the following
889  // (optionally cv-qualified) types:
890  //
891  // -- integral or enumeration type,
892  if (T->isIntegralOrEnumerationType() ||
893  // -- pointer to object or pointer to function,
894  T->isPointerType() ||
895  // -- reference to object or reference to function,
896  T->isReferenceType() ||
897  // -- pointer to member,
898  T->isMemberPointerType() ||
899  // -- std::nullptr_t.
900  T->isNullPtrType() ||
901  // If T is a dependent type, we can't do the check now, so we
902  // assume that it is well-formed.
903  T->isDependentType() ||
904  // Allow use of auto in template parameter declarations.
905  T->isUndeducedType()) {
906  // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
907  // are ignored when determining its type.
908  return T.getUnqualifiedType();
909  }
910 
911  // C++ [temp.param]p8:
912  //
913  // A non-type template-parameter of type "array of T" or
914  // "function returning T" is adjusted to be of type "pointer to
915  // T" or "pointer to function returning T", respectively.
916  else if (T->isArrayType() || T->isFunctionType())
917  return Context.getDecayedType(T);
918 
919  Diag(Loc, diag::err_template_nontype_parm_bad_type)
920  << T;
921 
922  return QualType();
923 }
924 
926  unsigned Depth,
927  unsigned Position,
928  SourceLocation EqualLoc,
929  Expr *Default) {
930  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
931 
932  if (TInfo->getType()->isUndeducedType()) {
934  diag::warn_cxx14_compat_template_nontype_parm_auto_type)
935  << QualType(TInfo->getType()->getContainedAutoType(), 0);
936  }
937 
938  assert(S->isTemplateParamScope() &&
939  "Non-type template parameter not in template parameter scope!");
940  bool Invalid = false;
941 
942  QualType T = CheckNonTypeTemplateParameterType(TInfo, D.getIdentifierLoc());
943  if (T.isNull()) {
944  T = Context.IntTy; // Recover with an 'int' type.
945  Invalid = true;
946  }
947 
948  IdentifierInfo *ParamName = D.getIdentifier();
949  bool IsParameterPack = D.hasEllipsis();
952  D.getLocStart(),
953  D.getIdentifierLoc(),
954  Depth, Position, ParamName, T,
955  IsParameterPack, TInfo);
956  Param->setAccess(AS_public);
957 
958  if (Invalid)
959  Param->setInvalidDecl();
960 
961  if (ParamName) {
963  ParamName);
964 
965  // Add the template parameter into the current scope.
966  S->AddDecl(Param);
967  IdResolver.AddDecl(Param);
968  }
969 
970  // C++0x [temp.param]p9:
971  // A default template-argument may be specified for any kind of
972  // template-parameter that is not a template parameter pack.
973  if (Default && IsParameterPack) {
974  Diag(EqualLoc, diag::err_template_param_pack_default_arg);
975  Default = nullptr;
976  }
977 
978  // Check the well-formedness of the default template argument, if provided.
979  if (Default) {
980  // Check for unexpanded parameter packs.
981  if (DiagnoseUnexpandedParameterPack(Default, UPPC_DefaultArgument))
982  return Param;
983 
984  TemplateArgument Converted;
985  ExprResult DefaultRes =
986  CheckTemplateArgument(Param, Param->getType(), Default, Converted);
987  if (DefaultRes.isInvalid()) {
988  Param->setInvalidDecl();
989  return Param;
990  }
991  Default = DefaultRes.get();
992 
993  Param->setDefaultArgument(Default);
994  }
995 
996  return Param;
997 }
998 
999 /// ActOnTemplateTemplateParameter - Called when a C++ template template
1000 /// parameter (e.g. T in template <template <typename> class T> class array)
1001 /// has been parsed. S is the current scope.
1003  SourceLocation TmpLoc,
1004  TemplateParameterList *Params,
1005  SourceLocation EllipsisLoc,
1007  SourceLocation NameLoc,
1008  unsigned Depth,
1009  unsigned Position,
1010  SourceLocation EqualLoc,
1012  assert(S->isTemplateParamScope() &&
1013  "Template template parameter not in template parameter scope!");
1014 
1015  // Construct the parameter object.
1016  bool IsParameterPack = EllipsisLoc.isValid();
1017  TemplateTemplateParmDecl *Param =
1019  NameLoc.isInvalid()? TmpLoc : NameLoc,
1020  Depth, Position, IsParameterPack,
1021  Name, Params);
1022  Param->setAccess(AS_public);
1023 
1024  // If the template template parameter has a name, then link the identifier
1025  // into the scope and lookup mechanisms.
1026  if (Name) {
1027  maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name);
1028 
1029  S->AddDecl(Param);
1030  IdResolver.AddDecl(Param);
1031  }
1032 
1033  if (Params->size() == 0) {
1034  Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
1035  << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
1036  Param->setInvalidDecl();
1037  }
1038 
1039  // C++0x [temp.param]p9:
1040  // A default template-argument may be specified for any kind of
1041  // template-parameter that is not a template parameter pack.
1042  if (IsParameterPack && !Default.isInvalid()) {
1043  Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1044  Default = ParsedTemplateArgument();
1045  }
1046 
1047  if (!Default.isInvalid()) {
1048  // Check only that we have a template template argument. We don't want to
1049  // try to check well-formedness now, because our template template parameter
1050  // might have dependent types in its template parameters, which we wouldn't
1051  // be able to match now.
1052  //
1053  // If none of the template template parameter's template arguments mention
1054  // other template parameters, we could actually perform more checking here.
1055  // However, it isn't worth doing.
1056  TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
1057  if (DefaultArg.getArgument().getAsTemplate().isNull()) {
1058  Diag(DefaultArg.getLocation(), diag::err_template_arg_not_valid_template)
1059  << DefaultArg.getSourceRange();
1060  return Param;
1061  }
1062 
1063  // Check for unexpanded parameter packs.
1064  if (DiagnoseUnexpandedParameterPack(DefaultArg.getLocation(),
1065  DefaultArg.getArgument().getAsTemplate(),
1066  UPPC_DefaultArgument))
1067  return Param;
1068 
1069  Param->setDefaultArgument(Context, DefaultArg);
1070  }
1071 
1072  return Param;
1073 }
1074 
1075 /// ActOnTemplateParameterList - Builds a TemplateParameterList, optionally
1076 /// constrained by RequiresClause, that contains the template parameters in
1077 /// Params.
1080  SourceLocation ExportLoc,
1081  SourceLocation TemplateLoc,
1082  SourceLocation LAngleLoc,
1083  ArrayRef<Decl *> Params,
1084  SourceLocation RAngleLoc,
1085  Expr *RequiresClause) {
1086  if (ExportLoc.isValid())
1087  Diag(ExportLoc, diag::warn_template_export_unsupported);
1088 
1090  Context, TemplateLoc, LAngleLoc,
1091  llvm::makeArrayRef((NamedDecl *const *)Params.data(), Params.size()),
1092  RAngleLoc, RequiresClause);
1093 }
1094 
1095 static void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS) {
1096  if (SS.isSet())
1098 }
1099 
1100 DeclResult
1101 Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
1102  SourceLocation KWLoc, CXXScopeSpec &SS,
1105  TemplateParameterList *TemplateParams,
1106  AccessSpecifier AS, SourceLocation ModulePrivateLoc,
1107  SourceLocation FriendLoc,
1108  unsigned NumOuterTemplateParamLists,
1109  TemplateParameterList** OuterTemplateParamLists,
1110  SkipBodyInfo *SkipBody) {
1111  assert(TemplateParams && TemplateParams->size() > 0 &&
1112  "No template parameters");
1113  assert(TUK != TUK_Reference && "Can only declare or define class templates");
1114  bool Invalid = false;
1115 
1116  // Check that we can declare a template here.
1117  if (CheckTemplateDeclScope(S, TemplateParams))
1118  return true;
1119 
1121  assert(Kind != TTK_Enum && "can't build template of enumerated type");
1122 
1123  // There is no such thing as an unnamed class template.
1124  if (!Name) {
1125  Diag(KWLoc, diag::err_template_unnamed_class);
1126  return true;
1127  }
1128 
1129  // Find any previous declaration with this name. For a friend with no
1130  // scope explicitly specified, we only look for tag declarations (per
1131  // C++11 [basic.lookup.elab]p2).
1132  DeclContext *SemanticContext;
1133  LookupResult Previous(*this, Name, NameLoc,
1134  (SS.isEmpty() && TUK == TUK_Friend)
1135  ? LookupTagName : LookupOrdinaryName,
1136  ForRedeclaration);
1137  if (SS.isNotEmpty() && !SS.isInvalid()) {
1138  SemanticContext = computeDeclContext(SS, true);
1139  if (!SemanticContext) {
1140  // FIXME: Horrible, horrible hack! We can't currently represent this
1141  // in the AST, and historically we have just ignored such friend
1142  // class templates, so don't complain here.
1143  Diag(NameLoc, TUK == TUK_Friend
1144  ? diag::warn_template_qualified_friend_ignored
1145  : diag::err_template_qualified_declarator_no_match)
1146  << SS.getScopeRep() << SS.getRange();
1147  return TUK != TUK_Friend;
1148  }
1149 
1150  if (RequireCompleteDeclContext(SS, SemanticContext))
1151  return true;
1152 
1153  // If we're adding a template to a dependent context, we may need to
1154  // rebuilding some of the types used within the template parameter list,
1155  // now that we know what the current instantiation is.
1156  if (SemanticContext->isDependentContext()) {
1157  ContextRAII SavedContext(*this, SemanticContext);
1158  if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
1159  Invalid = true;
1160  } else if (TUK != TUK_Friend && TUK != TUK_Reference)
1161  diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc);
1162 
1163  LookupQualifiedName(Previous, SemanticContext);
1164  } else {
1165  SemanticContext = CurContext;
1166 
1167  // C++14 [class.mem]p14:
1168  // If T is the name of a class, then each of the following shall have a
1169  // name different from T:
1170  // -- every member template of class T
1171  if (TUK != TUK_Friend &&
1172  DiagnoseClassNameShadow(SemanticContext,
1173  DeclarationNameInfo(Name, NameLoc)))
1174  return true;
1175 
1176  LookupName(Previous, S);
1177  }
1178 
1179  if (Previous.isAmbiguous())
1180  return true;
1181 
1182  NamedDecl *PrevDecl = nullptr;
1183  if (Previous.begin() != Previous.end())
1184  PrevDecl = (*Previous.begin())->getUnderlyingDecl();
1185 
1186  if (PrevDecl && PrevDecl->isTemplateParameter()) {
1187  // Maybe we will complain about the shadowed template parameter.
1188  DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
1189  // Just pretend that we didn't see the previous declaration.
1190  PrevDecl = nullptr;
1191  }
1192 
1193  // If there is a previous declaration with the same name, check
1194  // whether this is a valid redeclaration.
1195  ClassTemplateDecl *PrevClassTemplate
1196  = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
1197 
1198  // We may have found the injected-class-name of a class template,
1199  // class template partial specialization, or class template specialization.
1200  // In these cases, grab the template that is being defined or specialized.
1201  if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
1202  cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
1203  PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
1204  PrevClassTemplate
1205  = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
1206  if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
1207  PrevClassTemplate
1208  = cast<ClassTemplateSpecializationDecl>(PrevDecl)
1209  ->getSpecializedTemplate();
1210  }
1211  }
1212 
1213  if (TUK == TUK_Friend) {
1214  // C++ [namespace.memdef]p3:
1215  // [...] When looking for a prior declaration of a class or a function
1216  // declared as a friend, and when the name of the friend class or
1217  // function is neither a qualified name nor a template-id, scopes outside
1218  // the innermost enclosing namespace scope are not considered.
1219  if (!SS.isSet()) {
1220  DeclContext *OutermostContext = CurContext;
1221  while (!OutermostContext->isFileContext())
1222  OutermostContext = OutermostContext->getLookupParent();
1223 
1224  if (PrevDecl &&
1225  (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
1226  OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
1227  SemanticContext = PrevDecl->getDeclContext();
1228  } else {
1229  // Declarations in outer scopes don't matter. However, the outermost
1230  // context we computed is the semantic context for our new
1231  // declaration.
1232  PrevDecl = PrevClassTemplate = nullptr;
1233  SemanticContext = OutermostContext;
1234 
1235  // Check that the chosen semantic context doesn't already contain a
1236  // declaration of this name as a non-tag type.
1237  Previous.clear(LookupOrdinaryName);
1238  DeclContext *LookupContext = SemanticContext;
1239  while (LookupContext->isTransparentContext())
1240  LookupContext = LookupContext->getLookupParent();
1241  LookupQualifiedName(Previous, LookupContext);
1242 
1243  if (Previous.isAmbiguous())
1244  return true;
1245 
1246  if (Previous.begin() != Previous.end())
1247  PrevDecl = (*Previous.begin())->getUnderlyingDecl();
1248  }
1249  }
1250  } else if (PrevDecl &&
1251  !isDeclInScope(Previous.getRepresentativeDecl(), SemanticContext,
1252  S, SS.isValid()))
1253  PrevDecl = PrevClassTemplate = nullptr;
1254 
1255  if (auto *Shadow = dyn_cast_or_null<UsingShadowDecl>(
1256  PrevDecl ? Previous.getRepresentativeDecl() : nullptr)) {
1257  if (SS.isEmpty() &&
1258  !(PrevClassTemplate &&
1259  PrevClassTemplate->getDeclContext()->getRedeclContext()->Equals(
1260  SemanticContext->getRedeclContext()))) {
1261  Diag(KWLoc, diag::err_using_decl_conflict_reverse);
1262  Diag(Shadow->getTargetDecl()->getLocation(),
1263  diag::note_using_decl_target);
1264  Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
1265  // Recover by ignoring the old declaration.
1266  PrevDecl = PrevClassTemplate = nullptr;
1267  }
1268  }
1269 
1270  // TODO Memory management; associated constraints are not always stored.
1271  Expr *const CurAC = formAssociatedConstraints(TemplateParams, nullptr);
1272 
1273  if (PrevClassTemplate) {
1274  // Ensure that the template parameter lists are compatible. Skip this check
1275  // for a friend in a dependent context: the template parameter list itself
1276  // could be dependent.
1277  if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
1278  !TemplateParameterListsAreEqual(TemplateParams,
1279  PrevClassTemplate->getTemplateParameters(),
1280  /*Complain=*/true,
1281  TPL_TemplateMatch))
1282  return true;
1283 
1284  // Check for matching associated constraints on redeclarations.
1285  const Expr *const PrevAC = PrevClassTemplate->getAssociatedConstraints();
1286  const bool RedeclACMismatch = [&] {
1287  if (!(CurAC || PrevAC))
1288  return false; // Nothing to check; no mismatch.
1289  if (CurAC && PrevAC) {
1290  llvm::FoldingSetNodeID CurACInfo, PrevACInfo;
1291  CurAC->Profile(CurACInfo, Context, /*Canonical=*/true);
1292  PrevAC->Profile(PrevACInfo, Context, /*Canonical=*/true);
1293  if (CurACInfo == PrevACInfo)
1294  return false; // All good; no mismatch.
1295  }
1296  return true;
1297  }();
1298 
1299  if (RedeclACMismatch) {
1300  Diag(CurAC ? CurAC->getLocStart() : NameLoc,
1301  diag::err_template_different_associated_constraints);
1302  Diag(PrevAC ? PrevAC->getLocStart() : PrevClassTemplate->getLocation(),
1303  diag::note_template_prev_declaration) << /*declaration*/0;
1304  return true;
1305  }
1306 
1307  // C++ [temp.class]p4:
1308  // In a redeclaration, partial specialization, explicit
1309  // specialization or explicit instantiation of a class template,
1310  // the class-key shall agree in kind with the original class
1311  // template declaration (7.1.5.3).
1312  RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
1313  if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind,
1314  TUK == TUK_Definition, KWLoc, Name)) {
1315  Diag(KWLoc, diag::err_use_with_wrong_tag)
1316  << Name
1317  << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
1318  Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
1319  Kind = PrevRecordDecl->getTagKind();
1320  }
1321 
1322  // Check for redefinition of this class template.
1323  if (TUK == TUK_Definition) {
1324  if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
1325  // If we have a prior definition that is not visible, treat this as
1326  // simply making that previous definition visible.
1327  NamedDecl *Hidden = nullptr;
1328  if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
1329  SkipBody->ShouldSkip = true;
1330  auto *Tmpl = cast<CXXRecordDecl>(Hidden)->getDescribedClassTemplate();
1331  assert(Tmpl && "original definition of a class template is not a "
1332  "class template?");
1333  makeMergedDefinitionVisible(Hidden);
1334  makeMergedDefinitionVisible(Tmpl);
1335  return Def;
1336  }
1337 
1338  Diag(NameLoc, diag::err_redefinition) << Name;
1339  Diag(Def->getLocation(), diag::note_previous_definition);
1340  // FIXME: Would it make sense to try to "forget" the previous
1341  // definition, as part of error recovery?
1342  return true;
1343  }
1344  }
1345  } else if (PrevDecl) {
1346  // C++ [temp]p5:
1347  // A class template shall not have the same name as any other
1348  // template, class, function, object, enumeration, enumerator,
1349  // namespace, or type in the same scope (3.3), except as specified
1350  // in (14.5.4).
1351  Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
1352  Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1353  return true;
1354  }
1355 
1356  // Check the template parameter list of this declaration, possibly
1357  // merging in the template parameter list from the previous class
1358  // template declaration. Skip this check for a friend in a dependent
1359  // context, because the template parameter list might be dependent.
1360  if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
1361  CheckTemplateParameterList(
1362  TemplateParams,
1363  PrevClassTemplate ? PrevClassTemplate->getTemplateParameters()
1364  : nullptr,
1365  (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
1366  SemanticContext->isDependentContext())
1367  ? TPC_ClassTemplateMember
1368  : TUK == TUK_Friend ? TPC_FriendClassTemplate
1369  : TPC_ClassTemplate))
1370  Invalid = true;
1371 
1372  if (SS.isSet()) {
1373  // If the name of the template was qualified, we must be defining the
1374  // template out-of-line.
1375  if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
1376  Diag(NameLoc, TUK == TUK_Friend ? diag::err_friend_decl_does_not_match
1377  : diag::err_member_decl_does_not_match)
1378  << Name << SemanticContext << /*IsDefinition*/true << SS.getRange();
1379  Invalid = true;
1380  }
1381  }
1382 
1383  // If this is a templated friend in a dependent context we should not put it
1384  // on the redecl chain. In some cases, the templated friend can be the most
1385  // recent declaration tricking the template instantiator to make substitutions
1386  // there.
1387  // FIXME: Figure out how to combine with shouldLinkDependentDeclWithPrevious
1388  bool ShouldAddRedecl
1389  = !(TUK == TUK_Friend && CurContext->isDependentContext());
1390 
1391  CXXRecordDecl *NewClass =
1392  CXXRecordDecl::Create(Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
1393  PrevClassTemplate && ShouldAddRedecl ?
1394  PrevClassTemplate->getTemplatedDecl() : nullptr,
1395  /*DelayTypeCreation=*/true);
1396  SetNestedNameSpecifier(NewClass, SS);
1397  if (NumOuterTemplateParamLists > 0)
1399  Context, llvm::makeArrayRef(OuterTemplateParamLists,
1400  NumOuterTemplateParamLists));
1401 
1402  // Add alignment attributes if necessary; these attributes are checked when
1403  // the ASTContext lays out the structure.
1404  if (TUK == TUK_Definition) {
1405  AddAlignmentAttributesForRecord(NewClass);
1406  AddMsStructLayoutForRecord(NewClass);
1407  }
1408 
1409  // Attach the associated constraints when the declaration will not be part of
1410  // a decl chain.
1411  Expr *const ACtoAttach =
1412  PrevClassTemplate && ShouldAddRedecl ? nullptr : CurAC;
1413 
1414  ClassTemplateDecl *NewTemplate
1415  = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
1416  DeclarationName(Name), TemplateParams,
1417  NewClass, ACtoAttach);
1418 
1419  if (ShouldAddRedecl)
1420  NewTemplate->setPreviousDecl(PrevClassTemplate);
1421 
1422  NewClass->setDescribedClassTemplate(NewTemplate);
1423 
1424  if (ModulePrivateLoc.isValid())
1425  NewTemplate->setModulePrivate();
1426 
1427  // Build the type for the class template declaration now.
1428  QualType T = NewTemplate->getInjectedClassNameSpecialization();
1429  T = Context.getInjectedClassNameType(NewClass, T);
1430  assert(T->isDependentType() && "Class template type is not dependent?");
1431  (void)T;
1432 
1433  // If we are providing an explicit specialization of a member that is a
1434  // class template, make a note of that.
1435  if (PrevClassTemplate &&
1436  PrevClassTemplate->getInstantiatedFromMemberTemplate())
1437  PrevClassTemplate->setMemberSpecialization();
1438 
1439  // Set the access specifier.
1440  if (!Invalid && TUK != TUK_Friend && NewTemplate->getDeclContext()->isRecord())
1441  SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
1442 
1443  // Set the lexical context of these templates
1444  NewClass->setLexicalDeclContext(CurContext);
1445  NewTemplate->setLexicalDeclContext(CurContext);
1446 
1447  if (TUK == TUK_Definition)
1448  NewClass->startDefinition();
1449 
1450  if (Attr)
1451  ProcessDeclAttributeList(S, NewClass, Attr);
1452 
1453  if (PrevClassTemplate)
1454  mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
1455 
1456  AddPushedVisibilityAttribute(NewClass);
1457 
1458  if (TUK != TUK_Friend) {
1459  // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
1460  Scope *Outer = S;
1461  while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
1462  Outer = Outer->getParent();
1463  PushOnScopeChains(NewTemplate, Outer);
1464  } else {
1465  if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
1466  NewTemplate->setAccess(PrevClassTemplate->getAccess());
1467  NewClass->setAccess(PrevClassTemplate->getAccess());
1468  }
1469 
1470  NewTemplate->setObjectOfFriendDecl();
1471 
1472  // Friend templates are visible in fairly strange ways.
1473  if (!CurContext->isDependentContext()) {
1474  DeclContext *DC = SemanticContext->getRedeclContext();
1475  DC->makeDeclVisibleInContext(NewTemplate);
1476  if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
1477  PushOnScopeChains(NewTemplate, EnclosingScope,
1478  /* AddToContext = */ false);
1479  }
1480 
1481  FriendDecl *Friend = FriendDecl::Create(
1482  Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc);
1483  Friend->setAccess(AS_public);
1484  CurContext->addDecl(Friend);
1485  }
1486 
1487  if (Invalid) {
1488  NewTemplate->setInvalidDecl();
1489  NewClass->setInvalidDecl();
1490  }
1491 
1492  ActOnDocumentableDecl(NewTemplate);
1493 
1494  return NewTemplate;
1495 }
1496 
1497 namespace {
1498 /// Transform to convert portions of a constructor declaration into the
1499 /// corresponding deduction guide, per C++1z [over.match.class.deduct]p1.
1500 struct ConvertConstructorToDeductionGuideTransform {
1501  ConvertConstructorToDeductionGuideTransform(Sema &S,
1502  ClassTemplateDecl *Template)
1503  : SemaRef(S), Template(Template) {}
1504 
1505  Sema &SemaRef;
1506  ClassTemplateDecl *Template;
1507 
1508  DeclContext *DC = Template->getDeclContext();
1509  CXXRecordDecl *Primary = Template->getTemplatedDecl();
1510  DeclarationName DeductionGuideName =
1511  SemaRef.Context.DeclarationNames.getCXXDeductionGuideName(Template);
1512 
1513  QualType DeducedType = SemaRef.Context.getTypeDeclType(Primary);
1514 
1515  // Index adjustment to apply to convert depth-1 template parameters into
1516  // depth-0 template parameters.
1517  unsigned Depth1IndexAdjustment = Template->getTemplateParameters()->size();
1518 
1519  /// Transform a constructor declaration into a deduction guide.
1520  NamedDecl *transformConstructor(FunctionTemplateDecl *FTD,
1521  CXXConstructorDecl *CD) {
1523 
1524  LocalInstantiationScope Scope(SemaRef);
1525 
1526  // C++ [over.match.class.deduct]p1:
1527  // -- For each constructor of the class template designated by the
1528  // template-name, a function template with the following properties:
1529 
1530  // -- The template parameters are the template parameters of the class
1531  // template followed by the template parameters (including default
1532  // template arguments) of the constructor, if any.
1533  TemplateParameterList *TemplateParams = Template->getTemplateParameters();
1534  if (FTD) {
1535  TemplateParameterList *InnerParams = FTD->getTemplateParameters();
1536  SmallVector<NamedDecl *, 16> AllParams;
1537  AllParams.reserve(TemplateParams->size() + InnerParams->size());
1538  AllParams.insert(AllParams.begin(),
1539  TemplateParams->begin(), TemplateParams->end());
1540  SubstArgs.reserve(InnerParams->size());
1541 
1542  // Later template parameters could refer to earlier ones, so build up
1543  // a list of substituted template arguments as we go.
1544  for (NamedDecl *Param : *InnerParams) {
1546  Args.addOuterTemplateArguments(SubstArgs);
1547  Args.addOuterRetainedLevel();
1548  NamedDecl *NewParam = transformTemplateParameter(Param, Args);
1549  if (!NewParam)
1550  return nullptr;
1551  AllParams.push_back(NewParam);
1552  SubstArgs.push_back(SemaRef.Context.getCanonicalTemplateArgument(
1553  SemaRef.Context.getInjectedTemplateArg(NewParam)));
1554  }
1555  TemplateParams = TemplateParameterList::Create(
1556  SemaRef.Context, InnerParams->getTemplateLoc(),
1557  InnerParams->getLAngleLoc(), AllParams, InnerParams->getRAngleLoc(),
1558  /*FIXME: RequiresClause*/ nullptr);
1559  }
1560 
1561  // If we built a new template-parameter-list, track that we need to
1562  // substitute references to the old parameters into references to the
1563  // new ones.
1565  if (FTD) {
1566  Args.addOuterTemplateArguments(SubstArgs);
1567  Args.addOuterRetainedLevel();
1568  }
1569 
1572  assert(FPTL && "no prototype for constructor declaration");
1573 
1574  // Transform the type of the function, adjusting the return type and
1575  // replacing references to the old parameters with references to the
1576  // new ones.
1577  TypeLocBuilder TLB;
1579  QualType NewType = transformFunctionProtoType(TLB, FPTL, Params, Args);
1580  if (NewType.isNull())
1581  return nullptr;
1582  TypeSourceInfo *NewTInfo = TLB.getTypeSourceInfo(SemaRef.Context, NewType);
1583 
1584  return buildDeductionGuide(TemplateParams, CD->isExplicit(), NewTInfo,
1585  CD->getLocStart(), CD->getLocation(),
1586  CD->getLocEnd());
1587  }
1588 
1589  /// Build a deduction guide with the specified parameter types.
1590  NamedDecl *buildSimpleDeductionGuide(MutableArrayRef<QualType> ParamTypes) {
1591  SourceLocation Loc = Template->getLocation();
1592 
1593  // Build the requested type.
1595  EPI.HasTrailingReturn = true;
1596  QualType Result = SemaRef.BuildFunctionType(DeducedType, ParamTypes, Loc,
1597  DeductionGuideName, EPI);
1598  TypeSourceInfo *TSI = SemaRef.Context.getTrivialTypeSourceInfo(Result, Loc);
1599 
1600  FunctionProtoTypeLoc FPTL =
1602 
1603  // Build the parameters, needed during deduction / substitution.
1605  for (auto T : ParamTypes) {
1606  ParmVarDecl *NewParam = ParmVarDecl::Create(
1607  SemaRef.Context, DC, Loc, Loc, nullptr, T,
1608  SemaRef.Context.getTrivialTypeSourceInfo(T, Loc), SC_None, nullptr);
1609  NewParam->setScopeInfo(0, Params.size());
1610  FPTL.setParam(Params.size(), NewParam);
1611  Params.push_back(NewParam);
1612  }
1613 
1614  return buildDeductionGuide(Template->getTemplateParameters(), false, TSI,
1615  Loc, Loc, Loc);
1616  }
1617 
1618 private:
1619  /// Transform a constructor template parameter into a deduction guide template
1620  /// parameter, rebuilding any internal references to earlier parameters and
1621  /// renumbering as we go.
1622  NamedDecl *transformTemplateParameter(NamedDecl *TemplateParam,
1624  if (auto *TTP = dyn_cast<TemplateTypeParmDecl>(TemplateParam)) {
1625  // TemplateTypeParmDecl's index cannot be changed after creation, so
1626  // substitute it directly.
1627  auto *NewTTP = TemplateTypeParmDecl::Create(
1628  SemaRef.Context, DC, TTP->getLocStart(), TTP->getLocation(),
1629  /*Depth*/0, Depth1IndexAdjustment + TTP->getIndex(),
1630  TTP->getIdentifier(), TTP->wasDeclaredWithTypename(),
1631  TTP->isParameterPack());
1632  if (TTP->hasDefaultArgument()) {
1633  TypeSourceInfo *InstantiatedDefaultArg =
1634  SemaRef.SubstType(TTP->getDefaultArgumentInfo(), Args,
1635  TTP->getDefaultArgumentLoc(), TTP->getDeclName());
1636  if (InstantiatedDefaultArg)
1637  NewTTP->setDefaultArgument(InstantiatedDefaultArg);
1638  }
1639  SemaRef.CurrentInstantiationScope->InstantiatedLocal(TemplateParam,
1640  NewTTP);
1641  return NewTTP;
1642  }
1643 
1644  if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(TemplateParam))
1645  return transformTemplateParameterImpl(TTP, Args);
1646 
1647  return transformTemplateParameterImpl(
1648  cast<NonTypeTemplateParmDecl>(TemplateParam), Args);
1649  }
1650  template<typename TemplateParmDecl>
1651  TemplateParmDecl *
1652  transformTemplateParameterImpl(TemplateParmDecl *OldParam,
1654  // Ask the template instantiator to do the heavy lifting for us, then adjust
1655  // the index of the parameter once it's done.
1656  auto *NewParam =
1657  cast_or_null<TemplateParmDecl>(SemaRef.SubstDecl(OldParam, DC, Args));
1658  assert(NewParam->getDepth() == 0 && "unexpected template param depth");
1659  NewParam->setPosition(NewParam->getPosition() + Depth1IndexAdjustment);
1660  return NewParam;
1661  }
1662 
1663  QualType transformFunctionProtoType(TypeLocBuilder &TLB,
1667  SmallVector<QualType, 4> ParamTypes;
1668  const FunctionProtoType *T = TL.getTypePtr();
1669 
1670  // -- The types of the function parameters are those of the constructor.
1671  for (auto *OldParam : TL.getParams()) {
1672  ParmVarDecl *NewParam = transformFunctionTypeParam(OldParam, Args);
1673  if (!NewParam)
1674  return QualType();
1675  ParamTypes.push_back(NewParam->getType());
1676  Params.push_back(NewParam);
1677  }
1678 
1679  // -- The return type is the class template specialization designated by
1680  // the template-name and template arguments corresponding to the
1681  // template parameters obtained from the class template.
1682  //
1683  // We use the injected-class-name type of the primary template instead.
1684  // This has the convenient property that it is different from any type that
1685  // the user can write in a deduction-guide (because they cannot enter the
1686  // context of the template), so implicit deduction guides can never collide
1687  // with explicit ones.
1688  QualType ReturnType = DeducedType;
1689  TLB.pushTypeSpec(ReturnType).setNameLoc(Primary->getLocation());
1690 
1691  // Resolving a wording defect, we also inherit the variadicness of the
1692  // constructor.
1694  EPI.Variadic = T->isVariadic();
1695  EPI.HasTrailingReturn = true;
1696 
1697  QualType Result = SemaRef.BuildFunctionType(
1698  ReturnType, ParamTypes, TL.getLocStart(), DeductionGuideName, EPI);
1699  if (Result.isNull())
1700  return QualType();
1701 
1702  FunctionProtoTypeLoc NewTL = TLB.push<FunctionProtoTypeLoc>(Result);
1704  NewTL.setLParenLoc(TL.getLParenLoc());
1705  NewTL.setRParenLoc(TL.getRParenLoc());
1707  NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
1708  for (unsigned I = 0, E = NewTL.getNumParams(); I != E; ++I)
1709  NewTL.setParam(I, Params[I]);
1710 
1711  return Result;
1712  }
1713 
1714  ParmVarDecl *
1715  transformFunctionTypeParam(ParmVarDecl *OldParam,
1717  TypeSourceInfo *OldDI = OldParam->getTypeSourceInfo();
1718  TypeSourceInfo *NewDI;
1719  if (!Args.getNumLevels())
1720  NewDI = OldDI;
1721  else if (auto PackTL = OldDI->getTypeLoc().getAs<PackExpansionTypeLoc>()) {
1722  // Expand out the one and only element in each inner pack.
1723  Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, 0);
1724  NewDI =
1725  SemaRef.SubstType(PackTL.getPatternLoc(), Args,
1726  OldParam->getLocation(), OldParam->getDeclName());
1727  if (!NewDI) return nullptr;
1728  NewDI =
1729  SemaRef.CheckPackExpansion(NewDI, PackTL.getEllipsisLoc(),
1730  PackTL.getTypePtr()->getNumExpansions());
1731  } else
1732  NewDI = SemaRef.SubstType(OldDI, Args, OldParam->getLocation(),
1733  OldParam->getDeclName());
1734  if (!NewDI)
1735  return nullptr;
1736 
1737  // Canonicalize the type. This (for instance) replaces references to
1738  // typedef members of the current instantiations with the definitions of
1739  // those typedefs, avoiding triggering instantiation of the deduced type
1740  // during deduction.
1741  // FIXME: It would be preferable to retain type sugar and source
1742  // information here (and handle this in substitution instead).
1743  NewDI = SemaRef.Context.getTrivialTypeSourceInfo(
1744  SemaRef.Context.getCanonicalType(NewDI->getType()),
1745  OldParam->getLocation());
1746 
1747  // Resolving a wording defect, we also inherit default arguments from the
1748  // constructor.
1749  ExprResult NewDefArg;
1750  if (OldParam->hasDefaultArg()) {
1751  NewDefArg = Args.getNumLevels()
1752  ? SemaRef.SubstExpr(OldParam->getDefaultArg(), Args)
1753  : OldParam->getDefaultArg();
1754  if (NewDefArg.isInvalid())
1755  return nullptr;
1756  }
1757 
1758  ParmVarDecl *NewParam = ParmVarDecl::Create(SemaRef.Context, DC,
1759  OldParam->getInnerLocStart(),
1760  OldParam->getLocation(),
1761  OldParam->getIdentifier(),
1762  NewDI->getType(),
1763  NewDI,
1764  OldParam->getStorageClass(),
1765  NewDefArg.get());
1766  NewParam->setScopeInfo(OldParam->getFunctionScopeDepth(),
1767  OldParam->getFunctionScopeIndex());
1768  return NewParam;
1769  }
1770 
1771  NamedDecl *buildDeductionGuide(TemplateParameterList *TemplateParams,
1772  bool Explicit, TypeSourceInfo *TInfo,
1773  SourceLocation LocStart, SourceLocation Loc,
1774  SourceLocation LocEnd) {
1775  DeclarationNameInfo Name(DeductionGuideName, Loc);
1776  ArrayRef<ParmVarDecl *> Params =
1777  TInfo->getTypeLoc().castAs<FunctionProtoTypeLoc>().getParams();
1778 
1779  // Build the implicit deduction guide template.
1780  auto *Guide =
1781  CXXDeductionGuideDecl::Create(SemaRef.Context, DC, LocStart, Explicit,
1782  Name, TInfo->getType(), TInfo, LocEnd);
1783  Guide->setImplicit();
1784  Guide->setParams(Params);
1785 
1786  for (auto *Param : Params)
1787  Param->setDeclContext(Guide);
1788 
1789  auto *GuideTemplate = FunctionTemplateDecl::Create(
1790  SemaRef.Context, DC, Loc, DeductionGuideName, TemplateParams, Guide);
1791  GuideTemplate->setImplicit();
1792  Guide->setDescribedFunctionTemplate(GuideTemplate);
1793 
1794  if (isa<CXXRecordDecl>(DC)) {
1795  Guide->setAccess(AS_public);
1796  GuideTemplate->setAccess(AS_public);
1797  }
1798 
1799  DC->addDecl(GuideTemplate);
1800  return GuideTemplate;
1801  }
1802 };
1803 }
1804 
1806  SourceLocation Loc) {
1807  DeclContext *DC = Template->getDeclContext();
1808  if (DC->isDependentContext())
1809  return;
1810 
1811  ConvertConstructorToDeductionGuideTransform Transform(
1812  *this, cast<ClassTemplateDecl>(Template));
1813  if (!isCompleteType(Loc, Transform.DeducedType))
1814  return;
1815 
1816  // Check whether we've already declared deduction guides for this template.
1817  // FIXME: Consider storing a flag on the template to indicate this.
1818  auto Existing = DC->lookup(Transform.DeductionGuideName);
1819  for (auto *D : Existing)
1820  if (D->isImplicit())
1821  return;
1822 
1823  // In case we were expanding a pack when we attempted to declare deduction
1824  // guides, turn off pack expansion for everything we're about to do.
1825  ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
1826  // Create a template instantiation record to track the "instantiation" of
1827  // constructors into deduction guides.
1828  // FIXME: Add a kind for this to give more meaningful diagnostics. But can
1829  // this substitution process actually fail?
1830  InstantiatingTemplate BuildingDeductionGuides(*this, Loc, Template);
1831 
1832  // Convert declared constructors into deduction guide templates.
1833  // FIXME: Skip constructors for which deduction must necessarily fail (those
1834  // for which some class template parameter without a default argument never
1835  // appears in a deduced context).
1836  bool AddedAny = false;
1837  bool AddedCopyOrMove = false;
1838  for (NamedDecl *D : LookupConstructors(Transform.Primary)) {
1839  D = D->getUnderlyingDecl();
1840  if (D->isInvalidDecl() || D->isImplicit())
1841  continue;
1842  D = cast<NamedDecl>(D->getCanonicalDecl());
1843 
1844  auto *FTD = dyn_cast<FunctionTemplateDecl>(D);
1845  auto *CD =
1846  dyn_cast_or_null<CXXConstructorDecl>(FTD ? FTD->getTemplatedDecl() : D);
1847  // Class-scope explicit specializations (MS extension) do not result in
1848  // deduction guides.
1849  if (!CD || (!FTD && CD->isFunctionTemplateSpecialization()))
1850  continue;
1851 
1852  Transform.transformConstructor(FTD, CD);
1853  AddedAny = true;
1854 
1855  AddedCopyOrMove |= CD->isCopyOrMoveConstructor();
1856  }
1857 
1858  // Synthesize an X() -> X<...> guide if there were no declared constructors.
1859  // FIXME: The standard doesn't say (how) to do this.
1860  if (!AddedAny)
1861  Transform.buildSimpleDeductionGuide(None);
1862 
1863  // Synthesize an X(X<...>) -> X<...> guide if there was no declared constructor
1864  // resembling a copy or move constructor.
1865  // FIXME: The standard doesn't say (how) to do this.
1866  if (!AddedCopyOrMove)
1867  Transform.buildSimpleDeductionGuide(Transform.DeducedType);
1868 }
1869 
1870 /// \brief Diagnose the presence of a default template argument on a
1871 /// template parameter, which is ill-formed in certain contexts.
1872 ///
1873 /// \returns true if the default template argument should be dropped.
1876  SourceLocation ParamLoc,
1877  SourceRange DefArgRange) {
1878  switch (TPC) {
1880  case Sema::TPC_VarTemplate:
1882  return false;
1883 
1886  // C++ [temp.param]p9:
1887  // A default template-argument shall not be specified in a
1888  // function template declaration or a function template
1889  // definition [...]
1890  // If a friend function template declaration specifies a default
1891  // template-argument, that declaration shall be a definition and shall be
1892  // the only declaration of the function template in the translation unit.
1893  // (C++98/03 doesn't have this wording; see DR226).
1894  S.Diag(ParamLoc, S.getLangOpts().CPlusPlus11 ?
1895  diag::warn_cxx98_compat_template_parameter_default_in_function_template
1896  : diag::ext_template_parameter_default_in_function_template)
1897  << DefArgRange;
1898  return false;
1899 
1901  // C++0x [temp.param]p9:
1902  // A default template-argument shall not be specified in the
1903  // template-parameter-lists of the definition of a member of a
1904  // class template that appears outside of the member's class.
1905  S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
1906  << DefArgRange;
1907  return true;
1908 
1911  // C++ [temp.param]p9:
1912  // A default template-argument shall not be specified in a
1913  // friend template declaration.
1914  S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
1915  << DefArgRange;
1916  return true;
1917 
1918  // FIXME: C++0x [temp.param]p9 allows default template-arguments
1919  // for friend function templates if there is only a single
1920  // declaration (and it is a definition). Strange!
1921  }
1922 
1923  llvm_unreachable("Invalid TemplateParamListContext!");
1924 }
1925 
1926 /// \brief Check for unexpanded parameter packs within the template parameters
1927 /// of a template template parameter, recursively.
1929  TemplateTemplateParmDecl *TTP) {
1930  // A template template parameter which is a parameter pack is also a pack
1931  // expansion.
1932  if (TTP->isParameterPack())
1933  return false;
1934 
1936  for (unsigned I = 0, N = Params->size(); I != N; ++I) {
1937  NamedDecl *P = Params->getParam(I);
1938  if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
1939  if (!NTTP->isParameterPack() &&
1940  S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
1941  NTTP->getTypeSourceInfo(),
1943  return true;
1944 
1945  continue;
1946  }
1947 
1948  if (TemplateTemplateParmDecl *InnerTTP
1949  = dyn_cast<TemplateTemplateParmDecl>(P))
1950  if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
1951  return true;
1952  }
1953 
1954  return false;
1955 }
1956 
1957 /// \brief Checks the validity of a template parameter list, possibly
1958 /// considering the template parameter list from a previous
1959 /// declaration.
1960 ///
1961 /// If an "old" template parameter list is provided, it must be
1962 /// equivalent (per TemplateParameterListsAreEqual) to the "new"
1963 /// template parameter list.
1964 ///
1965 /// \param NewParams Template parameter list for a new template
1966 /// declaration. This template parameter list will be updated with any
1967 /// default arguments that are carried through from the previous
1968 /// template parameter list.
1969 ///
1970 /// \param OldParams If provided, template parameter list from a
1971 /// previous declaration of the same template. Default template
1972 /// arguments will be merged from the old template parameter list to
1973 /// the new template parameter list.
1974 ///
1975 /// \param TPC Describes the context in which we are checking the given
1976 /// template parameter list.
1977 ///
1978 /// \returns true if an error occurred, false otherwise.
1980  TemplateParameterList *OldParams,
1982  bool Invalid = false;
1983 
1984  // C++ [temp.param]p10:
1985  // The set of default template-arguments available for use with a
1986  // template declaration or definition is obtained by merging the
1987  // default arguments from the definition (if in scope) and all
1988  // declarations in scope in the same way default function
1989  // arguments are (8.3.6).
1990  bool SawDefaultArgument = false;
1991  SourceLocation PreviousDefaultArgLoc;
1992 
1993  // Dummy initialization to avoid warnings.
1994  TemplateParameterList::iterator OldParam = NewParams->end();
1995  if (OldParams)
1996  OldParam = OldParams->begin();
1997 
1998  bool RemoveDefaultArguments = false;
1999  for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2000  NewParamEnd = NewParams->end();
2001  NewParam != NewParamEnd; ++NewParam) {
2002  // Variables used to diagnose redundant default arguments
2003  bool RedundantDefaultArg = false;
2004  SourceLocation OldDefaultLoc;
2005  SourceLocation NewDefaultLoc;
2006 
2007  // Variable used to diagnose missing default arguments
2008  bool MissingDefaultArg = false;
2009 
2010  // Variable used to diagnose non-final parameter packs
2011  bool SawParameterPack = false;
2012 
2013  if (TemplateTypeParmDecl *NewTypeParm
2014  = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
2015  // Check the presence of a default argument here.
2016  if (NewTypeParm->hasDefaultArgument() &&
2018  NewTypeParm->getLocation(),
2019  NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
2020  .getSourceRange()))
2021  NewTypeParm->removeDefaultArgument();
2022 
2023  // Merge default arguments for template type parameters.
2024  TemplateTypeParmDecl *OldTypeParm
2025  = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr;
2026  if (NewTypeParm->isParameterPack()) {
2027  assert(!NewTypeParm->hasDefaultArgument() &&
2028  "Parameter packs can't have a default argument!");
2029  SawParameterPack = true;
2030  } else if (OldTypeParm && hasVisibleDefaultArgument(OldTypeParm) &&
2031  NewTypeParm->hasDefaultArgument()) {
2032  OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
2033  NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
2034  SawDefaultArgument = true;
2035  RedundantDefaultArg = true;
2036  PreviousDefaultArgLoc = NewDefaultLoc;
2037  } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
2038  // Merge the default argument from the old declaration to the
2039  // new declaration.
2040  NewTypeParm->setInheritedDefaultArgument(Context, OldTypeParm);
2041  PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
2042  } else if (NewTypeParm->hasDefaultArgument()) {
2043  SawDefaultArgument = true;
2044  PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
2045  } else if (SawDefaultArgument)
2046  MissingDefaultArg = true;
2047  } else if (NonTypeTemplateParmDecl *NewNonTypeParm
2048  = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
2049  // Check for unexpanded parameter packs.
2050  if (!NewNonTypeParm->isParameterPack() &&
2051  DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
2052  NewNonTypeParm->getTypeSourceInfo(),
2053  UPPC_NonTypeTemplateParameterType)) {
2054  Invalid = true;
2055  continue;
2056  }
2057 
2058  // Check the presence of a default argument here.
2059  if (NewNonTypeParm->hasDefaultArgument() &&
2061  NewNonTypeParm->getLocation(),
2062  NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
2063  NewNonTypeParm->removeDefaultArgument();
2064  }
2065 
2066  // Merge default arguments for non-type template parameters
2067  NonTypeTemplateParmDecl *OldNonTypeParm
2068  = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr;
2069  if (NewNonTypeParm->isParameterPack()) {
2070  assert(!NewNonTypeParm->hasDefaultArgument() &&
2071  "Parameter packs can't have a default argument!");
2072  if (!NewNonTypeParm->isPackExpansion())
2073  SawParameterPack = true;
2074  } else if (OldNonTypeParm && hasVisibleDefaultArgument(OldNonTypeParm) &&
2075  NewNonTypeParm->hasDefaultArgument()) {
2076  OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
2077  NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
2078  SawDefaultArgument = true;
2079  RedundantDefaultArg = true;
2080  PreviousDefaultArgLoc = NewDefaultLoc;
2081  } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
2082  // Merge the default argument from the old declaration to the
2083  // new declaration.
2084  NewNonTypeParm->setInheritedDefaultArgument(Context, OldNonTypeParm);
2085  PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
2086  } else if (NewNonTypeParm->hasDefaultArgument()) {
2087  SawDefaultArgument = true;
2088  PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
2089  } else if (SawDefaultArgument)
2090  MissingDefaultArg = true;
2091  } else {
2092  TemplateTemplateParmDecl *NewTemplateParm
2093  = cast<TemplateTemplateParmDecl>(*NewParam);
2094 
2095  // Check for unexpanded parameter packs, recursively.
2096  if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
2097  Invalid = true;
2098  continue;
2099  }
2100 
2101  // Check the presence of a default argument here.
2102  if (NewTemplateParm->hasDefaultArgument() &&
2104  NewTemplateParm->getLocation(),
2105  NewTemplateParm->getDefaultArgument().getSourceRange()))
2106  NewTemplateParm->removeDefaultArgument();
2107 
2108  // Merge default arguments for template template parameters
2109  TemplateTemplateParmDecl *OldTemplateParm
2110  = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr;
2111  if (NewTemplateParm->isParameterPack()) {
2112  assert(!NewTemplateParm->hasDefaultArgument() &&
2113  "Parameter packs can't have a default argument!");
2114  if (!NewTemplateParm->isPackExpansion())
2115  SawParameterPack = true;
2116  } else if (OldTemplateParm &&
2117  hasVisibleDefaultArgument(OldTemplateParm) &&
2118  NewTemplateParm->hasDefaultArgument()) {
2119  OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
2120  NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
2121  SawDefaultArgument = true;
2122  RedundantDefaultArg = true;
2123  PreviousDefaultArgLoc = NewDefaultLoc;
2124  } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
2125  // Merge the default argument from the old declaration to the
2126  // new declaration.
2127  NewTemplateParm->setInheritedDefaultArgument(Context, OldTemplateParm);
2128  PreviousDefaultArgLoc
2129  = OldTemplateParm->getDefaultArgument().getLocation();
2130  } else if (NewTemplateParm->hasDefaultArgument()) {
2131  SawDefaultArgument = true;
2132  PreviousDefaultArgLoc
2133  = NewTemplateParm->getDefaultArgument().getLocation();
2134  } else if (SawDefaultArgument)
2135  MissingDefaultArg = true;
2136  }
2137 
2138  // C++11 [temp.param]p11:
2139  // If a template parameter of a primary class template or alias template
2140  // is a template parameter pack, it shall be the last template parameter.
2141  if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
2142  (TPC == TPC_ClassTemplate || TPC == TPC_VarTemplate ||
2143  TPC == TPC_TypeAliasTemplate)) {
2144  Diag((*NewParam)->getLocation(),
2145  diag::err_template_param_pack_must_be_last_template_parameter);
2146  Invalid = true;
2147  }
2148 
2149  if (RedundantDefaultArg) {
2150  // C++ [temp.param]p12:
2151  // A template-parameter shall not be given default arguments
2152  // by two different declarations in the same scope.
2153  Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
2154  Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
2155  Invalid = true;
2156  } else if (MissingDefaultArg && TPC != TPC_FunctionTemplate) {
2157  // C++ [temp.param]p11:
2158  // If a template-parameter of a class template has a default
2159  // template-argument, each subsequent template-parameter shall either
2160  // have a default template-argument supplied or be a template parameter
2161  // pack.
2162  Diag((*NewParam)->getLocation(),
2163  diag::err_template_param_default_arg_missing);
2164  Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
2165  Invalid = true;
2166  RemoveDefaultArguments = true;
2167  }
2168 
2169  // If we have an old template parameter list that we're merging
2170  // in, move on to the next parameter.
2171  if (OldParams)
2172  ++OldParam;
2173  }
2174 
2175  // We were missing some default arguments at the end of the list, so remove
2176  // all of the default arguments.
2177  if (RemoveDefaultArguments) {
2178  for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2179  NewParamEnd = NewParams->end();
2180  NewParam != NewParamEnd; ++NewParam) {
2181  if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
2182  TTP->removeDefaultArgument();
2183  else if (NonTypeTemplateParmDecl *NTTP
2184  = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
2185  NTTP->removeDefaultArgument();
2186  else
2187  cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
2188  }
2189  }
2190 
2191  return Invalid;
2192 }
2193 
2194 namespace {
2195 
2196 /// A class which looks for a use of a certain level of template
2197 /// parameter.
2198 struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
2200 
2201  unsigned Depth;
2202 
2203  // Whether we're looking for a use of a template parameter that makes the
2204  // overall construct type-dependent / a dependent type. This is strictly
2205  // best-effort for now; we may fail to match at all for a dependent type
2206  // in some cases if this is set.
2207  bool IgnoreNonTypeDependent;
2208 
2209  bool Match;
2210  SourceLocation MatchLoc;
2211 
2212  DependencyChecker(unsigned Depth, bool IgnoreNonTypeDependent)
2213  : Depth(Depth), IgnoreNonTypeDependent(IgnoreNonTypeDependent),
2214  Match(false) {}
2215 
2216  DependencyChecker(TemplateParameterList *Params, bool IgnoreNonTypeDependent)
2217  : IgnoreNonTypeDependent(IgnoreNonTypeDependent), Match(false) {
2218  NamedDecl *ND = Params->getParam(0);
2219  if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
2220  Depth = PD->getDepth();
2221  } else if (NonTypeTemplateParmDecl *PD =
2222  dyn_cast<NonTypeTemplateParmDecl>(ND)) {
2223  Depth = PD->getDepth();
2224  } else {
2225  Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
2226  }
2227  }
2228 
2229  bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
2230  if (ParmDepth >= Depth) {
2231  Match = true;
2232  MatchLoc = Loc;
2233  return true;
2234  }
2235  return false;
2236  }
2237 
2238  bool TraverseStmt(Stmt *S, DataRecursionQueue *Q = nullptr) {
2239  // Prune out non-type-dependent expressions if requested. This can
2240  // sometimes result in us failing to find a template parameter reference
2241  // (if a value-dependent expression creates a dependent type), but this
2242  // mode is best-effort only.
2243  if (auto *E = dyn_cast_or_null<Expr>(S))
2244  if (IgnoreNonTypeDependent && !E->isTypeDependent())
2245  return true;
2246  return super::TraverseStmt(S, Q);
2247  }
2248 
2249  bool TraverseTypeLoc(TypeLoc TL) {
2250  if (IgnoreNonTypeDependent && !TL.isNull() &&
2251  !TL.getType()->isDependentType())
2252  return true;
2253  return super::TraverseTypeLoc(TL);
2254  }
2255 
2256  bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
2257  return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());
2258  }
2259 
2260  bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
2261  // For a best-effort search, keep looking until we find a location.
2262  return IgnoreNonTypeDependent || !Matches(T->getDepth());
2263  }
2264 
2265  bool TraverseTemplateName(TemplateName N) {
2266  if (TemplateTemplateParmDecl *PD =
2267  dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
2268  if (Matches(PD->getDepth()))
2269  return false;
2270  return super::TraverseTemplateName(N);
2271  }
2272 
2273  bool VisitDeclRefExpr(DeclRefExpr *E) {
2274  if (NonTypeTemplateParmDecl *PD =
2275  dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
2276  if (Matches(PD->getDepth(), E->getExprLoc()))
2277  return false;
2278  return super::VisitDeclRefExpr(E);
2279  }
2280 
2281  bool VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
2282  return TraverseType(T->getReplacementType());
2283  }
2284 
2285  bool
2286  VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *T) {
2287  return TraverseTemplateArgument(T->getArgumentPack());
2288  }
2289 
2290  bool TraverseInjectedClassNameType(const InjectedClassNameType *T) {
2291  return TraverseType(T->getInjectedSpecializationType());
2292  }
2293 };
2294 } // end anonymous namespace
2295 
2296 /// Determines whether a given type depends on the given parameter
2297 /// list.
2298 static bool
2300  DependencyChecker Checker(Params, /*IgnoreNonTypeDependent*/false);
2301  Checker.TraverseType(T);
2302  return Checker.Match;
2303 }
2304 
2305 // Find the source range corresponding to the named type in the given
2306 // nested-name-specifier, if any.
2308  QualType T,
2309  const CXXScopeSpec &SS) {
2311  while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) {
2312  if (const Type *CurType = NNS->getAsType()) {
2313  if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0)))
2314  return NNSLoc.getTypeLoc().getSourceRange();
2315  } else
2316  break;
2317 
2318  NNSLoc = NNSLoc.getPrefix();
2319  }
2320 
2321  return SourceRange();
2322 }
2323 
2324 /// \brief Match the given template parameter lists to the given scope
2325 /// specifier, returning the template parameter list that applies to the
2326 /// name.
2327 ///
2328 /// \param DeclStartLoc the start of the declaration that has a scope
2329 /// specifier or a template parameter list.
2330 ///
2331 /// \param DeclLoc The location of the declaration itself.
2332 ///
2333 /// \param SS the scope specifier that will be matched to the given template
2334 /// parameter lists. This scope specifier precedes a qualified name that is
2335 /// being declared.
2336 ///
2337 /// \param TemplateId The template-id following the scope specifier, if there
2338 /// is one. Used to check for a missing 'template<>'.
2339 ///
2340 /// \param ParamLists the template parameter lists, from the outermost to the
2341 /// innermost template parameter lists.
2342 ///
2343 /// \param IsFriend Whether to apply the slightly different rules for
2344 /// matching template parameters to scope specifiers in friend
2345 /// declarations.
2346 ///
2347 /// \param IsMemberSpecialization will be set true if the scope specifier
2348 /// denotes a fully-specialized type, and therefore this is a declaration of
2349 /// a member specialization.
2350 ///
2351 /// \returns the template parameter list, if any, that corresponds to the
2352 /// name that is preceded by the scope specifier @p SS. This template
2353 /// parameter list may have template parameters (if we're declaring a
2354 /// template) or may have no template parameters (if we're declaring a
2355 /// template specialization), or may be NULL (if what we're declaring isn't
2356 /// itself a template).
2358  SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
2359  TemplateIdAnnotation *TemplateId,
2360  ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
2361  bool &IsMemberSpecialization, bool &Invalid) {
2362  IsMemberSpecialization = false;
2363  Invalid = false;
2364 
2365  // The sequence of nested types to which we will match up the template
2366  // parameter lists. We first build this list by starting with the type named
2367  // by the nested-name-specifier and walking out until we run out of types.
2368  SmallVector<QualType, 4> NestedTypes;
2369  QualType T;
2370  if (SS.getScopeRep()) {
2371  if (CXXRecordDecl *Record
2372  = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
2373  T = Context.getTypeDeclType(Record);
2374  else
2375  T = QualType(SS.getScopeRep()->getAsType(), 0);
2376  }
2377 
2378  // If we found an explicit specialization that prevents us from needing
2379  // 'template<>' headers, this will be set to the location of that
2380  // explicit specialization.
2381  SourceLocation ExplicitSpecLoc;
2382 
2383  while (!T.isNull()) {
2384  NestedTypes.push_back(T);
2385 
2386  // Retrieve the parent of a record type.
2387  if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
2388  // If this type is an explicit specialization, we're done.
2390  = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
2391  if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) &&
2392  Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
2393  ExplicitSpecLoc = Spec->getLocation();
2394  break;
2395  }
2396  } else if (Record->getTemplateSpecializationKind()
2398  ExplicitSpecLoc = Record->getLocation();
2399  break;
2400  }
2401 
2402  if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
2403  T = Context.getTypeDeclType(Parent);
2404  else
2405  T = QualType();
2406  continue;
2407  }
2408 
2409  if (const TemplateSpecializationType *TST
2411  if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
2412  if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
2413  T = Context.getTypeDeclType(Parent);
2414  else
2415  T = QualType();
2416  continue;
2417  }
2418  }
2419 
2420  // Look one step prior in a dependent template specialization type.
2421  if (const DependentTemplateSpecializationType *DependentTST
2423  if (NestedNameSpecifier *NNS = DependentTST->getQualifier())
2424  T = QualType(NNS->getAsType(), 0);
2425  else
2426  T = QualType();
2427  continue;
2428  }
2429 
2430  // Look one step prior in a dependent name type.
2431  if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
2432  if (NestedNameSpecifier *NNS = DependentName->getQualifier())
2433  T = QualType(NNS->getAsType(), 0);
2434  else
2435  T = QualType();
2436  continue;
2437  }
2438 
2439  // Retrieve the parent of an enumeration type.
2440  if (const EnumType *EnumT = T->getAs<EnumType>()) {
2441  // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
2442  // check here.
2443  EnumDecl *Enum = EnumT->getDecl();
2444 
2445  // Get to the parent type.
2446  if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
2447  T = Context.getTypeDeclType(Parent);
2448  else
2449  T = QualType();
2450  continue;
2451  }
2452 
2453  T = QualType();
2454  }
2455  // Reverse the nested types list, since we want to traverse from the outermost
2456  // to the innermost while checking template-parameter-lists.
2457  std::reverse(NestedTypes.begin(), NestedTypes.end());
2458 
2459  // C++0x [temp.expl.spec]p17:
2460  // A member or a member template may be nested within many
2461  // enclosing class templates. In an explicit specialization for
2462  // such a member, the member declaration shall be preceded by a
2463  // template<> for each enclosing class template that is
2464  // explicitly specialized.
2465  bool SawNonEmptyTemplateParameterList = false;
2466 
2467  auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
2468  if (SawNonEmptyTemplateParameterList) {
2469  Diag(DeclLoc, diag::err_specialize_member_of_template)
2470  << !Recovery << Range;
2471  Invalid = true;
2472  IsMemberSpecialization = false;
2473  return true;
2474  }
2475 
2476  return false;
2477  };
2478 
2479  auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
2480  // Check that we can have an explicit specialization here.
2481  if (CheckExplicitSpecialization(Range, true))
2482  return true;
2483 
2484  // We don't have a template header, but we should.
2485  SourceLocation ExpectedTemplateLoc;
2486  if (!ParamLists.empty())
2487  ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
2488  else
2489  ExpectedTemplateLoc = DeclStartLoc;
2490 
2491  Diag(DeclLoc, diag::err_template_spec_needs_header)
2492  << Range
2493  << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
2494  return false;
2495  };
2496 
2497  unsigned ParamIdx = 0;
2498  for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
2499  ++TypeIdx) {
2500  T = NestedTypes[TypeIdx];
2501 
2502  // Whether we expect a 'template<>' header.
2503  bool NeedEmptyTemplateHeader = false;
2504 
2505  // Whether we expect a template header with parameters.
2506  bool NeedNonemptyTemplateHeader = false;
2507 
2508  // For a dependent type, the set of template parameters that we
2509  // expect to see.
2510  TemplateParameterList *ExpectedTemplateParams = nullptr;
2511 
2512  // C++0x [temp.expl.spec]p15:
2513  // A member or a member template may be nested within many enclosing
2514  // class templates. In an explicit specialization for such a member, the
2515  // member declaration shall be preceded by a template<> for each
2516  // enclosing class template that is explicitly specialized.
2517  if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
2519  = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
2520  ExpectedTemplateParams = Partial->getTemplateParameters();
2521  NeedNonemptyTemplateHeader = true;
2522  } else if (Record->isDependentType()) {
2523  if (Record->getDescribedClassTemplate()) {
2524  ExpectedTemplateParams = Record->getDescribedClassTemplate()
2525  ->getTemplateParameters();
2526  NeedNonemptyTemplateHeader = true;
2527  }
2528  } else if (ClassTemplateSpecializationDecl *Spec
2529  = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
2530  // C++0x [temp.expl.spec]p4:
2531  // Members of an explicitly specialized class template are defined
2532  // in the same manner as members of normal classes, and not using
2533  // the template<> syntax.
2534  if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
2535  NeedEmptyTemplateHeader = true;
2536  else
2537  continue;
2538  } else if (Record->getTemplateSpecializationKind()) {
2539  if (Record->getTemplateSpecializationKind()
2541  TypeIdx == NumTypes - 1)
2542  IsMemberSpecialization = true;
2543 
2544  continue;
2545  }
2546  } else if (const TemplateSpecializationType *TST
2548  if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
2549  ExpectedTemplateParams = Template->getTemplateParameters();
2550  NeedNonemptyTemplateHeader = true;
2551  }
2552  } else if (T->getAs<DependentTemplateSpecializationType>()) {
2553  // FIXME: We actually could/should check the template arguments here
2554  // against the corresponding template parameter list.
2555  NeedNonemptyTemplateHeader = false;
2556  }
2557 
2558  // C++ [temp.expl.spec]p16:
2559  // In an explicit specialization declaration for a member of a class
2560  // template or a member template that ap- pears in namespace scope, the
2561  // member template and some of its enclosing class templates may remain
2562  // unspecialized, except that the declaration shall not explicitly
2563  // specialize a class member template if its en- closing class templates
2564  // are not explicitly specialized as well.
2565  if (ParamIdx < ParamLists.size()) {
2566  if (ParamLists[ParamIdx]->size() == 0) {
2567  if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
2568  false))
2569  return nullptr;
2570  } else
2571  SawNonEmptyTemplateParameterList = true;
2572  }
2573 
2574  if (NeedEmptyTemplateHeader) {
2575  // If we're on the last of the types, and we need a 'template<>' header
2576  // here, then it's a member specialization.
2577  if (TypeIdx == NumTypes - 1)
2578  IsMemberSpecialization = true;
2579 
2580  if (ParamIdx < ParamLists.size()) {
2581  if (ParamLists[ParamIdx]->size() > 0) {
2582  // The header has template parameters when it shouldn't. Complain.
2583  Diag(ParamLists[ParamIdx]->getTemplateLoc(),
2584  diag::err_template_param_list_matches_nontemplate)
2585  << T
2586  << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
2587  ParamLists[ParamIdx]->getRAngleLoc())
2589  Invalid = true;
2590  return nullptr;
2591  }
2592 
2593  // Consume this template header.
2594  ++ParamIdx;
2595  continue;
2596  }
2597 
2598  if (!IsFriend)
2599  if (DiagnoseMissingExplicitSpecialization(
2601  return nullptr;
2602 
2603  continue;
2604  }
2605 
2606  if (NeedNonemptyTemplateHeader) {
2607  // In friend declarations we can have template-ids which don't
2608  // depend on the corresponding template parameter lists. But
2609  // assume that empty parameter lists are supposed to match this
2610  // template-id.
2611  if (IsFriend && T->isDependentType()) {
2612  if (ParamIdx < ParamLists.size() &&
2613  DependsOnTemplateParameters(T, ParamLists[ParamIdx]))
2614  ExpectedTemplateParams = nullptr;
2615  else
2616  continue;
2617  }
2618 
2619  if (ParamIdx < ParamLists.size()) {
2620  // Check the template parameter list, if we can.
2621  if (ExpectedTemplateParams &&
2622  !TemplateParameterListsAreEqual(ParamLists[ParamIdx],
2623  ExpectedTemplateParams,
2624  true, TPL_TemplateMatch))
2625  Invalid = true;
2626 
2627  if (!Invalid &&
2628  CheckTemplateParameterList(ParamLists[ParamIdx], nullptr,
2629  TPC_ClassTemplateMember))
2630  Invalid = true;
2631 
2632  ++ParamIdx;
2633  continue;
2634  }
2635 
2636  Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
2637  << T
2639  Invalid = true;
2640  continue;
2641  }
2642  }
2643 
2644  // If there were at least as many template-ids as there were template
2645  // parameter lists, then there are no template parameter lists remaining for
2646  // the declaration itself.
2647  if (ParamIdx >= ParamLists.size()) {
2648  if (TemplateId && !IsFriend) {
2649  // We don't have a template header for the declaration itself, but we
2650  // should.
2651  DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
2652  TemplateId->RAngleLoc));
2653 
2654  // Fabricate an empty template parameter list for the invented header.
2656  SourceLocation(), None,
2657  SourceLocation(), nullptr);
2658  }
2659 
2660  return nullptr;
2661  }
2662 
2663  // If there were too many template parameter lists, complain about that now.
2664  if (ParamIdx < ParamLists.size() - 1) {
2665  bool HasAnyExplicitSpecHeader = false;
2666  bool AllExplicitSpecHeaders = true;
2667  for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
2668  if (ParamLists[I]->size() == 0)
2669  HasAnyExplicitSpecHeader = true;
2670  else
2671  AllExplicitSpecHeaders = false;
2672  }
2673 
2674  Diag(ParamLists[ParamIdx]->getTemplateLoc(),
2675  AllExplicitSpecHeaders ? diag::warn_template_spec_extra_headers
2676  : diag::err_template_spec_extra_headers)
2677  << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
2678  ParamLists[ParamLists.size() - 2]->getRAngleLoc());
2679 
2680  // If there was a specialization somewhere, such that 'template<>' is
2681  // not required, and there were any 'template<>' headers, note where the
2682  // specialization occurred.
2683  if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader)
2684  Diag(ExplicitSpecLoc,
2685  diag::note_explicit_template_spec_does_not_need_header)
2686  << NestedTypes.back();
2687 
2688  // We have a template parameter list with no corresponding scope, which
2689  // means that the resulting template declaration can't be instantiated
2690  // properly (we'll end up with dependent nodes when we shouldn't).
2691  if (!AllExplicitSpecHeaders)
2692  Invalid = true;
2693  }
2694 
2695  // C++ [temp.expl.spec]p16:
2696  // In an explicit specialization declaration for a member of a class
2697  // template or a member template that ap- pears in namespace scope, the
2698  // member template and some of its enclosing class templates may remain
2699  // unspecialized, except that the declaration shall not explicitly
2700  // specialize a class member template if its en- closing class templates
2701  // are not explicitly specialized as well.
2702  if (ParamLists.back()->size() == 0 &&
2703  CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
2704  false))
2705  return nullptr;
2706 
2707  // Return the last template parameter list, which corresponds to the
2708  // entity being declared.
2709  return ParamLists.back();
2710 }
2711 
2713  if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
2714  Diag(Template->getLocation(), diag::note_template_declared_here)
2715  << (isa<FunctionTemplateDecl>(Template)
2716  ? 0
2717  : isa<ClassTemplateDecl>(Template)
2718  ? 1
2719  : isa<VarTemplateDecl>(Template)
2720  ? 2
2721  : isa<TypeAliasTemplateDecl>(Template) ? 3 : 4)
2722  << Template->getDeclName();
2723  return;
2724  }
2725 
2727  for (OverloadedTemplateStorage::iterator I = OST->begin(),
2728  IEnd = OST->end();
2729  I != IEnd; ++I)
2730  Diag((*I)->getLocation(), diag::note_template_declared_here)
2731  << 0 << (*I)->getDeclName();
2732 
2733  return;
2734  }
2735 }
2736 
2737 static QualType
2739  const SmallVectorImpl<TemplateArgument> &Converted,
2740  SourceLocation TemplateLoc,
2741  TemplateArgumentListInfo &TemplateArgs) {
2742  ASTContext &Context = SemaRef.getASTContext();
2743  switch (BTD->getBuiltinTemplateKind()) {
2744  case BTK__make_integer_seq: {
2745  // Specializations of __make_integer_seq<S, T, N> are treated like
2746  // S<T, 0, ..., N-1>.
2747 
2748  // C++14 [inteseq.intseq]p1:
2749  // T shall be an integer type.
2750  if (!Converted[1].getAsType()->isIntegralType(Context)) {
2751  SemaRef.Diag(TemplateArgs[1].getLocation(),
2752  diag::err_integer_sequence_integral_element_type);
2753  return QualType();
2754  }
2755 
2756  // C++14 [inteseq.make]p1:
2757  // If N is negative the program is ill-formed.
2758  TemplateArgument NumArgsArg = Converted[2];
2759  llvm::APSInt NumArgs = NumArgsArg.getAsIntegral();
2760  if (NumArgs < 0) {
2761  SemaRef.Diag(TemplateArgs[2].getLocation(),
2762  diag::err_integer_sequence_negative_length);
2763  return QualType();
2764  }
2765 
2766  QualType ArgTy = NumArgsArg.getIntegralType();
2767  TemplateArgumentListInfo SyntheticTemplateArgs;
2768  // The type argument gets reused as the first template argument in the
2769  // synthetic template argument list.
2770  SyntheticTemplateArgs.addArgument(TemplateArgs[1]);
2771  // Expand N into 0 ... N-1.
2772  for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned());
2773  I < NumArgs; ++I) {
2774  TemplateArgument TA(Context, I, ArgTy);
2775  SyntheticTemplateArgs.addArgument(SemaRef.getTrivialTemplateArgumentLoc(
2776  TA, ArgTy, TemplateArgs[2].getLocation()));
2777  }
2778  // The first template argument will be reused as the template decl that
2779  // our synthetic template arguments will be applied to.
2780  return SemaRef.CheckTemplateIdType(Converted[0].getAsTemplate(),
2781  TemplateLoc, SyntheticTemplateArgs);
2782  }
2783 
2785  // Specializations of
2786  // __type_pack_element<Index, T_1, ..., T_N>
2787  // are treated like T_Index.
2788  assert(Converted.size() == 2 &&
2789  "__type_pack_element should be given an index and a parameter pack");
2790 
2791  // If the Index is out of bounds, the program is ill-formed.
2792  TemplateArgument IndexArg = Converted[0], Ts = Converted[1];
2793  llvm::APSInt Index = IndexArg.getAsIntegral();
2794  assert(Index >= 0 && "the index used with __type_pack_element should be of "
2795  "type std::size_t, and hence be non-negative");
2796  if (Index >= Ts.pack_size()) {
2797  SemaRef.Diag(TemplateArgs[0].getLocation(),
2798  diag::err_type_pack_element_out_of_bounds);
2799  return QualType();
2800  }
2801 
2802  // We simply return the type at index `Index`.
2803  auto Nth = std::next(Ts.pack_begin(), Index.getExtValue());
2804  return Nth->getAsType();
2805  }
2806  llvm_unreachable("unexpected BuiltinTemplateDecl!");
2807 }
2808 
2809 /// Determine whether this alias template is "enable_if_t".
2810 static bool isEnableIfAliasTemplate(TypeAliasTemplateDecl *AliasTemplate) {
2811  return AliasTemplate->getName().equals("enable_if_t");
2812 }
2813 
2814 /// Collect all of the separable terms in the given condition, which
2815 /// might be a conjunction.
2816 ///
2817 /// FIXME: The right answer is to convert the logical expression into
2818 /// disjunctive normal form, so we can find the first failed term
2819 /// within each possible clause.
2820 static void collectConjunctionTerms(Expr *Clause,
2821  SmallVectorImpl<Expr *> &Terms) {
2822  if (auto BinOp = dyn_cast<BinaryOperator>(Clause->IgnoreParenImpCasts())) {
2823  if (BinOp->getOpcode() == BO_LAnd) {
2824  collectConjunctionTerms(BinOp->getLHS(), Terms);
2825  collectConjunctionTerms(BinOp->getRHS(), Terms);
2826  }
2827 
2828  return;
2829  }
2830 
2831  Terms.push_back(Clause);
2832 }
2833 
2834 // The ranges-v3 library uses an odd pattern of a top-level "||" with
2835 // a left-hand side that is value-dependent but never true. Identify
2836 // the idiom and ignore that term.
2838  // Top-level '||'.
2839  auto *BinOp = dyn_cast<BinaryOperator>(Cond->IgnoreParenImpCasts());
2840  if (!BinOp) return Cond;
2841 
2842  if (BinOp->getOpcode() != BO_LOr) return Cond;
2843 
2844  // With an inner '==' that has a literal on the right-hand side.
2845  Expr *LHS = BinOp->getLHS();
2846  auto *InnerBinOp = dyn_cast<BinaryOperator>(LHS->IgnoreParenImpCasts());
2847  if (!InnerBinOp) return Cond;
2848 
2849  if (InnerBinOp->getOpcode() != BO_EQ ||
2850  !isa<IntegerLiteral>(InnerBinOp->getRHS()))
2851  return Cond;
2852 
2853  // If the inner binary operation came from a macro expansion named
2854  // CONCEPT_REQUIRES or CONCEPT_REQUIRES_, return the right-hand side
2855  // of the '||', which is the real, user-provided condition.
2856  SourceLocation Loc = InnerBinOp->getExprLoc();
2857  if (!Loc.isMacroID()) return Cond;
2858 
2859  StringRef MacroName = PP.getImmediateMacroName(Loc);
2860  if (MacroName == "CONCEPT_REQUIRES" || MacroName == "CONCEPT_REQUIRES_")
2861  return BinOp->getRHS();
2862 
2863  return Cond;
2864 }
2865 
2866 /// Find the failed subexpression within enable_if, and describe it
2867 /// with a string.
2868 static std::pair<Expr *, std::string>
2870  Cond = lookThroughRangesV3Condition(S.PP, Cond);
2871 
2872  // Separate out all of the terms in a conjunction.
2873  SmallVector<Expr *, 4> Terms;
2874  collectConjunctionTerms(Cond, Terms);
2875 
2876  // Determine which term failed.
2877  Expr *FailedCond = nullptr;
2878  for (Expr *Term : Terms) {
2879  // The initialization of the parameter from the argument is
2880  // a constant-evaluated context.
2881  EnterExpressionEvaluationContext ConstantEvaluated(
2883 
2884  bool Succeeded;
2885  if (Term->EvaluateAsBooleanCondition(Succeeded, S.Context) &&
2886  !Succeeded) {
2887  FailedCond = Term->IgnoreParenImpCasts();
2888  break;
2889  }
2890  }
2891 
2892  if (!FailedCond)
2893  FailedCond = Cond->IgnoreParenImpCasts();
2894 
2895  std::string Description;
2896  {
2897  llvm::raw_string_ostream Out(Description);
2898  FailedCond->printPretty(Out, nullptr,
2900  }
2901  return { FailedCond, Description };
2902 }
2903 
2905  SourceLocation TemplateLoc,
2906  TemplateArgumentListInfo &TemplateArgs) {
2909  if (DTN && DTN->isIdentifier())
2910  // When building a template-id where the template-name is dependent,
2911  // assume the template is a type template. Either our assumption is
2912  // correct, or the code is ill-formed and will be diagnosed when the
2913  // dependent name is substituted.
2915  DTN->getQualifier(),
2916  DTN->getIdentifier(),
2917  TemplateArgs);
2918 
2919  TemplateDecl *Template = Name.getAsTemplateDecl();
2920  if (!Template || isa<FunctionTemplateDecl>(Template) ||
2921  isa<VarTemplateDecl>(Template)) {
2922  // We might have a substituted template template parameter pack. If so,
2923  // build a template specialization type for it.
2925  return Context.getTemplateSpecializationType(Name, TemplateArgs);
2926 
2927  Diag(TemplateLoc, diag::err_template_id_not_a_type)
2928  << Name;
2929  NoteAllFoundTemplates(Name);
2930  return QualType();
2931  }
2932 
2933  // Check that the template argument list is well-formed for this
2934  // template.
2936  if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
2937  false, Converted))
2938  return QualType();
2939 
2940  QualType CanonType;
2941 
2942  bool InstantiationDependent = false;
2943  if (TypeAliasTemplateDecl *AliasTemplate =
2944  dyn_cast<TypeAliasTemplateDecl>(Template)) {
2945  // Find the canonical type for this type alias template specialization.
2946  TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
2947  if (Pattern->isInvalidDecl())
2948  return QualType();
2949 
2951  Converted);
2952 
2953  // Only substitute for the innermost template argument list.
2954  MultiLevelTemplateArgumentList TemplateArgLists;
2955  TemplateArgLists.addOuterTemplateArguments(&StackTemplateArgs);
2956  unsigned Depth = AliasTemplate->getTemplateParameters()->getDepth();
2957  for (unsigned I = 0; I < Depth; ++I)
2958  TemplateArgLists.addOuterTemplateArguments(None);
2959 
2961  InstantiatingTemplate Inst(*this, TemplateLoc, Template);
2962  if (Inst.isInvalid())
2963  return QualType();
2964 
2965  CanonType = SubstType(Pattern->getUnderlyingType(),
2966  TemplateArgLists, AliasTemplate->getLocation(),
2967  AliasTemplate->getDeclName());
2968  if (CanonType.isNull()) {
2969  // If this was enable_if and we failed to find the nested type
2970  // within enable_if in a SFINAE context, dig out the specific
2971  // enable_if condition that failed and present that instead.
2972  if (isEnableIfAliasTemplate(AliasTemplate)) {
2973  if (auto DeductionInfo = isSFINAEContext()) {
2974  if (*DeductionInfo &&
2975  (*DeductionInfo)->hasSFINAEDiagnostic() &&
2976  (*DeductionInfo)->peekSFINAEDiagnostic().second.getDiagID() ==
2977  diag::err_typename_nested_not_found_enable_if &&
2978  TemplateArgs[0].getArgument().getKind()
2980  Expr *FailedCond;
2981  std::string FailedDescription;
2982  std::tie(FailedCond, FailedDescription) =
2984  *this, TemplateArgs[0].getSourceExpression());
2985 
2986  // Remove the old SFINAE diagnostic.
2987  PartialDiagnosticAt OldDiag =
2989  (*DeductionInfo)->takeSFINAEDiagnostic(OldDiag);
2990 
2991  // Add a new SFINAE diagnostic specifying which condition
2992  // failed.
2993  (*DeductionInfo)->addSFINAEDiagnostic(
2994  OldDiag.first,
2995  PDiag(diag::err_typename_nested_not_found_requirement)
2996  << FailedDescription
2997  << FailedCond->getSourceRange());
2998  }
2999  }
3000  }
3001 
3002  return QualType();
3003  }
3004  } else if (Name.isDependent() ||
3006  TemplateArgs, InstantiationDependent)) {
3007  // This class template specialization is a dependent
3008  // type. Therefore, its canonical type is another class template
3009  // specialization type that contains all of the converted
3010  // arguments in canonical form. This ensures that, e.g., A<T> and
3011  // A<T, T> have identical types when A is declared as:
3012  //
3013  // template<typename T, typename U = T> struct A;
3014  CanonType = Context.getCanonicalTemplateSpecializationType(Name, Converted);
3015 
3016  // This might work out to be a current instantiation, in which
3017  // case the canonical type needs to be the InjectedClassNameType.
3018  //
3019  // TODO: in theory this could be a simple hashtable lookup; most
3020  // changes to CurContext don't change the set of current
3021  // instantiations.
3022  if (isa<ClassTemplateDecl>(Template)) {
3023  for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
3024  // If we get out to a namespace, we're done.
3025  if (Ctx->isFileContext()) break;
3026 
3027  // If this isn't a record, keep looking.
3028  CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
3029  if (!Record) continue;
3030 
3031  // Look for one of the two cases with InjectedClassNameTypes
3032  // and check whether it's the same template.
3033  if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
3034  !Record->getDescribedClassTemplate())
3035  continue;
3036 
3037  // Fetch the injected class name type and check whether its
3038  // injected type is equal to the type we just built.
3039  QualType ICNT = Context.getTypeDeclType(Record);
3040  QualType Injected = cast<InjectedClassNameType>(ICNT)
3041  ->getInjectedSpecializationType();
3042 
3043  if (CanonType != Injected->getCanonicalTypeInternal())
3044  continue;
3045 
3046  // If so, the canonical type of this TST is the injected
3047  // class name type of the record we just found.
3048  assert(ICNT.isCanonical());
3049  CanonType = ICNT;
3050  break;
3051  }
3052  }
3053  } else if (ClassTemplateDecl *ClassTemplate
3054  = dyn_cast<ClassTemplateDecl>(Template)) {
3055  // Find the class template specialization declaration that
3056  // corresponds to these arguments.
3057  void *InsertPos = nullptr;
3059  = ClassTemplate->findSpecialization(Converted, InsertPos);
3060  if (!Decl) {
3061  // This is the first time we have referenced this class template
3062  // specialization. Create the canonical declaration and add it to
3063  // the set of specializations.
3065  ClassTemplate->getTemplatedDecl()->getTagKind(),
3066  ClassTemplate->getDeclContext(),
3067  ClassTemplate->getTemplatedDecl()->getLocStart(),
3068  ClassTemplate->getLocation(),
3069  ClassTemplate,
3070  Converted, nullptr);
3071  ClassTemplate->AddSpecialization(Decl, InsertPos);
3072  if (ClassTemplate->isOutOfLine())
3073  Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
3074  }
3075 
3076  if (Decl->getSpecializationKind() == TSK_Undeclared) {
3077  MultiLevelTemplateArgumentList TemplateArgLists;
3078  TemplateArgLists.addOuterTemplateArguments(Converted);
3079  InstantiateAttrsForDecl(TemplateArgLists, ClassTemplate->getTemplatedDecl(),
3080  Decl);
3081  }
3082 
3083  // Diagnose uses of this specialization.
3084  (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
3085 
3086  CanonType = Context.getTypeDeclType(Decl);
3087  assert(isa<RecordType>(CanonType) &&
3088  "type of non-dependent specialization is not a RecordType");
3089  } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Template)) {
3090  CanonType = checkBuiltinTemplateIdType(*this, BTD, Converted, TemplateLoc,
3091  TemplateArgs);
3092  }
3093 
3094  // Build the fully-sugared type for this class template
3095  // specialization, which refers back to the class template
3096  // specialization we created or found.
3097  return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
3098 }
3099 
3100 TypeResult
3102  TemplateTy TemplateD, IdentifierInfo *TemplateII,
3103  SourceLocation TemplateIILoc,
3104  SourceLocation LAngleLoc,
3105  ASTTemplateArgsPtr TemplateArgsIn,
3106  SourceLocation RAngleLoc,
3107  bool IsCtorOrDtorName, bool IsClassName) {
3108  if (SS.isInvalid())
3109  return true;
3110 
3111  if (!IsCtorOrDtorName && !IsClassName && SS.isSet()) {
3112  DeclContext *LookupCtx = computeDeclContext(SS, /*EnteringContext*/false);
3113 
3114  // C++ [temp.res]p3:
3115  // A qualified-id that refers to a type and in which the
3116  // nested-name-specifier depends on a template-parameter (14.6.2)
3117  // shall be prefixed by the keyword typename to indicate that the
3118  // qualified-id denotes a type, forming an
3119  // elaborated-type-specifier (7.1.5.3).
3120  if (!LookupCtx && isDependentScopeSpecifier(SS)) {
3121  Diag(SS.getBeginLoc(), diag::err_typename_missing_template)
3122  << SS.getScopeRep() << TemplateII->getName();
3123  // Recover as if 'typename' were specified.
3124  // FIXME: This is not quite correct recovery as we don't transform SS
3125  // into the corresponding dependent form (and we don't diagnose missing
3126  // 'template' keywords within SS as a result).
3127  return ActOnTypenameType(nullptr, SourceLocation(), SS, TemplateKWLoc,
3128  TemplateD, TemplateII, TemplateIILoc, LAngleLoc,
3129  TemplateArgsIn, RAngleLoc);
3130  }
3131 
3132  // Per C++ [class.qual]p2, if the template-id was an injected-class-name,
3133  // it's not actually allowed to be used as a type in most cases. Because
3134  // we annotate it before we know whether it's valid, we have to check for
3135  // this case here.
3136  auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
3137  if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
3138  Diag(TemplateIILoc,
3139  TemplateKWLoc.isInvalid()
3140  ? diag::err_out_of_line_qualified_id_type_names_constructor
3141  : diag::ext_out_of_line_qualified_id_type_names_constructor)
3142  << TemplateII << 0 /*injected-class-name used as template name*/
3143  << 1 /*if any keyword was present, it was 'template'*/;
3144  }
3145  }
3146 
3147  TemplateName Template = TemplateD.get();
3148 
3149  // Translate the parser's template argument list in our AST format.
3150  TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
3151  translateTemplateArguments(TemplateArgsIn, TemplateArgs);
3152 
3153  if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
3154  QualType T
3156  DTN->getQualifier(),
3157  DTN->getIdentifier(),
3158  TemplateArgs);
3159  // Build type-source information.
3160  TypeLocBuilder TLB;
3165  SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3166  SpecTL.setTemplateNameLoc(TemplateIILoc);
3167  SpecTL.setLAngleLoc(LAngleLoc);
3168  SpecTL.setRAngleLoc(RAngleLoc);
3169  for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
3170  SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
3171  return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
3172  }
3173 
3174  QualType Result = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
3175  if (Result.isNull())
3176  return true;
3177 
3178  // Build type-source information.
3179  TypeLocBuilder TLB;
3181  = TLB.push<TemplateSpecializationTypeLoc>(Result);
3182  SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3183  SpecTL.setTemplateNameLoc(TemplateIILoc);
3184  SpecTL.setLAngleLoc(LAngleLoc);
3185  SpecTL.setRAngleLoc(RAngleLoc);
3186  for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
3187  SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
3188 
3189  // NOTE: avoid constructing an ElaboratedTypeLoc if this is a
3190  // constructor or destructor name (in such a case, the scope specifier
3191  // will be attached to the enclosing Decl or Expr node).
3192  if (SS.isNotEmpty() && !IsCtorOrDtorName) {
3193  // Create an elaborated-type-specifier containing the nested-name-specifier.
3194  Result = Context.getElaboratedType(ETK_None, SS.getScopeRep(), Result);
3195  ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
3198  }
3199 
3200  return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
3201 }
3202 
3204  TypeSpecifierType TagSpec,
3205  SourceLocation TagLoc,
3206  CXXScopeSpec &SS,
3207  SourceLocation TemplateKWLoc,
3208  TemplateTy TemplateD,
3209  SourceLocation TemplateLoc,
3210  SourceLocation LAngleLoc,
3211  ASTTemplateArgsPtr TemplateArgsIn,
3212  SourceLocation RAngleLoc) {
3213  TemplateName Template = TemplateD.get();
3214 
3215  // Translate the parser's template argument list in our AST format.
3216  TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
3217  translateTemplateArguments(TemplateArgsIn, TemplateArgs);
3218 
3219  // Determine the tag kind
3221  ElaboratedTypeKeyword Keyword
3223 
3224  if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
3226  DTN->getQualifier(),
3227  DTN->getIdentifier(),
3228  TemplateArgs);
3229 
3230  // Build type-source information.
3231  TypeLocBuilder TLB;
3234  SpecTL.setElaboratedKeywordLoc(TagLoc);
3236  SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3237  SpecTL.setTemplateNameLoc(TemplateLoc);
3238  SpecTL.setLAngleLoc(LAngleLoc);
3239  SpecTL.setRAngleLoc(RAngleLoc);
3240  for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
3241  SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
3242  return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
3243  }
3244 
3245  if (TypeAliasTemplateDecl *TAT =
3246  dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) {
3247  // C++0x [dcl.type.elab]p2:
3248  // If the identifier resolves to a typedef-name or the simple-template-id
3249  // resolves to an alias template specialization, the
3250  // elaborated-type-specifier is ill-formed.
3251  Diag(TemplateLoc, diag::err_tag_reference_non_tag)
3252  << TAT << NTK_TypeAliasTemplate << TagKind;
3253  Diag(TAT->getLocation(), diag::note_declared_at);
3254  }
3255 
3256  QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
3257  if (Result.isNull())
3258  return TypeResult(true);
3259 
3260  // Check the tag kind
3261  if (const RecordType *RT = Result->getAs<RecordType>()) {
3262  RecordDecl *D = RT->getDecl();
3263 
3264  IdentifierInfo *Id = D->getIdentifier();
3265  assert(Id && "templated class must have an identifier");
3266 
3267  if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TUK_Definition,
3268  TagLoc, Id)) {
3269  Diag(TagLoc, diag::err_use_with_wrong_tag)
3270  << Result
3272  Diag(D->getLocation(), diag::note_previous_use);
3273  }
3274  }
3275 
3276  // Provide source-location information for the template specialization.
3277  TypeLocBuilder TLB;
3279  = TLB.push<TemplateSpecializationTypeLoc>(Result);
3280  SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3281  SpecTL.setTemplateNameLoc(TemplateLoc);
3282  SpecTL.setLAngleLoc(LAngleLoc);
3283  SpecTL.setRAngleLoc(RAngleLoc);
3284  for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
3285  SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
3286 
3287  // Construct an elaborated type containing the nested-name-specifier (if any)
3288  // and tag keyword.
3289  Result = Context.getElaboratedType(Keyword, SS.getScopeRep(), Result);
3290  ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
3291  ElabTL.setElaboratedKeywordLoc(TagLoc);
3293  return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
3294 }
3295 
3296 static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
3297  NamedDecl *PrevDecl,
3298  SourceLocation Loc,
3300 
3302 
3304  const TemplateArgument &Arg, unsigned Depth, unsigned Index) {
3305  switch (Arg.getKind()) {
3312  return false;
3313 
3314  case TemplateArgument::Type: {
3315  QualType Type = Arg.getAsType();
3316  const TemplateTypeParmType *TPT =
3318  return TPT && !Type.hasQualifiers() &&
3319  TPT->getDepth() == Depth && TPT->getIndex() == Index;
3320  }
3321 
3323  DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
3324  if (!DRE || !DRE->getDecl())
3325  return false;
3326  const NonTypeTemplateParmDecl *NTTP =
3327  dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
3328  return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
3329  }
3330 
3332  const TemplateTemplateParmDecl *TTP =
3333  dyn_cast_or_null<TemplateTemplateParmDecl>(
3335  return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
3336  }
3337  llvm_unreachable("unexpected kind of template argument");
3338 }
3339 
3342  if (Params->size() != Args.size())
3343  return false;
3344 
3345  unsigned Depth = Params->getDepth();
3346 
3347  for (unsigned I = 0, N = Args.size(); I != N; ++I) {
3348  TemplateArgument Arg = Args[I];
3349 
3350  // If the parameter is a pack expansion, the argument must be a pack
3351  // whose only element is a pack expansion.
3352  if (Params->getParam(I)->isParameterPack()) {
3353  if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
3354  !Arg.pack_begin()->isPackExpansion())
3355  return false;
3356  Arg = Arg.pack_begin()->getPackExpansionPattern();
3357  }
3358 
3359  if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))
3360  return false;
3361  }
3362 
3363  return true;
3364 }
3365 
3366 /// Convert the parser's template argument list representation into our form.
3369  TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
3370  TemplateId.RAngleLoc);
3371  ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
3372  TemplateId.NumArgs);
3373  S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
3374  return TemplateArgs;
3375 }
3376 
3377 template<typename PartialSpecDecl>
3378 static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial) {
3379  if (Partial->getDeclContext()->isDependentContext())
3380  return;
3381 
3382  // FIXME: Get the TDK from deduction in order to provide better diagnostics
3383  // for non-substitution-failure issues?
3384  TemplateDeductionInfo Info(Partial->getLocation());
3385  if (S.isMoreSpecializedThanPrimary(Partial, Info))
3386  return;
3387 
3388  auto *Template = Partial->getSpecializedTemplate();
3389  S.Diag(Partial->getLocation(),
3390  diag::ext_partial_spec_not_more_specialized_than_primary)
3391  << isa<VarTemplateDecl>(Template);
3392 
3393  if (Info.hasSFINAEDiagnostic()) {
3396  Info.takeSFINAEDiagnostic(Diag);
3397  SmallString<128> SFINAEArgString;
3398  Diag.second.EmitToString(S.getDiagnostics(), SFINAEArgString);
3399  S.Diag(Diag.first,
3400  diag::note_partial_spec_not_more_specialized_than_primary)
3401  << SFINAEArgString;
3402  }
3403 
3404  S.Diag(Template->getLocation(), diag::note_template_decl_here);
3405 }
3406 
3407 static void
3409  const llvm::SmallBitVector &DeducibleParams) {
3410  for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
3411  if (!DeducibleParams[I]) {
3412  NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
3413  if (Param->getDeclName())
3414  S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
3415  << Param->getDeclName();
3416  else
3417  S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
3418  << "(anonymous)";
3419  }
3420  }
3421 }
3422 
3423 
3424 template<typename PartialSpecDecl>
3426  PartialSpecDecl *Partial) {
3427  // C++1z [temp.class.spec]p8: (DR1495)
3428  // - The specialization shall be more specialized than the primary
3429  // template (14.5.5.2).
3430  checkMoreSpecializedThanPrimary(S, Partial);
3431 
3432  // C++ [temp.class.spec]p8: (DR1315)
3433  // - Each template-parameter shall appear at least once in the
3434  // template-id outside a non-deduced context.
3435  // C++1z [temp.class.spec.match]p3 (P0127R2)
3436  // If the template arguments of a partial specialization cannot be
3437  // deduced because of the structure of its template-parameter-list
3438  // and the template-id, the program is ill-formed.
3439  auto *TemplateParams = Partial->getTemplateParameters();
3440  llvm::SmallBitVector DeducibleParams(TemplateParams->size());
3441  S.MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
3442  TemplateParams->getDepth(), DeducibleParams);
3443 
3444  if (!DeducibleParams.all()) {
3445  unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
3446  S.Diag(Partial->getLocation(), diag::ext_partial_specs_not_deducible)
3447  << isa<VarTemplatePartialSpecializationDecl>(Partial)
3448  << (NumNonDeducible > 1)
3449  << SourceRange(Partial->getLocation(),
3450  Partial->getTemplateArgsAsWritten()->RAngleLoc);
3451  noteNonDeducibleParameters(S, TemplateParams, DeducibleParams);
3452  }
3453 }
3454 
3457  checkTemplatePartialSpecialization(*this, Partial);
3458 }
3459 
3462  checkTemplatePartialSpecialization(*this, Partial);
3463 }
3464 
3466  // C++1z [temp.param]p11:
3467  // A template parameter of a deduction guide template that does not have a
3468  // default-argument shall be deducible from the parameter-type-list of the
3469  // deduction guide template.
3470  auto *TemplateParams = TD->getTemplateParameters();
3471  llvm::SmallBitVector DeducibleParams(TemplateParams->size());
3472  MarkDeducedTemplateParameters(TD, DeducibleParams);
3473  for (unsigned I = 0; I != TemplateParams->size(); ++I) {
3474  // A parameter pack is deducible (to an empty pack).
3475  auto *Param = TemplateParams->getParam(I);
3476  if (Param->isParameterPack() || hasVisibleDefaultArgument(Param))
3477  DeducibleParams[I] = true;
3478  }
3479 
3480  if (!DeducibleParams.all()) {
3481  unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
3482  Diag(TD->getLocation(), diag::err_deduction_guide_template_not_deducible)
3483  << (NumNonDeducible > 1);
3484  noteNonDeducibleParameters(*this, TemplateParams, DeducibleParams);
3485  }
3486 }
3487 
3489  Scope *S, Declarator &D, TypeSourceInfo *DI, SourceLocation TemplateKWLoc,
3490  TemplateParameterList *TemplateParams, StorageClass SC,
3491  bool IsPartialSpecialization) {
3492  // D must be variable template id.
3493  assert(D.getName().getKind() == UnqualifiedId::IK_TemplateId &&
3494  "Variable template specialization is declared with a template it.");
3495 
3496  TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
3497  TemplateArgumentListInfo TemplateArgs =
3498  makeTemplateArgumentListInfo(*this, *TemplateId);
3499  SourceLocation TemplateNameLoc = D.getIdentifierLoc();
3500  SourceLocation LAngleLoc = TemplateId->LAngleLoc;
3501  SourceLocation RAngleLoc = TemplateId->RAngleLoc;
3502 
3503  TemplateName Name = TemplateId->Template.get();
3504 
3505  // The template-id must name a variable template.
3506  VarTemplateDecl *VarTemplate =
3507  dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
3508  if (!VarTemplate) {
3509  NamedDecl *FnTemplate;
3510  if (auto *OTS = Name.getAsOverloadedTemplate())
3511  FnTemplate = *OTS->begin();
3512  else
3513  FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
3514  if (FnTemplate)
3515  return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
3516  << FnTemplate->getDeclName();
3517  return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
3518  << IsPartialSpecialization;
3519  }
3520 
3521  // Check for unexpanded parameter packs in any of the template arguments.
3522  for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
3523  if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
3524  UPPC_PartialSpecialization))
3525  return true;
3526 
3527  // Check that the template argument list is well-formed for this
3528  // template.
3530  if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
3531  false, Converted))
3532  return true;
3533 
3534  // Find the variable template (partial) specialization declaration that
3535  // corresponds to these arguments.
3536  if (IsPartialSpecialization) {
3537  if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, VarTemplate,
3538  TemplateArgs.size(), Converted))
3539  return true;
3540 
3541  // FIXME: Move these checks to CheckTemplatePartialSpecializationArgs so we
3542  // also do them during instantiation.
3543  bool InstantiationDependent;
3544  if (!Name.isDependent() &&
3546  TemplateArgs.arguments(),
3547  InstantiationDependent)) {
3548  Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
3549  << VarTemplate->getDeclName();
3550  IsPartialSpecialization = false;
3551  }
3552 
3554  Converted)) {
3555  // C++ [temp.class.spec]p9b3:
3556  //
3557  // -- The argument list of the specialization shall not be identical
3558  // to the implicit argument list of the primary template.
3559  Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
3560  << /*variable template*/ 1
3561  << /*is definition*/(SC != SC_Extern && !CurContext->isRecord())
3562  << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
3563  // FIXME: Recover from this by treating the declaration as a redeclaration
3564  // of the primary template.
3565  return true;
3566  }
3567  }
3568 
3569  void *InsertPos = nullptr;
3570  VarTemplateSpecializationDecl *PrevDecl = nullptr;
3571 
3572  if (IsPartialSpecialization)
3573  // FIXME: Template parameter list matters too
3574  PrevDecl = VarTemplate->findPartialSpecialization(Converted, InsertPos);
3575  else
3576  PrevDecl = VarTemplate->findSpecialization(Converted, InsertPos);
3577 
3578  VarTemplateSpecializationDecl *Specialization = nullptr;
3579 
3580  // Check whether we can declare a variable template specialization in
3581  // the current scope.
3582  if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
3583  TemplateNameLoc,
3584  IsPartialSpecialization))
3585  return true;
3586 
3587  if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
3588  // Since the only prior variable template specialization with these
3589  // arguments was referenced but not declared, reuse that
3590  // declaration node as our own, updating its source location and
3591  // the list of outer template parameters to reflect our new declaration.
3592  Specialization = PrevDecl;
3593  Specialization->setLocation(TemplateNameLoc);
3594  PrevDecl = nullptr;
3595  } else if (IsPartialSpecialization) {
3596  // Create a new class template partial specialization declaration node.
3598  cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
3601  Context, VarTemplate->getDeclContext(), TemplateKWLoc,
3602  TemplateNameLoc, TemplateParams, VarTemplate, DI->getType(), DI, SC,
3603  Converted, TemplateArgs);
3604 
3605  if (!PrevPartial)
3606  VarTemplate->AddPartialSpecialization(Partial, InsertPos);
3607  Specialization = Partial;
3608 
3609  // If we are providing an explicit specialization of a member variable
3610  // template specialization, make a note of that.
3611  if (PrevPartial && PrevPartial->getInstantiatedFromMember())
3612  PrevPartial->setMemberSpecialization();
3613 
3614  CheckTemplatePartialSpecialization(Partial);
3615  } else {
3616  // Create a new class template specialization declaration node for
3617  // this explicit specialization or friend declaration.
3618  Specialization = VarTemplateSpecializationDecl::Create(
3619  Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
3620  VarTemplate, DI->getType(), DI, SC, Converted);
3621  Specialization->setTemplateArgsInfo(TemplateArgs);
3622 
3623  if (!PrevDecl)
3624  VarTemplate->AddSpecialization(Specialization, InsertPos);
3625  }
3626 
3627  // C++ [temp.expl.spec]p6:
3628  // If a template, a member template or the member of a class template is
3629  // explicitly specialized then that specialization shall be declared
3630  // before the first use of that specialization that would cause an implicit
3631  // instantiation to take place, in every translation unit in which such a
3632  // use occurs; no diagnostic is required.
3633  if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
3634  bool Okay = false;
3635  for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
3636  // Is there any previous explicit specialization declaration?
3638  Okay = true;
3639  break;
3640  }
3641  }
3642 
3643  if (!Okay) {
3644  SourceRange Range(TemplateNameLoc, RAngleLoc);
3645  Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
3646  << Name << Range;
3647 
3648  Diag(PrevDecl->getPointOfInstantiation(),
3649  diag::note_instantiation_required_here)
3650  << (PrevDecl->getTemplateSpecializationKind() !=
3652  return true;
3653  }
3654  }
3655 
3656  Specialization->setTemplateKeywordLoc(TemplateKWLoc);
3657  Specialization->setLexicalDeclContext(CurContext);
3658 
3659  // Add the specialization into its lexical context, so that it can
3660  // be seen when iterating through the list of declarations in that
3661  // context. However, specializations are not found by name lookup.
3662  CurContext->addDecl(Specialization);
3663 
3664  // Note that this is an explicit specialization.
3666 
3667  if (PrevDecl) {
3668  // Check that this isn't a redefinition of this specialization,
3669  // merging with previous declarations.
3670  LookupResult PrevSpec(*this, GetNameForDeclarator(D), LookupOrdinaryName,
3671  ForRedeclaration);
3672  PrevSpec.addDecl(PrevDecl);
3673  D.setRedeclaration(CheckVariableDeclaration(Specialization, PrevSpec));
3674  } else if (Specialization->isStaticDataMember() &&
3675  Specialization->isOutOfLine()) {
3676  Specialization->setAccess(VarTemplate->getAccess());
3677  }
3678 
3679  // Link instantiations of static data members back to the template from
3680  // which they were instantiated.
3681  if (Specialization->isStaticDataMember())
3682  Specialization->setInstantiationOfStaticDataMember(
3683  VarTemplate->getTemplatedDecl(),
3684  Specialization->getSpecializationKind());
3685 
3686  return Specialization;
3687 }
3688 
3689 namespace {
3690 /// \brief A partial specialization whose template arguments have matched
3691 /// a given template-id.
3692 struct PartialSpecMatchResult {
3694  TemplateArgumentList *Args;
3695 };
3696 } // end anonymous namespace
3697 
3698 DeclResult
3700  SourceLocation TemplateNameLoc,
3701  const TemplateArgumentListInfo &TemplateArgs) {
3702  assert(Template && "A variable template id without template?");
3703 
3704  // Check that the template argument list is well-formed for this template.
3706  if (CheckTemplateArgumentList(
3707  Template, TemplateNameLoc,
3708  const_cast<TemplateArgumentListInfo &>(TemplateArgs), false,
3709  Converted))
3710  return true;
3711 
3712  // Find the variable template specialization declaration that
3713  // corresponds to these arguments.
3714  void *InsertPos = nullptr;
3715  if (VarTemplateSpecializationDecl *Spec = Template->findSpecialization(
3716  Converted, InsertPos)) {
3717  checkSpecializationVisibility(TemplateNameLoc, Spec);
3718  // If we already have a variable template specialization, return it.
3719  return Spec;
3720  }
3721 
3722  // This is the first time we have referenced this variable template
3723  // specialization. Create the canonical declaration and add it to
3724  // the set of specializations, based on the closest partial specialization
3725  // that it represents. That is,
3726  VarDecl *InstantiationPattern = Template->getTemplatedDecl();
3728  Converted);
3729  TemplateArgumentList *InstantiationArgs = &TemplateArgList;
3730  bool AmbiguousPartialSpec = false;
3731  typedef PartialSpecMatchResult MatchResult;
3733  SourceLocation PointOfInstantiation = TemplateNameLoc;
3734  TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation,
3735  /*ForTakingAddress=*/false);
3736 
3737  // 1. Attempt to find the closest partial specialization that this
3738  // specializes, if any.
3739  // If any of the template arguments is dependent, then this is probably
3740  // a placeholder for an incomplete declarative context; which must be
3741  // complete by instantiation time. Thus, do not search through the partial
3742  // specializations yet.
3743  // TODO: Unify with InstantiateClassTemplateSpecialization()?
3744  // Perhaps better after unification of DeduceTemplateArguments() and
3745  // getMoreSpecializedPartialSpecialization().
3746  bool InstantiationDependent = false;
3748  TemplateArgs, InstantiationDependent)) {
3749 
3751  Template->getPartialSpecializations(PartialSpecs);
3752 
3753  for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
3754  VarTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
3755  TemplateDeductionInfo Info(FailedCandidates.getLocation());
3756 
3757  if (TemplateDeductionResult Result =
3758  DeduceTemplateArguments(Partial, TemplateArgList, Info)) {
3759  // Store the failed-deduction information for use in diagnostics, later.
3760  // TODO: Actually use the failed-deduction info?
3761  FailedCandidates.addCandidate().set(
3762  DeclAccessPair::make(Template, AS_public), Partial,
3763  MakeDeductionFailureInfo(Context, Result, Info));
3764  (void)Result;
3765  } else {
3766  Matched.push_back(PartialSpecMatchResult());
3767  Matched.back().Partial = Partial;
3768  Matched.back().Args = Info.take();
3769  }
3770  }
3771 
3772  if (Matched.size() >= 1) {
3773  SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
3774  if (Matched.size() == 1) {
3775  // -- If exactly one matching specialization is found, the
3776  // instantiation is generated from that specialization.
3777  // We don't need to do anything for this.
3778  } else {
3779  // -- If more than one matching specialization is found, the
3780  // partial order rules (14.5.4.2) are used to determine
3781  // whether one of the specializations is more specialized
3782  // than the others. If none of the specializations is more
3783  // specialized than all of the other matching
3784  // specializations, then the use of the variable template is
3785  // ambiguous and the program is ill-formed.
3786  for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
3787  PEnd = Matched.end();
3788  P != PEnd; ++P) {
3789  if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
3790  PointOfInstantiation) ==
3791  P->Partial)
3792  Best = P;
3793  }
3794 
3795  // Determine if the best partial specialization is more specialized than
3796  // the others.
3797  for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
3798  PEnd = Matched.end();
3799  P != PEnd; ++P) {
3800  if (P != Best && getMoreSpecializedPartialSpecialization(
3801  P->Partial, Best->Partial,
3802  PointOfInstantiation) != Best->Partial) {
3803  AmbiguousPartialSpec = true;
3804  break;
3805  }
3806  }
3807  }
3808 
3809  // Instantiate using the best variable template partial specialization.
3810  InstantiationPattern = Best->Partial;
3811  InstantiationArgs = Best->Args;
3812  } else {
3813  // -- If no match is found, the instantiation is generated
3814  // from the primary template.
3815  // InstantiationPattern = Template->getTemplatedDecl();
3816  }
3817  }
3818 
3819  // 2. Create the canonical declaration.
3820  // Note that we do not instantiate a definition until we see an odr-use
3821  // in DoMarkVarDeclReferenced().
3822  // FIXME: LateAttrs et al.?
3823  VarTemplateSpecializationDecl *Decl = BuildVarTemplateInstantiation(
3824  Template, InstantiationPattern, *InstantiationArgs, TemplateArgs,
3825  Converted, TemplateNameLoc, InsertPos /*, LateAttrs, StartingScope*/);
3826  if (!Decl)
3827  return true;
3828 
3829  if (AmbiguousPartialSpec) {
3830  // Partial ordering did not produce a clear winner. Complain.
3831  Decl->setInvalidDecl();
3832  Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
3833  << Decl;
3834 
3835  // Print the matching partial specializations.
3836  for (MatchResult P : Matched)
3837  Diag(P.Partial->getLocation(), diag::note_partial_spec_match)
3838  << getTemplateArgumentBindingsText(P.Partial->getTemplateParameters(),
3839  *P.Args);
3840  return true;
3841  }
3842 
3844  dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
3845  Decl->setInstantiationOf(D, InstantiationArgs);
3846 
3847  checkSpecializationVisibility(TemplateNameLoc, Decl);
3848 
3849  assert(Decl && "No variable template specialization?");
3850  return Decl;
3851 }
3852 
3853 ExprResult
3855  const DeclarationNameInfo &NameInfo,
3856  VarTemplateDecl *Template, SourceLocation TemplateLoc,
3857  const TemplateArgumentListInfo *TemplateArgs) {
3858 
3859  DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
3860  *TemplateArgs);
3861  if (Decl.isInvalid())
3862  return ExprError();
3863 
3864  VarDecl *Var = cast<VarDecl>(Decl.get());
3865  if (!Var->getTemplateSpecializationKind())
3867  NameInfo.getLoc());
3868 
3869  // Build an ordinary singleton decl ref.
3870  return BuildDeclarationNameExpr(SS, NameInfo, Var,
3871  /*FoundD=*/nullptr, TemplateArgs);
3872 }
3873 
3875  SourceLocation TemplateKWLoc,
3876  LookupResult &R,
3877  bool RequiresADL,
3878  const TemplateArgumentListInfo *TemplateArgs) {
3879  // FIXME: Can we do any checking at this point? I guess we could check the
3880  // template arguments that we have against the template name, if the template
3881  // name refers to a single template. That's not a terribly common case,
3882  // though.
3883  // foo<int> could identify a single function unambiguously
3884  // This approach does NOT work, since f<int>(1);
3885  // gets resolved prior to resorting to overload resolution
3886  // i.e., template<class T> void f(double);
3887  // vs template<class T, class U> void f(U);
3888 
3889  // These should be filtered out by our callers.
3890  assert(!R.empty() && "empty lookup results when building templateid");
3891  assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
3892 
3893  // In C++1y, check variable template ids.
3894  bool InstantiationDependent;
3895  if (R.getAsSingle<VarTemplateDecl>() &&
3897  *TemplateArgs, InstantiationDependent)) {
3898  return CheckVarTemplateId(SS, R.getLookupNameInfo(),
3900  TemplateKWLoc, TemplateArgs);
3901  }
3902 
3903  // We don't want lookup warnings at this point.
3904  R.suppressDiagnostics();
3905 
3909  TemplateKWLoc,
3910  R.getLookupNameInfo(),
3911  RequiresADL, TemplateArgs,
3912  R.begin(), R.end());
3913 
3914  return ULE;
3915 }
3916 
3917 // We actually only call this from template instantiation.
3918 ExprResult
3920  SourceLocation TemplateKWLoc,
3921  const DeclarationNameInfo &NameInfo,
3922  const TemplateArgumentListInfo *TemplateArgs) {
3923 
3924  assert(TemplateArgs || TemplateKWLoc.isValid());
3925  DeclContext *DC;
3926  if (!(DC = computeDeclContext(SS, false)) ||
3927  DC->isDependentContext() ||
3928  RequireCompleteDeclContext(SS, DC))
3929  return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
3930 
3931  bool MemberOfUnknownSpecialization;
3932  LookupResult R(*this, NameInfo, LookupOrdinaryName);
3933  LookupTemplateName(R, (Scope*)nullptr, SS, QualType(), /*Entering*/ false,
3934  MemberOfUnknownSpecialization);
3935 
3936  if (R.isAmbiguous())
3937  return ExprError();
3938 
3939  if (R.empty()) {
3940  Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_non_template)
3941  << NameInfo.getName() << SS.getRange();
3942  return ExprError();
3943  }
3944 
3945  if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
3946  Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
3947  << SS.getScopeRep()
3948  << NameInfo.getName().getAsString() << SS.getRange();
3949  Diag(Temp->getLocation(), diag::note_referenced_class_template);
3950  return ExprError();
3951  }
3952 
3953  return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL*/ false, TemplateArgs);
3954 }
3955 
3956 /// \brief Form a dependent template name.
3957 ///
3958 /// This action forms a dependent template name given the template
3959 /// name and its (presumably dependent) scope specifier. For
3960 /// example, given "MetaFun::template apply", the scope specifier \p
3961 /// SS will be "MetaFun::", \p TemplateKWLoc contains the location
3962 /// of the "template" keyword, and "apply" is the \p Name.
3964  CXXScopeSpec &SS,
3965  SourceLocation TemplateKWLoc,
3967  ParsedType ObjectType,
3968  bool EnteringContext,
3969  TemplateTy &Result,
3970  bool AllowInjectedClassName) {
3971  if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
3972  Diag(TemplateKWLoc,
3973  getLangOpts().CPlusPlus11 ?
3974  diag::warn_cxx98_compat_template_outside_of_template :
3975  diag::ext_template_outside_of_template)
3976  << FixItHint::CreateRemoval(TemplateKWLoc);
3977 
3978  DeclContext *LookupCtx = nullptr;
3979  if (SS.isSet())
3980  LookupCtx = computeDeclContext(SS, EnteringContext);
3981  if (!LookupCtx && ObjectType)
3982  LookupCtx = computeDeclContext(ObjectType.get());
3983  if (LookupCtx) {
3984  // C++0x [temp.names]p5:
3985  // If a name prefixed by the keyword template is not the name of
3986  // a template, the program is ill-formed. [Note: the keyword
3987  // template may not be applied to non-template members of class
3988  // templates. -end note ] [ Note: as is the case with the
3989  // typename prefix, the template prefix is allowed in cases
3990  // where it is not strictly necessary; i.e., when the
3991  // nested-name-specifier or the expression on the left of the ->
3992  // or . is not dependent on a template-parameter, or the use
3993  // does not appear in the scope of a template. -end note]
3994  //
3995  // Note: C++03 was more strict here, because it banned the use of
3996  // the "template" keyword prior to a template-name that was not a
3997  // dependent name. C++ DR468 relaxed this requirement (the
3998  // "template" keyword is now permitted). We follow the C++0x
3999  // rules, even in C++03 mode with a warning, retroactively applying the DR.
4000  bool MemberOfUnknownSpecialization;
4001  TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
4002  ObjectType, EnteringContext, Result,
4003  MemberOfUnknownSpecialization);
4004  if (TNK == TNK_Non_template && LookupCtx->isDependentContext() &&
4005  isa<CXXRecordDecl>(LookupCtx) &&
4006  (!cast<CXXRecordDecl>(LookupCtx)->hasDefinition() ||
4007  cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases())) {
4008  // This is a dependent template. Handle it below.
4009  } else if (TNK == TNK_Non_template) {
4010  Diag(Name.getLocStart(),
4011  diag::err_template_kw_refers_to_non_template)
4012  << GetNameFromUnqualifiedId(Name).getName()
4013  << Name.getSourceRange()
4014  << TemplateKWLoc;
4015  return TNK_Non_template;
4016  } else {
4017  // We found something; return it.
4018  auto *LookupRD = dyn_cast<CXXRecordDecl>(LookupCtx);
4019  if (!AllowInjectedClassName && SS.isSet() && LookupRD &&
4020  Name.getKind() == UnqualifiedId::IK_Identifier && Name.Identifier &&
4021  LookupRD->getIdentifier() == Name.Identifier) {
4022  // C++14 [class.qual]p2:
4023  // In a lookup in which function names are not ignored and the
4024  // nested-name-specifier nominates a class C, if the name specified
4025  // [...] is the injected-class-name of C, [...] the name is instead
4026  // considered to name the constructor
4027  //
4028  // We don't get here if naming the constructor would be valid, so we
4029  // just reject immediately and recover by treating the
4030  // injected-class-name as naming the template.
4031  Diag(Name.getLocStart(),
4032  diag::ext_out_of_line_qualified_id_type_names_constructor)
4033  << Name.Identifier << 0 /*injected-class-name used as template name*/
4034  << 1 /*'template' keyword was used*/;
4035  }
4036  return TNK;
4037  }
4038  }
4039 
4040  NestedNameSpecifier *Qualifier = SS.getScopeRep();
4041 
4042  switch (Name.getKind()) {
4044  Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
4045  Name.Identifier));
4047 
4049  Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
4051  return TNK_Function_template;
4052 
4054  llvm_unreachable("literal operator id cannot have a dependent scope");
4055 
4056  default:
4057  break;
4058  }
4059 
4060  Diag(Name.getLocStart(),
4061  diag::err_template_kw_refers_to_non_template)
4062  << GetNameFromUnqualifiedId(Name).getName()
4063  << Name.getSourceRange()
4064  << TemplateKWLoc;
4065  return TNK_Non_template;
4066 }
4067 
4069  TemplateArgumentLoc &AL,
4070  SmallVectorImpl<TemplateArgument> &Converted) {
4071  const TemplateArgument &Arg = AL.getArgument();
4072  QualType ArgType;
4073  TypeSourceInfo *TSI = nullptr;
4074 
4075  // Check template type parameter.
4076  switch(Arg.getKind()) {
4078  // C++ [temp.arg.type]p1:
4079  // A template-argument for a template-parameter which is a
4080  // type shall be a type-id.
4081  ArgType = Arg.getAsType();
4082  TSI = AL.getTypeSourceInfo();
4083  break;
4085  // We have a template type parameter but the template argument
4086  // is a template without any arguments.
4087  SourceRange SR = AL.getSourceRange();
4089  Diag(SR.getBegin(), diag::err_template_missing_args)
4090  << (int)getTemplateNameKindForDiagnostics(Name) << Name << SR;
4091  if (TemplateDecl *Decl = Name.getAsTemplateDecl())
4092  Diag(Decl->getLocation(), diag::note_template_decl_here);
4093 
4094  return true;
4095  }
4097  // We have a template type parameter but the template argument is an
4098  // expression; see if maybe it is missing the "typename" keyword.
4099  CXXScopeSpec SS;
4100  DeclarationNameInfo NameInfo;
4101 
4102  if (DeclRefExpr *ArgExpr = dyn_cast<DeclRefExpr>(Arg.getAsExpr())) {
4103  SS.Adopt(ArgExpr->getQualifierLoc());
4104  NameInfo = ArgExpr->getNameInfo();
4105  } else if (DependentScopeDeclRefExpr *ArgExpr =
4106  dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
4107  SS.Adopt(ArgExpr->getQualifierLoc());
4108  NameInfo = ArgExpr->getNameInfo();
4109  } else if (CXXDependentScopeMemberExpr *ArgExpr =
4110  dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
4111  if (ArgExpr->isImplicitAccess()) {
4112  SS.Adopt(ArgExpr->getQualifierLoc());
4113  NameInfo = ArgExpr->getMemberNameInfo();
4114  }
4115  }
4116 
4117  if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
4118  LookupResult Result(*this, NameInfo, LookupOrdinaryName);
4119  LookupParsedName(Result, CurScope, &SS);
4120 
4121  if (Result.getAsSingle<TypeDecl>() ||
4122  Result.getResultKind() ==
4124  // Suggest that the user add 'typename' before the NNS.
4125  SourceLocation Loc = AL.getSourceRange().getBegin();
4126  Diag(Loc, getLangOpts().MSVCCompat
4127  ? diag::ext_ms_template_type_arg_missing_typename
4128  : diag::err_template_arg_must_be_type_suggest)
4129  << FixItHint::CreateInsertion(Loc, "typename ");
4130  Diag(Param->getLocation(), diag::note_template_param_here);
4131 
4132  // Recover by synthesizing a type using the location information that we
4133  // already have.
4134  ArgType =
4136  TypeLocBuilder TLB;
4137  DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(ArgType);
4138  TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
4140  TL.setNameLoc(NameInfo.getLoc());
4141  TSI = TLB.getTypeSourceInfo(Context, ArgType);
4142 
4143  // Overwrite our input TemplateArgumentLoc so that we can recover
4144  // properly.
4145  AL = TemplateArgumentLoc(TemplateArgument(ArgType),
4147 
4148  break;
4149  }
4150  }
4151  // fallthrough
4152  LLVM_FALLTHROUGH;
4153  }
4154  default: {
4155  // We have a template type parameter but the template argument
4156  // is not a type.
4157  SourceRange SR = AL.getSourceRange();
4158  Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
4159  Diag(Param->getLocation(), diag::note_template_param_here);
4160 
4161  return true;
4162  }
4163  }
4164 
4165  if (CheckTemplateArgument(Param, TSI))
4166  return true;
4167 
4168  // Add the converted template type argument.
4169  ArgType = Context.getCanonicalType(ArgType);
4170 
4171  // Objective-C ARC:
4172  // If an explicitly-specified template argument type is a lifetime type
4173  // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
4174  if (getLangOpts().ObjCAutoRefCount &&
4175  ArgType->isObjCLifetimeType() &&
4176  !ArgType.getObjCLifetime()) {
4177  Qualifiers Qs;
4179  ArgType = Context.getQualifiedType(ArgType, Qs);
4180  }
4181 
4182  Converted.push_back(TemplateArgument(ArgType));
4183  return false;
4184 }
4185 
4186 /// \brief Substitute template arguments into the default template argument for
4187 /// the given template type parameter.
4188 ///
4189 /// \param SemaRef the semantic analysis object for which we are performing
4190 /// the substitution.
4191 ///
4192 /// \param Template the template that we are synthesizing template arguments
4193 /// for.
4194 ///
4195 /// \param TemplateLoc the location of the template name that started the
4196 /// template-id we are checking.
4197 ///
4198 /// \param RAngleLoc the location of the right angle bracket ('>') that
4199 /// terminates the template-id.
4200 ///
4201 /// \param Param the template template parameter whose default we are
4202 /// substituting into.
4203 ///
4204 /// \param Converted the list of template arguments provided for template
4205 /// parameters that precede \p Param in the template parameter list.
4206 /// \returns the substituted template argument, or NULL if an error occurred.
4207 static TypeSourceInfo *
4209  TemplateDecl *Template,
4210  SourceLocation TemplateLoc,
4211  SourceLocation RAngleLoc,
4212  TemplateTypeParmDecl *Param,
4213  SmallVectorImpl<TemplateArgument> &Converted) {
4214  TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
4215 
4216  // If the argument type is dependent, instantiate it now based
4217  // on the previously-computed template arguments.
4218  if (ArgType->getType()->isDependentType()) {
4219  Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
4220  Param, Template, Converted,
4221  SourceRange(TemplateLoc, RAngleLoc));
4222  if (Inst.isInvalid())
4223  return nullptr;
4224 
4225  TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
4226 
4227  // Only substitute for the innermost template argument list.
4228  MultiLevelTemplateArgumentList TemplateArgLists;
4229  TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
4230  for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4231  TemplateArgLists.addOuterTemplateArguments(None);
4232 
4233  Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
4234  ArgType =
4235  SemaRef.SubstType(ArgType, TemplateArgLists,
4236  Param->getDefaultArgumentLoc(), Param->getDeclName());
4237  }
4238 
4239  return ArgType;
4240 }
4241 
4242 /// \brief Substitute template arguments into the default template argument for
4243 /// the given non-type template parameter.
4244 ///
4245 /// \param SemaRef the semantic analysis object for which we are performing
4246 /// the substitution.
4247 ///
4248 /// \param Template the template that we are synthesizing template arguments
4249 /// for.
4250 ///
4251 /// \param TemplateLoc the location of the template name that started the
4252 /// template-id we are checking.
4253 ///
4254 /// \param RAngleLoc the location of the right angle bracket ('>') that
4255 /// terminates the template-id.
4256 ///
4257 /// \param Param the non-type template parameter whose default we are
4258 /// substituting into.
4259 ///
4260 /// \param Converted the list of template arguments provided for template
4261 /// parameters that precede \p Param in the template parameter list.
4262 ///
4263 /// \returns the substituted template argument, or NULL if an error occurred.
4264 static ExprResult
4266  TemplateDecl *Template,
4267  SourceLocation TemplateLoc,
4268  SourceLocation RAngleLoc,
4269  NonTypeTemplateParmDecl *Param,
4270  SmallVectorImpl<TemplateArgument> &Converted) {
4271  Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
4272  Param, Template, Converted,
4273  SourceRange(TemplateLoc, RAngleLoc));
4274  if (Inst.isInvalid())
4275  return ExprError();
4276 
4277  TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
4278 
4279  // Only substitute for the innermost template argument list.
4280  MultiLevelTemplateArgumentList TemplateArgLists;
4281  TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
4282  for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4283  TemplateArgLists.addOuterTemplateArguments(None);
4284 
4285  EnterExpressionEvaluationContext ConstantEvaluated(
4287  return SemaRef.SubstExpr(Param->getDefaultArgument(), TemplateArgLists);
4288 }
4289 
4290 /// \brief Substitute template arguments into the default template argument for
4291 /// the given template template parameter.
4292 ///
4293 /// \param SemaRef the semantic analysis object for which we are performing
4294 /// the substitution.
4295 ///
4296 /// \param Template the template that we are synthesizing template arguments
4297 /// for.
4298 ///
4299 /// \param TemplateLoc the location of the template name that started the
4300 /// template-id we are checking.
4301 ///
4302 /// \param RAngleLoc the location of the right angle bracket ('>') that
4303 /// terminates the template-id.
4304 ///
4305 /// \param Param the template template parameter whose default we are
4306 /// substituting into.
4307 ///
4308 /// \param Converted the list of template arguments provided for template
4309 /// parameters that precede \p Param in the template parameter list.
4310 ///
4311 /// \param QualifierLoc Will be set to the nested-name-specifier (with
4312 /// source-location information) that precedes the template name.
4313 ///
4314 /// \returns the substituted template argument, or NULL if an error occurred.
4315 static TemplateName
4317  TemplateDecl *Template,
4318  SourceLocation TemplateLoc,
4319  SourceLocation RAngleLoc,
4320  TemplateTemplateParmDecl *Param,
4322  NestedNameSpecifierLoc &QualifierLoc) {
4324  SemaRef, TemplateLoc, TemplateParameter(Param), Template, Converted,
4325  SourceRange(TemplateLoc, RAngleLoc));
4326  if (Inst.isInvalid())
4327  return TemplateName();
4328 
4329  TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
4330 
4331  // Only substitute for the innermost template argument list.
4332  MultiLevelTemplateArgumentList TemplateArgLists;
4333  TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
4334  for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4335  TemplateArgLists.addOuterTemplateArguments(None);
4336 
4337  Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
4338  // Substitute into the nested-name-specifier first,
4339  QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc();
4340  if (QualifierLoc) {
4341  QualifierLoc =
4342  SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgLists);
4343  if (!QualifierLoc)
4344  return TemplateName();
4345  }
4346 
4347  return SemaRef.SubstTemplateName(
4348  QualifierLoc,
4351  TemplateArgLists);
4352 }
4353 
4354 /// \brief If the given template parameter has a default template
4355 /// argument, substitute into that default template argument and
4356 /// return the corresponding template argument.
4359  SourceLocation TemplateLoc,
4360  SourceLocation RAngleLoc,
4361  Decl *Param,
4363  &Converted,
4364  bool &HasDefaultArg) {
4365  HasDefaultArg = false;
4366 
4367  if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
4368  if (!hasVisibleDefaultArgument(TypeParm))
4369  return TemplateArgumentLoc();
4370 
4371  HasDefaultArg = true;
4372  TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
4373  TemplateLoc,
4374  RAngleLoc,
4375  TypeParm,
4376  Converted);
4377  if (DI)
4378  return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
4379 
4380  return TemplateArgumentLoc();
4381  }
4382 
4383  if (NonTypeTemplateParmDecl *NonTypeParm
4384  = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
4385  if (!hasVisibleDefaultArgument(NonTypeParm))
4386  return TemplateArgumentLoc();
4387 
4388  HasDefaultArg = true;
4389  ExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
4390  TemplateLoc,
4391  RAngleLoc,
4392  NonTypeParm,
4393  Converted);
4394  if (Arg.isInvalid())
4395  return TemplateArgumentLoc();
4396 
4397  Expr *ArgE = Arg.getAs<Expr>();
4398  return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
4399  }
4400 
4401  TemplateTemplateParmDecl *TempTempParm
4402  = cast<TemplateTemplateParmDecl>(Param);
4403  if (!hasVisibleDefaultArgument(TempTempParm))
4404  return TemplateArgumentLoc();
4405 
4406  HasDefaultArg = true;
4407  NestedNameSpecifierLoc QualifierLoc;
4408  TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
4409  TemplateLoc,
4410  RAngleLoc,
4411  TempTempParm,
4412  Converted,
4413  QualifierLoc);
4414  if (TName.isNull())
4415  return TemplateArgumentLoc();
4416 
4417  return TemplateArgumentLoc(TemplateArgument(TName),
4418  TempTempParm->getDefaultArgument().getTemplateQualifierLoc(),
4419  TempTempParm->getDefaultArgument().getTemplateNameLoc());
4420 }
4421 
4422 /// Convert a template-argument that we parsed as a type into a template, if
4423 /// possible. C++ permits injected-class-names to perform dual service as
4424 /// template template arguments and as template type arguments.
4426  // Extract and step over any surrounding nested-name-specifier.
4427  NestedNameSpecifierLoc QualLoc;
4428  if (auto ETLoc = TLoc.getAs<ElaboratedTypeLoc>()) {
4429  if (ETLoc.getTypePtr()->getKeyword() != ETK_None)
4430  return TemplateArgumentLoc();
4431 
4432  QualLoc = ETLoc.getQualifierLoc();
4433  TLoc = ETLoc.getNamedTypeLoc();
4434  }
4435 
4436  // If this type was written as an injected-class-name, it can be used as a
4437  // template template argument.
4438  if (auto InjLoc = TLoc.getAs<InjectedClassNameTypeLoc>())
4439  return TemplateArgumentLoc(InjLoc.getTypePtr()->getTemplateName(),
4440  QualLoc, InjLoc.getNameLoc());
4441 
4442  // If this type was written as an injected-class-name, it may have been
4443  // converted to a RecordType during instantiation. If the RecordType is
4444  // *not* wrapped in a TemplateSpecializationType and denotes a class
4445  // template specialization, it must have come from an injected-class-name.
4446  if (auto RecLoc = TLoc.getAs<RecordTypeLoc>())
4447  if (auto *CTSD =
4448  dyn_cast<ClassTemplateSpecializationDecl>(RecLoc.getDecl()))
4449  return TemplateArgumentLoc(TemplateName(CTSD->getSpecializedTemplate()),
4450  QualLoc, RecLoc.getNameLoc());
4451 
4452  return TemplateArgumentLoc();
4453 }
4454 
4455 /// \brief Check that the given template argument corresponds to the given
4456 /// template parameter.
4457 ///
4458 /// \param Param The template parameter against which the argument will be
4459 /// checked.
4460 ///
4461 /// \param Arg The template argument, which may be updated due to conversions.
4462 ///
4463 /// \param Template The template in which the template argument resides.
4464 ///
4465 /// \param TemplateLoc The location of the template name for the template
4466 /// whose argument list we're matching.
4467 ///
4468 /// \param RAngleLoc The location of the right angle bracket ('>') that closes
4469 /// the template argument list.
4470 ///
4471 /// \param ArgumentPackIndex The index into the argument pack where this
4472 /// argument will be placed. Only valid if the parameter is a parameter pack.
4473 ///
4474 /// \param Converted The checked, converted argument will be added to the
4475 /// end of this small vector.
4476 ///
4477 /// \param CTAK Describes how we arrived at this particular template argument:
4478 /// explicitly written, deduced, etc.
4479 ///
4480 /// \returns true on error, false otherwise.
4482  TemplateArgumentLoc &Arg,
4483  NamedDecl *Template,
4484  SourceLocation TemplateLoc,
4485  SourceLocation RAngleLoc,
4486  unsigned ArgumentPackIndex,
4489  // Check template type parameters.
4490  if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
4491  return CheckTemplateTypeArgument(TTP, Arg, Converted);
4492 
4493  // Check non-type template parameters.
4494  if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
4495  // Do substitution on the type of the non-type template parameter
4496  // with the template arguments we've seen thus far. But if the
4497  // template has a dependent context then we cannot substitute yet.
4498  QualType NTTPType = NTTP->getType();
4499  if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
4500  NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
4501 
4502  if (NTTPType->isDependentType() &&
4503  !isa<TemplateTemplateParmDecl>(Template) &&
4504  !Template->getDeclContext()->isDependentContext()) {
4505  // Do substitution on the type of the non-type template parameter.
4506  InstantiatingTemplate Inst(*this, TemplateLoc, Template,
4507  NTTP, Converted,
4508  SourceRange(TemplateLoc, RAngleLoc));
4509  if (Inst.isInvalid())
4510  return true;
4511 
4513  Converted);
4514  NTTPType = SubstType(NTTPType,
4515  MultiLevelTemplateArgumentList(TemplateArgs),
4516  NTTP->getLocation(),
4517  NTTP->getDeclName());
4518  // If that worked, check the non-type template parameter type
4519  // for validity.
4520  if (!NTTPType.isNull())
4521  NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
4522  NTTP->getLocation());
4523  if (NTTPType.isNull())
4524  return true;
4525  }
4526 
4527  switch (Arg.getArgument().getKind()) {
4529  llvm_unreachable("Should never see a NULL template argument here");
4530 
4532  TemplateArgument Result;
4533  ExprResult Res =
4534  CheckTemplateArgument(NTTP, NTTPType, Arg.getArgument().getAsExpr(),
4535  Result, CTAK);
4536  if (Res.isInvalid())
4537  return true;
4538 
4539  // If the resulting expression is new, then use it in place of the
4540  // old expression in the template argument.
4541  if (Res.get() != Arg.getArgument().getAsExpr()) {
4542  TemplateArgument TA(Res.get());
4543  Arg = TemplateArgumentLoc(TA, Res.get());
4544  }
4545 
4546  Converted.push_back(Result);
4547  break;
4548  }
4549 
4553  // We've already checked this template argument, so just copy
4554  // it to the list of converted arguments.
4555  Converted.push_back(Arg.getArgument());
4556  break;
4557 
4560  // We were given a template template argument. It may not be ill-formed;
4561  // see below.
4562  if (DependentTemplateName *DTN
4565  // We have a template argument such as \c T::template X, which we
4566  // parsed as a template template argument. However, since we now
4567  // know that we need a non-type template argument, convert this
4568  // template name into an expression.
4569 
4570  DeclarationNameInfo NameInfo(DTN->getIdentifier(),
4571  Arg.getTemplateNameLoc());
4572 
4573  CXXScopeSpec SS;
4574  SS.Adopt(Arg.getTemplateQualifierLoc());
4575  // FIXME: the template-template arg was a DependentTemplateName,
4576  // so it was provided with a template keyword. However, its source
4577  // location is not stored in the template argument structure.
4578  SourceLocation TemplateKWLoc;
4580  Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
4581  nullptr);
4582 
4583  // If we parsed the template argument as a pack expansion, create a
4584  // pack expansion expression.
4586  E = ActOnPackExpansion(E.get(), Arg.getTemplateEllipsisLoc());
4587  if (E.isInvalid())
4588  return true;
4589  }
4590 
4591  TemplateArgument Result;
4592  E = CheckTemplateArgument(NTTP, NTTPType, E.get(), Result);
4593  if (E.isInvalid())
4594  return true;
4595 
4596  Converted.push_back(Result);
4597  break;
4598  }
4599 
4600  // We have a template argument that actually does refer to a class
4601  // template, alias template, or template template parameter, and
4602  // therefore cannot be a non-type template argument.
4603  Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
4604  << Arg.getSourceRange();
4605 
4606  Diag(Param->getLocation(), diag::note_template_param_here);
4607  return true;
4608 
4609  case TemplateArgument::Type: {
4610  // We have a non-type template parameter but the template
4611  // argument is a type.
4612 
4613  // C++ [temp.arg]p2:
4614  // In a template-argument, an ambiguity between a type-id and
4615  // an expression is resolved to a type-id, regardless of the
4616  // form of the corresponding template-parameter.
4617  //
4618  // We warn specifically about this case, since it can be rather
4619  // confusing for users.
4620  QualType T = Arg.getArgument().getAsType();
4621  SourceRange SR = Arg.getSourceRange();
4622  if (T->isFunctionType())
4623  Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
4624  else
4625  Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
4626  Diag(Param->getLocation(), diag::note_template_param_here);
4627  return true;
4628  }
4629 
4631  llvm_unreachable("Caller must expand template argument packs");
4632  }
4633 
4634  return false;
4635  }
4636 
4637 
4638  // Check template template parameters.
4639  TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
4640 
4641  // Substitute into the template parameter list of the template
4642  // template parameter, since previously-supplied template arguments
4643  // may appear within the template template parameter.
4644  {
4645  // Set up a template instantiation context.
4647  InstantiatingTemplate Inst(*this, TemplateLoc, Template,
4648  TempParm, Converted,
4649  SourceRange(TemplateLoc, RAngleLoc));
4650  if (Inst.isInvalid())
4651  return true;
4652 
4653  TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
4654  TempParm = cast_or_null<TemplateTemplateParmDecl>(
4655  SubstDecl(TempParm, CurContext,
4656  MultiLevelTemplateArgumentList(TemplateArgs)));
4657  if (!TempParm)
4658  return true;
4659  }
4660 
4661  // C++1z [temp.local]p1: (DR1004)
4662  // When [the injected-class-name] is used [...] as a template-argument for
4663  // a template template-parameter [...] it refers to the class template
4664  // itself.
4665  if (Arg.getArgument().getKind() == TemplateArgument::Type) {
4667  Arg.getTypeSourceInfo()->getTypeLoc());
4668  if (!ConvertedArg.getArgument().isNull())
4669  Arg = ConvertedArg;
4670  }
4671 
4672  switch (Arg.getArgument().getKind()) {
4674  llvm_unreachable("Should never see a NULL template argument here");
4675 
4678  if (CheckTemplateArgument(TempParm, Arg, ArgumentPackIndex))
4679  return true;
4680 
4681  Converted.push_back(Arg.getArgument());
4682  break;
4683 
4686  // We have a template template parameter but the template
4687  // argument does not refer to a template.
4688  Diag(Arg.getLocation(), diag::err_template_arg_must_be_template)
4689  << getLangOpts().CPlusPlus11;
4690  return true;
4691 
4693  llvm_unreachable("Declaration argument with template template parameter");
4695  llvm_unreachable("Integral argument with template template parameter");
4697  llvm_unreachable("Null pointer argument with template template parameter");
4698 
4700  llvm_unreachable("Caller must expand template argument packs");
4701  }
4702 
4703  return false;
4704 }
4705 
4706 /// \brief Diagnose an arity mismatch in the
4707 static bool diagnoseArityMismatch(Sema &S, TemplateDecl *Template,
4708  SourceLocation TemplateLoc,
4709  TemplateArgumentListInfo &TemplateArgs) {
4710  TemplateParameterList *Params = Template->getTemplateParameters();
4711  unsigned NumParams = Params->size();
4712  unsigned NumArgs = TemplateArgs.size();
4713 
4714  SourceRange Range;
4715  if (NumArgs > NumParams)
4716  Range = SourceRange(TemplateArgs[NumParams].getLocation(),
4717  TemplateArgs.getRAngleLoc());
4718  S.Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
4719  << (NumArgs > NumParams)
4720  << (int)S.getTemplateNameKindForDiagnostics(TemplateName(Template))
4721  << Template << Range;
4722  S.Diag(Template->getLocation(), diag::note_template_decl_here)
4723  << Params->getSourceRange();
4724  return true;
4725 }
4726 
4727 /// \brief Check whether the template parameter is a pack expansion, and if so,
4728 /// determine the number of parameters produced by that expansion. For instance:
4729 ///
4730 /// \code
4731 /// template<typename ...Ts> struct A {
4732 /// template<Ts ...NTs, template<Ts> class ...TTs, typename ...Us> struct B;
4733 /// };
4734 /// \endcode
4735 ///
4736 /// In \c A<int,int>::B, \c NTs and \c TTs have expanded pack size 2, and \c Us
4737 /// is not a pack expansion, so returns an empty Optional.
4739  if (NonTypeTemplateParmDecl *NTTP
4740  = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
4741  if (NTTP->isExpandedParameterPack())
4742  return NTTP->getNumExpansionTypes();
4743  }
4744 
4745  if (TemplateTemplateParmDecl *TTP
4746  = dyn_cast<TemplateTemplateParmDecl>(Param)) {
4747  if (TTP->isExpandedParameterPack())
4748  return TTP->getNumExpansionTemplateParameters();
4749  }
4750 
4751  return None;
4752 }
4753 
4754 /// Diagnose a missing template argument.
4755 template<typename TemplateParmDecl>
4757  TemplateDecl *TD,
4758  const TemplateParmDecl *D,
4759  TemplateArgumentListInfo &Args) {
4760  // Dig out the most recent declaration of the template parameter; there may be
4761  // declarations of the template that are more recent than TD.
4762  D = cast<TemplateParmDecl>(cast<TemplateDecl>(TD->getMostRecentDecl())
4763  ->getTemplateParameters()
4764  ->getParam(D->getIndex()));
4765 
4766  // If there's a default argument that's not visible, diagnose that we're
4767  // missing a module import.
4769  if (D->hasDefaultArgument() && !S.hasVisibleDefaultArgument(D, &Modules)) {
4770  S.diagnoseMissingImport(Loc, cast<NamedDecl>(TD),
4771  D->getDefaultArgumentLoc(), Modules,
4773  /*Recover*/true);
4774  return true;
4775  }
4776 
4777  // FIXME: If there's a more recent default argument that *is* visible,
4778  // diagnose that it was declared too late.
4779 
4780  return diagnoseArityMismatch(S, TD, Loc, Args);
4781 }
4782 
4783 /// \brief Check that the given template argument list is well-formed
4784 /// for specializing the given template.
4786  TemplateDecl *Template, SourceLocation TemplateLoc,
4787  TemplateArgumentListInfo &TemplateArgs, bool PartialTemplateArgs,
4789  bool UpdateArgsWithConversions) {
4790  // Make a copy of the template arguments for processing. Only make the
4791  // changes at the end when successful in matching the arguments to the
4792  // template.
4793  TemplateArgumentListInfo NewArgs = TemplateArgs;
4794 
4795  TemplateParameterList *Params = Template->getTemplateParameters();
4796 
4797  SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
4798 
4799  // C++ [temp.arg]p1:
4800  // [...] The type and form of each template-argument specified in
4801  // a template-id shall match the type and form specified for the
4802  // corresponding parameter declared by the template in its
4803  // template-parameter-list.
4804  bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
4805  SmallVector<TemplateArgument, 2> ArgumentPack;
4806  unsigned ArgIdx = 0, NumArgs = NewArgs.size();
4807  LocalInstantiationScope InstScope(*this, true);
4808  for (TemplateParameterList::iterator Param = Params->begin(),
4809  ParamEnd = Params->end();
4810  Param != ParamEnd; /* increment in loop */) {
4811  // If we have an expanded parameter pack, make sure we don't have too
4812  // many arguments.
4813  if (Optional<unsigned> Expansions = getExpandedPackSize(*Param)) {
4814  if (*Expansions == ArgumentPack.size()) {
4815  // We're done with this parameter pack. Pack up its arguments and add
4816  // them to the list.
4817  Converted.push_back(
4818  TemplateArgument::CreatePackCopy(Context, ArgumentPack));
4819  ArgumentPack.clear();
4820 
4821  // This argument is assigned to the next parameter.
4822  ++Param;
4823  continue;
4824  } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
4825  // Not enough arguments for this parameter pack.
4826  Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
4827  << false
4828  << (int)getTemplateNameKindForDiagnostics(TemplateName(Template))
4829  << Template;
4830  Diag(Template->getLocation(), diag::note_template_decl_here)
4831  << Params->getSourceRange();
4832  return true;
4833  }
4834  }
4835 
4836  if (ArgIdx < NumArgs) {
4837  // Check the template argument we were given.
4838  if (CheckTemplateArgument(*Param, NewArgs[ArgIdx], Template,
4839  TemplateLoc, RAngleLoc,
4840  ArgumentPack.size(), Converted))
4841  return true;
4842 
4843  bool PackExpansionIntoNonPack =
4844  NewArgs[ArgIdx].getArgument().isPackExpansion() &&
4845  (!(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param));
4846  if (PackExpansionIntoNonPack && isa<TypeAliasTemplateDecl>(Template)) {
4847  // Core issue 1430: we have a pack expansion as an argument to an
4848  // alias template, and it's not part of a parameter pack. This
4849  // can't be canonicalized, so reject it now.
4850  Diag(NewArgs[ArgIdx].getLocation(),
4851  diag::err_alias_template_expansion_into_fixed_list)
4852  << NewArgs[ArgIdx].getSourceRange();
4853  Diag((*Param)->getLocation(), diag::note_template_param_here);
4854  return true;
4855  }
4856 
4857  // We're now done with this argument.
4858  ++ArgIdx;
4859 
4860  if ((*Param)->isTemplateParameterPack()) {
4861  // The template parameter was a template parameter pack, so take the
4862  // deduced argument and place it on the argument pack. Note that we
4863  // stay on the same template parameter so that we can deduce more
4864  // arguments.
4865  ArgumentPack.push_back(Converted.pop_back_val());
4866  } else {
4867  // Move to the next template parameter.
4868  ++Param;
4869  }
4870 
4871  // If we just saw a pack expansion into a non-pack, then directly convert
4872  // the remaining arguments, because we don't know what parameters they'll
4873  // match up with.
4874  if (PackExpansionIntoNonPack) {
4875  if (!ArgumentPack.empty()) {
4876  // If we were part way through filling in an expanded parameter pack,
4877  // fall back to just producing individual arguments.
4878  Converted.insert(Converted.end(),
4879  ArgumentPack.begin(), ArgumentPack.end());
4880  ArgumentPack.clear();
4881  }
4882 
4883  while (ArgIdx < NumArgs) {
4884  Converted.push_back(NewArgs[ArgIdx].getArgument());
4885  ++ArgIdx;
4886  }
4887 
4888  return false;
4889  }
4890 
4891  continue;
4892  }
4893 
4894  // If we're checking a partial template argument list, we're done.
4895  if (PartialTemplateArgs) {
4896  if ((*Param)->isTemplateParameterPack() && !ArgumentPack.empty())
4897  Converted.push_back(
4898  TemplateArgument::CreatePackCopy(Context, ArgumentPack));
4899 
4900  return false;
4901  }
4902 
4903  // If we have a template parameter pack with no more corresponding
4904  // arguments, just break out now and we'll fill in the argument pack below.
4905  if ((*Param)->isTemplateParameterPack()) {
4906  assert(!getExpandedPackSize(*Param) &&
4907  "Should have dealt with this already");
4908 
4909  // A non-expanded parameter pack before the end of the parameter list
4910  // only occurs for an ill-formed template parameter list, unless we've
4911  // got a partial argument list for a function template, so just bail out.
4912  if (Param + 1 != ParamEnd)
4913  return true;
4914 
4915  Converted.push_back(
4916  TemplateArgument::CreatePackCopy(Context, ArgumentPack));
4917  ArgumentPack.clear();
4918 
4919  ++Param;
4920  continue;
4921  }
4922 
4923  // Check whether we have a default argument.
4924  TemplateArgumentLoc Arg;
4925 
4926  // Retrieve the default template argument from the template
4927  // parameter. For each kind of template parameter, we substitute the
4928  // template arguments provided thus far and any "outer" template arguments
4929  // (when the template parameter was part of a nested template) into
4930  // the default argument.
4931  if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
4932  if (!hasVisibleDefaultArgument(TTP))
4933  return diagnoseMissingArgument(*this, TemplateLoc, Template, TTP,
4934  NewArgs);
4935 
4937  Template,
4938  TemplateLoc,
4939  RAngleLoc,
4940  TTP,
4941  Converted);
4942  if (!ArgType)
4943  return true;
4944 
4945  Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
4946  ArgType);
4947  } else if (NonTypeTemplateParmDecl *NTTP
4948  = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
4949  if (!hasVisibleDefaultArgument(NTTP))
4950  return diagnoseMissingArgument(*this, TemplateLoc, Template, NTTP,
4951  NewArgs);
4952 
4953  ExprResult E = SubstDefaultTemplateArgument(*this, Template,
4954  TemplateLoc,
4955  RAngleLoc,
4956  NTTP,
4957  Converted);
4958  if (E.isInvalid())
4959  return true;
4960 
4961  Expr *Ex = E.getAs<Expr>();
4962  Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
4963  } else {
4964  TemplateTemplateParmDecl *TempParm
4965  = cast<TemplateTemplateParmDecl>(*Param);
4966 
4967  if (!hasVisibleDefaultArgument(TempParm))
4968  return diagnoseMissingArgument(*this, TemplateLoc, Template, TempParm,
4969  NewArgs);
4970 
4971  NestedNameSpecifierLoc QualifierLoc;
4973  TemplateLoc,
4974  RAngleLoc,
4975  TempParm,
4976  Converted,
4977  QualifierLoc);
4978  if (Name.isNull())
4979  return true;
4980 
4981  Arg = TemplateArgumentLoc(TemplateArgument(Name), QualifierLoc,
4982  TempParm->getDefaultArgument().getTemplateNameLoc());
4983  }
4984 
4985  // Introduce an instantiation record that describes where we are using
4986  // the default template argument. We're not actually instantiating a
4987  // template here, we just create this object to put a note into the
4988  // context stack.
4989  InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param, Converted,
4990  SourceRange(TemplateLoc, RAngleLoc));
4991  if (Inst.isInvalid())
4992  return true;
4993 
4994  // Check the default template argument.
4995  if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
4996  RAngleLoc, 0, Converted))
4997  return true;
4998 
4999  // Core issue 150 (assumed resolution): if this is a template template
5000  // parameter, keep track of the default template arguments from the
5001  // template definition.
5002  if (isTemplateTemplateParameter)
5003  NewArgs.addArgument(Arg);
5004 
5005  // Move to the next template parameter and argument.
5006  ++Param;
5007  ++ArgIdx;
5008  }
5009 
5010  // If we're performing a partial argument substitution, allow any trailing
5011  // pack expansions; they might be empty. This can happen even if
5012  // PartialTemplateArgs is false (the list of arguments is complete but
5013  // still dependent).
5014  if (ArgIdx < NumArgs && CurrentInstantiationScope &&
5015  CurrentInstantiationScope->getPartiallySubstitutedPack()) {
5016  while (ArgIdx < NumArgs && NewArgs[ArgIdx].getArgument().isPackExpansion())
5017  Converted.push_back(NewArgs[ArgIdx++].getArgument());
5018  }
5019 
5020  // If we have any leftover arguments, then there were too many arguments.
5021  // Complain and fail.
5022  if (ArgIdx < NumArgs)
5023  return diagnoseArityMismatch(*this, Template, TemplateLoc, NewArgs);
5024 
5025  // No problems found with the new argument list, propagate changes back
5026  // to caller.
5027  if (UpdateArgsWithConversions)
5028  TemplateArgs = std::move(NewArgs);
5029 
5030  return false;
5031 }
5032 
5033 namespace {
5034  class UnnamedLocalNoLinkageFinder
5035  : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
5036  {
5037  Sema &S;
5038  SourceRange SR;
5039 
5041 
5042  public:
5043  UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
5044 
5045  bool Visit(QualType T) {
5046  return T.isNull() ? false : inherited::Visit(T.getTypePtr());
5047  }
5048 
5049 #define TYPE(Class, Parent) \
5050  bool Visit##Class##Type(const Class##Type *);
5051 #define ABSTRACT_TYPE(Class, Parent) \
5052  bool Visit##Class##Type(const Class##Type *) { return false; }
5053 #define NON_CANONICAL_TYPE(Class, Parent) \
5054  bool Visit##Class##Type(const Class##Type *) { return false; }
5055 #include "clang/AST/TypeNodes.def"
5056 
5057  bool VisitTagDecl(const TagDecl *Tag);
5058  bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
5059  };
5060 } // end anonymous namespace
5061 
5062 bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
5063  return false;
5064 }
5065 
5066 bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
5067  return Visit(T->getElementType());
5068 }
5069 
5070 bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
5071  return Visit(T->getPointeeType());
5072 }
5073 
5074 bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
5075  const BlockPointerType* T) {
5076  return Visit(T->getPointeeType());
5077 }
5078 
5079 bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
5080  const LValueReferenceType* T) {
5081  return Visit(T->getPointeeType());
5082 }
5083 
5084 bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
5085  const RValueReferenceType* T) {
5086  return Visit(T->getPointeeType());
5087 }
5088 
5089 bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
5090  const MemberPointerType* T) {
5091  return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
5092 }
5093 
5094 bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
5095  const ConstantArrayType* T) {
5096  return Visit(T->getElementType());
5097 }
5098 
5099 bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
5100  const IncompleteArrayType* T) {
5101  return Visit(T->getElementType());
5102 }
5103 
5104 bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
5105  const VariableArrayType* T) {
5106  return Visit(T->getElementType());
5107 }
5108 
5109 bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
5110  const DependentSizedArrayType* T) {
5111  return Visit(T->getElementType());
5112 }
5113 
5114 bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
5115  const DependentSizedExtVectorType* T) {
5116  return Visit(T->getElementType());
5117 }
5118 
5119 bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
5120  return Visit(T->getElementType());
5121 }
5122 
5123 bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
5124  return Visit(T->getElementType());
5125 }
5126 
5127 bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
5128  const FunctionProtoType* T) {
5129  for (const auto &A : T->param_types()) {
5130  if (Visit(A))
5131  return true;
5132  }
5133 
5134  return Visit(T->getReturnType());
5135 }
5136 
5137 bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
5138  const FunctionNoProtoType* T) {
5139  return Visit(T->getReturnType());
5140 }
5141 
5142 bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
5143  const UnresolvedUsingType*) {
5144  return false;
5145 }
5146 
5147 bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
5148  return false;
5149 }
5150 
5151 bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
5152  return Visit(T->getUnderlyingType());
5153 }
5154 
5155 bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
5156  return false;
5157 }
5158 
5159 bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
5160  const UnaryTransformType*) {
5161  return false;
5162 }
5163 
5164 bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
5165  return Visit(T->getDeducedType());
5166 }
5167 
5168 bool UnnamedLocalNoLinkageFinder::VisitDeducedTemplateSpecializationType(
5170  return Visit(T->getDeducedType());
5171 }
5172 
5173 bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
5174  return VisitTagDecl(T->getDecl());
5175 }
5176 
5177 bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
5178  return VisitTagDecl(T->getDecl());
5179 }
5180 
5181 bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
5182  const TemplateTypeParmType*) {
5183  return false;
5184 }
5185 
5186 bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
5188  return false;
5189 }
5190 
5191 bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
5192  const TemplateSpecializationType*) {
5193  return false;
5194 }
5195 
5196 bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
5197  const InjectedClassNameType* T) {
5198  return VisitTagDecl(T->getDecl());
5199 }
5200 
5201 bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
5202  const DependentNameType* T) {
5203  return VisitNestedNameSpecifier(T->getQualifier());
5204 }
5205 
5206 bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
5208  return VisitNestedNameSpecifier(T->getQualifier());
5209 }
5210 
5211 bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
5212  const PackExpansionType* T) {
5213  return Visit(T->getPattern());
5214 }
5215 
5216 bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
5217  return false;
5218 }
5219 
5220 bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
5221  const ObjCInterfaceType *) {
5222  return false;
5223 }
5224 
5225 bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
5226  const ObjCObjectPointerType *) {
5227  return false;
5228 }
5229 
5230 bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
5231  return Visit(T->getValueType());
5232 }
5233 
5234 bool UnnamedLocalNoLinkageFinder::VisitPipeType(const PipeType* T) {
5235  return false;
5236 }
5237 
5238 bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
5239  if (Tag->getDeclContext()->isFunctionOrMethod()) {
5240  S.Diag(SR.getBegin(),
5241  S.getLangOpts().CPlusPlus11 ?
5242  diag::warn_cxx98_compat_template_arg_local_type :
5243  diag::ext_template_arg_local_type)
5244  << S.Context.getTypeDeclType(Tag) << SR;
5245  return true;
5246  }
5247 
5248  if (!Tag->hasNameForLinkage()) {
5249  S.Diag(SR.getBegin(),
5250  S.getLangOpts().CPlusPlus11 ?
5251  diag::warn_cxx98_compat_template_arg_unnamed_type :
5252  diag::ext_template_arg_unnamed_type) << SR;
5253  S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
5254  return true;
5255  }
5256 
5257  return false;
5258 }
5259 
5260 bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
5261  NestedNameSpecifier *NNS) {
5262  if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
5263  return true;
5264 
5265  switch (NNS->getKind()) {
5271  return false;
5272 
5275  return Visit(QualType(NNS->getAsType(), 0));
5276  }
5277  llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
5278 }
5279 
5280 /// \brief Check a template argument against its corresponding
5281 /// template type parameter.
5282 ///
5283 /// This routine implements the semantics of C++ [temp.arg.type]. It
5284 /// returns true if an error occurred, and false otherwise.
5286  TypeSourceInfo *ArgInfo) {
5287  assert(ArgInfo && "invalid TypeSourceInfo");
5288  QualType Arg = ArgInfo->getType();
5289  SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
5290 
5291  if (Arg->isVariablyModifiedType()) {
5292  return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
5293  } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
5294  return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
5295  }
5296 
5297  // C++03 [temp.arg.type]p2:
5298  // A local type, a type with no linkage, an unnamed type or a type
5299  // compounded from any of these types shall not be used as a
5300  // template-argument for a template type-parameter.
5301  //
5302  // C++11 allows these, and even in C++03 we allow them as an extension with
5303  // a warning.
5304  if (LangOpts.CPlusPlus11 || Arg->hasUnnamedOrLocalType()) {
5305  UnnamedLocalNoLinkageFinder Finder(*this, SR);
5306  (void)Finder.Visit(Context.getCanonicalType(Arg));
5307  }
5308 
5309  return false;
5310 }
5311 
5316 };
5317 
5318 /// \brief Determine whether the given template argument is a null pointer
5319 /// value of the appropriate type.
5320 static NullPointerValueKind
5322  QualType ParamType, Expr *Arg,
5323  Decl *Entity = nullptr) {
5324  if (Arg->isValueDependent() || Arg->isTypeDependent())
5325  return NPV_NotNullPointer;
5326 
5327  // dllimport'd entities aren't constant but are available inside of template
5328  // arguments.
5329  if (Entity && Entity->hasAttr<DLLImportAttr>())
5330  return NPV_NotNullPointer;
5331 
5332  if (!S.isCompleteType(Arg->getExprLoc(), ParamType))
5333  llvm_unreachable(
5334  "Incomplete parameter type in isNullPointerValueTemplateArgument!");
5335 
5336  if (!S.getLangOpts().CPlusPlus11)
5337  return NPV_NotNullPointer;
5338 
5339  // Determine whether we have a constant expression.
5341  if (ArgRV.isInvalid())
5342  return NPV_Error;
5343  Arg = ArgRV.get();
5344 
5345  Expr::EvalResult EvalResult;
5347  EvalResult.Diag = &Notes;
5348  if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
5349  EvalResult.HasSideEffects) {
5350  SourceLocation DiagLoc = Arg->getExprLoc();
5351 
5352  // If our only note is the usual "invalid subexpression" note, just point
5353  // the caret at its location rather than producing an essentially
5354  // redundant note.
5355  if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
5356  diag::note_invalid_subexpr_in_const_expr) {
5357  DiagLoc = Notes[0].first;
5358  Notes.clear();
5359  }
5360 
5361  S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
5362  << Arg->getType() << Arg->getSourceRange();
5363  for (unsigned I = 0, N = Notes.size(); I != N; ++I)
5364  S.Diag(Notes[I].first, Notes[I].second);
5365 
5366  S.Diag(Param->getLocation(), diag::note_template_param_here);
5367  return NPV_Error;
5368  }
5369 
5370  // C++11 [temp.arg.nontype]p1:
5371  // - an address constant expression of type std::nullptr_t
5372  if (Arg->getType()->isNullPtrType())
5373  return NPV_NullPointer;
5374 
5375  // - a constant expression that evaluates to a null pointer value (4.10); or
5376  // - a constant expression that evaluates to a null member pointer value
5377  // (4.11); or
5378  if ((EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) ||
5379  (EvalResult.Val.isMemberPointer() &&
5380  !EvalResult.Val.getMemberPointerDecl())) {
5381  // If our expression has an appropriate type, we've succeeded.
5382  bool ObjCLifetimeConversion;
5383  if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
5384  S.IsQualificationConversion(Arg->getType(), ParamType, false,
5385  ObjCLifetimeConversion))
5386  return NPV_NullPointer;
5387 
5388  // The types didn't match, but we know we got a null pointer; complain,
5389  // then recover as if the types were correct.
5390  S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
5391  << Arg->getType() << ParamType << Arg->getSourceRange();
5392  S.Diag(Param->getLocation(), diag::note_template_param_here);
5393  return NPV_NullPointer;
5394  }
5395 
5396  // If we don't have a null pointer value, but we do have a NULL pointer
5397  // constant, suggest a cast to the appropriate type.
5399  std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
5400  S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
5401  << ParamType << FixItHint::CreateInsertion(Arg->getLocStart(), Code)
5403  ")");
5404  S.Diag(Param->getLocation(), diag::note_template_param_here);
5405  return NPV_NullPointer;
5406  }
5407 
5408  // FIXME: If we ever want to support general, address-constant expressions
5409  // as non-type template arguments, we should return the ExprResult here to
5410  // be interpreted by the caller.
5411  return NPV_NotNullPointer;
5412 }
5413 
5414 /// \brief Checks whether the given template argument is compatible with its
5415 /// template parameter.
5417  Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
5418  Expr *Arg, QualType ArgType) {
5419  bool ObjCLifetimeConversion;
5420  if (ParamType->isPointerType() &&
5421  !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
5422  S.IsQualificationConversion(ArgType, ParamType, false,
5423  ObjCLifetimeConversion)) {
5424  // For pointer-to-object types, qualification conversions are
5425  // permitted.
5426  } else {
5427  if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
5428  if (!ParamRef->getPointeeType()->isFunctionType()) {
5429  // C++ [temp.arg.nontype]p5b3:
5430  // For a non-type template-parameter of type reference to
5431  // object, no conversions apply. The type referred to by the
5432  // reference may be more cv-qualified than the (otherwise
5433  // identical) type of the template- argument. The
5434  // template-parameter is bound directly to the
5435  // template-argument, which shall be an lvalue.
5436 
5437  // FIXME: Other qualifiers?
5438  unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
5439  unsigned ArgQuals = ArgType.getCVRQualifiers();
5440 
5441  if ((ParamQuals | ArgQuals) != ParamQuals) {
5442  S.Diag(Arg->getLocStart(),
5443  diag::err_template_arg_ref_bind_ignores_quals)
5444  << ParamType << Arg->getType() << Arg->getSourceRange();
5445  S.Diag(Param->getLocation(), diag::note_template_param_here);
5446  return true;
5447  }
5448  }
5449  }
5450 
5451  // At this point, the template argument refers to an object or
5452  // function with external linkage. We now need to check whether the
5453  // argument and parameter types are compatible.
5454  if (!S.Context.hasSameUnqualifiedType(ArgType,
5455  ParamType.getNonReferenceType())) {
5456  // We can't perform this conversion or binding.
5457  if (ParamType->isReferenceType())
5458  S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind)
5459  << ParamType << ArgIn->getType() << Arg->getSourceRange();
5460  else
5461  S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
5462  << ArgIn->getType() << ParamType << Arg->getSourceRange();
5463  S.Diag(Param->getLocation(), diag::note_template_param_here);
5464  return true;
5465  }
5466  }
5467 
5468  return false;
5469 }
5470 
5471 /// \brief Checks whether the given template argument is the address
5472 /// of an object or function according to C++ [temp.arg.nontype]p1.
5473 static bool
5475  NonTypeTemplateParmDecl *Param,
5476  QualType ParamType,
5477  Expr *ArgIn,
5478  TemplateArgument &Converted) {
5479  bool Invalid = false;
5480  Expr *Arg = ArgIn;
5481  QualType ArgType = Arg->getType();
5482 
5483  bool AddressTaken = false;
5484  SourceLocation AddrOpLoc;
5485  if (S.getLangOpts().MicrosoftExt) {
5486  // Microsoft Visual C++ strips all casts, allows an arbitrary number of
5487  // dereference and address-of operators.
5488  Arg = Arg->IgnoreParenCasts();
5489 
5490  bool ExtWarnMSTemplateArg = false;
5491  UnaryOperatorKind FirstOpKind;
5492  SourceLocation FirstOpLoc;
5493  while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
5494  UnaryOperatorKind UnOpKind = UnOp->getOpcode();
5495  if (UnOpKind == UO_Deref)
5496  ExtWarnMSTemplateArg = true;
5497  if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
5498  Arg = UnOp->getSubExpr()->IgnoreParenCasts();
5499  if (!AddrOpLoc.isValid()) {
5500  FirstOpKind = UnOpKind;
5501  FirstOpLoc = UnOp->getOperatorLoc();
5502  }
5503  } else
5504  break;
5505  }
5506  if (FirstOpLoc.isValid()) {
5507  if (ExtWarnMSTemplateArg)
5508  S.Diag(ArgIn->getLocStart(), diag::ext_ms_deref_template_argument)
5509  << ArgIn->getSourceRange();
5510 
5511  if (FirstOpKind == UO_AddrOf)
5512  AddressTaken = true;
5513  else if (Arg->getType()->isPointerType()) {
5514  // We cannot let pointers get dereferenced here, that is obviously not a
5515  // constant expression.
5516  assert(FirstOpKind == UO_Deref);
5517  S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
5518  << Arg->getSourceRange();
5519  }
5520  }
5521  } else {
5522  // See through any implicit casts we added to fix the type.
5523  Arg = Arg->IgnoreImpCasts();
5524 
5525  // C++ [temp.arg.nontype]p1:
5526  //
5527  // A template-argument for a non-type, non-template
5528  // template-parameter shall be one of: [...]
5529  //
5530  // -- the address of an object or function with external
5531  // linkage, including function templates and function
5532  // template-ids but excluding non-static class members,
5533  // expressed as & id-expression where the & is optional if
5534  // the name refers to a function or array, or if the
5535  // corresponding template-parameter is a reference; or
5536 
5537  // In C++98/03 mode, give an extension warning on any extra parentheses.
5538  // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
5539  bool ExtraParens = false;
5540  while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
5541  if (!Invalid && !ExtraParens) {
5542  S.Diag(Arg->getLocStart(),
5543  S.getLangOpts().CPlusPlus11
5544  ? diag::warn_cxx98_compat_template_arg_extra_parens
5545  : diag::ext_template_arg_extra_parens)
5546  << Arg->getSourceRange();
5547  ExtraParens = true;
5548  }
5549 
5550  Arg = Parens->getSubExpr();
5551  }
5552 
5553  while (SubstNonTypeTemplateParmExpr *subst =
5554  dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
5555  Arg = subst->getReplacement()->IgnoreImpCasts();
5556 
5557  if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
5558  if (UnOp->getOpcode() == UO_AddrOf) {
5559  Arg = UnOp->getSubExpr();
5560  AddressTaken = true;
5561  AddrOpLoc = UnOp->getOperatorLoc();
5562  }
5563  }
5564 
5565  while (SubstNonTypeTemplateParmExpr *subst =
5566  dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
5567  Arg = subst->getReplacement()->IgnoreImpCasts();
5568  }
5569 
5570  DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg);
5571  ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
5572 
5573  // If our parameter has pointer type, check for a null template value.
5574  if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
5575  switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn,
5576  Entity)) {
5577  case NPV_NullPointer:
5578  S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
5579  Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
5580  /*isNullPtr=*/true);
5581  return false;
5582 
5583  case NPV_Error:
5584  return true;
5585 
5586  case NPV_NotNullPointer:
5587  break;
5588  }
5589  }
5590 
5591  // Stop checking the precise nature of the argument if it is value dependent,
5592  // it should be checked when instantiated.
5593  if (Arg->isValueDependent()) {
5594  Converted = TemplateArgument(ArgIn);
5595  return false;
5596  }
5597 
5598  if (isa<CXXUuidofExpr>(Arg)) {
5599  if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType,
5600  ArgIn, Arg, ArgType))
5601  return true;
5602 
5603  Converted = TemplateArgument(ArgIn);
5604  return false;
5605  }
5606 
5607  if (!DRE) {
5608  S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
5609  << Arg->getSourceRange();
5610  S.Diag(Param->getLocation(), diag::note_template_param_here);
5611  return true;
5612  }
5613 
5614  // Cannot refer to non-static data members
5615  if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) {
5616  S.Diag(Arg->getLocStart(), diag::err_template_arg_field)
5617  << Entity << Arg->getSourceRange();
5618  S.Diag(Param->getLocation(), diag::note_template_param_here);
5619  return true;
5620  }
5621 
5622  // Cannot refer to non-static member functions
5623  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
5624  if (!Method->isStatic()) {
5625  S.Diag(Arg->getLocStart(), diag::err_template_arg_method)
5626  << Method << Arg->getSourceRange();
5627  S.Diag(Param->getLocation(), diag::note_template_param_here);
5628  return true;
5629  }
5630  }
5631 
5632  FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
5633  VarDecl *Var = dyn_cast<VarDecl>(Entity);
5634 
5635  // A non-type template argument must refer to an object or function.
5636  if (!Func && !Var) {
5637  // We found something, but we don't know specifically what it is.
5638  S.Diag(Arg->getLocStart(), diag::err_template_arg_not_object_or_func)
5639  << Arg->getSourceRange();
5640  S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
5641  return true;
5642  }
5643 
5644  // Address / reference template args must have external linkage in C++98.
5645  if (Entity->getFormalLinkage() == InternalLinkage) {
5646  S.Diag(Arg->getLocStart(), S.getLangOpts().CPlusPlus11 ?
5647  diag::warn_cxx98_compat_template_arg_object_internal :
5648  diag::ext_template_arg_object_internal)
5649  << !Func << Entity << Arg->getSourceRange();
5650  S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
5651  << !Func;
5652  } else if (!Entity->hasLinkage()) {
5653  S.Diag(Arg->getLocStart(), diag::err_template_arg_object_no_linkage)
5654  << !Func << Entity << Arg->getSourceRange();
5655  S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
5656  << !Func;
5657  return true;
5658  }
5659 
5660  if (Func) {
5661  // If the template parameter has pointer type, the function decays.
5662  if (ParamType->isPointerType() && !AddressTaken)
5663  ArgType = S.Context.getPointerType(Func->getType());
5664  else if (AddressTaken && ParamType->isReferenceType()) {
5665  // If we originally had an address-of operator, but the
5666  // parameter has reference type, complain and (if things look
5667  // like they will work) drop the address-of operator.
5668  if (!S.Context.hasSameUnqualifiedType(Func->getType(),
5669  ParamType.getNonReferenceType())) {
5670  S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
5671  << ParamType;
5672  S.Diag(Param->getLocation(), diag::note_template_param_here);
5673  return true;
5674  }
5675 
5676  S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
5677  << ParamType
5678  << FixItHint::CreateRemoval(AddrOpLoc);
5679  S.Diag(Param->getLocation(), diag::note_template_param_here);
5680 
5681  ArgType = Func->getType();
5682  }
5683  } else {
5684  // A value of reference type is not an object.
5685  if (Var->getType()->isReferenceType()) {
5686  S.Diag(Arg->getLocStart(),
5687  diag::err_template_arg_reference_var)
5688  << Var->getType() << Arg->getSourceRange();
5689  S.Diag(Param->getLocation(), diag::note_template_param_here);
5690  return true;
5691  }
5692 
5693  // A template argument must have static storage duration.
5694  if (Var->getTLSKind()) {
5695  S.Diag(Arg->getLocStart(), diag::err_template_arg_thread_local)
5696  << Arg->getSourceRange();
5697  S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
5698  return true;
5699  }
5700 
5701  // If the template parameter has pointer type, we must have taken
5702  // the address of this object.
5703  if (ParamType->isReferenceType()) {
5704  if (AddressTaken) {
5705  // If we originally had an address-of operator, but the
5706  // parameter has reference type, complain and (if things look
5707  // like they will work) drop the address-of operator.
5708  if (!S.Context.hasSameUnqualifiedType(Var->getType(),
5709  ParamType.getNonReferenceType())) {
5710  S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
5711  << ParamType;
5712  S.Diag(Param->getLocation(), diag::note_template_param_here);
5713  return true;
5714  }
5715 
5716  S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
5717  << ParamType
5718  << FixItHint::CreateRemoval(AddrOpLoc);
5719  S.Diag(Param->getLocation(), diag::note_template_param_here);
5720 
5721  ArgType = Var->getType();
5722  }
5723  } else if (!AddressTaken && ParamType->isPointerType()) {
5724  if (Var->getType()->isArrayType()) {
5725  // Array-to-pointer decay.
5726  ArgType = S.Context.getArrayDecayedType(Var->getType());
5727  } else {
5728  // If the template parameter has pointer type but the address of
5729  // this object was not taken, complain and (possibly) recover by
5730  // taking the address of the entity.
5731  ArgType = S.Context.getPointerType(Var->getType());
5732  if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
5733  S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
5734  << ParamType;
5735  S.Diag(Param->getLocation(), diag::note_template_param_here);
5736  return true;
5737  }
5738 
5739  S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
5740  << ParamType
5741  << FixItHint::CreateInsertion(Arg->getLocStart(), "&");
5742 
5743  S.Diag(Param->getLocation(), diag::note_template_param_here);
5744  }
5745  }
5746  }
5747 
5748  if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
5749  Arg, ArgType))
5750  return true;
5751 
5752  // Create the template argument.
5753  Converted =
5754  TemplateArgument(cast<ValueDecl>(Entity->getCanonicalDecl()), ParamType);
5755  S.MarkAnyDeclReferenced(Arg->getLocStart(), Entity, false);
5756  return false;
5757 }
5758 
5759 /// \brief Checks whether the given template argument is a pointer to
5760 /// member constant according to C++ [temp.arg.nontype]p1.
5762  NonTypeTemplateParmDecl *Param,
5763  QualType ParamType,
5764  Expr *&ResultArg,
5765  TemplateArgument &Converted) {
5766  bool Invalid = false;
5767 
5768  Expr *Arg = ResultArg;
5769  bool ObjCLifetimeConversion;
5770 
5771  // C++ [temp.arg.nontype]p1:
5772  //
5773  // A template-argument for a non-type, non-template
5774  // template-parameter shall be one of: [...]
5775  //
5776  // -- a pointer to member expressed as described in 5.3.1.
5777  DeclRefExpr *DRE = nullptr;
5778 
5779  // In C++98/03 mode, give an extension warning on any extra parentheses.
5780  // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
5781  bool ExtraParens = false;
5782  while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
5783  if (!Invalid && !ExtraParens) {
5784  S.Diag(Arg->getLocStart(),
5785  S.getLangOpts().CPlusPlus11 ?
5786  diag::warn_cxx98_compat_template_arg_extra_parens :
5787  diag::ext_template_arg_extra_parens)
5788  << Arg->getSourceRange();
5789  ExtraParens = true;
5790  }
5791 
5792  Arg = Parens->getSubExpr();
5793  }
5794 
5795  while (SubstNonTypeTemplateParmExpr *subst =
5796  dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
5797  Arg = subst->getReplacement()->IgnoreImpCasts();
5798 
5799  // A pointer-to-member constant written &Class::member.
5800  if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
5801  if (UnOp->getOpcode() == UO_AddrOf) {
5802  DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
5803  if (DRE && !DRE->getQualifier())
5804  DRE = nullptr;
5805  }
5806  }
5807  // A constant of pointer-to-member type.
5808  else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
5809  if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
5810  if (VD->getType()->isMemberPointerType()) {
5811  if (isa<NonTypeTemplateParmDecl>(VD)) {
5812  if (Arg->isTypeDependent() || Arg->isValueDependent()) {
5813  Converted = TemplateArgument(Arg);
5814  } else {
5815  VD = cast<ValueDecl>(VD->getCanonicalDecl());
5816  Converted = TemplateArgument(VD, ParamType);
5817  }
5818  return Invalid;
5819  }
5820  }
5821  }
5822 
5823  DRE = nullptr;
5824  }
5825 
5826  ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
5827 
5828  // Check for a null pointer value.
5829  switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ResultArg,
5830  Entity)) {
5831  case NPV_Error:
5832  return true;
5833  case NPV_NullPointer:
5834  S.Diag(ResultArg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
5835  Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
5836  /*isNullPtr*/true);
5837  return false;
5838  case NPV_NotNullPointer:
5839  break;
5840  }
5841 
5842  if (S.IsQualificationConversion(ResultArg->getType(),
5843  ParamType.getNonReferenceType(), false,
5844  ObjCLifetimeConversion)) {
5845  ResultArg = S.ImpCastExprToType(ResultArg, ParamType, CK_NoOp,
5846  ResultArg->getValueKind())
5847  .get();
5848  } else if (!S.Context.hasSameUnqualifiedType(
5849  ResultArg->getType(), ParamType.getNonReferenceType())) {
5850  // We can't perform this conversion.
5851  S.Diag(ResultArg->getLocStart(), diag::err_template_arg_not_convertible)
5852  << ResultArg->getType() << ParamType << ResultArg->getSourceRange();
5853  S.Diag(Param->getLocation(), diag::note_template_param_here);
5854  return true;
5855  }
5856 
5857  if (!DRE)
5858  return S.Diag(Arg->getLocStart(),
5859  diag::err_template_arg_not_pointer_to_member_form)
5860  << Arg->getSourceRange();
5861 
5862  if (isa<FieldDecl>(DRE->getDecl()) ||
5863  isa<IndirectFieldDecl>(DRE->getDecl()) ||
5864  isa<CXXMethodDecl>(DRE->getDecl())) {
5865  assert((isa<FieldDecl>(DRE->getDecl()) ||
5866  isa<IndirectFieldDecl>(DRE->getDecl()) ||
5867  !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
5868  "Only non-static member pointers can make it here");
5869 
5870  // Okay: this is the address of a non-static member, and therefore
5871  // a member pointer constant.
5872  if (Arg->isTypeDependent() || Arg->isValueDependent()) {
5873  Converted = TemplateArgument(Arg);
5874  } else {
5875  ValueDecl *D = cast<ValueDecl>(DRE->getDecl()->getCanonicalDecl());
5876  Converted = TemplateArgument(D, ParamType);
5877  }
5878  return Invalid;
5879  }
5880 
5881  // We found something else, but we don't know specifically what it is.
5882  S.Diag(Arg->getLocStart(),
5883  diag::err_template_arg_not_pointer_to_member_form)
5884  << Arg->getSourceRange();
5885  S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
5886  return true;
5887 }
5888 
5889 /// \brief Check a template argument against its corresponding
5890 /// non-type template parameter.
5891 ///
5892 /// This routine implements the semantics of C++ [temp.arg.nontype].
5893 /// If an error occurred, it returns ExprError(); otherwise, it
5894 /// returns the converted template argument. \p ParamType is the
5895 /// type of the non-type template parameter after it has been instantiated.
5897  QualType ParamType, Expr *Arg,
5898  TemplateArgument &Converted,
5900  SourceLocation StartLoc = Arg->getLocStart();
5901 
5902  // If the parameter type somehow involves auto, deduce the type now.
5903  if (getLangOpts().CPlusPlus1z && ParamType->isUndeducedType()) {
5904  // During template argument deduction, we allow 'decltype(auto)' to
5905  // match an arbitrary dependent argument.
5906  // FIXME: The language rules don't say what happens in this case.
5907  // FIXME: We get an opaque dependent type out of decltype(auto) if the
5908  // expression is merely instantiation-dependent; is this enough?
5909  if (CTAK == CTAK_Deduced && Arg->isTypeDependent()) {
5910  auto *AT = dyn_cast<AutoType>(ParamType);
5911  if (AT && AT->isDecltypeAuto()) {
5912  Converted = TemplateArgument(Arg);
5913  return Arg;
5914  }
5915  }
5916 
5917  // When checking a deduced template argument, deduce from its type even if
5918  // the type is dependent, in order to check the types of non-type template
5919  // arguments line up properly in partial ordering.
5921  if (CTAK != CTAK_Specified)
5922  Depth = Param->getDepth() + 1;
5923  if (DeduceAutoType(
5924  Context.getTrivialTypeSourceInfo(ParamType, Param->getLocation()),
5925  Arg, ParamType, Depth) == DAR_Failed) {
5926  Diag(Arg->getExprLoc(),
5927  diag::err_non_type_template_parm_type_deduction_failure)
5928  << Param->getDeclName() << Param->getType() << Arg->getType()
5929  << Arg->getSourceRange();
5930  Diag(Param->getLocation(), diag::note_template_param_here);
5931  return ExprError();
5932  }
5933  // CheckNonTypeTemplateParameterType will produce a diagnostic if there's
5934  // an error. The error message normally references the parameter
5935  // declaration, but here we'll pass the argument location because that's
5936  // where the parameter type is deduced.
5937  ParamType = CheckNonTypeTemplateParameterType(ParamType, Arg->getExprLoc());
5938  if (ParamType.isNull()) {
5939  Diag(Param->getLocation(), diag::note_template_param_here);
5940  return ExprError();
5941  }
5942  }
5943 
5944  // We should have already dropped all cv-qualifiers by now.
5945  assert(!ParamType.hasQualifiers() &&
5946  "non-type template parameter type cannot be qualified");
5947 
5948  if (CTAK == CTAK_Deduced &&
5950  Arg->getType())) {
5951  // FIXME: If either type is dependent, we skip the check. This isn't
5952  // correct, since during deduction we're supposed to have replaced each
5953  // template parameter with some unique (non-dependent) placeholder.
5954  // FIXME: If the argument type contains 'auto', we carry on and fail the
5955  // type check in order to force specific types to be more specialized than
5956  // 'auto'. It's not clear how partial ordering with 'auto' is supposed to
5957  // work.
5958  if ((ParamType->isDependentType() || Arg->isTypeDependent()) &&
5959  !Arg->getType()->getContainedAutoType()) {
5960  Converted = TemplateArgument(Arg);
5961  return Arg;
5962  }
5963  // FIXME: This attempts to implement C++ [temp.deduct.type]p17. Per DR1770,
5964  // we should actually be checking the type of the template argument in P,
5965  // not the type of the template argument deduced from A, against the
5966  // template parameter type.
5967  Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
5968  << Arg->getType()
5969  << ParamType.getUnqualifiedType();
5970  Diag(Param->getLocation(), diag::note_template_param_here);
5971  return ExprError();
5972  }
5973 
5974  // If either the parameter has a dependent type or the argument is
5975  // type-dependent, there's nothing we can check now.
5976  if (ParamType->isDependentType() || Arg->isTypeDependent()) {
5977  // FIXME: Produce a cloned, canonical expression?
5978  Converted = TemplateArgument(Arg);
5979  return Arg;
5980  }
5981 
5982  // The initialization of the parameter from the argument is
5983  // a constant-evaluated context.
5984  EnterExpressionEvaluationContext ConstantEvaluated(
5986 
5987  if (getLangOpts().CPlusPlus1z) {
5988  // C++1z [temp.arg.nontype]p1:
5989  // A template-argument for a non-type template parameter shall be
5990  // a converted constant expression of the type of the template-parameter.
5991  APValue Value;
5993  Arg, ParamType, Value, CCEK_TemplateArg);
5994  if (ArgResult.isInvalid())
5995  return ExprError();
5996 
5997  // For a value-dependent argument, CheckConvertedConstantExpression is
5998  // permitted (and expected) to be unable to determine a value.
5999  if (ArgResult.get()->isValueDependent()) {
6000  Converted = TemplateArgument(ArgResult.get());
6001  return ArgResult;
6002  }
6003 
6004  QualType CanonParamType = Context.getCanonicalType(ParamType);
6005 
6006  // Convert the APValue to a TemplateArgument.
6007  switch (Value.getKind()) {
6009  assert(ParamType->isNullPtrType());
6010  Converted = TemplateArgument(CanonParamType, /*isNullPtr*/true);
6011  break;
6012  case APValue::Int:
6013  assert(ParamType->isIntegralOrEnumerationType());
6014  Converted = TemplateArgument(Context, Value.getInt(), CanonParamType);
6015  break;
6016  case APValue::MemberPointer: {
6017  assert(ParamType->isMemberPointerType());
6018 
6019  // FIXME: We need TemplateArgument representation and mangling for these.
6020  if (!Value.getMemberPointerPath().empty()) {
6021  Diag(Arg->getLocStart(),
6022  diag::err_template_arg_member_ptr_base_derived_not_supported)
6023  << Value.getMemberPointerDecl() << ParamType
6024  << Arg->getSourceRange();
6025  return ExprError();
6026  }
6027 
6028  auto *VD = const_cast<ValueDecl*>(Value.getMemberPointerDecl());
6029  Converted = VD ? TemplateArgument(VD, CanonParamType)
6030  : TemplateArgument(CanonParamType, /*isNullPtr*/true);
6031  break;
6032  }
6033  case APValue::LValue: {
6034  // For a non-type template-parameter of pointer or reference type,
6035  // the value of the constant expression shall not refer to
6036  assert(ParamType->isPointerType() || ParamType->isReferenceType() ||
6037  ParamType->isNullPtrType());
6038  // -- a temporary object
6039  // -- a string literal
6040  // -- the result of a typeid expression, or
6041  // -- a predefined __func__ variable
6042  if (auto *E = Value.getLValueBase().dyn_cast<const Expr*>()) {
6043  if (isa<CXXUuidofExpr>(E)) {
6044  Converted = TemplateArgument(const_cast<Expr*>(E));
6045  break;
6046  }
6047  Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
6048  << Arg->getSourceRange();
6049  return ExprError();
6050  }
6051  auto *VD = const_cast<ValueDecl *>(
6052  Value.getLValueBase().dyn_cast<const ValueDecl *>());
6053  // -- a subobject
6054  if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 &&
6055  VD && VD->getType()->isArrayType() &&
6056  Value.getLValuePath()[0].ArrayIndex == 0 &&
6057  !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
6058  // Per defect report (no number yet):
6059  // ... other than a pointer to the first element of a complete array
6060  // object.
6061  } else if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
6062  Value.isLValueOnePastTheEnd()) {
6063  Diag(StartLoc, diag::err_non_type_template_arg_subobject)
6064  << Value.getAsString(Context, ParamType);
6065  return ExprError();
6066  }
6067  assert((VD || !ParamType->isReferenceType()) &&
6068  "null reference should not be a constant expression");
6069  assert((!VD || !ParamType->isNullPtrType()) &&
6070  "non-null value of type nullptr_t?");
6071  Converted = VD ? TemplateArgument(VD, CanonParamType)
6072  : TemplateArgument(CanonParamType, /*isNullPtr*/true);
6073  break;
6074  }
6076  return Diag(StartLoc, diag::err_non_type_template_arg_addr_label_diff);
6077  case APValue::Float:
6078  case APValue::ComplexInt:
6079  case APValue::ComplexFloat:
6080  case APValue::Vector:
6081  case APValue::Array:
6082  case APValue::Struct:
6083  case APValue::Union:
6084  llvm_unreachable("invalid kind for template argument");
6085  }
6086 
6087  return ArgResult.get();
6088  }
6089 
6090  // C++ [temp.arg.nontype]p5:
6091  // The following conversions are performed on each expression used
6092  // as a non-type template-argument. If a non-type
6093  // template-argument cannot be converted to the type of the
6094  // corresponding template-parameter then the program is
6095  // ill-formed.
6096  if (ParamType->isIntegralOrEnumerationType()) {
6097  // C++11:
6098  // -- for a non-type template-parameter of integral or
6099  // enumeration type, conversions permitted in a converted
6100  // constant expression are applied.
6101  //
6102  // C++98:
6103  // -- for a non-type template-parameter of integral or
6104  // enumeration type, integral promotions (4.5) and integral
6105  // conversions (4.7) are applied.
6106 
6107  if (getLangOpts().CPlusPlus11) {
6108  // C++ [temp.arg.nontype]p1:
6109  // A template-argument for a non-type, non-template template-parameter
6110  // shall be one of:
6111  //
6112  // -- for a non-type template-parameter of integral or enumeration
6113  // type, a converted constant expression of the type of the
6114  // template-parameter; or
6115  llvm::APSInt Value;
6116  ExprResult ArgResult =
6117  CheckConvertedConstantExpression(Arg, ParamType, Value,
6118  CCEK_TemplateArg);
6119  if (ArgResult.isInvalid())
6120  return ExprError();
6121 
6122  // We can't check arbitrary value-dependent arguments.
6123  if (ArgResult.get()->isValueDependent()) {
6124  Converted = TemplateArgument(ArgResult.get());
6125  return ArgResult;
6126  }
6127 
6128  // Widen the argument value to sizeof(parameter type). This is almost
6129  // always a no-op, except when the parameter type is bool. In
6130  // that case, this may extend the argument from 1 bit to 8 bits.
6131  QualType IntegerType = ParamType;
6132  if (const EnumType *Enum = IntegerType->getAs<EnumType>())
6133  IntegerType = Enum->getDecl()->getIntegerType();
6134  Value = Value.extOrTrunc(Context.getTypeSize(IntegerType));
6135 
6136  Converted = TemplateArgument(Context, Value,
6137  Context.getCanonicalType(ParamType));
6138  return ArgResult;
6139  }
6140 
6141  ExprResult ArgResult = DefaultLvalueConversion(Arg);
6142  if (ArgResult.isInvalid())
6143  return ExprError();
6144  Arg = ArgResult.get();
6145 
6146  QualType ArgType = Arg->getType();
6147 
6148  // C++ [temp.arg.nontype]p1:
6149  // A template-argument for a non-type, non-template
6150  // template-parameter shall be one of:
6151  //
6152  // -- an integral constant-expression of integral or enumeration
6153  // type; or
6154  // -- the name of a non-type template-parameter; or
6155  SourceLocation NonConstantLoc;
6156  llvm::APSInt Value;
6157  if (!ArgType->isIntegralOrEnumerationType()) {
6158  Diag(Arg->getLocStart(),
6159  diag::err_template_arg_not_integral_or_enumeral)
6160  << ArgType << Arg->getSourceRange();
6161  Diag(Param->getLocation(), diag::note_template_param_here);
6162  return ExprError();
6163  } else if (!Arg->isValueDependent()) {
6164  class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
6165  QualType T;
6166 
6167  public:
6168  TmplArgICEDiagnoser(QualType T) : T(T) { }
6169 
6170  void diagnoseNotICE(Sema &S, SourceLocation Loc,
6171  SourceRange SR) override {
6172  S.Diag(Loc, diag::err_template_arg_not_ice) << T << SR;
6173  }
6174  } Diagnoser(ArgType);
6175 
6176  Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser,
6177  false).get();
6178  if (!Arg)
6179  return ExprError();
6180  }
6181 
6182  // From here on out, all we care about is the unqualified form
6183  // of the argument type.
6184  ArgType = ArgType.getUnqualifiedType();
6185 
6186  // Try to convert the argument to the parameter's type.
6187  if (Context.hasSameType(ParamType, ArgType)) {
6188  // Okay: no conversion necessary
6189  } else if (ParamType->isBooleanType()) {
6190  // This is an integral-to-boolean conversion.
6191  Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).get();
6192  } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
6193  !ParamType->isEnumeralType()) {
6194  // This is an integral promotion or conversion.
6195  Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).get();
6196  } else {
6197  // We can't perform this conversion.
6198  Diag(Arg->getLocStart(),
6199  diag::err_template_arg_not_convertible)
6200  << Arg->getType() << ParamType << Arg->getSourceRange();
6201  Diag(Param->getLocation(), diag::note_template_param_here);
6202  return ExprError();
6203  }
6204 
6205  // Add the value of this argument to the list of converted
6206  // arguments. We use the bitwidth and signedness of the template
6207  // parameter.
6208  if (Arg->isValueDependent()) {
6209  // The argument is value-dependent. Create a new
6210  // TemplateArgument with the converted expression.
6211  Converted = TemplateArgument(Arg);
6212  return Arg;
6213  }
6214 
6215  QualType IntegerType = Context.getCanonicalType(ParamType);
6216  if (const EnumType *Enum = IntegerType->getAs<EnumType>())
6217  IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
6218 
6219  if (ParamType->isBooleanType()) {
6220  // Value must be zero or one.
6221  Value = Value != 0;
6222  unsigned AllowedBits = Context.getTypeSize(IntegerType);
6223  if (Value.getBitWidth() != AllowedBits)
6224  Value = Value.extOrTrunc(AllowedBits);
6225  Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
6226  } else {
6227  llvm::APSInt OldValue = Value;
6228 
6229  // Coerce the template argument's value to the value it will have
6230  // based on the template parameter's type.
6231  unsigned AllowedBits = Context.getTypeSize(IntegerType);
6232  if (Value.getBitWidth() != AllowedBits)
6233  Value = Value.extOrTrunc(AllowedBits);
6234  Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
6235 
6236  // Complain if an unsigned parameter received a negative value.
6237  if (IntegerType->isUnsignedIntegerOrEnumerationType()
6238  && (OldValue.isSigned() && OldValue.isNegative())) {
6239  Diag(Arg->getLocStart(), diag::warn_template_arg_negative)
6240  << OldValue.toString(10) << Value.toString(10) << Param->getType()
6241  << Arg->getSourceRange();
6242  Diag(Param->getLocation(), diag::note_template_param_here);
6243  }
6244 
6245  // Complain if we overflowed the template parameter's type.
6246  unsigned RequiredBits;
6247  if (IntegerType->isUnsignedIntegerOrEnumerationType())
6248  RequiredBits = OldValue.getActiveBits();
6249  else if (OldValue.isUnsigned())
6250  RequiredBits = OldValue.getActiveBits() + 1;
6251  else
6252  RequiredBits = OldValue.getMinSignedBits();
6253  if (RequiredBits > AllowedBits) {
6254  Diag(Arg->getLocStart(),
6255  diag::warn_template_arg_too_large)
6256  << OldValue.toString(10) << Value.toString(10) << Param->getType()
6257  << Arg->getSourceRange();
6258  Diag(Param->getLocation(), diag::note_template_param_here);
6259  }
6260  }
6261 
6262  Converted = TemplateArgument(Context, Value,
6263  ParamType->isEnumeralType()
6264  ? Context.getCanonicalType(ParamType)
6265  : IntegerType);
6266  return Arg;
6267  }
6268 
6269  QualType ArgType = Arg->getType();
6270  DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
6271 
6272  // Handle pointer-to-function, reference-to-function, and
6273  // pointer-to-member-function all in (roughly) the same way.
6274  if (// -- For a non-type template-parameter of type pointer to
6275  // function, only the function-to-pointer conversion (4.3) is
6276  // applied. If the template-argument represents a set of
6277  // overloaded functions (or a pointer to such), the matching
6278  // function is selected from the set (13.4).
6279  (ParamType->isPointerType() &&
6280  ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
6281  // -- For a non-type template-parameter of type reference to
6282  // function, no conversions apply. If the template-argument
6283  // represents a set of overloaded functions, the matching
6284  // function is selected from the set (13.4).
6285  (ParamType->isReferenceType() &&
6286  ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
6287  // -- For a non-type template-parameter of type pointer to
6288  // member function, no conversions apply. If the
6289  // template-argument represents a set of overloaded member
6290  // functions, the matching member function is selected from
6291  // the set (13.4).
6292  (ParamType->isMemberPointerType() &&
6293  ParamType->getAs<MemberPointerType>()->getPointeeType()
6294  ->isFunctionType())) {
6295 
6296  if (Arg->getType() == Context.OverloadTy) {
6297  if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
6298  true,
6299  FoundResult)) {
6300  if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
6301  return ExprError();
6302 
6303  Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
6304  ArgType = Arg->getType();
6305  } else
6306  return ExprError();
6307  }
6308 
6309  if (!ParamType->isMemberPointerType()) {
6311  ParamType,
6312  Arg, Converted))
6313  return ExprError();
6314  return Arg;
6315  }
6316 
6317  if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
6318  Converted))
6319  return ExprError();
6320  return Arg;
6321  }
6322 
6323  if (ParamType->isPointerType()) {
6324  // -- for a non-type template-parameter of type pointer to
6325  // object, qualification conversions (4.4) and the
6326  // array-to-pointer conversion (4.2) are applied.
6327  // C++0x also allows a value of std::nullptr_t.
6328  assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
6329  "Only object pointers allowed here");
6330 
6332  ParamType,
6333  Arg, Converted))
6334  return ExprError();
6335  return Arg;
6336  }
6337 
6338  if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
6339  // -- For a non-type template-parameter of type reference to
6340  // object, no conversions apply. The type referred to by the
6341  // reference may be more cv-qualified than the (otherwise
6342  // identical) type of the template-argument. The
6343  // template-parameter is bound directly to the
6344  // template-argument, which must be an lvalue.
6345  assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
6346  "Only object references allowed here");
6347 
6348  if (Arg->getType() == Context.OverloadTy) {
6349  if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
6350  ParamRefType->getPointeeType(),
6351  true,
6352  FoundResult)) {
6353  if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
6354  return ExprError();
6355 
6356  Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
6357  ArgType = Arg->getType();
6358  } else
6359  return ExprError();
6360  }
6361 
6363  ParamType,
6364  Arg, Converted))
6365  return ExprError();
6366  return Arg;
6367  }
6368 
6369  // Deal with parameters of type std::nullptr_t.
6370  if (ParamType->isNullPtrType()) {
6371  if (Arg->isTypeDependent() || Arg->isValueDependent()) {
6372  Converted = TemplateArgument(Arg);
6373  return Arg;
6374  }
6375 
6376  switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) {
6377  case NPV_NotNullPointer:
6378  Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
6379  << Arg->getType() << ParamType;
6380  Diag(Param->getLocation(), diag::note_template_param_here);
6381  return ExprError();
6382 
6383  case NPV_Error:
6384  return ExprError();
6385 
6386  case NPV_NullPointer:
6387  Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
6388  Converted = TemplateArgument(Context.getCanonicalType(ParamType),
6389  /*isNullPtr*/true);
6390  return Arg;
6391  }
6392  }
6393 
6394  // -- For a non-type template-parameter of type pointer to data
6395  // member, qualification conversions (4.4) are applied.
6396  assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
6397 
6398  if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
6399  Converted))
6400  return ExprError();
6401  return Arg;
6402 }
6403 
6407 
6408 /// \brief Check a template argument against its corresponding
6409 /// template template parameter.
6410 ///
6411 /// This routine implements the semantics of C++ [temp.arg.template].
6412 /// It returns true if an error occurred, and false otherwise.
6414  TemplateArgumentLoc &Arg,
6415  unsigned ArgumentPackIndex) {
6417  TemplateDecl *Template = Name.getAsTemplateDecl();
6418  if (!Template) {
6419  // Any dependent template name is fine.
6420  assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
6421  return false;
6422  }
6423 
6424  if (Template->isInvalidDecl())
6425  return true;
6426 
6427  // C++0x [temp.arg.template]p1:
6428  // A template-argument for a template template-parameter shall be
6429  // the name of a class template or an alias template, expressed as an
6430  // id-expression. When the template-argument names a class template, only
6431  // primary class templates are considered when matching the
6432  // template template argument with the corresponding parameter;
6433  // partial specializations are not considered even if their
6434  // parameter lists match that of the template template parameter.
6435  //
6436  // Note that we also allow template template parameters here, which
6437  // will happen when we are dealing with, e.g., class template
6438  // partial specializations.
6439  if (!isa<ClassTemplateDecl>(Template) &&
6440  !isa<TemplateTemplateParmDecl>(Template) &&
6441  !isa<TypeAliasTemplateDecl>(Template) &&
6442  !isa<BuiltinTemplateDecl>(Template)) {
6443  assert(isa<FunctionTemplateDecl>(Template) &&
6444  "Only function templates are possible here");
6445  Diag(Arg.getLocation(), diag::err_template_arg_not_valid_template);
6446  Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
6447  << Template;
6448  }
6449 
6450  TemplateParameterList *Params = Param->getTemplateParameters();
6451  if (Param->isExpandedParameterPack())
6452  Params = Param->getExpansionTemplateParameters(ArgumentPackIndex);
6453 
6454  // C++1z [temp.arg.template]p3: (DR 150)
6455  // A template-argument matches a template template-parameter P when P
6456  // is at least as specialized as the template-argument A.
6457  if (getLangOpts().RelaxedTemplateTemplateArgs) {
6458  // Quick check for the common case:
6459  // If P contains a parameter pack, then A [...] matches P if each of A's
6460  // template parameters matches the corresponding template parameter in
6461  // the template-parameter-list of P.
6462  if (TemplateParameterListsAreEqual(
6463  Template->getTemplateParameters(), Params, false,
6464  TPL_TemplateTemplateArgumentMatch, Arg.getLocation()))
6465  return false;
6466 
6467  if (isTemplateTemplateParameterAtLeastAsSpecializedAs(Params, Template,
6468  Arg.getLocation()))
6469  return false;
6470  // FIXME: Produce better diagnostics for deduction failures.
6471  }
6472 
6473  return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
6474  Params,
6475  true,
6476  TPL_TemplateTemplateArgumentMatch,
6477  Arg.getLocation());
6478 }
6479 
6480 /// \brief Given a non-type template argument that refers to a
6481 /// declaration and the type of its corresponding non-type template
6482 /// parameter, produce an expression that properly refers to that
6483 /// declaration.
6484 ExprResult
6486  QualType ParamType,
6487  SourceLocation Loc) {
6488  // C++ [temp.param]p8:
6489  //
6490  // A non-type template-parameter of type "array of T" or
6491  // "function returning T" is adjusted to be of type "pointer to
6492  // T" or "pointer to function returning T", respectively.
6493  if (ParamType->isArrayType())
6494  ParamType = Context.getArrayDecayedType(ParamType);
6495  else if (ParamType->isFunctionType())
6496  ParamType = Context.getPointerType(ParamType);
6497 
6498  // For a NULL non-type template argument, return nullptr casted to the
6499  // parameter's type.
6500  if (Arg.getKind() == TemplateArgument::NullPtr) {
6501  return ImpCastExprToType(
6503  ParamType,
6504  ParamType->getAs<MemberPointerType>()
6505  ? CK_NullToMemberPointer
6506  : CK_NullToPointer);
6507  }
6508  assert(Arg.getKind() == TemplateArgument::Declaration &&
6509  "Only declaration template arguments permitted here");
6510 
6511  ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
6512 
6513  if (VD->getDeclContext()->isRecord() &&
6514  (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
6515  isa<IndirectFieldDecl>(VD))) {
6516  // If the value is a class member, we might have a pointer-to-member.
6517  // Determine whether the non-type template template parameter is of
6518  // pointer-to-member type. If so, we need to build an appropriate
6519  // expression for a pointer-to-member, since a "normal" DeclRefExpr
6520  // would refer to the member itself.
6521  if (ParamType->isMemberPointerType()) {
6522  QualType ClassType
6523  = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
6524  NestedNameSpecifier *Qualifier
6525  = NestedNameSpecifier::Create(Context, nullptr, false,
6526  ClassType.getTypePtr());
6527  CXXScopeSpec SS;
6528  SS.MakeTrivial(Context, Qualifier, Loc);
6529 
6530  // The actual value-ness of this is unimportant, but for
6531  // internal consistency's sake, references to instance methods
6532  // are r-values.
6533  ExprValueKind VK = VK_LValue;
6534  if (isa<CXXMethodDecl>(VD) && cast<CXXMethodDecl>(VD)->isInstance())
6535  VK = VK_RValue;
6536 
6537  ExprResult RefExpr = BuildDeclRefExpr(VD,
6538  VD->getType().getNonReferenceType(),
6539  VK,
6540  Loc,
6541  &SS);
6542  if (RefExpr.isInvalid())
6543  return ExprError();
6544 
6545  RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
6546 
6547  // We might need to perform a trailing qualification conversion, since
6548  // the element type on the parameter could be more qualified than the
6549  // element type in the expression we constructed.
6550  bool ObjCLifetimeConversion;
6551  if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
6552  ParamType.getUnqualifiedType(), false,
6553  ObjCLifetimeConversion))
6554  RefExpr = ImpCastExprToType(RefExpr.get(), ParamType.getUnqualifiedType(), CK_NoOp);
6555 
6556  assert(!RefExpr.isInvalid() &&
6557  Context.hasSameType(((Expr*) RefExpr.get())->getType(),
6558  ParamType.getUnqualifiedType()));
6559  return RefExpr;
6560  }
6561  }
6562 
6563  QualType T = VD->getType().getNonReferenceType();
6564 
6565  if (ParamType->isPointerType()) {
6566  // When the non-type template parameter is a pointer, take the
6567  // address of the declaration.
6568  ExprResult RefExpr = BuildDeclRefExpr(VD, T, VK_LValue, Loc);
6569  if (RefExpr.isInvalid())
6570  return ExprError();
6571 
6572  if (!Context.hasSameUnqualifiedType(ParamType->getPointeeType(), T) &&
6573  (T->isFunctionType() || T->isArrayType())) {
6574  // Decay functions and arrays unless we're forming a pointer to array.
6575  RefExpr = DefaultFunctionArrayConversion(RefExpr.get());
6576  if (RefExpr.isInvalid())
6577  return ExprError();
6578 
6579  return RefExpr;
6580  }
6581 
6582  // Take the address of everything else
6583  return CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
6584  }
6585 
6586  ExprValueKind VK = VK_RValue;
6587 
6588  // If the non-type template parameter has reference type, qualify the
6589  // resulting declaration reference with the extra qualifiers on the
6590  // type that the reference refers to.
6591  if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>()) {
6592  VK = VK_LValue;
6593  T = Context.getQualifiedType(T,
6594  TargetRef->getPointeeType().getQualifiers());
6595  } else if (isa<FunctionDecl>(VD)) {
6596  // References to functions are always lvalues.
6597  VK = VK_LValue;
6598  }
6599 
6600  return BuildDeclRefExpr(VD, T, VK, Loc);
6601 }
6602 
6603 /// \brief Construct a new expression that refers to the given
6604 /// integral template argument with the given source-location
6605 /// information.
6606 ///
6607 /// This routine takes care of the mapping from an integral template
6608 /// argument (which may have any integral type) to the appropriate
6609 /// literal value.
6610 ExprResult
6612  SourceLocation Loc) {
6613  assert(Arg.getKind() == TemplateArgument::Integral &&
6614  "Operation is only valid for integral template arguments");
6615  QualType OrigT = Arg.getIntegralType();
6616 
6617  // If this is an enum type that we're instantiating, we need to use an integer
6618  // type the same size as the enumerator. We don't want to build an
6619  // IntegerLiteral with enum type. The integer type of an enum type can be of
6620  // any integral type with C++11 enum classes, make sure we create the right
6621  // type of literal for it.
6622  QualType T = OrigT;
6623  if (const EnumType *ET = OrigT->getAs<EnumType>())
6624  T = ET->getDecl()->getIntegerType();
6625 
6626  Expr *E;
6627  if (T->isAnyCharacterType()) {
6628  // This does not need to handle u8 character literals because those are
6629  // of type char, and so can also be covered by an ASCII character literal.
6631  if (T->isWideCharType())
6632  Kind = CharacterLiteral::Wide;
6633  else if (T->isChar16Type())
6634  Kind = CharacterLiteral::UTF16;
6635  else if (T->isChar32Type())
6636  Kind = CharacterLiteral::UTF32;
6637  else
6638  Kind = CharacterLiteral::Ascii;
6639 
6640  E = new (Context) CharacterLiteral(Arg.getAsIntegral().getZExtValue(),
6641  Kind, T, Loc);
6642  } else if (T->isBooleanType()) {
6643  E = new (Context) CXXBoolLiteralExpr(Arg.getAsIntegral().getBoolValue(),
6644  T, Loc);
6645  } else if (T->isNullPtrType()) {
6647  } else {
6648  E = IntegerLiteral::Create(Context, Arg.getAsIntegral(), T, Loc);
6649  }
6650 
6651  if (OrigT->isEnumeralType()) {
6652  // FIXME: This is a hack. We need a better way to handle substituted
6653  // non-type template parameters.
6654  E = CStyleCastExpr::Create(Context, OrigT, VK_RValue, CK_IntegralCast, E,
6655  nullptr,
6656  Context.getTrivialTypeSourceInfo(OrigT, Loc),
6657  Loc, Loc);
6658  }
6659 
6660  return E;
6661 }
6662 
6663 /// \brief Match two template parameters within template parameter lists.
6665  bool Complain,
6667  SourceLocation TemplateArgLoc) {
6668  // Check the actual kind (type, non-type, template).
6669  if (Old->getKind() != New->getKind()) {
6670  if (Complain) {
6671  unsigned NextDiag = diag::err_template_param_different_kind;
6672  if (TemplateArgLoc.isValid()) {
6673  S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
6674  NextDiag = diag::note_template_param_different_kind;
6675  }
6676  S.Diag(New->getLocation(), NextDiag)
6677  << (Kind != Sema::TPL_TemplateMatch);
6678  S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
6679  << (Kind != Sema::TPL_TemplateMatch);
6680  }
6681 
6682  return false;
6683  }
6684 
6685  // Check that both are parameter packs or neither are parameter packs.
6686  // However, if we are matching a template template argument to a
6687  // template template parameter, the template template parameter can have
6688  // a parameter pack where the template template argument does not.
6689  if (Old->isTemplateParameterPack() != New->isTemplateParameterPack() &&
6691  Old->isTemplateParameterPack())) {
6692  if (Complain) {
6693  unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
6694  if (TemplateArgLoc.isValid()) {
6695  S.Diag(TemplateArgLoc,
6696  diag::err_template_arg_template_params_mismatch);
6697  NextDiag = diag::note_template_parameter_pack_non_pack;
6698  }
6699 
6700  unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
6701  : isa<NonTypeTemplateParmDecl>(New)? 1
6702  : 2;
6703  S.Diag(New->getLocation(), NextDiag)
6704  << ParamKind << New->isParameterPack();
6705  S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
6706  << ParamKind << Old->isParameterPack();
6707  }
6708 
6709  return false;
6710  }
6711 
6712  // For non-type template parameters, check the type of the parameter.
6713  if (NonTypeTemplateParmDecl *OldNTTP
6714  = dyn_cast<NonTypeTemplateParmDecl>(Old)) {
6715  NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(New);
6716 
6717  // If we are matching a template template argument to a template
6718  // template parameter and one of the non-type template parameter types
6719  // is dependent, then we must wait until template instantiation time
6720  // to actually compare the arguments.
6722  (OldNTTP->getType()->isDependentType() ||
6723  NewNTTP->getType()->isDependentType()))
6724  return true;
6725 
6726  if (!S.Context.hasSameType(OldNTTP->getType(), NewNTTP->getType())) {
6727  if (Complain) {
6728  unsigned NextDiag = diag::err_template_nontype_parm_different_type;
6729  if (TemplateArgLoc.isValid()) {
6730  S.Diag(TemplateArgLoc,
6731  diag::err_template_arg_template_params_mismatch);
6732  NextDiag = diag::note_template_nontype_parm_different_type;
6733  }
6734  S.Diag(NewNTTP->getLocation(), NextDiag)
6735  << NewNTTP->getType()
6736  << (Kind != Sema::TPL_TemplateMatch);
6737  S.Diag(OldNTTP->getLocation(),
6738  diag::note_template_nontype_parm_prev_declaration)
6739  << OldNTTP->getType();
6740  }
6741 
6742  return false;
6743  }
6744 
6745  return true;
6746  }
6747 
6748  // For template template parameters, check the template parameter types.
6749  // The template parameter lists of template template
6750  // parameters must agree.
6751  if (TemplateTemplateParmDecl *OldTTP
6752  = dyn_cast<TemplateTemplateParmDecl>(Old)) {
6753  TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(New);
6755  OldTTP->getTemplateParameters(),
6756  Complain,
6757  (Kind == Sema::TPL_TemplateMatch
6759  : Kind),
6760  TemplateArgLoc);
6761  }
6762 
6763  return true;
6764 }
6765 
6766 /// \brief Diagnose a known arity mismatch when comparing template argument
6767 /// lists.
6768 static
6770  TemplateParameterList *New,
6771  TemplateParameterList *Old,
6773  SourceLocation TemplateArgLoc) {
6774  unsigned NextDiag = diag::err_template_param_list_different_arity;
6775  if (TemplateArgLoc.isValid()) {
6776  S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
6777  NextDiag = diag::note_template_param_list_different_arity;
6778  }
6779  S.Diag(New->getTemplateLoc(), NextDiag)
6780  << (New->size() > Old->size())
6781  << (Kind != Sema::TPL_TemplateMatch)
6782  << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
6783  S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
6784  << (Kind != Sema::TPL_TemplateMatch)
6785  << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
6786 }
6787 
6788 /// \brief Determine whether the given template parameter lists are
6789 /// equivalent.
6790 ///
6791 /// \param New The new template parameter list, typically written in the
6792 /// source code as part of a new template declaration.
6793 ///
6794 /// \param Old The old template parameter list, typically found via
6795 /// name lookup of the template declared with this template parameter
6796 /// list.
6797 ///
6798 /// \param Complain If true, this routine will produce a diagnostic if
6799 /// the template parameter lists are not equivalent.
6800 ///
6801 /// \param Kind describes how we are to match the template parameter lists.
6802 ///
6803 /// \param TemplateArgLoc If this source location is valid, then we
6804 /// are actually checking the template parameter list of a template
6805 /// argument (New) against the template parameter list of its
6806 /// corresponding template template parameter (Old). We produce
6807 /// slightly different diagnostics in this scenario.
6808 ///
6809 /// \returns True if the template parameter lists are equal, false
6810 /// otherwise.
6811 bool
6813  TemplateParameterList *Old,
6814  bool Complain,
6816  SourceLocation TemplateArgLoc) {
6817  if (Old->size() != New->size() && Kind != TPL_TemplateTemplateArgumentMatch) {
6818  if (Complain)
6819  DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
6820  TemplateArgLoc);
6821 
6822  return false;
6823  }
6824 
6825  // C++0x [temp.arg.template]p3:
6826  // A template-argument matches a template template-parameter (call it P)
6827  // when each of the template parameters in the template-parameter-list of
6828  // the template-argument's corresponding class template or alias template
6829  // (call it A) matches the corresponding template parameter in the
6830  // template-parameter-list of P. [...]
6831  TemplateParameterList::iterator NewParm = New->begin();
6832  TemplateParameterList::iterator NewParmEnd = New->end();
6833  for (TemplateParameterList::iterator OldParm = Old->begin(),
6834  OldParmEnd = Old->end();
6835  OldParm != OldParmEnd; ++OldParm) {
6836  if (Kind != TPL_TemplateTemplateArgumentMatch ||
6837  !(*OldParm)->isTemplateParameterPack()) {
6838  if (NewParm == NewParmEnd) {
6839  if (Complain)
6840  DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
6841  TemplateArgLoc);
6842 
6843  return false;
6844  }
6845 
6846  if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
6847  Kind, TemplateArgLoc))
6848  return false;
6849 
6850  ++NewParm;
6851  continue;
6852  }
6853 
6854  // C++0x [temp.arg.template]p3:
6855  // [...] When P's template- parameter-list contains a template parameter
6856  // pack (14.5.3), the template parameter pack will match zero or more
6857  // template parameters or template parameter packs in the
6858  // template-parameter-list of A with the same type and form as the
6859  // template parameter pack in P (ignoring whether those template
6860  // parameters are template parameter packs).
6861  for (; NewParm != NewParmEnd; ++NewParm) {
6862  if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
6863  Kind, TemplateArgLoc))
6864  return false;
6865  }
6866  }
6867 
6868  // Make sure we exhausted all of the arguments.
6869  if (NewParm != NewParmEnd) {
6870  if (Complain)
6871  DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
6872  TemplateArgLoc);
6873 
6874  return false;
6875  }
6876 
6877  return true;
6878 }
6879 
6880 /// \brief Check whether a template can be declared within this scope.
6881 ///
6882 /// If the template declaration is valid in this scope, returns
6883 /// false. Otherwise, issues a diagnostic and returns true.
6884 bool
6886  if (!S)
6887  return false;
6888 
6889  // Find the nearest enclosing declaration scope.
6890  while ((S->getFlags() & Scope::DeclScope) == 0 ||
6891  (S->getFlags() & Scope::TemplateParamScope) != 0)
6892  S = S->getParent();
6893 
6894  // C++ [temp]p4:
6895  // A template [...] shall not have C linkage.
6896  DeclContext *Ctx = S->getEntity();
6897  if (Ctx && Ctx->isExternCContext()) {
6898  Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
6899  << TemplateParams->getSourceRange();
6900  if (const LinkageSpecDecl *LSD = Ctx->getExternCContext())
6901  Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
6902  return true;
6903  }
6904  Ctx = Ctx->getRedeclContext();
6905 
6906  // C++ [temp]p2:
6907  // A template-declaration can appear only as a namespace scope or
6908  // class scope declaration.
6909  if (Ctx) {
6910  if (Ctx->isFileContext())
6911  return false;
6912  if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Ctx)) {
6913  // C++ [temp.mem]p2:
6914  // A local class shall not have member templates.
6915  if (RD->isLocalClass())
6916  return Diag(TemplateParams->getTemplateLoc(),
6917  diag::err_template_inside_local_class)
6918  << TemplateParams->getSourceRange();
6919  else
6920  return false;
6921  }
6922  }
6923 
6924  return Diag(TemplateParams->getTemplateLoc(),
6925  diag::err_template_outside_namespace_or_class_scope)
6926  << TemplateParams->getSourceRange();
6927 }
6928 
6929 /// \brief Determine what kind of template specialization the given declaration
6930 /// is.
6932  if (!D)
6933  return TSK_Undeclared;
6934 
6935  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
6936  return Record->getTemplateSpecializationKind();
6937  if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
6938  return Function->getTemplateSpecializationKind();
6939  if (VarDecl *Var = dyn_cast<VarDecl>(D))
6940  return Var->getTemplateSpecializationKind();
6941 
6942  return TSK_Undeclared;
6943 }
6944 
6945 /// \brief Check whether a specialization is well-formed in the current
6946 /// context.
6947 ///
6948 /// This routine determines whether a template specialization can be declared
6949 /// in the current context (C++ [temp.expl.spec]p2).
6950 ///
6951 /// \param S the semantic analysis object for which this check is being
6952 /// performed.
6953 ///
6954 /// \param Specialized the entity being specialized or instantiated, which
6955 /// may be a kind of template (class template, function template, etc.) or
6956 /// a member of a class template (member function, static data member,
6957 /// member class).
6958 ///
6959 /// \param PrevDecl the previous declaration of this entity, if any.
6960 ///
6961 /// \param Loc the location of the explicit specialization or instantiation of
6962 /// this entity.
6963 ///
6964 /// \param IsPartialSpecialization whether this is a partial specialization of
6965 /// a class template.
6966 ///
6967 /// \returns true if there was an error that we cannot recover from, false
6968 /// otherwise.
6970  NamedDecl *Specialized,
6971  NamedDecl *PrevDecl,
6972  SourceLocation Loc,
6973  bool IsPartialSpecialization) {
6974  // Keep these "kind" numbers in sync with the %select statements in the
6975  // various diagnostics emitted by this routine.
6976  int EntityKind = 0;
6977  if (isa<ClassTemplateDecl>(Specialized))
6978  EntityKind = IsPartialSpecialization? 1 : 0;
6979  else if (isa<VarTemplateDecl>(Specialized))
6980  EntityKind = IsPartialSpecialization ? 3 : 2;
6981  else if (isa<FunctionTemplateDecl>(Specialized))
6982  EntityKind = 4;
6983  else if (isa<CXXMethodDecl>(Specialized))
6984  EntityKind = 5;
6985  else if (isa<VarDecl>(Specialized))
6986  EntityKind = 6;
6987  else if (isa<RecordDecl>(Specialized))
6988  EntityKind = 7;
6989  else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11)
6990  EntityKind = 8;
6991  else {
6992  S.Diag(Loc, diag::err_template_spec_unknown_kind)
6993  << S.getLangOpts().CPlusPlus11;
6994  S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
6995  return true;
6996  }
6997 
6998  // C++ [temp.expl.spec]p2:
6999  // An explicit specialization shall be declared in the namespace
7000  // of which the template is a member, or, for member templates, in
7001  // the namespace of which the enclosing class or enclosing class
7002  // template is a member. An explicit specialization of a member
7003  // function, member class or static data member of a class
7004  // template shall be declared in the namespace of which the class
7005  // template is a member. Such a declaration may also be a
7006  // definition. If the declaration is not a definition, the
7007  // specialization may be defined later in the name- space in which
7008  // the explicit specialization was declared, or in a namespace
7009  // that encloses the one in which the explicit specialization was
7010  // declared.
7012  S.Diag(Loc, diag::err_template_spec_decl_function_scope)
7013  << Specialized;
7014  return true;
7015  }
7016 
7017  if (S.CurContext->isRecord() && !IsPartialSpecialization) {
7018  if (S.getLangOpts().MicrosoftExt) {
7019  // Do not warn for class scope explicit specialization during
7020  // instantiation, warning was already emitted during pattern
7021  // semantic analysis.
7022  if (!S.inTemplateInstantiation())
7023  S.Diag(Loc, diag::ext_function_specialization_in_class)
7024  << Specialized;
7025  } else {
7026  S.Diag(Loc, diag::err_template_spec_decl_class_scope)
7027  << Specialized;
7028  return true;
7029  }
7030  }
7031 
7032  if (S.CurContext->isRecord() &&
7033  !S.CurContext->Equals(Specialized->getDeclContext())) {
7034  // Make sure that we're specializing in the right record context.
7035  // Otherwise, things can go horribly wrong.
7036  S.Diag(Loc, diag::err_template_spec_decl_class_scope)
7037  << Specialized;
7038  return true;
7039  }
7040 
7041  // C++ [temp.class.spec]p6:
7042  // A class template partial specialization may be declared or redeclared
7043  // in any namespace scope in which its definition may be defined (14.5.1
7044  // and 14.5.2).
7045  DeclContext *SpecializedContext
7046  = Specialized->getDeclContext()->getEnclosingNamespaceContext();
7048 
7049  // Make sure that this redeclaration (or definition) occurs in an enclosing
7050  // namespace.
7051  // Note that HandleDeclarator() performs this check for explicit
7052  // specializations of function templates, static data members, and member
7053  // functions, so we skip the check here for those kinds of entities.
7054  // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
7055  // Should we refactor that check, so that it occurs later?
7056  if (!DC->Encloses(SpecializedContext) &&
7057  !(isa<FunctionTemplateDecl>(Specialized) ||
7058  isa<FunctionDecl>(Specialized) ||
7059  isa<VarTemplateDecl>(Specialized) ||
7060  isa<VarDecl>(Specialized))) {
7061  if (isa<TranslationUnitDecl>(SpecializedContext))
7062  S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
7063  << EntityKind << Specialized;
7064  else if (isa<NamespaceDecl>(SpecializedContext)) {
7065  int Diag = diag::err_template_spec_redecl_out_of_scope;
7066  if (S.getLangOpts().MicrosoftExt)
7067  Diag = diag::ext_ms_template_spec_redecl_out_of_scope;
7068  S.Diag(Loc, Diag) << EntityKind << Specialized
7069  << cast<NamedDecl>(SpecializedContext);
7070  } else
7071  llvm_unreachable("unexpected namespace context for specialization");
7072 
7073  S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
7074  } else if ((!PrevDecl ||
7076  getTemplateSpecializationKind(PrevDecl) ==
7078  // C++ [temp.exp.spec]p2:
7079  // An explicit specialization shall be declared in the namespace of which
7080  // the template is a member, or, for member templates, in the namespace
7081  // of which the enclosing class or enclosing class template is a member.
7082  // An explicit specialization of a member function, member class or
7083  // static data member of a class template shall be declared in the
7084  // namespace of which the class template is a member.
7085  //
7086  // C++11 [temp.expl.spec]p2:
7087  // An explicit specialization shall be declared in a namespace enclosing
7088  // the specialized template.
7089  // C++11 [temp.explicit]p3:
7090  // An explicit instantiation shall appear in an enclosing namespace of its
7091  // template.
7092  if (!DC->InEnclosingNamespaceSetOf(SpecializedContext)) {
7093  bool IsCPlusPlus11Extension = DC->Encloses(SpecializedContext);
7094  if (isa<TranslationUnitDecl>(SpecializedContext)) {
7095  assert(!IsCPlusPlus11Extension &&
7096  "DC encloses TU but isn't in enclosing namespace set");
7097  S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
7098  << EntityKind << Specialized;
7099  } else if (isa<NamespaceDecl>(SpecializedContext)) {
7100  int Diag;
7101  if (!IsCPlusPlus11Extension)
7102  Diag = diag::err_template_spec_decl_out_of_scope;
7103  else if (!S.getLangOpts().CPlusPlus11)
7104  Diag = diag::ext_template_spec_decl_out_of_scope;
7105  else
7106  Diag = diag::warn_cxx98_compat_template_spec_decl_out_of_scope;
7107  S.Diag(Loc, Diag)
7108  << EntityKind << Specialized << cast<NamedDecl>(SpecializedContext);
7109  }
7110 
7111  S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
7112  }
7113  }
7114 
7115  return false;
7116 }
7117 
7119  if (!E->isTypeDependent())
7120  return SourceLocation();
7121  DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
7122  Checker.TraverseStmt(E);
7123  if (Checker.MatchLoc.isInvalid())
7124  return E->getSourceRange();
7125  return Checker.MatchLoc;
7126 }
7127 
7129  if (!TL.getType()->isDependentType())
7130  return SourceLocation();
7131  DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
7132  Checker.TraverseTypeLoc(TL);
7133  if (Checker.MatchLoc.isInvalid())
7134  return TL.getSourceRange();
7135  return Checker.MatchLoc;
7136 }
7137 
7138 /// \brief Subroutine of Sema::CheckTemplatePartialSpecializationArgs
7139 /// that checks non-type template partial specialization arguments.
7141  Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
7142  const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
7143  for (unsigned I = 0; I != NumArgs; ++I) {
7144  if (Args[I].getKind() == TemplateArgument::Pack) {
7146  S, TemplateNameLoc, Param, Args[I].pack_begin(),
7147  Args[I].pack_size(), IsDefaultArgument))
7148  return true;
7149 
7150  continue;
7151  }
7152 
7153  if (Args[I].getKind() != TemplateArgument::Expression)
7154  continue;
7155 
7156  Expr *ArgExpr = Args[I].getAsExpr();
7157 
7158  // We can have a pack expansion of any of the bullets below.
7159  if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
7160  ArgExpr = Expansion->getPattern();
7161 
7162  // Strip off any implicit casts we added as part of type checking.
7163  while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
7164  ArgExpr = ICE->getSubExpr();
7165 
7166  // C++ [temp.class.spec]p8:
7167  // A non-type argument is non-specialized if it is the name of a
7168  // non-type parameter. All other non-type arguments are
7169  // specialized.
7170  //
7171  // Below, we check the two conditions that only apply to
7172  // specialized non-type arguments, so skip any non-specialized
7173  // arguments.
7174  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
7175  if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
7176  continue;
7177 
7178  // C++ [temp.class.spec]p9:
7179  // Within the argument list of a class template partial
7180  // specialization, the following restrictions apply:
7181  // -- A partially specialized non-type argument expression
7182  // shall not involve a template parameter of the partial
7183  // specialization except when the argument expression is a
7184  // simple identifier.
7185  // -- The type of a template parameter corresponding to a
7186  // specialized non-type argument shall not be dependent on a
7187  // parameter of the specialization.
7188  // DR1315 removes the first bullet, leaving an incoherent set of rules.
7189  // We implement a compromise between the original rules and DR1315:
7190  // -- A specialized non-type template argument shall not be
7191  // type-dependent and the corresponding template parameter
7192  // shall have a non-dependent type.
7193  SourceRange ParamUseRange =
7194  findTemplateParameterInType(Param->getDepth(), ArgExpr);
7195  if (ParamUseRange.isValid()) {
7196  if (IsDefaultArgument) {
7197  S.Diag(TemplateNameLoc,
7198  diag::err_dependent_non_type_arg_in_partial_spec);
7199  S.Diag(ParamUseRange.getBegin(),
7200  diag::note_dependent_non_type_default_arg_in_partial_spec)
7201  << ParamUseRange;
7202  } else {
7203  S.Diag(ParamUseRange.getBegin(),
7204  diag::err_dependent_non_type_arg_in_partial_spec)
7205  << ParamUseRange;
7206  }
7207  return true;
7208  }
7209 
7210  ParamUseRange = findTemplateParameter(
7211  Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc());
7212  if (ParamUseRange.isValid()) {
7213  S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getLocStart(),
7214  diag::err_dependent_typed_non_type_arg_in_partial_spec)
7215  << Param->getType();
7216  S.Diag(Param->getLocation(), diag::note_template_param_here)
7217  << (IsDefaultArgument ? ParamUseRange : SourceRange())
7218  << ParamUseRange;
7219  return true;
7220  }
7221  }
7222 
7223  return false;
7224 }
7225 
7226 /// \brief Check the non-type template arguments of a class template
7227 /// partial specialization according to C++ [temp.class.spec]p9.
7228 ///
7229 /// \param TemplateNameLoc the location of the template name.
7230 /// \param PrimaryTemplate the template parameters of the primary class
7231 /// template.
7232 /// \param NumExplicit the number of explicitly-specified template arguments.
7233 /// \param TemplateArgs the template arguments of the class template
7234 /// partial specialization.
7235 ///
7236 /// \returns \c true if there was an error, \c false otherwise.
7238  SourceLocation TemplateNameLoc, TemplateDecl *PrimaryTemplate,
7239  unsigned NumExplicit, ArrayRef<TemplateArgument> TemplateArgs) {
7240  // We have to be conservative when checking a template in a dependent
7241  // context.
7242  if (PrimaryTemplate->getDeclContext()->isDependentContext())
7243  return false;
7244 
7245  TemplateParameterList *TemplateParams =
7246  PrimaryTemplate->getTemplateParameters();
7247  for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
7249  = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
7250  if (!Param)
7251  continue;
7252 
7253  if (CheckNonTypeTemplatePartialSpecializationArgs(*this, TemplateNameLoc,
7254  Param, &TemplateArgs[I],
7255  1, I >= NumExplicit))
7256  return true;
7257  }
7258 
7259  return false;
7260 }
7261 
7262 DeclResult
7264  TagUseKind TUK,
7265  SourceLocation KWLoc,
7266  SourceLocation ModulePrivateLoc,
7267  TemplateIdAnnotation &TemplateId,
7270  TemplateParameterLists,
7271  SkipBodyInfo *SkipBody) {
7272  assert(TUK != TUK_Reference && "References are not specializations");
7273 
7274  CXXScopeSpec &SS = TemplateId.SS;
7275 
7276  // NOTE: KWLoc is the location of the tag keyword. This will instead
7277  // store the location of the outermost template keyword in the declaration.
7278  SourceLocation TemplateKWLoc = TemplateParameterLists.size() > 0
7279  ? TemplateParameterLists[0]->getTemplateLoc() : KWLoc;
7280  SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
7281  SourceLocation LAngleLoc = TemplateId.LAngleLoc;
7282  SourceLocation RAngleLoc = TemplateId.RAngleLoc;
7283 
7284  // Find the class template we're specializing
7285  TemplateName Name = TemplateId.Template.get();
7286  ClassTemplateDecl *ClassTemplate
7287  = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
7288 
7289  if (!ClassTemplate) {
7290  Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
7291  << (Name.getAsTemplateDecl() &&
7292  isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
7293  return true;
7294  }
7295 
7296  bool isMemberSpecialization = false;
7297  bool isPartialSpecialization = false;
7298 
7299  // Check the validity of the template headers that introduce this
7300  // template.
7301  // FIXME: We probably shouldn't complain about these headers for
7302  // friend declarations.
7303  bool Invalid = false;
7304  TemplateParameterList *TemplateParams =
7305  MatchTemplateParametersToScopeSpecifier(
7306  KWLoc, TemplateNameLoc, SS, &TemplateId,
7307  TemplateParameterLists, TUK == TUK_Friend, isMemberSpecialization,
7308  Invalid);
7309  if (Invalid)
7310  return true;
7311 
7312  if (TemplateParams && TemplateParams->size() > 0) {
7313  isPartialSpecialization = true;
7314 
7315  if (TUK == TUK_Friend) {
7316  Diag(KWLoc, diag::err_partial_specialization_friend)
7317  << SourceRange(LAngleLoc, RAngleLoc);
7318  return true;
7319  }
7320 
7321  // C++ [temp.class.spec]p10:
7322  // The template parameter list of a specialization shall not
7323  // contain default template argument values.
7324  for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
7325  Decl *Param = TemplateParams->getParam(I);
7326  if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
7327  if (TTP->hasDefaultArgument()) {
7328  Diag(TTP->getDefaultArgumentLoc(),
7329  diag::err_default_arg_in_partial_spec);
7330  TTP->removeDefaultArgument();
7331  }
7332  } else if (NonTypeTemplateParmDecl *NTTP
7333  = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
7334  if (Expr *DefArg = NTTP->getDefaultArgument()) {
7335  Diag(NTTP->getDefaultArgumentLoc(),
7336  diag::err_default_arg_in_partial_spec)
7337  << DefArg->getSourceRange();
7338  NTTP->removeDefaultArgument();
7339  }
7340  } else {
7341  TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
7342  if (TTP->hasDefaultArgument()) {
7344  diag::err_default_arg_in_partial_spec)
7345  << TTP->getDefaultArgument().getSourceRange();
7346  TTP->removeDefaultArgument();
7347  }
7348  }
7349  }
7350  } else if (TemplateParams) {
7351  if (TUK == TUK_Friend)
7352  Diag(KWLoc, diag::err_template_spec_friend)
7354  SourceRange(TemplateParams->getTemplateLoc(),
7355  TemplateParams->getRAngleLoc()))
7356  << SourceRange(LAngleLoc, RAngleLoc);
7357  } else {
7358  assert(TUK == TUK_Friend && "should have a 'template<>' for this decl");
7359  }
7360 
7361  // Check that the specialization uses the same tag kind as the
7362  // original template.
7364  assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
7365  if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
7366  Kind, TUK == TUK_Definition, KWLoc,
7367  ClassTemplate->getIdentifier())) {
7368  Diag(KWLoc, diag::err_use_with_wrong_tag)
7369  << ClassTemplate
7371  ClassTemplate->getTemplatedDecl()->getKindName());
7372  Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
7373  diag::note_previous_use);
7374  Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
7375  }
7376 
7377  // Translate the parser's template argument list in our AST format.
7378  TemplateArgumentListInfo TemplateArgs =
7379  makeTemplateArgumentListInfo(*this, TemplateId);
7380 
7381  // Check for unexpanded parameter packs in any of the template arguments.
7382  for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
7383  if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
7384  UPPC_PartialSpecialization))
7385  return true;
7386 
7387  // Check that the template argument list is well-formed for this
7388  // template.
7390  if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
7391  TemplateArgs, false, Converted))
7392  return true;
7393 
7394  // Find the class template (partial) specialization declaration that
7395  // corresponds to these arguments.
7396  if (isPartialSpecialization) {
7397  if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, ClassTemplate,
7398  TemplateArgs.size(), Converted))
7399  return true;
7400 
7401  // FIXME: Move this to CheckTemplatePartialSpecializationArgs so we
7402  // also do it during instantiation.
7403  bool InstantiationDependent;
7404  if (!Name.isDependent() &&
7406  TemplateArgs.arguments(), InstantiationDependent)) {
7407  Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
7408  << ClassTemplate->getDeclName();
7409  isPartialSpecialization = false;
7410  }
7411  }
7412 
7413  void *InsertPos = nullptr;
7414  ClassTemplateSpecializationDecl *PrevDecl = nullptr;
7415 
7416  if (isPartialSpecialization)
7417  // FIXME: Template parameter list matters, too
7418  PrevDecl = ClassTemplate->findPartialSpecialization(Converted, InsertPos);
7419  else
7420  PrevDecl = ClassTemplate->findSpecialization(Converted, InsertPos);
7421 
7422  ClassTemplateSpecializationDecl *Specialization = nullptr;
7423 
7424  // Check whether we can declare a class template specialization in
7425  // the current scope.
7426  if (TUK != TUK_Friend &&
7427  CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
7428  TemplateNameLoc,
7429  isPartialSpecialization))
7430  return true;
7431 
7432  // The canonical type
7433  QualType CanonType;
7434  if (isPartialSpecialization) {
7435  // Build the canonical type that describes the converted template
7436  // arguments of the class template partial specialization.
7437  TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
7438  CanonType = Context.getTemplateSpecializationType(CanonTemplate,
7439  Converted);
7440 
7441  if (Context.hasSameType(CanonType,
7442  ClassTemplate->getInjectedClassNameSpecialization())) {
7443  // C++ [temp.class.spec]p9b3:
7444  //
7445  // -- The argument list of the specialization shall not be identical
7446  // to the implicit argument list of the primary template.
7447  //
7448  // This rule has since been removed, because it's redundant given DR1495,
7449  // but we keep it because it produces better diagnostics and recovery.
7450  Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
7451  << /*class template*/0 << (TUK == TUK_Definition)
7452  << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
7453  return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
7454  ClassTemplate->getIdentifier(),
7455  TemplateNameLoc,
7456  Attr,
7457  TemplateParams,
7458  AS_none, /*ModulePrivateLoc=*/SourceLocation(),
7459  /*FriendLoc*/SourceLocation(),
7460  TemplateParameterLists.size() - 1,
7461  TemplateParameterLists.data());
7462  }
7463 
7464  // Create a new class template partial specialization declaration node.
7466  = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
7469  ClassTemplate->getDeclContext(),
7470  KWLoc, TemplateNameLoc,
7471  TemplateParams,
7472  ClassTemplate,
7473  Converted,
7474  TemplateArgs,
7475  CanonType,
7476  PrevPartial);
7477  SetNestedNameSpecifier(Partial, SS);
7478  if (TemplateParameterLists.size() > 1 && SS.isSet()) {
7479  Partial->setTemplateParameterListsInfo(
7480  Context, TemplateParameterLists.drop_back(1));
7481  }
7482 
7483  if (!PrevPartial)
7484  ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
7485  Specialization = Partial;
7486 
7487  // If we are providing an explicit specialization of a member class
7488  // template specialization, make a note of that.
7489  if (PrevPartial && PrevPartial->getInstantiatedFromMember())
7490  PrevPartial->setMemberSpecialization();
7491 
7492  CheckTemplatePartialSpecialization(Partial);
7493  } else {
7494  // Create a new class template specialization declaration node for
7495  // this explicit specialization or friend declaration.
7496  Specialization
7498  ClassTemplate->getDeclContext(),
7499  KWLoc, TemplateNameLoc,
7500  ClassTemplate,
7501  Converted,
7502  PrevDecl);
7503  SetNestedNameSpecifier(Specialization, SS);
7504  if (TemplateParameterLists.size() > 0) {
7505  Specialization->setTemplateParameterListsInfo(Context,
7506  TemplateParameterLists);
7507  }
7508 
7509  if (!PrevDecl)
7510  ClassTemplate->AddSpecialization(Specialization, InsertPos);
7511 
7512  if (CurContext->isDependentContext()) {
7513  // -fms-extensions permits specialization of nested classes without
7514  // fully specializing the outer class(es).
7515  assert(getLangOpts().MicrosoftExt &&
7516  "Only possible with -fms-extensions!");
7517  TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
7519  CanonTemplate, Converted);
7520  } else {
7521  CanonType = Context.getTypeDeclType(Specialization);
7522  }
7523  }
7524 
7525  // C++ [temp.expl.spec]p6:
7526  // If a template, a member template or the member of a class template is
7527  // explicitly specialized then that specialization shall be declared
7528  // before the first use of that specialization that would cause an implicit
7529  // instantiation to take place, in every translation unit in which such a
7530  // use occurs; no diagnostic is required.
7531  if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
7532  bool Okay = false;
7533  for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
7534  // Is there any previous explicit specialization declaration?
7536  Okay = true;
7537  break;
7538  }
7539  }
7540 
7541  if (!Okay) {
7542  SourceRange Range(TemplateNameLoc, RAngleLoc);
7543  Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
7544  << Context.getTypeDeclType(Specialization) << Range;
7545 
7546  Diag(PrevDecl->getPointOfInstantiation(),
7547  diag::note_instantiation_required_here)
7548  << (PrevDecl->getTemplateSpecializationKind()
7550  return true;
7551  }
7552  }
7553 
7554  // If this is not a friend, note that this is an explicit specialization.
7555  if (TUK != TUK_Friend)
7557 
7558  // Check that this isn't a redefinition of this specialization.
7559  if (TUK == TUK_Definition) {
7560  RecordDecl *Def = Specialization->getDefinition();
7561  NamedDecl *Hidden = nullptr;
7562  if (Def && SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
7563  SkipBody->ShouldSkip = true;
7564  makeMergedDefinitionVisible(Hidden);
7565  // From here on out, treat this as just a redeclaration.
7566  TUK = TUK_Declaration;
7567  } else if (Def) {
7568  SourceRange Range(TemplateNameLoc, RAngleLoc);
7569  Diag(TemplateNameLoc, diag::err_redefinition) << Specialization << Range;
7570  Diag(Def->getLocation(), diag::note_previous_definition);
7571  Specialization->setInvalidDecl();
7572  return true;
7573  }
7574  }
7575 
7576  if (Attr)
7577  ProcessDeclAttributeList(S, Specialization, Attr);
7578 
7579  // Add alignment attributes if necessary; these attributes are checked when
7580  // the ASTContext lays out the structure.
7581  if (TUK == TUK_Definition) {
7582  AddAlignmentAttributesForRecord(Specialization);
7583  AddMsStructLayoutForRecord(Specialization);
7584  }
7585 
7586  if (ModulePrivateLoc.isValid())
7587  Diag(Specialization->getLocation(), diag::err_module_private_specialization)
7588  << (isPartialSpecialization? 1 : 0)
7589  << FixItHint::CreateRemoval(ModulePrivateLoc);
7590 
7591  // Build the fully-sugared type for this class template
7592  // specialization as the user wrote in the specialization
7593  // itself. This means that we'll pretty-print the type retrieved
7594  // from the specialization's declaration the way that the user
7595  // actually wrote the specialization, rather than formatting the
7596  // name based on the "canonical" representation used to store the
7597  // template arguments in the specialization.
7598  TypeSourceInfo *WrittenTy
7599  = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
7600  TemplateArgs, CanonType);
7601  if (TUK != TUK_Friend) {
7602  Specialization->setTypeAsWritten(WrittenTy);
7603  Specialization->setTemplateKeywordLoc(TemplateKWLoc);
7604  }
7605 
7606  // C++ [temp.expl.spec]p9:
7607  // A template explicit specialization is in the scope of the
7608  // namespace in which the template was defined.
7609  //
7610  // We actually implement this paragraph where we set the semantic
7611  // context (in the creation of the ClassTemplateSpecializationDecl),
7612  // but we also maintain the lexical context where the actual
7613  // definition occurs.
7614  Specialization->setLexicalDeclContext(CurContext);
7615 
7616  // We may be starting the definition of this specialization.
7617  if (TUK == TUK_Definition)
7618  Specialization->startDefinition();
7619 
7620  if (TUK == TUK_Friend) {
7621  FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
7622  TemplateNameLoc,
7623  WrittenTy,
7624  /*FIXME:*/KWLoc);
7625  Friend->setAccess(AS_public);
7626  CurContext->addDecl(Friend);
7627  } else {
7628  // Add the specialization into its lexical context, so that it can
7629  // be seen when iterating through the list of declarations in that
7630  // context. However, specializations are not found by name lookup.
7631  CurContext->addDecl(Specialization);
7632  }
7633  return Specialization;
7634 }
7635 
7637  MultiTemplateParamsArg TemplateParameterLists,
7638  Declarator &D) {
7639  Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
7640  ActOnDocumentableDecl(NewDecl);
7641  return NewDecl;
7642 }
7643 
7644 /// \brief Strips various properties off an implicit instantiation
7645 /// that has just been explicitly specialized.
7647  D->dropAttr<DLLImportAttr>();
7648  D->dropAttr<DLLExportAttr>();
7649 
7650  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
7651  FD->setInlineSpecified(false);
7652 }
7653 
7654 /// \brief Compute the diagnostic location for an explicit instantiation
7655 // declaration or definition.
7657  NamedDecl* D, SourceLocation PointOfInstantiation) {
7658  // Explicit instantiations following a specialization have no effect and
7659  // hence no PointOfInstantiation. In that case, walk decl backwards
7660  // until a valid name loc is found.
7661  SourceLocation PrevDiagLoc = PointOfInstantiation;
7662  for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
7663  Prev = Prev->getPreviousDecl()) {
7664  PrevDiagLoc = Prev->getLocation();
7665  }
7666  assert(PrevDiagLoc.isValid() &&
7667  "Explicit instantiation without point of instantiation?");
7668  return PrevDiagLoc;
7669 }
7670 
7671 /// \brief Diagnose cases where we have an explicit template specialization
7672 /// before/after an explicit template instantiation, producing diagnostics
7673 /// for those cases where they are required and determining whether the
7674 /// new specialization/instantiation will have any effect.
7675 ///
7676 /// \param NewLoc the location of the new explicit specialization or
7677 /// instantiation.
7678 ///
7679 /// \param NewTSK the kind of the new explicit specialization or instantiation.
7680 ///
7681 /// \param PrevDecl the previous declaration of the entity.
7682 ///
7683 /// \param PrevTSK the kind of the old explicit specialization or instantiatin.
7684 ///
7685 /// \param PrevPointOfInstantiation if valid, indicates where the previus
7686 /// declaration was instantiated (either implicitly or explicitly).
7687 ///
7688 /// \param HasNoEffect will be set to true to indicate that the new
7689 /// specialization or instantiation has no effect and should be ignored.
7690 ///
7691 /// \returns true if there was an error that should prevent the introduction of
7692 /// the new declaration into the AST, false otherwise.
7693 bool
7696  NamedDecl *PrevDecl,
7698  SourceLocation PrevPointOfInstantiation,
7699  bool &HasNoEffect) {
7700  HasNoEffect = false;
7701 
7702  switch (NewTSK) {
7703  case TSK_Undeclared:
7705  assert(
7706  (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
7707  "previous declaration must be implicit!");
7708  return false;
7709 
7711  switch (PrevTSK) {
7712  case TSK_Undeclared:
7714  // Okay, we're just specializing something that is either already
7715  // explicitly specialized or has merely been mentioned without any
7716  // instantiation.
7717  return false;
7718 
7720  if (PrevPointOfInstantiation.isInvalid()) {
7721  // The declaration itself has not actually been instantiated, so it is
7722  // still okay to specialize it.
7723  StripImplicitInstantiation(PrevDecl);
7724  return false;
7725  }
7726  // Fall through
7727  LLVM_FALLTHROUGH;
7728 
7731  assert((PrevTSK == TSK_ImplicitInstantiation ||
7732  PrevPointOfInstantiation.isValid()) &&
7733  "Explicit instantiation without point of instantiation?");
7734 
7735  // C++ [temp.expl.spec]p6:
7736  // If a template, a member template or the member of a class template
7737  // is explicitly specialized then that specialization shall be declared
7738  // before the first use of that specialization that would cause an
7739  // implicit instantiation to take place, in every translation unit in
7740  // which such a use occurs; no diagnostic is required.
7741  for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
7742  // Is there any previous explicit specialization declaration?
7744  return false;
7745  }
7746 
7747  Diag(NewLoc, diag::err_specialization_after_instantiation)
7748  << PrevDecl;
7749  Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
7750  << (PrevTSK != TSK_ImplicitInstantiation);
7751 
7752  return true;
7753  }
7754  llvm_unreachable("The switch over PrevTSK must be exhaustive.");
7755 
7757  switch (PrevTSK) {
7759  // This explicit instantiation declaration is redundant (that's okay).
7760  HasNoEffect = true;
7761  return false;
7762 
7763  case TSK_Undeclared:
7765  // We're explicitly instantiating something that may have already been
7766  // implicitly instantiated; that's fine.
7767  return false;
7768 
7770  // C++0x [temp.explicit]p4:
7771  // For a given set of template parameters, if an explicit instantiation
7772  // of a template appears after a declaration of an explicit
7773  // specialization for that template, the explicit instantiation has no
7774  // effect.
7775  HasNoEffect = true;
7776  return false;
7777 
7779  // C++0x [temp.explicit]p10:
7780  // If an entity is the subject of both an explicit instantiation
7781  // declaration and an explicit instantiation definition in the same
7782  // translation unit, the definition shall follow the declaration.
7783  Diag(NewLoc,
7784  diag::err_explicit_instantiation_declaration_after_definition);
7785 
7786  // Explicit instantiations following a specialization have no effect and
7787  // hence no PrevPointOfInstantiation. In that case, walk decl backwards
7788  // until a valid name loc is found.
7789  Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
7790  diag::note_explicit_instantiation_definition_here);
7791  HasNoEffect = true;
7792  return false;
7793  }
7794 
7796  switch (PrevTSK) {
7797  case TSK_Undeclared:
7799  // We're explicitly instantiating something that may have already been
7800  // implicitly instantiated; that's fine.
7801  return false;
7802 
7804  // C++ DR 259, C++0x [temp.explicit]p4:
7805  // For a given set of template parameters, if an explicit
7806  // instantiation of a template appears after a declaration of
7807  // an explicit specialization for that template, the explicit
7808  // instantiation has no effect.
7809  Diag(NewLoc, diag::warn_explicit_instantiation_after_specialization)
7810  << PrevDecl;
7811  Diag(PrevDecl->getLocation(),
7812  diag::note_previous_template_specialization);
7813  HasNoEffect = true;
7814  return false;
7815 
7817  // We're explicity instantiating a definition for something for which we
7818  // were previously asked to suppress instantiations. That's fine.
7819 
7820  // C++0x [temp.explicit]p4:
7821  // For a given set of template parameters, if an explicit instantiation
7822  // of a template appears after a declaration of an explicit
7823  // specialization for that template, the explicit instantiation has no
7824  // effect.
7825  for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
7826  // Is there any previous explicit specialization declaration?
7828  HasNoEffect = true;
7829  break;
7830  }
7831  }
7832 
7833  return false;
7834 
7836  // C++0x [temp.spec]p5:
7837  // For a given template and a given set of template-arguments,
7838  // - an explicit instantiation definition shall appear at most once
7839  // in a program,
7840 
7841  // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
7842  Diag(NewLoc, (getLangOpts().MSVCCompat)
7843  ? diag::ext_explicit_instantiation_duplicate
7844  : diag::err_explicit_instantiation_duplicate)
7845  << PrevDecl;
7846  Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
7847  diag::note_previous_explicit_instantiation);
7848  HasNoEffect = true;
7849  return false;
7850  }
7851  }
7852 
7853  llvm_unreachable("Missing specialization/instantiation case?");
7854 }
7855 
7856 /// \brief Perform semantic analysis for the given dependent function
7857 /// template specialization.
7858 ///
7859 /// The only possible way to get a dependent function template specialization
7860 /// is with a friend declaration, like so:
7861 ///
7862 /// \code
7863 /// template <class T> void foo(T);
7864 /// template <class T> class A {
7865 /// friend void foo<>(T);
7866 /// };
7867 /// \endcode
7868 ///
7869 /// There really isn't any useful analysis we can do here, so we
7870 /// just store the information.
7871 bool
7873  const TemplateArgumentListInfo &ExplicitTemplateArgs,
7875  // Remove anything from Previous that isn't a function template in
7876  // the correct context.
7877  DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
7878  LookupResult::Filter F = Previous.makeFilter();
7879  while (F.hasNext()) {
7880  NamedDecl *D = F.next()->getUnderlyingDecl();
7881  if (!isa<FunctionTemplateDecl>(D) ||
7882  !FDLookupContext->InEnclosingNamespaceSetOf(
7884  F.erase();
7885  }
7886  F.done();
7887 
7888  // Should this be diagnosed here?
7889  if (Previous.empty()) return true;
7890 
7892  ExplicitTemplateArgs);
7893  return false;
7894 }
7895 
7896 /// \brief Perform semantic analysis for the given function template
7897 /// specialization.
7898 ///
7899 /// This routine performs all of the semantic analysis required for an
7900 /// explicit function template specialization. On successful completion,
7901 /// the function declaration \p FD will become a function template
7902 /// specialization.
7903 ///
7904 /// \param FD the function declaration, which will be updated to become a
7905 /// function template specialization.
7906 ///
7907 /// \param ExplicitTemplateArgs the explicitly-provided template arguments,
7908 /// if any. Note that this may be valid info even when 0 arguments are
7909 /// explicitly provided as in, e.g., \c void sort<>(char*, char*);
7910 /// as it anyway contains info on the angle brackets locations.
7911 ///
7912 /// \param Previous the set of declarations that may be specialized by
7913 /// this function specialization.
7915  FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
7917  // The set of function template specializations that could match this
7918  // explicit function template specialization.
7919  UnresolvedSet<8> Candidates;
7920  TemplateSpecCandidateSet FailedCandidates(FD->getLocation(),
7921  /*ForTakingAddress=*/false);
7922 
7923  llvm::SmallDenseMap<FunctionDecl *, TemplateArgumentListInfo, 8>
7924  ConvertedTemplateArgs;
7925 
7926  DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
7927  for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7928  I != E; ++I) {
7929  NamedDecl *Ovl = (*I)->getUnderlyingDecl();
7930  if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
7931  // Only consider templates found within the same semantic lookup scope as
7932  // FD.
7933  if (!FDLookupContext->InEnclosingNamespaceSetOf(
7934  Ovl->getDeclContext()->getRedeclContext()))
7935  continue;
7936 
7937  // When matching a constexpr member function template specialization
7938  // against the primary template, we don't yet know whether the
7939  // specialization has an implicit 'const' (because we don't know whether
7940  // it will be a static member function until we know which template it
7941  // specializes), so adjust it now assuming it specializes this template.
7942  QualType FT = FD->getType();
7943  if (FD->isConstexpr()) {
7944  CXXMethodDecl *OldMD =
7945  dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
7946  if (OldMD && OldMD->isConst()) {
7947  const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
7951  FPT->getParamTypes(), EPI);
7952  }
7953  }
7954 
7956  if (ExplicitTemplateArgs)
7957  Args = *ExplicitTemplateArgs;
7958 
7959  // C++ [temp.expl.spec]p11:
7960  // A trailing template-argument can be left unspecified in the
7961  // template-id naming an explicit function template specialization
7962  // provided it can be deduced from the function argument type.
7963  // Perform template argument deduction to determine whether we may be
7964  // specializing this template.
7965  // FIXME: It is somewhat wasteful to build
7966  TemplateDeductionInfo Info(FailedCandidates.getLocation());
7967  FunctionDecl *Specialization = nullptr;
7969  cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()),
7970  ExplicitTemplateArgs ? &Args : nullptr, FT, Specialization,
7971  Info)) {
7972  // Template argument deduction failed; record why it failed, so
7973  // that we can provide nifty diagnostics.
7974  FailedCandidates.addCandidate().set(
7975  I.getPair(), FunTmpl->getTemplatedDecl(),
7976  MakeDeductionFailureInfo(Context, TDK, Info));
7977  (void)TDK;
7978  continue;
7979  }
7980 
7981  // Target attributes are part of the cuda function signature, so
7982  // the deduced template's cuda target must match that of the
7983  // specialization. Given that C++ template deduction does not
7984  // take target attributes into account, we reject candidates
7985  // here that have a different target.
7986  if (LangOpts.CUDA &&
7987  IdentifyCUDATarget(Specialization,
7988  /* IgnoreImplicitHDAttributes = */ true) !=
7989  IdentifyCUDATarget(FD, /* IgnoreImplicitHDAttributes = */ true)) {
7990  FailedCandidates.addCandidate().set(
7991  I.getPair(), FunTmpl->getTemplatedDecl(),
7992  MakeDeductionFailureInfo(Context, TDK_CUDATargetMismatch, Info));
7993  continue;
7994  }
7995 
7996  // Record this candidate.
7997  if (ExplicitTemplateArgs)
7998  ConvertedTemplateArgs[Specialization] = std::move(Args);
7999  Candidates.addDecl(Specialization, I.getAccess());
8000  }
8001  }
8002 
8003  // Find the most specialized function template.
8004  UnresolvedSetIterator Result = getMostSpecialized(
8005  Candidates.begin(), Candidates.end(), FailedCandidates,
8006  FD->getLocation(),
8007  PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(),
8008  PDiag(diag::err_function_template_spec_ambiguous)
8009  << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
8010  PDiag(diag::note_function_template_spec_matched));
8011 
8012  if (Result == Candidates.end())
8013  return true;
8014 
8015  // Ignore access information; it doesn't figure into redeclaration checking.
8016  FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
8017 
8018  // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare [...]
8019  // an explicit specialization (14.8.3) [...] of a concept definition.
8020  if (Specialization->getPrimaryTemplate()->isConcept()) {
8021  Diag(FD->getLocation(), diag::err_concept_specialized)
8022  << 0 /*function*/ << 1 /*explicitly specialized*/;
8023  Diag(Specialization->getLocation(), diag::note_previous_declaration);
8024  return true;
8025  }
8026 
8028  = Specialization->getTemplateSpecializationInfo();
8029  assert(SpecInfo && "Function template specialization info missing?");
8030 
8031  // Note: do not overwrite location info if previous template
8032  // specialization kind was explicit.
8034  if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
8035  Specialization->setLocation(FD->getLocation());
8036  Specialization->setLexicalDeclContext(FD->getLexicalDeclContext());
8037  // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
8038  // function can differ from the template declaration with respect to
8039  // the constexpr specifier.
8040  // FIXME: We need an update record for this AST mutation.
8041  // FIXME: What if there are multiple such prior declarations (for instance,
8042  // from different modules)?
8043  Specialization->setConstexpr(FD->isConstexpr());
8044  }
8045 
8046  // FIXME: Check if the prior specialization has a point of instantiation.
8047  // If so, we have run afoul of .
8048 
8049  // If this is a friend declaration, then we're not really declaring
8050  // an explicit specialization.
8051  bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
8052 
8053  // Check the scope of this explicit specialization.
8054  if (!isFriend &&
8056  Specialization->getPrimaryTemplate(),
8057  Specialization, FD->getLocation(),
8058  false))
8059  return true;
8060 
8061  // C++ [temp.expl.spec]p6:
8062  // If a template, a member template or the member of a class template is
8063  // explicitly specialized then that specialization shall be declared
8064  // before the first use of that specialization that would cause an implicit
8065  // instantiation to take place, in every translation unit in which such a
8066  // use occurs; no diagnostic is required.
8067  bool HasNoEffect = false;
8068  if (!isFriend &&
8069  CheckSpecializationInstantiationRedecl(FD->getLocation(),
8071  Specialization,
8072  SpecInfo->getTemplateSpecializationKind(),
8073  SpecInfo->getPointOfInstantiation(),
8074  HasNoEffect))
8075  return true;
8076 
8077  // Mark the prior declaration as an explicit specialization, so that later
8078  // clients know that this is an explicit specialization.
8079  if (!isFriend) {
8080  // Since explicit specializations do not inherit '=delete' from their
8081  // primary function template - check if the 'specialization' that was
8082  // implicitly generated (during template argument deduction for partial
8083  // ordering) from the most specialized of all the function templates that
8084  // 'FD' could have been specializing, has a 'deleted' definition. If so,
8085  // first check that it was implicitly generated during template argument
8086  // deduction by making sure it wasn't referenced, and then reset the deleted
8087  // flag to not-deleted, so that we can inherit that information from 'FD'.
8088  if (Specialization->isDeleted() && !SpecInfo->isExplicitSpecialization() &&
8089  !Specialization->getCanonicalDecl()->isReferenced()) {
8090  // FIXME: This assert will not hold in the presence of modules.
8091  assert(
8092  Specialization->getCanonicalDecl() == Specialization &&
8093  "This must be the only existing declaration of this specialization");
8094  // FIXME: We need an update record for this AST mutation.
8095  Specialization->setDeletedAsWritten(false);
8096  }
8097  // FIXME: We need an update record for this AST mutation.
8099  MarkUnusedFileScopedDecl(Specialization);
8100  }
8101 
8102  // Turn the given function declaration into a function template
8103  // specialization, with the template arguments from the previous
8104  // specialization.
8105  // Take copies of (semantic and syntactic) template argument lists.
8106  const TemplateArgumentList* TemplArgs = new (Context)
8107  TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
8108  FD->setFunctionTemplateSpecialization(
8109  Specialization->getPrimaryTemplate(), TemplArgs, /*InsertPos=*/nullptr,
8110  SpecInfo->getTemplateSpecializationKind(),
8111  ExplicitTemplateArgs ? &ConvertedTemplateArgs[Specialization] : nullptr);
8112 
8113  // A function template specialization inherits the target attributes
8114  // of its template. (We require the attributes explicitly in the
8115  // code to match, but a template may have implicit attributes by
8116  // virtue e.g. of being constexpr, and it passes these implicit
8117  // attributes on to its specializations.)
8118  if (LangOpts.CUDA)
8119  inheritCUDATargetAttrs(FD, *Specialization->getPrimaryTemplate());
8120 
8121  // The "previous declaration" for this function template specialization is
8122  // the prior function template specialization.
8123  Previous.clear();
8124  Previous.addDecl(Specialization);
8125  return false;
8126 }
8127 
8128 /// \brief Perform semantic analysis for the given non-template member
8129 /// specialization.
8130 ///
8131 /// This routine performs all of the semantic analysis required for an
8132 /// explicit member function specialization. On successful completion,
8133 /// the function declaration \p FD will become a member function
8134 /// specialization.
8135 ///
8136 /// \param Member the member declaration, which will be updated to become a
8137 /// specialization.
8138 ///
8139 /// \param Previous the set of declarations, one of which may be specialized
8140 /// by this function specialization; the set will be modified to contain the
8141 /// redeclared member.
8142 bool
8144  assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
8145 
8146  // Try to find the member we are instantiating.
8147  NamedDecl *FoundInstantiation = nullptr;
8148  NamedDecl *Instantiation = nullptr;
8149  NamedDecl *InstantiatedFrom = nullptr;
8150  MemberSpecializationInfo *MSInfo = nullptr;
8151 
8152  if (Previous.empty()) {
8153  // Nowhere to look anyway.
8154  } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
8155  for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8156  I != E; ++I) {
8157  NamedDecl *D = (*I)->getUnderlyingDecl();
8158  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
8159  QualType Adjusted = Function->getType();
8160  if (!hasExplicitCallingConv(Adjusted))
8161  Adjusted = adjustCCAndNoReturn(Adjusted, Method->getType());
8162  if (Context.hasSameType(Adjusted, Method->getType())) {
8163  FoundInstantiation = *I;
8164  Instantiation = Method;
8165  InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
8166  MSInfo = Method->getMemberSpecializationInfo();
8167  break;
8168  }
8169  }
8170  }
8171  } else if (isa<VarDecl>(Member)) {
8172  VarDecl *PrevVar;
8173  if (Previous.isSingleResult() &&
8174  (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
8175  if (PrevVar->isStaticDataMember()) {
8176  FoundInstantiation = Previous.getRepresentativeDecl();
8177  Instantiation = PrevVar;
8178  InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
8179  MSInfo = PrevVar->getMemberSpecializationInfo();
8180  }
8181  } else if (isa<RecordDecl>(Member)) {
8182  CXXRecordDecl *PrevRecord;
8183  if (Previous.isSingleResult() &&
8184  (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
8185  FoundInstantiation = Previous.getRepresentativeDecl();
8186  Instantiation = PrevRecord;
8187  InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
8188  MSInfo = PrevRecord->getMemberSpecializationInfo();
8189  }
8190  } else if (isa<EnumDecl>(Member)) {
8191  EnumDecl *PrevEnum;
8192  if (Previous.isSingleResult() &&
8193  (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) {
8194  FoundInstantiation = Previous.getRepresentativeDecl();
8195  Instantiation = PrevEnum;
8196  InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
8197  MSInfo = PrevEnum->getMemberSpecializationInfo();
8198  }
8199  }
8200 
8201  if (!Instantiation) {
8202  // There is no previous declaration that matches. Since member
8203  // specializations are always out-of-line, the caller will complain about
8204  // this mismatch later.
8205  return false;
8206  }
8207 
8208  // A member specialization in a friend declaration isn't really declaring
8209  // an explicit specialization, just identifying a specific (possibly implicit)
8210  // specialization. Don't change the template specialization kind.
8211  //
8212  // FIXME: Is this really valid? Other compilers reject.
8213  if (Member->getFriendObjectKind() != Decl::FOK_None) {
8214  // Preserve instantiation information.
8215  if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
8216  cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
8217  cast<CXXMethodDecl>(InstantiatedFrom),
8218  cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
8219  } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
8220  cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
8221  cast<CXXRecordDecl>(InstantiatedFrom),
8222  cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
8223  }
8224 
8225  Previous.clear();
8226  Previous.addDecl(FoundInstantiation);
8227  return false;
8228  }
8229 
8230  // Make sure that this is a specialization of a member.
8231  if (!InstantiatedFrom) {
8232  Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
8233  << Member;
8234  Diag(Instantiation->getLocation(), diag::note_specialized_decl);
8235  return true;
8236  }
8237 
8238  // C++ [temp.expl.spec]p6:
8239  // If a template, a member template or the member of a class template is
8240  // explicitly specialized then that specialization shall be declared
8241  // before the first use of that specialization that would cause an implicit
8242  // instantiation to take place, in every translation unit in which such a
8243  // use occurs; no diagnostic is required.
8244  assert(MSInfo && "Member specialization info missing?");
8245 
8246  bool HasNoEffect = false;
8247  if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
8249  Instantiation,
8251  MSInfo->getPointOfInstantiation(),
8252  HasNoEffect))
8253  return true;
8254 
8255  // Check the scope of this explicit specialization.
8257  InstantiatedFrom,
8258  Instantiation, Member->getLocation(),
8259  false))
8260  return true;
8261 
8262  // Note that this member specialization is an "instantiation of" the
8263  // corresponding member of the original template.
8264  if (auto *MemberFunction = dyn_cast<FunctionDecl>(Member)) {
8265  FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
8266  if (InstantiationFunction->getTemplateSpecializationKind() ==
8268  // Explicit specializations of member functions of class templates do not
8269  // inherit '=delete' from the member function they are specializing.
8270  if (InstantiationFunction->isDeleted()) {
8271  // FIXME: This assert will not hold in the presence of modules.
8272  assert(InstantiationFunction->getCanonicalDecl() ==
8273  InstantiationFunction);
8274  // FIXME: We need an update record for this AST mutation.
8275  InstantiationFunction->setDeletedAsWritten(false);
8276  }
8277  }
8278 
8279  MemberFunction->setInstantiationOfMemberFunction(
8280  cast<CXXMethodDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
8281  } else if (auto *MemberVar = dyn_cast<VarDecl>(Member)) {
8282  MemberVar->setInstantiationOfStaticDataMember(
8283  cast<VarDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
8284  } else if (auto *MemberClass = dyn_cast<CXXRecordDecl>(Member)) {
8285  MemberClass->setInstantiationOfMemberClass(
8286  cast<CXXRecordDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
8287  } else if (auto *MemberEnum = dyn_cast<EnumDecl>(Member)) {
8288  MemberEnum->setInstantiationOfMemberEnum(
8289  cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
8290  } else {
8291  llvm_unreachable("unknown member specialization kind");
8292  }
8293 
8294  // Save the caller the trouble of having to figure out which declaration
8295  // this specialization matches.
8296  Previous.clear();
8297  Previous.addDecl(FoundInstantiation);
8298  return false;
8299 }
8300 
8301 /// Complete the explicit specialization of a member of a class template by
8302 /// updating the instantiated member to be marked as an explicit specialization.
8303 ///
8304 /// \param OrigD The member declaration instantiated from the template.
8305 /// \param Loc The location of the explicit specialization of the member.
8306 template<typename DeclT>
8307 static void completeMemberSpecializationImpl(Sema &S, DeclT *OrigD,
8308  SourceLocation Loc) {
8309  if (OrigD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
8310  return;
8311 
8312  // FIXME: Inform AST mutation listeners of this AST mutation.
8313  // FIXME: If there are multiple in-class declarations of the member (from
8314  // multiple modules, or a declaration and later definition of a member type),
8315  // should we update all of them?
8316  OrigD->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
8317  OrigD->setLocation(Loc);
8318 }
8319 
8322  NamedDecl *Instantiation = cast<NamedDecl>(Member->getCanonicalDecl());
8323  if (Instantiation == Member)
8324  return;
8325 
8326  if (auto *Function = dyn_cast<CXXMethodDecl>(Instantiation))
8327  completeMemberSpecializationImpl(*this, Function, Member->getLocation());
8328  else if (auto *Var = dyn_cast<VarDecl>(Instantiation))
8329  completeMemberSpecializationImpl(*this, Var, Member->getLocation());
8330  else if (auto *Record = dyn_cast<CXXRecordDecl>(Instantiation))
8331  completeMemberSpecializationImpl(*this, Record, Member->getLocation());
8332  else if (auto *Enum = dyn_cast<EnumDecl>(Instantiation))
8333  completeMemberSpecializationImpl(*this, Enum, Member->getLocation());
8334  else
8335  llvm_unreachable("unknown member specialization kind");
8336 }
8337 
8338 /// \brief Check the scope of an explicit instantiation.
8339 ///
8340 /// \returns true if a serious error occurs, false otherwise.
8342  SourceLocation InstLoc,
8343  bool WasQualifiedName) {
8345  DeclContext *CurContext = S.CurContext->getRedeclContext();
8346 
8347  if (CurContext->isRecord()) {
8348  S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
8349  << D;
8350  return true;
8351  }
8352 
8353  // C++11 [temp.explicit]p3:
8354  // An explicit instantiation shall appear in an enclosing namespace of its
8355  // template. If the name declared in the explicit instantiation is an
8356  // unqualified name, the explicit instantiation shall appear in the
8357  // namespace where its template is declared or, if that namespace is inline
8358  // (7.3.1), any namespace from its enclosing namespace set.
8359  //
8360  // This is DR275, which we do not retroactively apply to C++98/03.
8361  if (WasQualifiedName) {
8362  if (CurContext->Encloses(OrigContext))
8363  return false;
8364  } else {
8365  if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
8366  return false;
8367  }
8368 
8369  if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
8370  if (WasQualifiedName)
8371  S.Diag(InstLoc,
8372  S.getLangOpts().CPlusPlus11?
8373  diag::err_explicit_instantiation_out_of_scope :
8374  diag::warn_explicit_instantiation_out_of_scope_0x)
8375  << D << NS;
8376  else
8377  S.Diag(InstLoc,
8378  S.getLangOpts().CPlusPlus11?
8379  diag::err_explicit_instantiation_unqualified_wrong_namespace :
8380  diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
8381  << D << NS;
8382  } else
8383  S.Diag(InstLoc,
8384  S.getLangOpts().CPlusPlus11?
8385  diag::err_explicit_instantiation_must_be_global :
8386  diag::warn_explicit_instantiation_must_be_global_0x)
8387  << D;
8388  S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
8389  return false;
8390 }
8391 
8392 /// \brief Determine whether the given scope specifier has a template-id in it.
8394  if (!SS.isSet())
8395  return false;
8396 
8397  // C++11 [temp.explicit]p3:
8398  // If the explicit instantiation is for a member function, a member class
8399  // or a static data member of a class template specialization, the name of
8400  // the class template specialization in the qualified-id for the member
8401  // name shall be a simple-template-id.
8402  //
8403  // C++98 has the same restriction, just worded differently.
8404  for (NestedNameSpecifier *NNS = SS.getScopeRep(); NNS;
8405  NNS = NNS->getPrefix())
8406  if (const Type *T = NNS->getAsType())
8407  if (isa<TemplateSpecializationType>(T))
8408  return true;
8409 
8410  return false;
8411 }
8412 
8413 /// Make a dllexport or dllimport attr on a class template specialization take
8414 /// effect.
8417  auto *A = cast_or_null<InheritableAttr>(getDLLAttr(Def));
8418  assert(A && "dllExportImportClassTemplateSpecialization called "
8419  "on Def without dllexport or dllimport");
8420 
8421  // We reject explicit instantiations in class scope, so there should
8422  // never be any delayed exported classes to worry about.
8423  assert(S.DelayedDllExportClasses.empty() &&
8424  "delayed exports present at explicit instantiation");
8426 
8427  // Propagate attribute to base class templates.
8428  for (auto &B : Def->bases()) {
8429  if (auto *BT = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
8430  B.getType()->getAsCXXRecordDecl()))
8432  }
8433 
8435 }
8436 
8437 // Explicit instantiation of a class template specialization
8438 DeclResult
8440  SourceLocation ExternLoc,
8441  SourceLocation TemplateLoc,
8442  unsigned TagSpec,
8443  SourceLocation KWLoc,
8444  const CXXScopeSpec &SS,
8445  TemplateTy TemplateD,
8446  SourceLocation TemplateNameLoc,
8447  SourceLocation LAngleLoc,
8448  ASTTemplateArgsPtr TemplateArgsIn,
8449  SourceLocation RAngleLoc,
8450  AttributeList *Attr) {
8451  // Find the class template we're specializing
8452  TemplateName Name = TemplateD.get();
8453  TemplateDecl *TD = Name.getAsTemplateDecl();
8454  // Check that the specialization uses the same tag kind as the
8455  // original template.
8457  assert(Kind != TTK_Enum &&
8458  "Invalid enum tag in class template explicit instantiation!");
8459 
8460  ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(TD);
8461 
8462  if (!ClassTemplate) {
8463  NonTagKind NTK = getNonTagTypeDeclKind(TD, Kind);
8464  Diag(TemplateNameLoc, diag::err_tag_reference_non_tag) << TD << NTK << Kind;
8465  Diag(TD->getLocation(), diag::note_previous_use);
8466  return true;
8467  }
8468 
8469  if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
8470  Kind, /*isDefinition*/false, KWLoc,
8471  ClassTemplate->getIdentifier())) {
8472  Diag(KWLoc, diag::err_use_with_wrong_tag)
8473  << ClassTemplate
8475  ClassTemplate->getTemplatedDecl()->getKindName());
8476  Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
8477  diag::note_previous_use);
8478  Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
8479  }
8480 
8481  // C++0x [temp.explicit]p2:
8482  // There are two forms of explicit instantiation: an explicit instantiation
8483  // definition and an explicit instantiation declaration. An explicit
8484  // instantiation declaration begins with the extern keyword. [...]
8485  TemplateSpecializationKind TSK = ExternLoc.isInvalid()
8488 
8490  // Check for dllexport class template instantiation declarations.
8491  for (AttributeList *A = Attr; A; A = A->getNext()) {
8492  if (A->getKind() == AttributeList::AT_DLLExport) {
8493  Diag(ExternLoc,
8494  diag::warn_attribute_dllexport_explicit_instantiation_decl);
8495  Diag(A->getLoc(), diag::note_attribute);
8496  break;
8497  }
8498  }
8499 
8500  if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) {
8501  Diag(ExternLoc,
8502  diag::warn_attribute_dllexport_explicit_instantiation_decl);
8503  Diag(A->getLocation(), diag::note_attribute);
8504  }
8505  }
8506 
8507  // In MSVC mode, dllimported explicit instantiation definitions are treated as
8508  // instantiation declarations for most purposes.
8509  bool DLLImportExplicitInstantiationDef = false;
8512  // Check for dllimport class template instantiation definitions.
8513  bool DLLImport =
8514  ClassTemplate->getTemplatedDecl()->getAttr<DLLImportAttr>();
8515  for (AttributeList *A = Attr; A; A = A->getNext()) {
8516  if (A->getKind() == AttributeList::AT_DLLImport)
8517  DLLImport = true;
8518  if (A->getKind() == AttributeList::AT_DLLExport) {
8519  // dllexport trumps dllimport here.
8520  DLLImport = false;
8521  break;
8522  }
8523  }
8524  if (DLLImport) {
8526  DLLImportExplicitInstantiationDef = true;
8527  }
8528  }
8529 
8530  // Translate the parser's template argument list in our AST format.
8531  TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
8532  translateTemplateArguments(TemplateArgsIn, TemplateArgs);
8533 
8534  // Check that the template argument list is well-formed for this
8535  // template.
8537  if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
8538  TemplateArgs, false, Converted))
8539  return true;
8540 
8541  // Find the class template specialization declaration that
8542  // corresponds to these arguments.
8543  void *InsertPos = nullptr;
8545  = ClassTemplate->findSpecialization(Converted, InsertPos);
8546 
8547  TemplateSpecializationKind PrevDecl_TSK
8548  = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
8549 
8550  // C++0x [temp.explicit]p2:
8551  // [...] An explicit instantiation shall appear in an enclosing
8552  // namespace of its template. [...]
8553  //
8554  // This is C++ DR 275.
8555  if (CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
8556  SS.isSet()))
8557  return true;
8558 
8559  ClassTemplateSpecializationDecl *Specialization = nullptr;
8560 
8561  bool HasNoEffect = false;
8562  if (PrevDecl) {
8563  if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
8564  PrevDecl, PrevDecl_TSK,
8565  PrevDecl->getPointOfInstantiation(),
8566  HasNoEffect))
8567  return PrevDecl;
8568 
8569  // Even though HasNoEffect == true means that this explicit instantiation
8570  // has no effect on semantics, we go on to put its syntax in the AST.
8571 
8572  if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
8573  PrevDecl_TSK == TSK_Undeclared) {
8574  // Since the only prior class template specialization with these
8575  // arguments was referenced but not declared, reuse that
8576  // declaration node as our own, updating the source location
8577  // for the template name to reflect our new declaration.
8578  // (Other source locations will be updated later.)
8579  Specialization = PrevDecl;
8580  Specialization->setLocation(TemplateNameLoc);
8581  PrevDecl = nullptr;
8582  }
8583 
8584  if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
8585  DLLImportExplicitInstantiationDef) {
8586  // The new specialization might add a dllimport attribute.
8587  HasNoEffect = false;
8588  }
8589  }
8590 
8591  if (!Specialization) {
8592  // Create a new class template specialization declaration node for
8593  // this explicit specialization.
8594  Specialization
8596  ClassTemplate->getDeclContext(),
8597  KWLoc, TemplateNameLoc,
8598  ClassTemplate,
8599  Converted,
8600  PrevDecl);
8601  SetNestedNameSpecifier(Specialization, SS);
8602 
8603  if (!HasNoEffect && !PrevDecl) {
8604  // Insert the new specialization.
8605  ClassTemplate->AddSpecialization(Specialization, InsertPos);
8606  }
8607  }
8608 
8609  // Build the fully-sugared type for this explicit instantiation as
8610  // the user wrote in the explicit instantiation itself. This means
8611  // that we'll pretty-print the type retrieved from the
8612  // specialization's declaration the way that the user actually wrote
8613  // the explicit instantiation, rather than formatting the name based
8614  // on the "canonical" representation used to store the template
8615  // arguments in the specialization.
8616  TypeSourceInfo *WrittenTy
8617  = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
8618  TemplateArgs,
8619  Context.getTypeDeclType(Specialization));
8620  Specialization->setTypeAsWritten(WrittenTy);
8621 
8622  // Set source locations for keywords.
8623  Specialization->setExternLoc(ExternLoc);
8624  Specialization->setTemplateKeywordLoc(TemplateLoc);
8625  Specialization->setBraceRange(SourceRange());
8626 
8627  bool PreviouslyDLLExported = Specialization->hasAttr<DLLExportAttr>();
8628  if (Attr)
8629  ProcessDeclAttributeList(S, Specialization, Attr);
8630 
8631  // Add the explicit instantiation into its lexical context. However,
8632  // since explicit instantiations are never found by name lookup, we
8633  // just put it into the declaration context directly.
8634  Specialization->setLexicalDeclContext(CurContext);
8635  CurContext->addDecl(Specialization);
8636 
8637  // Syntax is now OK, so return if it has no other effect on semantics.
8638  if (HasNoEffect) {
8639  // Set the template specialization kind.
8640  Specialization->setTemplateSpecializationKind(TSK);
8641  return Specialization;
8642  }
8643 
8644  // C++ [temp.explicit]p3:
8645  // A definition of a class template or class member template
8646  // shall be in scope at the point of the explicit instantiation of
8647  // the class template or class member template.
8648  //
8649  // This check comes when we actually try to perform the
8650  // instantiation.
8652  = cast_or_null<ClassTemplateSpecializationDecl>(
8653  Specialization->getDefinition());
8654  if (!Def)
8655  InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
8656  else if (TSK == TSK_ExplicitInstantiationDefinition) {
8657  MarkVTableUsed(TemplateNameLoc, Specialization, true);
8658  Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
8659  }
8660 
8661  // Instantiate the members of this class template specialization.
8662  Def = cast_or_null<ClassTemplateSpecializationDecl>(
8663  Specialization->getDefinition());
8664  if (Def) {
8666  // Fix a TSK_ExplicitInstantiationDeclaration followed by a
8667  // TSK_ExplicitInstantiationDefinition
8668  if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
8670  DLLImportExplicitInstantiationDef)) {
8671  // FIXME: Need to notify the ASTMutationListener that we did this.
8673 
8674  if (!getDLLAttr(Def) && getDLLAttr(Specialization) &&
8676  Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())) {
8677  // In the MS ABI, an explicit instantiation definition can add a dll
8678  // attribute to a template with a previous instantiation declaration.
8679  // MinGW doesn't allow this.
8680  auto *A = cast<InheritableAttr>(
8681  getDLLAttr(Specialization)->clone(getASTContext()));
8682  A->setInherited(true);
8683  Def->addAttr(A);
8685  }
8686  }
8687 
8688  // Fix a TSK_ImplicitInstantiation followed by a
8689  // TSK_ExplicitInstantiationDefinition
8690  bool NewlyDLLExported =
8691  !PreviouslyDLLExported && Specialization->hasAttr<DLLExportAttr>();
8692  if (Old_TSK == TSK_ImplicitInstantiation && NewlyDLLExported &&
8694  Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())) {
8695  // In the MS ABI, an explicit instantiation definition can add a dll
8696  // attribute to a template with a previous implicit instantiation.
8697  // MinGW doesn't allow this. We limit clang to only adding dllexport, to
8698  // avoid potentially strange codegen behavior. For example, if we extend
8699  // this conditional to dllimport, and we have a source file calling a
8700  // method on an implicitly instantiated template class instance and then
8701  // declaring a dllimport explicit instantiation definition for the same
8702  // template class, the codegen for the method call will not respect the
8703  // dllimport, while it will with cl. The Def will already have the DLL
8704  // attribute, since the Def and Specialization will be the same in the
8705  // case of Old_TSK == TSK_ImplicitInstantiation, and we already added the
8706  // attribute to the Specialization; we just need to make it take effect.
8707  assert(Def == Specialization &&
8708  "Def and Specialization should match for implicit instantiation");
8710  }
8711 
8712  // Set the template specialization kind. Make sure it is set before
8713  // instantiating the members which will trigger ASTConsumer callbacks.
8714  Specialization->setTemplateSpecializationKind(TSK);
8715  InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
8716  } else {
8717 
8718  // Set the template specialization kind.
8719  Specialization->setTemplateSpecializationKind(TSK);
8720  }
8721 
8722  return Specialization;
8723 }
8724 
8725 // Explicit instantiation of a member class of a class template.
8726 DeclResult
8728  SourceLocation ExternLoc,
8729  SourceLocation TemplateLoc,
8730  unsigned TagSpec,
8731  SourceLocation KWLoc,
8732  CXXScopeSpec &SS,
8734  SourceLocation NameLoc,
8735  AttributeList *Attr) {
8736 
8737  bool Owned = false;
8738  bool IsDependent = false;
8739  Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference,
8740  KWLoc, SS, Name, NameLoc, Attr, AS_none,
8741  /*ModulePrivateLoc=*/SourceLocation(),
8742  MultiTemplateParamsArg(), Owned, IsDependent,
8743  SourceLocation(), false, TypeResult(),
8744  /*IsTypeSpecifier*/false,
8745  /*IsTemplateParamOrArg*/false);
8746  assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
8747 
8748  if (!TagD)
8749  return true;
8750 
8751  TagDecl *Tag = cast<TagDecl>(TagD);
8752  assert(!Tag->isEnum() && "shouldn't see enumerations here");
8753 
8754  if (Tag->isInvalidDecl())
8755  return true;
8756 
8757  CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
8758  CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
8759  if (!Pattern) {
8760  Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
8761  << Context.getTypeDeclType(Record);
8762  Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
8763  return true;
8764  }
8765 
8766  // C++0x [temp.explicit]p2:
8767  // If the explicit instantiation is for a class or member class, the
8768  // elaborated-type-specifier in the declaration shall include a
8769  // simple-template-id.
8770  //
8771  // C++98 has the same restriction, just worded differently.
8772  if (!ScopeSpecifierHasTemplateId(SS))
8773  Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
8774  << Record << SS.getRange();
8775 
8776  // C++0x [temp.explicit]p2:
8777  // There are two forms of explicit instantiation: an explicit instantiation
8778  // definition and an explicit instantiation declaration. An explicit
8779  // instantiation declaration begins with the extern keyword. [...]
8783 
8784  // C++0x [temp.explicit]p2:
8785  // [...] An explicit instantiation shall appear in an enclosing
8786  // namespace of its template. [...]
8787  //
8788  // This is C++ DR 275.
8789  CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
8790 
8791  // Verify that it is okay to explicitly instantiate here.
8792  CXXRecordDecl *PrevDecl
8793  = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
8794  if (!PrevDecl && Record->getDefinition())
8795  PrevDecl = Record;
8796  if (PrevDecl) {
8798  bool HasNoEffect = false;
8799  assert(MSInfo && "No member specialization information?");
8800  if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
8801  PrevDecl,
8803  MSInfo->getPointOfInstantiation(),
8804  HasNoEffect))
8805  return true;
8806  if (HasNoEffect)
8807  return TagD;
8808  }
8809 
8810  CXXRecordDecl *RecordDef
8811  = cast_or_null<CXXRecordDecl>(Record->getDefinition());
8812  if (!RecordDef) {
8813  // C++ [temp.explicit]p3:
8814  // A definition of a member class of a class template shall be in scope
8815  // at the point of an explicit instantiation of the member class.
8816  CXXRecordDecl *Def
8817  = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
8818  if (!Def) {
8819  Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
8820  << 0 << Record->getDeclName() << Record->getDeclContext();
8821  Diag(Pattern->getLocation(), diag::note_forward_declaration)
8822  << Pattern;
8823  return true;
8824  } else {
8825  if (InstantiateClass(NameLoc, Record, Def,
8826  getTemplateInstantiationArgs(Record),
8827  TSK))
8828  return true;
8829 
8830  RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
8831  if (!RecordDef)
8832  return true;
8833  }
8834  }
8835 
8836  // Instantiate all of the members of the class.
8837  InstantiateClassMembers(NameLoc, RecordDef,
8838  getTemplateInstantiationArgs(Record), TSK);
8839 
8841  MarkVTableUsed(NameLoc, RecordDef, true);
8842 
8843  // FIXME: We don't have any representation for explicit instantiations of
8844  // member classes. Such a representation is not needed for compilation, but it
8845  // should be available for clients that want to see all of the declarations in
8846  // the source code.
8847  return TagD;
8848 }
8849 
8851  SourceLocation ExternLoc,
8852  SourceLocation TemplateLoc,
8853  Declarator &D) {
8854  // Explicit instantiations always require a name.
8855  // TODO: check if/when DNInfo should replace Name.
8856  DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
8857  DeclarationName Name = NameInfo.getName();
8858  if (!Name) {
8859  if (!D.isInvalidType())
8861  diag::err_explicit_instantiation_requires_name)
8862  << D.getDeclSpec().getSourceRange()
8863  << D.getSourceRange();
8864 
8865  return true;
8866  }
8867 
8868  // The scope passed in may not be a decl scope. Zip up the scope tree until
8869  // we find one that is.
8870  while ((S->getFlags() & Scope::DeclScope) == 0 ||
8871  (S->getFlags() & Scope::TemplateParamScope) != 0)
8872  S = S->getParent();
8873 
8874  // Determine the type of the declaration.
8875  TypeSourceInfo *T = GetTypeForDeclarator(D, S);
8876  QualType R = T->getType();
8877  if (R.isNull())
8878  return true;
8879 
8880  // C++ [dcl.stc]p1:
8881  // A storage-class-specifier shall not be specified in [...] an explicit
8882  // instantiation (14.7.2) directive.
8884  Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
8885  << Name;
8886  return true;
8887  } else if (D.getDeclSpec().getStorageClassSpec()
8889  // Complain about then remove the storage class specifier.
8890  Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
8892 
8894  }
8895 
8896  // C++0x [temp.explicit]p1:
8897  // [...] An explicit instantiation of a function template shall not use the
8898  // inline or constexpr specifiers.
8899  // Presumably, this also applies to member functions of class templates as
8900  // well.
8901  if (D.getDeclSpec().isInlineSpecified())
8903  getLangOpts().CPlusPlus11 ?
8904  diag::err_explicit_instantiation_inline :
8905  diag::warn_explicit_instantiation_inline_0x)
8908  // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
8909  // not already specified.
8911  diag::err_explicit_instantiation_constexpr);
8912 
8913  // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
8914  // applied only to the definition of a function template or variable template,
8915  // declared in namespace scope.
8916  if (D.getDeclSpec().isConceptSpecified()) {
8918  diag::err_concept_specified_specialization) << 0;
8919  return true;
8920  }
8921 
8922  // A deduction guide is not on the list of entities that can be explicitly
8923  // instantiated.
8925  Diag(D.getDeclSpec().getLocStart(), diag::err_deduction_guide_specialized)
8926  << /*explicit instantiation*/ 0;
8927  return true;
8928  }
8929 
8930  // C++0x [temp.explicit]p2:
8931  // There are two forms of explicit instantiation: an explicit instantiation
8932  // definition and an explicit instantiation declaration. An explicit
8933  // instantiation declaration begins with the extern keyword. [...]
8937 
8938  LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
8939  LookupParsedName(Previous, S, &D.getCXXScopeSpec());
8940 
8941  if (!R->isFunctionType()) {
8942  // C++ [temp.explicit]p1:
8943  // A [...] static data member of a class template can be explicitly
8944  // instantiated from the member definition associated with its class
8945  // template.
8946  // C++1y [temp.explicit]p1:
8947  // A [...] variable [...] template specialization can be explicitly
8948  // instantiated from its template.
8949  if (Previous.isAmbiguous())
8950  return true;
8951 
8952  VarDecl *Prev = Previous.getAsSingle<VarDecl>();
8953  VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
8954 
8955  if (!PrevTemplate) {
8956  if (!Prev || !Prev->isStaticDataMember()) {
8957  // We expect to see a data data member here.
8958  Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
8959  << Name;
8960  for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
8961  P != PEnd; ++P)
8962  Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
8963  return true;
8964  }
8965 
8966  if (!Prev->getInstantiatedFromStaticDataMember()) {
8967  // FIXME: Check for explicit specialization?
8968  Diag(D.getIdentifierLoc(),
8969  diag::err_explicit_instantiation_data_member_not_instantiated)
8970  << Prev;
8971  Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
8972  // FIXME: Can we provide a note showing where this was declared?
8973  return true;
8974  }
8975  } else {
8976  // Explicitly instantiate a variable template.
8977 
8978  // C++1y [dcl.spec.auto]p6:
8979  // ... A program that uses auto or decltype(auto) in a context not
8980  // explicitly allowed in this section is ill-formed.
8981  //
8982  // This includes auto-typed variable template instantiations.
8983  if (R->isUndeducedType()) {
8984  Diag(T->getTypeLoc().getLocStart(),
8985  diag::err_auto_not_allowed_var_inst);
8986  return true;
8987  }
8988 
8990  // C++1y [temp.explicit]p3:
8991  // If the explicit instantiation is for a variable, the unqualified-id
8992  // in the declaration shall be a template-id.
8993  Diag(D.getIdentifierLoc(),
8994  diag::err_explicit_instantiation_without_template_id)
8995  << PrevTemplate;
8996  Diag(PrevTemplate->getLocation(),
8997  diag::note_explicit_instantiation_here);
8998  return true;
8999  }
9000 
9001  // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare an
9002  // explicit instantiation (14.8.2) [...] of a concept definition.
9003  if (PrevTemplate->isConcept()) {
9004  Diag(D.getIdentifierLoc(), diag::err_concept_specialized)
9005  << 1 /*variable*/ << 0 /*explicitly instantiated*/;
9006  Diag(PrevTemplate->getLocation(), diag::note_previous_declaration);
9007  return true;
9008  }
9009 
9010  // Translate the parser's template argument list into our AST format.
9011  TemplateArgumentListInfo TemplateArgs =
9013 
9014  DeclResult Res = CheckVarTemplateId(PrevTemplate, TemplateLoc,
9015  D.getIdentifierLoc(), TemplateArgs);
9016  if (Res.isInvalid())
9017  return true;
9018 
9019  // Ignore access control bits, we don't need them for redeclaration
9020  // checking.
9021  Prev = cast<VarDecl>(Res.get());
9022  }
9023 
9024  // C++0x [temp.explicit]p2:
9025  // If the explicit instantiation is for a member function, a member class
9026  // or a static data member of a class template specialization, the name of
9027  // the class template specialization in the qualified-id for the member
9028  // name shall be a simple-template-id.
9029  //
9030  // C++98 has the same restriction, just worded differently.
9031  //
9032  // This does not apply to variable template specializations, where the
9033  // template-id is in the unqualified-id instead.
9034  if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate)
9035  Diag(D.getIdentifierLoc(),
9036  diag::ext_explicit_instantiation_without_qualified_id)
9037  << Prev << D.getCXXScopeSpec().getRange();
9038 
9039  // Check the scope of this explicit instantiation.
9040  CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
9041 
9042  // Verify that it is okay to explicitly instantiate here.
9045  bool HasNoEffect = false;
9046  if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
9047  PrevTSK, POI, HasNoEffect))
9048  return true;
9049 
9050  if (!HasNoEffect) {
9051  // Instantiate static data member or variable template.
9052 
9053  Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
9054  if (PrevTemplate) {
9055  // Merge attributes.
9057  ProcessDeclAttributeList(S, Prev, Attr);
9058  }
9060  InstantiateVariableDefinition(D.getIdentifierLoc(), Prev);
9061  }
9062 
9063  // Check the new variable specialization against the parsed input.
9064  if (PrevTemplate && Prev && !Context.hasSameType(Prev->getType(), R)) {
9065  Diag(T->getTypeLoc().getLocStart(),
9066  diag::err_invalid_var_template_spec_type)
9067  << 0 << PrevTemplate << R << Prev->getType();
9068  Diag(PrevTemplate->getLocation(), diag::note_template_declared_here)
9069  << 2 << PrevTemplate->getDeclName();
9070  return true;
9071  }
9072 
9073  // FIXME: Create an ExplicitInstantiation node?
9074  return (Decl*) nullptr;
9075  }
9076 
9077  // If the declarator is a template-id, translate the parser's template
9078  // argument list into our AST format.
9079  bool HasExplicitTemplateArgs = false;
9080  TemplateArgumentListInfo TemplateArgs;
9082  TemplateArgs = makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
9083  HasExplicitTemplateArgs = true;
9084  }
9085 
9086  // C++ [temp.explicit]p1:
9087  // A [...] function [...] can be explicitly instantiated from its template.
9088  // A member function [...] of a class template can be explicitly
9089  // instantiated from the member definition associated with its class
9090  // template.
9091  UnresolvedSet<8> TemplateMatches;
9092  FunctionDecl *NonTemplateMatch = nullptr;
9094  TemplateSpecCandidateSet FailedCandidates(D.getIdentifierLoc());
9095  for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
9096  P != PEnd; ++P) {
9097  NamedDecl *Prev = *P;
9098  if (!HasExplicitTemplateArgs) {
9099  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
9100  QualType Adjusted = adjustCCAndNoReturn(R, Method->getType(),
9101  /*AdjustExceptionSpec*/true);
9102  if (Context.hasSameUnqualifiedType(Method->getType(), Adjusted)) {
9103  if (Method->getPrimaryTemplate()) {
9104  TemplateMatches.addDecl(Method, P.getAccess());
9105  } else {
9106  // FIXME: Can this assert ever happen? Needs a test.
9107  assert(!NonTemplateMatch && "Multiple NonTemplateMatches");
9108  NonTemplateMatch = Method;
9109  }
9110  }
9111  }
9112  }
9113 
9114  FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
9115  if (!FunTmpl)
9116  continue;
9117 
9118  TemplateDeductionInfo Info(FailedCandidates.getLocation());
9119  FunctionDecl *Specialization = nullptr;
9120  if (TemplateDeductionResult TDK
9121  = DeduceTemplateArguments(FunTmpl,
9122  (HasExplicitTemplateArgs ? &TemplateArgs
9123  : nullptr),
9124  R, Specialization, Info)) {
9125  // Keep track of almost-matches.
9126  FailedCandidates.addCandidate()
9127  .set(P.getPair(), FunTmpl->getTemplatedDecl(),
9128  MakeDeductionFailureInfo(Context, TDK, Info));
9129  (void)TDK;
9130  continue;
9131  }
9132 
9133  // Target attributes are part of the cuda function signature, so
9134  // the cuda target of the instantiated function must match that of its
9135  // template. Given that C++ template deduction does not take
9136  // target attributes into account, we reject candidates here that
9137  // have a different target.
9138  if (LangOpts.CUDA &&
9139  IdentifyCUDATarget(Specialization,
9140  /* IgnoreImplicitHDAttributes = */ true) !=
9141  IdentifyCUDATarget(Attr)) {
9142  FailedCandidates.addCandidate().set(
9143  P.getPair(), FunTmpl->getTemplatedDecl(),
9144  MakeDeductionFailureInfo(Context, TDK_CUDATargetMismatch, Info));
9145  continue;
9146  }
9147 
9148  TemplateMatches.addDecl(Specialization, P.getAccess());
9149  }
9150 
9151  FunctionDecl *Specialization = NonTemplateMatch;
9152  if (!Specialization) {
9153  // Find the most specialized function template specialization.
9154  UnresolvedSetIterator Result = getMostSpecialized(
9155  TemplateMatches.begin(), TemplateMatches.end(), FailedCandidates,
9156  D.getIdentifierLoc(),
9157  PDiag(diag::err_explicit_instantiation_not_known) << Name,
9158  PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
9159  PDiag(diag::note_explicit_instantiation_candidate));
9160 
9161  if (Result == TemplateMatches.end())
9162  return true;
9163 
9164  // Ignore access control bits, we don't need them for redeclaration checking.
9165  Specialization = cast<FunctionDecl>(*Result);
9166  }
9167 
9168  // C++11 [except.spec]p4
9169  // In an explicit instantiation an exception-specification may be specified,
9170  // but is not required.
9171  // If an exception-specification is specified in an explicit instantiation
9172  // directive, it shall be compatible with the exception-specifications of
9173  // other declarations of that function.
9174  if (auto *FPT = R->getAs<FunctionProtoType>())
9175  if (FPT->hasExceptionSpec()) {
9176  unsigned DiagID =
9177  diag::err_mismatched_exception_spec_explicit_instantiation;
9178  if (getLangOpts().MicrosoftExt)
9179  DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
9180  bool Result = CheckEquivalentExceptionSpec(
9181  PDiag(DiagID) << Specialization->getType(),
9182  PDiag(diag::note_explicit_instantiation_here),
9183  Specialization->getType()->getAs<FunctionProtoType>(),
9184  Specialization->getLocation(), FPT, D.getLocStart());
9185  // In Microsoft mode, mismatching exception specifications just cause a
9186  // warning.
9187  if (!getLangOpts().MicrosoftExt && Result)
9188  return true;
9189  }
9190 
9191  if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
9192  Diag(D.getIdentifierLoc(),
9193  diag::err_explicit_instantiation_member_function_not_instantiated)
9194  << Specialization
9195  << (Specialization->getTemplateSpecializationKind() ==
9197  Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
9198  return true;
9199  }
9200 
9201  FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
9202  if (!PrevDecl && Specialization->isThisDeclarationADefinition())
9203  PrevDecl = Specialization;
9204 
9205  if (PrevDecl) {
9206  bool HasNoEffect = false;
9207  if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
9208  PrevDecl,
9209  PrevDecl->getTemplateSpecializationKind(),
9210  PrevDecl->getPointOfInstantiation(),
9211  HasNoEffect))
9212  return true;
9213 
9214  // FIXME: We may still want to build some representation of this
9215  // explicit specialization.
9216  if (HasNoEffect)
9217  return (Decl*) nullptr;
9218  }
9219 
9220  Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
9221  if (Attr)
9222  ProcessDeclAttributeList(S, Specialization, Attr);
9223 
9224  if (Specialization->isDefined()) {
9225  // Let the ASTConsumer know that this function has been explicitly
9226  // instantiated now, and its linkage might have changed.
9227  Consumer.HandleTopLevelDecl(DeclGroupRef(Specialization));
9228  } else if (TSK == TSK_ExplicitInstantiationDefinition)
9229  InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
9230 
9231  // C++0x [temp.explicit]p2:
9232  // If the explicit instantiation is for a member function, a member class
9233  // or a static data member of a class template specialization, the name of
9234  // the class template specialization in the qualified-id for the member
9235  // name shall be a simple-template-id.
9236  //
9237  // C++98 has the same restriction, just worded differently.
9238  FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
9239  if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
9240  D.getCXXScopeSpec().isSet() &&
9242  Diag(D.getIdentifierLoc(),
9243  diag::ext_explicit_instantiation_without_qualified_id)
9244  << Specialization << D.getCXXScopeSpec().getRange();
9245 
9246  // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare an
9247  // explicit instantiation (14.8.2) [...] of a concept definition.
9248  if (FunTmpl && FunTmpl->isConcept() &&
9250  Diag(D.getIdentifierLoc(), diag::err_concept_specialized)
9251  << 0 /*function*/ << 0 /*explicitly instantiated*/;
9252  Diag(FunTmpl->getLocation(), diag::note_previous_declaration);
9253  return true;
9254  }
9255 
9257  FunTmpl? (NamedDecl *)FunTmpl
9258  : Specialization->getInstantiatedFromMemberFunction(),
9259  D.getIdentifierLoc(),
9260  D.getCXXScopeSpec().isSet());
9261 
9262  // FIXME: Create some kind of ExplicitInstantiationDecl here.
9263  return (Decl*) nullptr;
9264 }
9265 
9266 TypeResult
9267 Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
9268  const CXXScopeSpec &SS, IdentifierInfo *Name,
9269  SourceLocation TagLoc, SourceLocation NameLoc) {
9270  // This has to hold, because SS is expected to be defined.
9271  assert(Name && "Expected a name in a dependent tag");
9272 
9273  NestedNameSpecifier *NNS = SS.getScopeRep();
9274  if (!NNS)
9275  return true;
9276 
9278 
9279  if (TUK == TUK_Declaration || TUK == TUK_Definition) {
9280  Diag(NameLoc, diag::err_dependent_tag_decl)
9281  << (TUK == TUK_Definition) << Kind << SS.getRange();
9282  return true;
9283  }
9284 
9285  // Create the resulting type.
9287  QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
9288 
9289  // Create type-source location information for this type.
9290  TypeLocBuilder TLB;
9292  TL.setElaboratedKeywordLoc(TagLoc);
9294  TL.setNameLoc(NameLoc);
9295  return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
9296 }
9297 
9298 TypeResult
9300  const CXXScopeSpec &SS, const IdentifierInfo &II,
9301  SourceLocation IdLoc) {
9302  if (SS.isInvalid())
9303  return true;
9304 
9305  if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
9306  Diag(TypenameLoc,
9307  getLangOpts().CPlusPlus11 ?
9308  diag::warn_cxx98_compat_typename_outside_of_template :
9309  diag::ext_typename_outside_of_template)
9310  << FixItHint::CreateRemoval(TypenameLoc);
9311 
9313  QualType T = CheckTypenameType(TypenameLoc.isValid()? ETK_Typename : ETK_None,
9314  TypenameLoc, QualifierLoc, II, IdLoc);
9315  if (T.isNull())
9316  return true;
9317 
9319  if (isa<DependentNameType>(T)) {
9321  TL.setElaboratedKeywordLoc(TypenameLoc);
9322  TL.setQualifierLoc(QualifierLoc);
9323  TL.setNameLoc(IdLoc);
9324  } else {
9326  TL.setElaboratedKeywordLoc(TypenameLoc);
9327  TL.setQualifierLoc(QualifierLoc);
9328  TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
9329  }
9330 
9331  return CreateParsedType(T, TSI);
9332 }
9333 
9334 TypeResult
9336  SourceLocation TypenameLoc,
9337  const CXXScopeSpec &SS,
9338  SourceLocation TemplateKWLoc,
9339  TemplateTy TemplateIn,
9340  IdentifierInfo *TemplateII,
9341  SourceLocation TemplateIILoc,
9342  SourceLocation LAngleLoc,
9343  ASTTemplateArgsPtr TemplateArgsIn,
9344  SourceLocation RAngleLoc) {
9345  if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
9346  Diag(TypenameLoc,
9347  getLangOpts().CPlusPlus11 ?
9348  diag::warn_cxx98_compat_typename_outside_of_template :
9349  diag::ext_typename_outside_of_template)
9350  << FixItHint::CreateRemoval(TypenameLoc);
9351 
9352  // Strangely, non-type results are not ignored by this lookup, so the
9353  // program is ill-formed if it finds an injected-class-name.
9354  if (TypenameLoc.isValid()) {
9355  auto *LookupRD =
9356  dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, false));
9357  if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
9358  Diag(TemplateIILoc,
9359  diag::ext_out_of_line_qualified_id_type_names_constructor)
9360  << TemplateII << 0 /*injected-class-name used as template name*/
9361  << (TemplateKWLoc.isValid() ? 1 : 0 /*'template'/'typename' keyword*/);
9362  }
9363  }
9364 
9365  // Translate the parser's template argument list in our AST format.
9366  TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
9367  translateTemplateArguments(TemplateArgsIn, TemplateArgs);
9368 
9369  TemplateName Template = TemplateIn.get();
9370  if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
9371  // Construct a dependent template specialization type.
9372  assert(DTN && "dependent template has non-dependent name?");
9373  assert(DTN->getQualifier() == SS.getScopeRep());
9375  DTN->getQualifier(),
9376  DTN->getIdentifier(),
9377  TemplateArgs);
9378 
9379  // Create source-location information for this type.
9383  SpecTL.setElaboratedKeywordLoc(TypenameLoc);
9385  SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
9386  SpecTL.setTemplateNameLoc(TemplateIILoc);
9387  SpecTL.setLAngleLoc(LAngleLoc);
9388  SpecTL.setRAngleLoc(RAngleLoc);
9389  for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
9390  SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
9391  return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
9392  }
9393 
9394  QualType T = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
9395  if (T.isNull())
9396  return true;
9397 
9398  // Provide source-location information for the template specialization type.
9401  = Builder.push<TemplateSpecializationTypeLoc>(T);
9402  SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
9403  SpecTL.setTemplateNameLoc(TemplateIILoc);
9404  SpecTL.setLAngleLoc(LAngleLoc);
9405  SpecTL.setRAngleLoc(RAngleLoc);
9406  for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
9407  SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
9408 
9410  ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
9411  TL.setElaboratedKeywordLoc(TypenameLoc);
9413 
9414  TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
9415  return CreateParsedType(T, TSI);
9416 }
9417 
9418 
9419 /// Determine whether this failed name lookup should be treated as being
9420 /// disabled by a usage of std::enable_if.
9422  SourceRange &CondRange, Expr *&Cond) {
9423  // We must be looking for a ::type...
9424  if (!II.isStr("type"))
9425  return false;
9426 
9427  // ... within an explicitly-written template specialization...
9428  if (!NNS || !NNS.getNestedNameSpecifier()->getAsType())
9429  return false;
9430  TypeLoc EnableIfTy = NNS.getTypeLoc();
9431  TemplateSpecializationTypeLoc EnableIfTSTLoc =
9432  EnableIfTy.getAs<TemplateSpecializationTypeLoc>();
9433  if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
9434  return false;
9435  const TemplateSpecializationType *EnableIfTST =
9436  cast<TemplateSpecializationType>(EnableIfTSTLoc.getTypePtr());
9437 
9438  // ... which names a complete class template declaration...
9439  const TemplateDecl *EnableIfDecl =
9440  EnableIfTST->getTemplateName().getAsTemplateDecl();
9441  if (!EnableIfDecl || EnableIfTST->isIncompleteType())
9442  return false;
9443 
9444  // ... called "enable_if".
9445  const IdentifierInfo *EnableIfII =
9446  EnableIfDecl->getDeclName().getAsIdentifierInfo();
9447  if (!EnableIfII || !EnableIfII->isStr("enable_if"))
9448  return false;
9449 
9450  // Assume the first template argument is the condition.
9451  CondRange = EnableIfTSTLoc.getArgLoc(0).getSourceRange();
9452 
9453  // Dig out the condition.
9454  Cond = nullptr;
9455  if (EnableIfTSTLoc.getArgLoc(0).getArgument().getKind()
9457  return true;
9458 
9459  Cond = EnableIfTSTLoc.getArgLoc(0).getSourceExpression();
9460 
9461  // Ignore Boolean literals; they add no value.
9462  if (isa<CXXBoolLiteralExpr>(Cond->IgnoreParenCasts()))
9463  Cond = nullptr;
9464 
9465  return true;
9466 }
9467 
9468 /// \brief Build the type that describes a C++ typename specifier,
9469 /// e.g., "typename T::type".
9470 QualType
9472  SourceLocation KeywordLoc,
9473  NestedNameSpecifierLoc QualifierLoc,
9474  const IdentifierInfo &II,
9475  SourceLocation IILoc) {
9476  CXXScopeSpec SS;
9477  SS.Adopt(QualifierLoc);
9478 
9479  DeclContext *Ctx = computeDeclContext(SS);
9480  if (!Ctx) {
9481  // If the nested-name-specifier is dependent and couldn't be
9482  // resolved to a type, build a typename type.
9483  assert(QualifierLoc.getNestedNameSpecifier()->isDependent());
9484  return Context.getDependentNameType(Keyword,
9485  QualifierLoc.getNestedNameSpecifier(),
9486  &II);
9487  }
9488 
9489  // If the nested-name-specifier refers to the current instantiation,
9490  // the "typename" keyword itself is superfluous. In C++03, the
9491  // program is actually ill-formed. However, DR 382 (in C++0x CD1)
9492  // allows such extraneous "typename" keywords, and we retroactively
9493  // apply this DR to C++03 code with only a warning. In any case we continue.
9494 
9495  if (RequireCompleteDeclContext(SS, Ctx))
9496  return QualType();
9497 
9498  DeclarationName Name(&II);
9499  LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
9500  LookupQualifiedName(Result, Ctx, SS);
9501  unsigned DiagID = 0;
9502  Decl *Referenced = nullptr;
9503  switch (Result.getResultKind()) {
9504  case LookupResult::NotFound: {
9505  // If we're looking up 'type' within a template named 'enable_if', produce
9506  // a more specific diagnostic.
9507  SourceRange CondRange;
9508  Expr *Cond = nullptr;
9509  if (isEnableIf(QualifierLoc, II, CondRange, Cond)) {
9510  // If we have a condition, narrow it down to the specific failed
9511  // condition.
9512  if (Cond) {
9513  Expr *FailedCond;
9514  std::string FailedDescription;
9515  std::tie(FailedCond, FailedDescription) =
9516  findFailedEnableIfCondition(*this, Cond);
9517 
9518  Diag(FailedCond->getExprLoc(),
9519  diag::err_typename_nested_not_found_requirement)
9520  << FailedDescription
9521  << FailedCond->getSourceRange();
9522  return QualType();
9523  }
9524 
9525  Diag(CondRange.getBegin(), diag::err_typename_nested_not_found_enable_if)
9526  << Ctx << CondRange;
9527  return QualType();
9528  }
9529 
9530  DiagID = diag::err_typename_nested_not_found;
9531  break;
9532  }
9533 
9535  // We found a using declaration that is a value. Most likely, the using
9536  // declaration itself is meant to have the 'typename' keyword.
9537  SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
9538  IILoc);
9539  Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
9540  << Name << Ctx << FullRange;
9541  if (UnresolvedUsingValueDecl *Using
9542  = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
9543  SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
9544  Diag(Loc, diag::note_using_value_decl_missing_typename)
9545  << FixItHint::CreateInsertion(Loc, "typename ");
9546  }
9547  }
9548  // Fall through to create a dependent typename type, from which we can recover
9549  // better.
9550  LLVM_FALLTHROUGH;
9551 
9553  // Okay, it's a member of an unknown instantiation.
9554  return Context.getDependentNameType(Keyword,
9555  QualifierLoc.getNestedNameSpecifier(),
9556  &II);
9557 
9558  case LookupResult::Found:
9559  if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
9560  // C++ [class.qual]p2:
9561  // In a lookup in which function names are not ignored and the
9562  // nested-name-specifier nominates a class C, if the name specified
9563  // after the nested-name-specifier, when looked up in C, is the
9564  // injected-class-name of C [...] then the name is instead considered
9565  // to name the constructor of class C.
9566  //
9567  // Unlike in an elaborated-type-specifier, function names are not ignored
9568  // in typename-specifier lookup. However, they are ignored in all the
9569  // contexts where we form a typename type with no keyword (that is, in
9570  // mem-initializer-ids, base-specifiers, and elaborated-type-specifiers).
9571  //
9572  // FIXME: That's not strictly true: mem-initializer-id lookup does not
9573  // ignore functions, but that appears to be an oversight.
9574  auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(Ctx);
9575  auto *FoundRD = dyn_cast<CXXRecordDecl>(Type);
9576  if (Keyword == ETK_Typename && LookupRD && FoundRD &&
9577  FoundRD->isInjectedClassName() &&
9578  declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
9579  Diag(IILoc, diag::ext_out_of_line_qualified_id_type_names_constructor)
9580  << &II << 1 << 0 /*'typename' keyword used*/;
9581 
9582  // We found a type. Build an ElaboratedType, since the
9583  // typename-specifier was just sugar.
9584  MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
9585  return Context.getElaboratedType(Keyword,
9586  QualifierLoc.getNestedNameSpecifier(),
9588  }
9589 
9590  // C++ [dcl.type.simple]p2:
9591  // A type-specifier of the form
9592  // typename[opt] nested-name-specifier[opt] template-name
9593  // is a placeholder for a deduced class type [...].
9594  if (getLangOpts().CPlusPlus1z) {
9595  if (auto *TD = getAsTypeTemplateDecl(Result.getFoundDecl())) {
9596  return Context.getElaboratedType(
9597  Keyword, QualifierLoc.getNestedNameSpecifier(),
9599  QualType(), false));
9600  }
9601  }
9602 
9603  DiagID = diag::err_typename_nested_not_type;
9604  Referenced = Result.getFoundDecl();
9605  break;
9606 
9608  DiagID = diag::err_typename_nested_not_type;
9609  Referenced = *Result.begin();
9610  break;
9611 
9613  return QualType();
9614  }
9615 
9616  // If we get here, it's because name lookup did not find a
9617  // type. Emit an appropriate diagnostic and return an error.
9618  SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
9619  IILoc);
9620  Diag(IILoc, DiagID) << FullRange << Name << Ctx;
9621  if (Referenced)
9622  Diag(Referenced->getLocation(), diag::note_typename_refers_here)
9623  << Name;
9624  return QualType();
9625 }
9626 
9627 namespace {
9628  // See Sema::RebuildTypeInCurrentInstantiation
9629  class CurrentInstantiationRebuilder
9630  : public TreeTransform<CurrentInstantiationRebuilder> {
9631  SourceLocation Loc;
9632  DeclarationName Entity;
9633 
9634  public:
9636 
9637  CurrentInstantiationRebuilder(Sema &SemaRef,
9638  SourceLocation Loc,
9639  DeclarationName Entity)
9640  : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
9641  Loc(Loc), Entity(Entity) { }
9642 
9643  /// \brief Determine whether the given type \p T has already been
9644  /// transformed.
9645  ///
9646  /// For the purposes of type reconstruction, a type has already been
9647  /// transformed if it is NULL or if it is not dependent.
9648  bool AlreadyTransformed(QualType T) {
9649  return T.isNull() || !T->isDependentType();
9650  }
9651 
9652  /// \brief Returns the location of the entity whose type is being
9653  /// rebuilt.
9654  SourceLocation getBaseLocation() { return Loc; }
9655 
9656  /// \brief Returns the name of the entity whose type is being rebuilt.
9657  DeclarationName getBaseEntity() { return Entity; }
9658 
9659  /// \brief Sets the "base" location and entity when that
9660  /// information is known based on another transformation.
9661  void setBase(SourceLocation Loc, DeclarationName Entity) {
9662  this->Loc = Loc;
9663  this->Entity = Entity;
9664  }
9665 
9666  ExprResult TransformLambdaExpr(LambdaExpr *E) {
9667  // Lambdas never need to be transformed.
9668  return E;
9669  }
9670  };
9671 } // end anonymous namespace
9672 
9673 /// \brief Rebuilds a type within the context of the current instantiation.
9674 ///
9675 /// The type \p T is part of the type of an out-of-line member definition of
9676 /// a class template (or class template partial specialization) that was parsed
9677 /// and constructed before we entered the scope of the class template (or
9678 /// partial specialization thereof). This routine will rebuild that type now
9679 /// that we have entered the declarator's scope, which may produce different
9680 /// canonical types, e.g.,
9681 ///
9682 /// \code
9683 /// template<typename T>
9684 /// struct X {
9685 /// typedef T* pointer;
9686 /// pointer data();
9687 /// };
9688 ///
9689 /// template<typename T>
9690 /// typename X<T>::pointer X<T>::data() { ... }
9691 /// \endcode
9692 ///
9693 /// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
9694 /// since we do not know that we can look into X<T> when we parsed the type.
9695 /// This function will rebuild the type, performing the lookup of "pointer"
9696 /// in X<T> and returning an ElaboratedType whose canonical type is the same
9697 /// as the canonical type of T*, allowing the return types of the out-of-line
9698 /// definition and the declaration to match.
9700  SourceLocation Loc,
9702  if (!T || !T->getType()->isDependentType())
9703  return T;
9704 
9705  CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
9706  return Rebuilder.TransformType(T);
9707 }
9708 
9710  CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
9711  DeclarationName());
9712  return Rebuilder.TransformExpr(E);
9713 }
9714 
9716  if (SS.isInvalid())
9717  return true;
9718 
9720  CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
9721  DeclarationName());
9722  NestedNameSpecifierLoc Rebuilt
9723  = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
9724  if (!Rebuilt)
9725  return true;
9726 
9727  SS.Adopt(Rebuilt);
9728  return false;
9729 }
9730 
9731 /// \brief Rebuild the template parameters now that we know we're in a current
9732 /// instantiation.
9734  TemplateParameterList *Params) {
9735  for (unsigned I = 0, N = Params->size(); I != N; ++I) {
9736  Decl *Param = Params->getParam(I);
9737 
9738  // There is nothing to rebuild in a type parameter.
9739  if (isa<TemplateTypeParmDecl>(Param))
9740  continue;
9741 
9742  // Rebuild the template parameter list of a template template parameter.
9743  if (TemplateTemplateParmDecl *TTP
9744  = dyn_cast<TemplateTemplateParmDecl>(Param)) {
9745  if (RebuildTemplateParamsInCurrentInstantiation(
9746  TTP->getTemplateParameters()))
9747  return true;
9748 
9749  continue;
9750  }
9751 
9752  // Rebuild the type of a non-type template parameter.
9753  NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Param);
9754  TypeSourceInfo *NewTSI
9755  = RebuildTypeInCurrentInstantiation(NTTP->getTypeSourceInfo(),
9756  NTTP->getLocation(),
9757  NTTP->getDeclName());
9758  if (!NewTSI)
9759  return true;
9760 
9761  if (NewTSI != NTTP->getTypeSourceInfo()) {
9762  NTTP->setTypeSourceInfo(NewTSI);
9763  NTTP->setType(NewTSI->getType());
9764  }
9765  }
9766 
9767  return false;
9768 }
9769 
9770 /// \brief Produces a formatted string that describes the binding of
9771 /// template parameters to template arguments.
9772 std::string
9774  const TemplateArgumentList &Args) {
9775  return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
9776 }
9777 
9778 std::string
9780  const TemplateArgument *Args,
9781  unsigned NumArgs) {
9782  SmallString<128> Str;
9783  llvm::raw_svector_ostream Out(Str);
9784 
9785  if (!Params || Params->size() == 0 || NumArgs == 0)
9786  return std::string();
9787 
9788  for (unsigned I = 0, N = Params->size(); I != N; ++I) {
9789  if (I >= NumArgs)
9790  break;
9791 
9792  if (I == 0)
9793  Out << "[with ";
9794  else
9795  Out << ", ";
9796 
9797  if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
9798  Out << Id->getName();
9799  } else {
9800  Out << '$' << I;
9801  }
9802 
9803  Out << " = ";
9804  Args[I].print(getPrintingPolicy(), Out);
9805  }
9806 
9807  Out << ']';
9808  return Out.str();
9809 }
9810 
9812  CachedTokens &Toks) {
9813  if (!FD)
9814  return;
9815 
9816  auto LPT = llvm::make_unique<LateParsedTemplate>();
9817 
9818  // Take tokens to avoid allocations
9819  LPT->Toks.swap(Toks);
9820  LPT->D = FnD;
9821  LateParsedTemplateMap.insert(std::make_pair(FD, std::move(LPT)));
9822 
9823  FD->setLateTemplateParsed(true);
9824 }
9825 
9827  if (!FD)
9828  return;
9829  FD->setLateTemplateParsed(false);
9830 }
9831 
9833  DeclContext *DC = CurContext;
9834 
9835  while (DC) {
9836  if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
9837  const FunctionDecl *FD = RD->isLocalClass();
9838  return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
9839  } else if (DC->isTranslationUnit() || DC->isNamespace())
9840  return false;
9841 
9842  DC = DC->getParent();
9843  }
9844  return false;
9845 }
9846 
9847 namespace {
9848 /// \brief Walk the path from which a declaration was instantiated, and check
9849 /// that every explicit specialization along that path is visible. This enforces
9850 /// C++ [temp.expl.spec]/6:
9851 ///
9852 /// If a template, a member template or a member of a class template is
9853 /// explicitly specialized then that specialization shall be declared before
9854 /// the first use of that specialization that would cause an implicit
9855 /// instantiation to take place, in every translation unit in which such a
9856 /// use occurs; no diagnostic is required.
9857 ///
9858 /// and also C++ [temp.class.spec]/1:
9859 ///
9860 /// A partial specialization shall be declared before the first use of a
9861 /// class template specialization that would make use of the partial
9862 /// specialization as the result of an implicit or explicit instantiation
9863 /// in every translation unit in which such a use occurs; no diagnostic is
9864 /// required.
9865 class ExplicitSpecializationVisibilityChecker {
9866  Sema &S;
9867  SourceLocation Loc;
9869 
9870 public:
9871  ExplicitSpecializationVisibilityChecker(Sema &S, SourceLocation Loc)
9872  : S(S), Loc(Loc) {}
9873 
9874  void check(NamedDecl *ND) {
9875  if (auto *FD = dyn_cast<FunctionDecl>(ND))
9876  return checkImpl(FD);
9877  if (auto *RD = dyn_cast<CXXRecordDecl>(ND))
9878  return checkImpl(RD);
9879  if (auto *VD = dyn_cast<VarDecl>(ND))
9880  return checkImpl(VD);
9881  if (auto *ED = dyn_cast<EnumDecl>(ND))
9882  return checkImpl(ED);
9883  }
9884 
9885 private:
9886  void diagnose(NamedDecl *D, bool IsPartialSpec) {
9889  const bool Recover = true;
9890 
9891  // If we got a custom set of modules (because only a subset of the
9892  // declarations are interesting), use them, otherwise let
9893  // diagnoseMissingImport intelligently pick some.
9894  if (Modules.empty())
9895  S.diagnoseMissingImport(Loc, D, Kind, Recover);
9896  else
9897  S.diagnoseMissingImport(Loc, D, D->getLocation(), Modules, Kind, Recover);
9898  }
9899 
9900  // Check a specific declaration. There are three problematic cases:
9901  //
9902  // 1) The declaration is an explicit specialization of a template
9903  // specialization.
9904  // 2) The declaration is an explicit specialization of a member of an
9905  // templated class.
9906  // 3) The declaration is an instantiation of a template, and that template
9907  // is an explicit specialization of a member of a templated class.
9908  //
9909  // We don't need to go any deeper than that, as the instantiation of the
9910  // surrounding class / etc is not triggered by whatever triggered this
9911  // instantiation, and thus should be checked elsewhere.
9912  template<typename SpecDecl>
9913  void checkImpl(SpecDecl *Spec) {
9914  bool IsHiddenExplicitSpecialization = false;
9915  if (Spec->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) {
9916  IsHiddenExplicitSpecialization =
9917  Spec->getMemberSpecializationInfo()
9918  ? !S.hasVisibleMemberSpecialization(Spec, &Modules)
9919  : !S.hasVisibleExplicitSpecialization(Spec, &Modules);
9920  } else {
9921  checkInstantiated(Spec);
9922  }
9923 
9924  if (IsHiddenExplicitSpecialization)
9925  diagnose(Spec->getMostRecentDecl(), false);
9926  }
9927 
9928  void checkInstantiated(FunctionDecl *FD) {
9929  if (auto *TD = FD->getPrimaryTemplate())
9930  checkTemplate(TD);
9931  }
9932 
9933  void checkInstantiated(CXXRecordDecl *RD) {
9934  auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD);
9935  if (!SD)
9936  return;
9937 
9938  auto From = SD->getSpecializedTemplateOrPartial();
9939  if (auto *TD = From.dyn_cast<ClassTemplateDecl *>())
9940  checkTemplate(TD);
9941  else if (auto *TD =
9942  From.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
9943  if (!S.hasVisibleDeclaration(TD))
9944  diagnose(TD, true);
9945  checkTemplate(TD);
9946  }
9947  }
9948 
9949  void checkInstantiated(VarDecl *RD) {
9950  auto *SD = dyn_cast<VarTemplateSpecializationDecl>(RD);
9951  if (!SD)
9952  return;
9953 
9954  auto From = SD->getSpecializedTemplateOrPartial();
9955  if (auto *TD = From.dyn_cast<VarTemplateDecl *>())
9956  checkTemplate(TD);
9957  else if (auto *TD =
9958  From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
9959  if (!S.hasVisibleDeclaration(TD))
9960  diagnose(TD, true);
9961  checkTemplate(TD);
9962  }
9963  }
9964 
9965  void checkInstantiated(EnumDecl *FD) {}
9966 
9967  template<typename TemplDecl>
9968  void checkTemplate(TemplDecl *TD) {
9969  if (TD->isMemberSpecialization()) {
9970  if (!S.hasVisibleMemberSpecialization(TD, &Modules))
9971  diagnose(TD->getMostRecentDecl(), false);
9972  }
9973  }
9974 };
9975 } // end anonymous namespace
9976 
9978  if (!getLangOpts().Modules)
9979  return;
9980 
9981  ExplicitSpecializationVisibilityChecker(*this, Loc).check(Spec);
9982 }
9983 
9984 /// \brief Check whether a template partial specialization that we've discovered
9985 /// is hidden, and produce suitable diagnostics if so.
9987  NamedDecl *Spec) {
9989  if (!hasVisibleDeclaration(Spec, &Modules))
9990  diagnoseMissingImport(Loc, Spec, Spec->getLocation(), Modules,
9991  MissingImportKind::PartialSpecialization,
9992  /*Recover*/true);
9993 }
MutableArrayRef< TemplateParameterList * > MultiTemplateParamsArg
Definition: Ownership.h:266
unsigned getFlags() const
getFlags - Return the flags for this scope.
Definition: Scope.h:210
void printPretty(raw_ostream &OS, PrinterHelper *Helper, const PrintingPolicy &Policy, unsigned Indentation=0) const
bool isObjCObjectOrInterfaceType() const
Definition: Type.h:5790
QualType getElaboratedType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, QualType NamedType) const
ExprResult BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg, SourceLocation Loc)
Construct a new expression that refers to the given integral template argument with the given source-...
Defines the clang::ASTContext interface.
SourceLocation getPointOfInstantiation() const
Retrieve the first point of instantiation of this function template specialization.
Definition: DeclTemplate.h:568
void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex)
Definition: Decl.h:1467
T getAs() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition: TypeLoc.h:64
The null pointer literal (C++11 [lex.nullptr])
Definition: ExprCXX.h:520
IdKind getKind() const
Determine what kind of name we have.
Definition: DeclSpec.h:1001
void setImplicit(bool I=true)
Definition: DeclBase.h:538
FunctionDecl - An instance of this class is created to represent a function declaration or definition...
Definition: Decl.h:1618
void setTemplateSpecializationKind(TemplateSpecializationKind TSK)
Set the template specialization kind.
Definition: DeclTemplate.h:557
bool isVariadic() const
Definition: Type.h:3442
Name lookup found a set of overloaded functions that met the criteria.
Definition: Lookup.h:49
int Position
TypeResult ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK, const CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation TagLoc, SourceLocation NameLoc)
BuiltinTemplateKind getBuiltinTemplateKind() const
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
DeclResult ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, SourceLocation ModulePrivateLoc, TemplateIdAnnotation &TemplateId, AttributeList *Attr, MultiTemplateParamsArg TemplateParameterLists, SkipBodyInfo *SkipBody=nullptr)
bool isTransparentContext() const
isTransparentContext - Determines whether this context is a "transparent" context, meaning that the members declared in this context are semantically declared in the nearest enclosing non-transparent (opaque) context but are lexically declared in this context.
Definition: DeclBase.cpp:1041
TemplateArgument getPackExpansionPattern() const
When the template argument is a pack expansion, returns the pattern of the pack expansion.
static bool CheckTemplateArgumentIsCompatibleWithParameter(Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn, Expr *Arg, QualType ArgType)
Checks whether the given template argument is compatible with its template parameter.
bool isTemplateParameter() const
isTemplateParameter - Determines whether this declaration is a template parameter.
Definition: DeclBase.h:1906
bool isNullPtrType() const
Definition: Type.h:5919
StringRef getName() const
getName - Get the name of identifier for this declaration as a StringRef.
Definition: Decl.h:237
unsigned getDepth() const
Definition: Type.h:4024
TemplateParameterList * getExpansionTemplateParameters(unsigned I) const
Retrieve a particular expansion type within an expanded parameter pack.
Expr * getSourceExpression() const
Definition: TemplateBase.h:484
bool TemplateParameterListsAreEqual(TemplateParameterList *New, TemplateParameterList *Old, bool Complain, TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc=SourceLocation())
Determine whether the given template parameter lists are equivalent.
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:2224
SourceLocation getDefaultArgumentLoc() const
Retrieves the location of the default argument declaration.
Represents the dependent type named by a dependently-scoped typename using declaration, e.g.
Definition: Type.h:3550
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this class is an instantiation of a member class of a class template specialization, retrieves the member specialization information.
Definition: DeclCXX.cpp:1343
TemplateSpecializationKind getTemplateSpecializationKind() const
If this variable is an instantiation of a variable template or a static data member of a class templa...
Definition: Decl.cpp:2363
A (possibly-)qualified type.
Definition: Type.h:616
Simple class containing the result of Sema::CorrectTypo.
TemplateDeductionResult
Describes the result of template argument deduction.
Definition: Sema.h:6772
base_class_range bases()
Definition: DeclCXX.h:737
bool isInvalid() const
Definition: Ownership.h:159
void setDefaultArgument(TypeSourceInfo *DefArg)
Set the default argument for this template parameter.
bool CheckTemplateParameterList(TemplateParameterList *NewParams, TemplateParameterList *OldParams, TemplateParamListContext TPC)
Checks the validity of a template parameter list, possibly considering the template parameter list fr...
void setTemplateKeywordLoc(SourceLocation Loc)
Sets the location of the template keyword.
bool isMacroID() const
llvm::APSInt getAsIntegral() const
Retrieve the template argument as an integral value.
Definition: TemplateBase.h:279
SourceRange getSourceRange() const LLVM_READONLY
Return the source range that covers this unqualified-id.
Definition: DeclSpec.h:1119
A stack-allocated class that identifies which local variable declaration instantiations are present i...
Definition: Template.h:202
void diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName, SourceLocation Less, SourceLocation Greater)
bool isMemberPointerType() const
Definition: Type.h:5736
bool isSuppressingDiagnostics() const
Determines whether this lookup is suppressing diagnostics.
Definition: Lookup.h:573
static CXXDependentScopeMemberExpr * Create(const ASTContext &C, Expr *Base, QualType BaseType, bool IsArrow, SourceLocation OperatorLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierFoundInScope, DeclarationNameInfo MemberNameInfo, const TemplateArgumentListInfo *TemplateArgs)
Definition: ExprCXX.cpp:1128
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc...
Definition: Sema.h:2954
IdentifierInfo * getIdentifier() const
getIdentifier - Get the identifier that names this declaration, if there is one.
Definition: Decl.h:232
void addOuterTemplateArguments(const TemplateArgumentList *TemplateArgs)
Add a new outermost level to the multi-level template argument list.
Definition: Template.h:111
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type...
Definition: Type.cpp:2618
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:1804
const LangOptions & getLangOpts() const
Definition: Sema.h:1166
void setLookupName(DeclarationName Name)
Sets the name to look up.
Definition: Lookup.h:254
SourceLocation TemplateNameLoc
TemplateNameLoc - The location of the template name within the source.
ParsedType getAsType() const
Retrieve the template type argument's type.
static UnresolvedLookupExpr * Create(const ASTContext &C, CXXRecordDecl *NamingClass, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, bool ADL, bool Overloaded, UnresolvedSetIterator Begin, UnresolvedSetIterator End)
Definition: ExprCXX.h:2703
void setRParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:1399
DeclClass * getAsSingle() const
Definition: Lookup.h:493
bool hasDefaultArg() const
hasDefaultArg - Determines whether this parameter has a default argument, either parsed or not...
Definition: Decl.cpp:2521
Stmt - This represents one statement.
Definition: Stmt.h:60
NamedDecl * getRepresentativeDecl() const
Fetches a representative decl. Useful for lazy diagnostics.
Definition: Lookup.h:510
IdentifierInfo * Identifier
When Kind == IK_Identifier, the parsed identifier, or when Kind == IK_UserLiteralId, the identifier suffix.
Definition: DeclSpec.h:948
Filter makeFilter()
Create a filter for this result set.
Definition: Lookup.h:667
bool isExternCContext() const
Determines whether this context or some of its ancestors is a linkage specification context that spec...
Definition: DeclBase.cpp:1060
void setLAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:1588
void setExceptionSpecRange(SourceRange R)
Definition: TypeLoc.h:1412
bool isAnyCharacterType() const
Determine whether this type is any of the built-in character types.
Definition: Type.cpp:1724
We are matching the template parameter lists of two templates that might be redeclarations.
Definition: Sema.h:6314
void setPreviousDecl(decl_type *PrevDecl)
Set the previous declaration.
Definition: Decl.h:3968
TypeLoc getNamedTypeLoc() const
Definition: TypeLoc.h:1905
TemplateDecl * getAsTemplateDecl() const
Retrieve the underlying template declaration that this template name refers to, if known...
Provides information about an attempted template argument deduction, whose success or failure was des...
ClassTemplateSpecializationDecl * findSpecialization(ArrayRef< TemplateArgument > Args, void *&InsertPos)
Return the specialization with the provided arguments if it exists, otherwise return the insertion po...
static bool DiagnoseDefaultTemplateArgument(Sema &S, Sema::TemplateParamListContext TPC, SourceLocation ParamLoc, SourceRange DefArgRange)
Diagnose the presence of a default template argument on a template parameter, which is ill-formed in ...
The name refers to a function template or a set of overloaded functions that includes at least one fu...
Definition: TemplateKinds.h:26
const Scope * getParent() const
getParent - Return the scope that this is nested in.
Definition: Scope.h:218
bool CheckTemplatePartialSpecializationArgs(SourceLocation Loc, TemplateDecl *PrimaryTemplate, unsigned NumExplicitArgs, ArrayRef< TemplateArgument > Args)
Check the non-type template arguments of a class template partial specialization according to C++ [te...
The name refers to a dependent template name:
Definition: TemplateKinds.h:46
Microsoft's '__super' specifier, stored as a CXXRecordDecl* of the class it appeared in...
Represents a qualified type name for which the type name is dependent.
Definition: Type.h:4642
void setObjCLifetime(ObjCLifetime type)
Definition: Type.h:312
unsigned getFunctionScopeIndex() const
Returns the index of this parameter in its prototype or method scope.
Definition: Decl.h:1487
The template argument is an expression, and we've not resolved it to one of the other forms yet...
Definition: TemplateBase.h:69
CXXRecordDecl * getDecl() const
Definition: Type.cpp:3095
static TemplateTemplateParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation L, unsigned D, unsigned P, bool ParameterPack, IdentifierInfo *Id, TemplateParameterList *Params)
std::string getTemplateArgumentBindingsText(const TemplateParameterList *Params, const TemplateArgumentList &Args)
Produces a formatted string that describes the binding of template parameters to template arguments...
void erase()
Erase the last element returned from this iterator.
Definition: Lookup.h:639
static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D)
Determine what kind of template specialization the given declaration is.
CXXRecordDecl * getTemplatedDecl() const
Get the underlying class declarations of the template.
QualType getUnderlyingType() const
Definition: Decl.h:2727
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition: Sema.h:1243
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:81
bool isChar16Type() const
Definition: Type.cpp:1710
A reference to a name which we were able to look up during parsing but could not resolve to a specifi...
Definition: ExprCXX.h:2655
void setDefaultArgument(const ASTContext &C, const TemplateArgumentLoc &DefArg)
Set the default argument for this template parameter, and whether that default argument was inherited...
Defines the C++ template declaration subclasses.
StringRef P
Represents a C++11 auto or C++14 decltype(auto) type.
Definition: Type.h:4206
bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS)
bool isEnumeralType() const
Definition: Type.h:5772
static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context, QualType T, const CXXScopeSpec &SS)
Not a friend object.
Definition: DeclBase.h:1061
ParenExpr - This represents a parethesized expression, e.g.
Definition: Expr.h:1662
Decl * getPreviousDecl()
Retrieve the previous declaration that declares the same entity as this declaration, or NULL if there is no previous declaration.
Definition: DeclBase.h:922
SCS getStorageClassSpec() const
Definition: DeclSpec.h:448
void AddDecl(Decl *D)
Definition: Scope.h:275
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this enumeration is an instantiation of a member enumeration of a class template specialization...
Definition: Decl.h:3331
std::string getAsString() const
Definition: Type.h:942
pack_iterator pack_begin() const
Iterator referencing the first argument of a template argument pack.
Definition: TemplateBase.h:316
PtrTy get() const
Definition: Ownership.h:163
static ElaboratedTypeKeyword getKeywordForTagTypeKind(TagTypeKind Tag)
Converts a TagTypeKind into an elaborated type keyword.
Definition: Type.cpp:2409
QualType getPointeeType() const
Definition: Type.h:2461
IdentifierInfo * getAsIdentifierInfo() const
getAsIdentifierInfo - Retrieve the IdentifierInfo * stored in this declaration name, or NULL if this declaration name isn't a simple identifier.
The base class of the type hierarchy.
Definition: Type.h:1303
bool isMemberPointer() const
Definition: APValue.h:192
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1009
SourceLocation getLocalRangeBegin() const
Definition: TypeLoc.h:1375
void setTemplateParameterListsInfo(ASTContext &Context, ArrayRef< TemplateParameterList * > TPLists)
Definition: Decl.cpp:3741
iterator begin() const
Definition: Lookup.h:321
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition: Type.h:5522
void setTemplateKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2020
Declaration of a variable template.
TemplateParamListContext
The context in which we are checking a template parameter list.
Definition: Sema.h:6046
The template argument is a declaration that was provided for a pointer, reference, or pointer to member non-type template parameter.
Definition: TemplateBase.h:51
NamespaceDecl - Represent a C++ namespace.
Definition: Decl.h:461
NestedNameSpecifier * getPrefix() const
Return the prefix of this nested name specifier.
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition: Sema.cpp:45
bool hasLValuePath() const
Definition: APValue.cpp:568
void setSpecializationKind(TemplateSpecializationKind TSK)
NamedDecl * getParam(unsigned Idx)
Definition: DeclTemplate.h:112
SourceLocation getInlineSpecLoc() const
Definition: DeclSpec.h:565
AccessSpecifier
A C++ access specifier (public, private, protected), plus the special value "none" which means differ...
Definition: Specifiers.h:94
bool isBooleanType() const
Definition: Type.h:5969
A container of type source information.
Definition: Decl.h:62
unsigned getIndex() const
Definition: Type.h:4025
Expr * getAsExpr() const
Retrieve the template argument as an expression.
Definition: TemplateBase.h:306
void setTemplateArgsInfo(const TemplateArgumentListInfo &ArgsInfo)
bool DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation, NamedDecl *Instantiation, bool InstantiatedFromMember, const NamedDecl *Pattern, const NamedDecl *PatternDef, TemplateSpecializationKind TSK, bool Complain=true)
Determine whether we would be unable to instantiate this template (because it either has no definitio...
SourceLocation getLocEnd() const LLVM_READONLY
Definition: DeclBase.h:403
static void StripImplicitInstantiation(NamedDecl *D)
Strips various properties off an implicit instantiation that has just been explicitly specialized...
static FriendDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, FriendUnion Friend_, SourceLocation FriendL, ArrayRef< TemplateParameterList * > FriendTypeTPLists=None)
Definition: DeclFriend.cpp:27
T getAsAdjusted() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLock is not of the desire...
Definition: TypeLoc.h:2204
Abstract base class used for diagnosing integer constant expression violations.
Definition: Sema.h:9697
bool isConceptSpecified() const
Definition: DeclSpec.h:711
static NullPointerValueKind isNullPointerValueTemplateArgument(Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *Arg, Decl *Entity=nullptr)
Determine whether the given template argument is a null pointer value of the appropriate type...
bool CheckTemplateArgumentList(TemplateDecl *Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs, bool PartialTemplateArgs, SmallVectorImpl< TemplateArgument > &Converted, bool UpdateArgsWithConversions=true)
Check that the given template arguments can be be provided to the given template, converting the argu...
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2329
TemplateName SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name, SourceLocation Loc, const MultiLevelTemplateArgumentList &TemplateArgs)
An identifier, stored as an IdentifierInfo*.
void Adopt(NestedNameSpecifierLoc Other)
Adopt an existing nested-name-specifier (with source-range information).
Definition: DeclSpec.cpp:125
FriendDecl - Represents the declaration of a friend entity, which can be a function, a type, or a templated function or type.
Definition: DeclFriend.h:40
RAII object that enters a new expression evaluation context.
Definition: Sema.h:10497
VarDecl - An instance of this class is created to represent a variable declaration or definition...
Definition: Decl.h:758
bool hasNext() const
Definition: Lookup.h:624
static NestedNameSpecifier * Create(const ASTContext &Context, NestedNameSpecifier *Prefix, IdentifierInfo *II)
Builds a specifier combining a prefix and an identifier.
Information about one declarator, including the parsed type information and the identifier.
Definition: DeclSpec.h:1733
static SourceLocation DiagLocForExplicitInstantiation(NamedDecl *D, SourceLocation PointOfInstantiation)
Compute the diagnostic location for an explicit instantiation.
Represents an empty template argument, e.g., one that has not been deduced.
Definition: TemplateBase.h:46
Extra information about a function prototype.
Definition: Type.h:3234
AccessSpecifier getAccess() const
Definition: DeclBase.h:451
bool isCanonical() const
Definition: Type.h:5533
SourceLocation getLocation() const
Retrieve the location of the template argument.
TypeSpecifierType
Specifies the kind of type.
Definition: Specifiers.h:45
Represents a C++17 deduced template specialization type.
Definition: Type.h:4241
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:1924
Represents a variable template specialization, which refers to a variable template with a given set o...
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition: Decl.h:377
SmallVector< CXXRecordDecl *, 4 > DelayedDllExportClasses
Definition: Sema.h:10446
static bool isTemplateArgumentTemplateParameter(const TemplateArgument &Arg, unsigned Depth, unsigned Index)
A namespace, stored as a NamespaceDecl*.
VarTemplatePartialSpecializationDecl * getInstantiatedFromMember() const
Retrieve the member variable template partial specialization from which this particular variable temp...
Stores a list of template parameters for a TemplateDecl and its derived classes.
Definition: DeclTemplate.h:50
TemplateArgumentLoc SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template, SourceLocation TemplateLoc, SourceLocation RAngleLoc, Decl *Param, SmallVectorImpl< TemplateArgument > &Converted, bool &HasDefaultArg)
If the given template parameter has a default template argument, substitute into that default templat...
Describes how types, statements, expressions, and declarations should be printed. ...
Definition: PrettyPrinter.h:38
static Optional< unsigned > getExpandedPackSize(NamedDecl *Param)
Check whether the template parameter is a pack expansion, and if so, determine the number of paramete...
ParmVarDecl - Represents a parameter to a function.
Definition: Decl.h:1434
Represents the result of substituting a type for a template type parameter.
Definition: Type.h:4062
NullPointerConstantKind isNullPointerConstant(ASTContext &Ctx, NullPointerConstantValueDependence NPC) const
isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to a Null pointer constant...
Definition: Expr.cpp:3209
Defines the clang::Expr interface and subclasses for C++ expressions.
void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD, CachedTokens &Toks)
bool isPackExpansion() const
Determine whether this template argument is a pack expansion.
bool isEmpty() const
No scope specifier.
Definition: DeclSpec.h:189
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:1885
Represents the builtin template declaration which is used to implement __make_integer_seq and other b...
A reasonable base class for TypeLocs that correspond to types that are written as a type-specifier...
Definition: TypeLoc.h:492
The collection of all-type qualifiers we support.
Definition: Type.h:118
Information about a template-id annotation token.
PipeType - OpenCL20.
Definition: Type.h:5419
const IdentifierInfo * getIdentifier() const
Returns the identifier to which this template name refers.
Definition: TemplateName.h:474
static void DiagnoseTemplateParameterListArityMismatch(Sema &S, TemplateParameterList *New, TemplateParameterList *Old, Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc)
Diagnose a known arity mismatch when comparing template argument lists.
QualType getArrayDecayedType(QualType T) const
Return the properly qualified result of decaying the specified array type to a pointer.
static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL)
void setTemplateSpecializationKind(TemplateSpecializationKind TSK)
Set the kind of specialization or template instantiation this is.
Definition: DeclCXX.cpp:1377
Base wrapper for a particular "section" of type source info.
Definition: TypeLoc.h:40
Expr * IgnoreImpCasts() LLVM_READONLY
IgnoreImpCasts - Skip past any implicit casts which might surround this expression.
Definition: Expr.h:2847
RecordDecl - Represents a struct/union/class.
Definition: Decl.h:3354
A semantic tree transformation that allows one to transform one abstract syntax tree into another...
Definition: TreeTransform.h:96
static bool hasVisibleDefaultArgument(Sema &S, const ParmDecl *D, llvm::SmallVectorImpl< Module * > *Modules)
AutoType * getContainedAutoType() const
Get the AutoType whose type will be deduced for a variable with an initializer of this type...
Definition: Type.h:1894
Scope * getTemplateParamParent()
Definition: Scope.h:253
TemplateIdAnnotation * TemplateId
When Kind == IK_TemplateId or IK_ConstructorTemplateId, the template-id annotation that contains the ...
Definition: DeclSpec.h:972
QualType getElementType() const
Definition: Type.h:2773
DeclarationName getName() const
getName - Returns the embedded declaration name.
bool isConst() const
Definition: DeclCXX.h:1944
One of these records is kept for each identifier that is lexed.
Represents a class template specialization, which refers to a class template with a given set of temp...
iterator end() const
Definition: Lookup.h:322
Name lookup results in an ambiguity; use getAmbiguityKind to figure out what kind of ambiguity we hav...
Definition: Lookup.h:59
ArrayRef< const CXXRecordDecl * > getMemberPointerPath() const
Definition: APValue.cpp:629
void setLocalRangeEnd(SourceLocation L)
Definition: TypeLoc.h:1385
OverloadedTemplateStorage * getAsOverloadedTemplate() const
Retrieve the underlying, overloaded function template.
void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl)
DiagnoseTemplateParameterShadow - Produce a diagnostic complaining that the template parameter 'PrevD...
EnumDecl * getInstantiatedFromMemberEnum() const
Returns the enumeration (declared within the template) from which this enumeration type was instantia...
Definition: Decl.cpp:3844
void replace(NamedDecl *D)
Replaces the current entry with the given one, preserving the access bits.
Definition: Lookup.h:646
bool isNull() const
Definition: TypeLoc.h:102
bool hasAttr() const
Definition: DeclBase.h:521
static bool isEnableIfAliasTemplate(TypeAliasTemplateDecl *AliasTemplate)
Determine whether this alias template is "enable_if_t".
ExprResult RebuildExprInCurrentInstantiation(Expr *E)
Represents a class type in Objective C.
Definition: Type.h:4969
AttributeList * getList() const
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition: Type.h:1813
CXXRecordDecl * getPreviousDecl()
Definition: DeclCXX.h:678
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:128
A C++ nested-name-specifier augmented with source location information.
Represents a dependent template name that cannot be resolved prior to template instantiation.
Definition: TemplateName.h:412
NestedNameSpecifierLoc SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS, const MultiLevelTemplateArgumentList &TemplateArgs)
ArrayRef< QualType > getParamTypes() const
Definition: Type.h:3343
static NamedDecl * isAcceptableTemplateName(ASTContext &Context, NamedDecl *Orig, bool AllowFunctionTemplates)
Determine whether the declaration found is acceptable as the name of a template and, if so, return that template declaration.
bool isIdentifier() const
Determine whether this template name refers to an identifier.
Definition: TemplateName.h:471
The template argument is an integral value stored in an llvm::APSInt that was provided for an integra...
Definition: TemplateBase.h:57
SourceLocation getPointOfInstantiation() const
If this variable is an instantiation of a variable template or a static data member of a class templa...
Definition: Decl.cpp:2373
void setArgLocInfo(unsigned i, TemplateArgumentLocInfo AI)
Definition: TypeLoc.h:1602
const CXXScopeSpec & getCXXScopeSpec() const
getCXXScopeSpec - Return the C++ scope specifier (global scope or nested-name-specifier) that is part...
Definition: DeclSpec.h:1864
bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD, const TemplateArgumentListInfo &ExplicitTemplateArgs, LookupResult &Previous)
Perform semantic analysis for the given dependent function template specialization.
Decl * ActOnNonTypeTemplateParameter(Scope *S, Declarator &D, unsigned Depth, unsigned Position, SourceLocation EqualLoc, Expr *DefaultArg)
static bool anyDependentTemplateArguments(ArrayRef< TemplateArgumentLoc > Args, bool &InstantiationDependent)
Determine whether any of the given template arguments are dependent.
Definition: Type.cpp:3138
Base class for callback objects used by Sema::CorrectTypo to check the validity of a potential typo c...
bool isReferenceType() const
Definition: Type.h:5721
TypeSourceInfo * getTypeSourceInfo(ASTContext &Context, QualType T)
Creates a TypeSourceInfo for the given type.
SourceLocation getLocalRangeEnd() const
Definition: TypeLoc.h:1382
VarTemplatePartialSpecializationDecl * findPartialSpecialization(ArrayRef< TemplateArgument > Args, void *&InsertPos)
Return the partial specialization with the provided arguments if it exists, otherwise return the inse...
FunctionDecl * getTemplatedDecl() const
Get the underlying function declaration of the template.
Definition: DeclTemplate.h:998
void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec)
We've found a use of a templated declaration that would trigger an implicit instantiation.
static SourceRange findTemplateParameterInType(unsigned Depth, Expr *E)
SourceLocation getLocation() const
Fetches the primary location of the argument.
Definition: TemplateBase.h:460
OverloadedOperatorKind Operator
The kind of overloaded operator.
Definition: DeclSpec.h:931
An operation on a type.
Definition: TypeVisitor.h:65
QualType getCanonicalTemplateSpecializationType(TemplateName T, ArrayRef< TemplateArgument > Args) const
void startDefinition()
Starts the definition of this tag declaration.
Definition: Decl.cpp:3675
struct OFI OperatorFunctionId
When Kind == IK_OperatorFunctionId, the overloaded operator that we parsed.
Definition: DeclSpec.h:952
bool isChar32Type() const
Definition: Type.cpp:1716
CXXRecordDecl * getDefinition() const
Definition: DeclCXX.h:695
bool isTranslationUnit() const
Definition: DeclBase.h:1364
unsigned size() const
Retrieve the number of template arguments in this template argument list.
Definition: DeclTemplate.h:253
NestedNameSpecifier * getQualifier() const
Retrieve the qualification on this type.
Definition: Type.h:4662
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:1934
TagKind getTagKind() const
Definition: Decl.h:3019
The iterator over UnresolvedSets.
Definition: UnresolvedSet.h:27
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2103
Represents the result of substituting a set of types for a template type parameter pack...
Definition: Type.h:4117
A non-type template parameter, stored as an expression.
static CXXDeductionGuideDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, bool IsExplicit, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, SourceLocation EndLocation)
Definition: DeclCXX.cpp:1535
bool hasAnyAcceptableTemplateNames(LookupResult &R, bool AllowFunctionTemplates=true)
SourceLocation getLocStart() const LLVM_READONLY
Definition: DeclSpec.h:1885
bool DiagnoseUnknownTemplateName(const IdentifierInfo &II, SourceLocation IILoc, Scope *S, const CXXScopeSpec *SS, TemplateTy &SuggestedTemplate, TemplateNameKind &SuggestedKind)
bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous)
Perform semantic analysis for the given non-template member specialization.
static QualType checkBuiltinTemplateIdType(Sema &SemaRef, BuiltinTemplateDecl *BTD, const SmallVectorImpl< TemplateArgument > &Converted, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs)
void ClearStorageClassSpecs()
Definition: DeclSpec.h:462
The type of a non-type template parameter.
Definition: Sema.h:6463
TypeSourceInfo * getTypeSourceInfo() const
Definition: TemplateBase.h:479
SourceRange getSourceRange() const LLVM_READONLY
Fetches the full source range of the argument.
void set(DeclAccessPair Found, Decl *Spec, DeductionFailureInfo Info)
ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose=true)
DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
Definition: SemaExpr.cpp:416
QualType getTypeDeclType(const TypeDecl *Decl, const TypeDecl *PrevDecl=nullptr) const
Return the unique reference to the type for the specified type declaration.
Definition: ASTContext.h:1295
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:2128
SourceLocation getTemplateEllipsisLoc() const
Definition: TemplateBase.h:516
No entity found met the criteria within the current instantiation,, but there were dependent base cla...
Definition: Lookup.h:41
QualType getUnderlyingType() const
Definition: Type.h:3655
void setDefaultArgument(Expr *DefArg)
Set the default argument for this template parameter, and whether that default argument was inherited...
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition: Decl.h:947
An r-value expression (a pr-value in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:106
llvm::PointerUnion< VarTemplateDecl *, VarTemplatePartialSpecializationDecl * > getSpecializedTemplateOrPartial() const
Retrieve the variable template or variable template partial specialization which was specialized by t...
Provides information about a function template specialization, which is a FunctionDecl that has been ...
Definition: DeclTemplate.h:494
T * getAttr() const
Definition: DeclBase.h:518
bool hasDefaultArgument() const
Determine whether this template parameter has a default argument.
ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, bool isAddressOfOperand, const TemplateArgumentListInfo *TemplateArgs)
ActOnDependentIdExpression - Handle a dependent id-expression that was just parsed.
static void maybeDiagnoseTemplateParameterShadow(Sema &SemaRef, Scope *S, SourceLocation Loc, IdentifierInfo *Name)
Represents a C++ unqualified-id that has been parsed.
Definition: DeclSpec.h:899
TemplateArgument getArgumentPack() const
Definition: Type.cpp:3113
bool isCompleteType(SourceLocation Loc, QualType T)
Definition: Sema.h:1585
An rvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:2424
static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From, QualType T, APValue &Value, Sema::CCEKind CCE, bool RequireInt)
CheckConvertedConstantExpression - Check that the expression From is a converted constant expression ...
param_type_range param_types() const
Definition: Type.h:3465
SourceLocation getLAngleLoc() const
Definition: DeclTemplate.h:153
SmallVectorImpl< PartialDiagnosticAt > * Diag
Diag - If this is non-null, it will be filled in with a stack of notes indicating why evaluation fail...
Definition: Expr.h:555
DeclContext * getEnclosingNamespaceContext()
Retrieve the nearest enclosing namespace context.
Definition: DeclBase.cpp:1642
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:505
Represents the results of name lookup.
Definition: Lookup.h:32
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:643
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
void setRAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:2041
const LangOptions & getLangOpts() const
Definition: ASTContext.h:659
Wrapper for source info for injected class names of class templates.
Definition: TypeLoc.h:649
static void dllExportImportClassTemplateSpecialization(Sema &S, ClassTemplateSpecializationDecl *Def)
Make a dllexport or dllimport attr on a class template specialization take effect.
TemplateSpecCandidateSet - A set of generalized overload candidates, used in template specializations...
APValue Val
Val - This is the value the expression can be folded to.
Definition: Expr.h:570
A convenient class for passing around template argument information.
Definition: TemplateBase.h:524
TemplateName getTemplateName() const
Retrieve the name of the template that we are specializing.
Definition: Type.h:4382
QualType getReturnType() const
Definition: Type.h:3065
void FilterAcceptableTemplateNames(LookupResult &R, bool AllowFunctionTemplates=true)
const ValueDecl * getMemberPointerDecl() const
Definition: APValue.cpp:615
bool hasDefaultArgument() const
Determine whether this template parameter has a default argument.
bool isMoreSpecializedThanPrimary(ClassTemplatePartialSpecializationDecl *T, sema::TemplateDeductionInfo &Info)
ParsedTemplateTy getAsTemplate() const
Retrieve the template template argument's template name.
KindType getKind() const
Determine what kind of template argument we have.
bool isObjCLifetimeType() const
Returns true if objects of this type have lifetime semantics under ARC.
Definition: Type.cpp:3770
TemplateDecl * getAsTypeTemplateDecl(Decl *D)
Represents a typeof (or typeof) expression (a GCC extension).
Definition: Type.h:3602
NestedNameSpecifierLoc getTemplateQualifierLoc() const
Definition: TemplateBase.h:504
char * location_data() const
Retrieve the data associated with the source-location information.
Definition: DeclSpec.h:217
static TemplateTypeParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation KeyLoc, SourceLocation NameLoc, unsigned D, unsigned P, IdentifierInfo *Id, bool Typename, bool ParameterPack)
SourceLocation getLocStart() const LLVM_READONLY
Definition: DeclSpec.h:1122
TypeDecl - Represents a declaration of a type.
Definition: Decl.h:2642
void setRedeclaration(bool Val)
Definition: DeclSpec.h:2421
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:2967
bool isValueDependent() const
isValueDependent - Determines whether this expression is value-dependent (C++ [temp.dep.constexpr]).
Definition: Expr.h:148
RecordDecl * getDecl() const
Definition: Type.h:3793
static bool MatchTemplateParameterKind(Sema &S, NamedDecl *New, NamedDecl *Old, bool Complain, Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc)
Match two template parameters within template parameter lists.
ParsedTemplateArgument * getTemplateArgs()
Retrieves a pointer to the template arguments.
Expr * IgnoreParenCasts() LLVM_READONLY
IgnoreParenCasts - Ignore parentheses and casts.
Definition: Expr.cpp:2399
void setSpecializationKind(TemplateSpecializationKind TSK)
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:39
static TemplateArgument CreatePackCopy(ASTContext &Context, ArrayRef< TemplateArgument > Args)
Create a new template argument pack by copying the given set of template arguments.
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition: DeclBase.h:1118
NonTagKind
Common ways to introduce type names without a tag for use in diagnostics.
Definition: Sema.h:2129
NullPointerValueKind
bool isDependent() const
Whether this nested name specifier refers to a dependent type or not.
SourceLocation getRAngleLoc() const
Definition: TemplateBase.h:541
Represents a C++ nested-name-specifier or a global scope specifier.
Definition: DeclSpec.h:63
SourceLocation getConceptSpecLoc() const
Definition: DeclSpec.h:712
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types...
Definition: Type.cpp:1930
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC)...
Definition: DeclBase.h:796
SourceLocation getTemplateNameLoc() const
Definition: TemplateBase.h:510
NestedNameSpecifier * getQualifier() const
Return the nested name specifier that qualifies this name.
Definition: TemplateName.h:468
std::string getAsString() const
getNameAsString - Retrieve the human-readable string for this name.
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
Definition: ExprCXX.h:1519
Preprocessor & PP
Definition: Sema.h:304
static IntegerLiteral * Create(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l)
Returns a new integer literal with value 'V' and type 'type'.
Definition: Expr.cpp:748
Decl * ActOnTemplateDeclarator(Scope *S, MultiTemplateParamsArg TemplateParameterLists, Declarator &D)
Represents a C++ member access expression where the actual member referenced could not be resolved be...
Definition: ExprCXX.h:3112
TemplateSpecializationKind getSpecializationKind() const
Determine the kind of specialization that this declaration represents.
A class that does preordor or postorder depth-first traversal on the entire Clang AST and visits each...
void setLocalRangeBegin(SourceLocation L)
Definition: TypeLoc.h:1378
static bool CheckTemplateArgumentPointerToMember(Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *&ResultArg, TemplateArgument &Converted)
Checks whether the given template argument is a pointer to member constant according to C++ [temp...
DeclResult CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, AttributeList *Attr, TemplateParameterList *TemplateParams, AccessSpecifier AS, SourceLocation ModulePrivateLoc, SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists, TemplateParameterList **OuterTemplateParamLists, SkipBodyInfo *SkipBody=nullptr)
Represents a linkage specification.
Definition: DeclCXX.h:2666
ParsedTemplateArgument getTemplatePackExpansion(SourceLocation EllipsisLoc) const
Retrieve a pack expansion of the given template template argument.
static FunctionTemplateDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params, NamedDecl *Decl)
Create a function template node.
SourceLocation getLocStart() const LLVM_READONLY
Definition: DeclSpec.h:504
void addDecl(NamedDecl *D)
Add a declaration to these results with its natural access.
Definition: Lookup.h:412
We are matching the template parameter lists of a template template argument against the template par...
Definition: Sema.h:6335
SourceRange getSourceRange() const LLVM_READONLY
Definition: DeclSpec.h:503
detail::InMemoryDirectory::const_iterator I
unsigned getNumParams() const
Definition: TypeLoc.h:1426
Decl * ActOnTypeParameter(Scope *S, bool Typename, SourceLocation EllipsisLoc, SourceLocation KeyLoc, IdentifierInfo *ParamName, SourceLocation ParamNameLoc, unsigned Depth, unsigned Position, SourceLocation EqualLoc, ParsedType DefaultArg)
ActOnTypeParameter - Called when a C++ template type parameter (e.g., "typename T") has been parsed...
The current context is "potentially evaluated" in C++11 terms, but the expression is evaluated at com...
QualType getCanonicalTypeInternal() const
Definition: Type.h:2045
QualType getInjectedClassNameType(CXXRecordDecl *Decl, QualType TST) const
getInjectedClassNameType - Return the unique reference to the injected class name type for the specif...
QualType getType() const
Definition: Decl.h:589
bool isInvalid() const
TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg, QualType NTTPType, SourceLocation Loc)
Allocate a TemplateArgumentLoc where all locations have been initialized to the given location...
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:841
T castAs() const
Convert to the specified TypeLoc type, asserting that this TypeLoc is of the desired type...
Definition: TypeLoc.h:53
RAII object used to change the argument pack substitution index within a Sema object.
Definition: Sema.h:7165
The lookup results will be used for redeclaration of a name, if an entity by that name already exists...
Definition: Sema.h:3005
NestedNameSpecifier * getQualifier() const
If the name was qualified, retrieves the nested-name-specifier that precedes the name.
Definition: Expr.h:1065
TypeSpecTypeLoc pushTypeSpec(QualType T)
Pushes space for a typespec TypeLoc.
Represents an extended vector type where either the type or size is dependent.
Definition: Type.h:2759
const UnresolvedSetImpl & asUnresolvedSet() const
Definition: Lookup.h:317
SourceRange getRange() const
Definition: DeclSpec.h:68
bool isDefined(const FunctionDecl *&Definition) const
isDefined - Returns true if the function is defined at all, including a deleted definition.
Definition: Decl.cpp:2586
TyLocType push(QualType T)
Pushes space for a new TypeLoc of the given type.
SourceLocation getLoc() const
getLoc - Returns the main location of the declaration name.
SourceLocation LAngleLoc
The location of the '<' before the template argument list.
EnumDecl * getDecl() const
Definition: Type.h:3816
We are matching the template parameter lists of two template template parameters as part of matching ...
Definition: Sema.h:6324
Represents a K&R-style 'int foo()' function, which has no information available about its arguments...
Definition: Type.h:3095
TemplateName getUnderlying() const
Definition: TemplateName.h:337
bool isTemplateParameterPack() const
isTemplateParameter - Determines whether this declaration is a template parameter pack...
Definition: DeclBase.cpp:180
QualType CheckTemplateIdType(TemplateName Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs)
void CheckDeductionGuideTemplate(FunctionTemplateDecl *TD)
static Sema::TemplateDeductionResult DeduceTemplateArguments(Sema &S, TemplateParameterList *TemplateParams, const TemplateArgument &Param, TemplateArgument Arg, TemplateDeductionInfo &Info, SmallVectorImpl< DeducedTemplateArgument > &Deduced)
QualType getValueType() const
Gets the type contained by this atomic type, i.e.
Definition: Type.h:5402
QualType getInjectedSpecializationType() const
Definition: Type.h:4469
FunctionTemplateSpecializationInfo * getTemplateSpecializationInfo() const
If this function is actually a function template specialization, retrieve information about this func...
Definition: Decl.cpp:3308
bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param, TemplateArgumentLoc &Arg, SmallVectorImpl< TemplateArgument > &Converted)
DeclSpec & getMutableDeclSpec()
getMutableDeclSpec - Return a non-const version of the DeclSpec.
Definition: DeclSpec.h:1856
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:269
bool isNamespace() const
Definition: DeclBase.h:1372
TypeAliasDecl - Represents the declaration of a typedef-name via a C++0x alias-declaration.
Definition: Decl.h:2790
llvm::PointerUnion< ClassTemplateDecl *, ClassTemplatePartialSpecializationDecl * > getSpecializedTemplateOrPartial() const
Retrieve the class template or class template partial specialization which was specialized by this...
TypeLoc getTypeLoc() const
For a nested-name-specifier that refers to a type, retrieve the type with source-location information...
TemplateParameterList * ActOnTemplateParameterList(unsigned Depth, SourceLocation ExportLoc, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ArrayRef< Decl * > Params, SourceLocation RAngleLoc, Expr *RequiresClause)
ActOnTemplateParameterList - Builds a TemplateParameterList, optionally constrained by RequiresClause...
bool hasVisibleDefaultArgument(const NamedDecl *D, llvm::SmallVectorImpl< Module * > *Modules=nullptr)
Determine if the template parameter D has a visible default argument.
bool CheckTemplateArgument(NamedDecl *Param, TemplateArgumentLoc &Arg, NamedDecl *Template, SourceLocation TemplateLoc, SourceLocation RAngleLoc, unsigned ArgumentPackIndex, SmallVectorImpl< TemplateArgument > &Converted, CheckTemplateArgumentKind CTAK=CTAK_Specified)
Check that the given template argument corresponds to the given template parameter.
const DeclarationNameInfo & getLookupNameInfo() const
Gets the name info to look up.
Definition: Lookup.h:239
Represents a prototype with parameter type info, e.g.
Definition: Type.h:3129
void MakeTrivial(ASTContext &Context, NestedNameSpecifier *Qualifier, SourceRange R)
Make a new nested-name-specifier from incomplete source-location information.
Definition: DeclSpec.cpp:119
CXXRecordDecl * getInstantiatedFromMemberClass() const
If this record is an instantiation of a member class, retrieves the member class from which it was in...
Definition: DeclCXX.cpp:1336
void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse)
Perform marking for a reference to an arbitrary declaration.
Definition: SemaExpr.cpp:14636
SourceLocation getLocStart() const LLVM_READONLY
Definition: Decl.h:2666
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition: Type.h:1028
bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const
EvaluateAsRValue - Return true if this is a constant which we can fold to an rvalue using any crazy t...
static TypeSourceInfo * SubstDefaultTemplateArgument(Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc, SourceLocation RAngleLoc, TemplateTypeParmDecl *Param, SmallVectorImpl< TemplateArgument > &Converted)
Substitute template arguments into the default template argument for the given template type paramete...
SourceLocation getLocEnd() const LLVM_READONLY
Definition: Stmt.cpp:270
static bool CheckNonTypeTemplatePartialSpecializationArgs(Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param, const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument)
Subroutine of Sema::CheckTemplatePartialSpecializationArgs that checks non-type template partial spec...
DeclarationNameTable DeclarationNames
Definition: ASTContext.h:516
Specifies that the expression should never be value-dependent.
Definition: Expr.h:695
bool CheckSpecializationInstantiationRedecl(SourceLocation NewLoc, TemplateSpecializationKind NewTSK, NamedDecl *PrevDecl, TemplateSpecializationKind PrevTSK, SourceLocation PrevPtOfInstantiation, bool &SuppressNew)
Diagnose cases where we have an explicit template specialization before/after an explicit template in...
void addOuterRetainedLevel()
Add an outermost level that we are not substituting.
Definition: Template.h:127
ASTContext * Context
bool isEnum() const
Definition: Decl.h:3029
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this variable is an instantiation of a static data member of a class template specialization, retrieves the member specialization information.
Definition: Decl.cpp:2392
TemplateParameterListEqualKind
Enumeration describing how template parameter lists are compared for equality.
Definition: Sema.h:6306
void setArgLocInfo(unsigned i, TemplateArgumentLocInfo AI)
Definition: TypeLoc.h:2049
bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams)
Check whether a template can be declared within this scope.
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee...
Definition: Type.cpp:414
NameKind getNameKind() const
getNameKind - Determine what kind of name this is.
void setTemplateNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:2027
QualType getDependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, const IdentifierInfo *Name, const TemplateArgumentListInfo &Args) const
Represents an array type in C++ whose size is a value-dependent expression.
Definition: Type.h:2700
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition: Type.cpp:1760
SpecifierKind getKind() const
Determine what kind of nested name specifier is stored.
int * Depth
bool hasDefaultArgument() const
Determine whether this template parameter has a default argument.
bool isDeleted() const
Whether this function has been deleted.
Definition: Decl.h:1979
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Definition: TargetCXXABI.h:154
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:2001
QualType getPointeeType() const
Definition: Type.h:2341
ValueDecl - Represent the declaration of a variable (in which case it is an lvalue) a function (in wh...
Definition: Decl.h:580
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition: Type.h:5975
Expr - This represents one expression.
Definition: Expr.h:105
Defines the clang::LangOptions interface.
DeclResult CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc, SourceLocation TemplateNameLoc, const TemplateArgumentListInfo &TemplateArgs)
DeclarationName getLookupName() const
Gets the name to look up.
Definition: Lookup.h:249
LookupNameKind
Describes the kind of name lookup to perform.
Definition: Sema.h:2950
StringRef getName() const
Return the actual identifier string.
static ClassTemplatePartialSpecializationDecl * Create(ASTContext &Context, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, TemplateParameterList *Params, ClassTemplateDecl *SpecializedTemplate, ArrayRef< TemplateArgument > Args, const TemplateArgumentListInfo &ArgInfos, QualType CanonInjectedType, ClassTemplatePartialSpecializationDecl *PrevDecl)
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition: Specifiers.h:103
The "typename" keyword precedes the qualified type name, e.g., typename T::type.
Definition: Type.h:4516
CXXRecordDecl * getNamingClass() const
Returns the 'naming class' for this lookup, i.e.
Definition: Lookup.h:389
StateNode * Previous
Declaration of a template type parameter.
SourceLocation getNameLoc() const
Gets the location of the identifier.
Definition: Lookup.h:591
This file defines the classes used to store parsed information about declaration-specifiers and decla...
bool Encloses(const DeclContext *DC) const
Determine whether this declaration context encloses the declaration context DC.
Definition: DeclBase.cpp:1080
const LinkageSpecDecl * getExternCContext() const
Retrieve the nearest enclosing C linkage specification context.
Definition: DeclBase.cpp:1064
ElaboratedTypeKeyword
The elaboration keyword that precedes a qualified type name or introduces an elaborated-type-specifie...
Definition: Type.h:4503
The template argument is a null pointer or null pointer to member that was provided for a non-type te...
Definition: TemplateBase.h:54
TemplateName getOverloadedTemplateName(UnresolvedSetIterator Begin, UnresolvedSetIterator End) const
Retrieve the template name that corresponds to a non-empty lookup.
SourceLocation getEllipsisLoc() const
Retrieve the location of the ellipsis that makes a template template argument into a pack expansion...
ExprResult BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc)
Given a non-type template argument that refers to a declaration and the type of its corresponding non...
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition: DeclBase.cpp:111
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:956
NamedDecl * getFoundDecl() const
Fetch the unique decl found by this lookup.
Definition: Lookup.h:503
SourceLocation getLocation() const
Kind getKind() const
Definition: DeclBase.h:410
ArgKind getKind() const
Return the kind of stored template argument.
Definition: TemplateBase.h:213
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:3347
DeclContext * getDeclContext()
Definition: DeclBase.h:416
TemplateParameterList * MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId, ArrayRef< TemplateParameterList * > ParamLists, bool IsFriend, bool &IsMemberSpecialization, bool &Invalid)
Match the given template parameter lists to the given scope specifier, returning the template paramet...
static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec)
Converts a type specifier (DeclSpec::TST) into a tag type kind.
Definition: Type.cpp:2396
SubstTemplateTemplateParmPackStorage * getAsSubstTemplateTemplateParmPack() const
Retrieve the substituted template template parameter pack, if known.
static TemplateParameterList * Create(const ASTContext &C, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ArrayRef< NamedDecl * > Params, SourceLocation RAngleLoc, Expr *RequiresClause)
void setMemberSpecialization()
Note that this member template is a specialization.
Definition: DeclTemplate.h:854
void NoteAllFoundTemplates(TemplateName Name)
NonTypeTemplateParmDecl - Declares a non-type template parameter, e.g., "Size" in.
Represents a C++ template name within the type system.
Definition: TemplateName.h:176
static DependentScopeDeclRefExpr * Create(const ASTContext &C, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs)
Definition: ExprCXX.cpp:391
Represents the type decltype(expr) (C++11).
Definition: Type.h:3667
bool CheckFunctionTemplateSpecialization(FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs, LookupResult &Previous)
Perform semantic analysis for the given function template specialization.
TypeSourceInfo * getTemplateSpecializationTypeInfo(TemplateName T, SourceLocation TLoc, const TemplateArgumentListInfo &Args, QualType Canon=QualType()) const
A namespace alias, stored as a NamespaceAliasDecl*.
void setLateTemplateParsed(bool ILT=true)
Definition: Decl.h:1903
ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, bool RequiresADL, const TemplateArgumentListInfo *TemplateArgs)
bool isConstexprSpecified() const
Definition: DeclSpec.h:708
void setModulePrivate()
Specify that this declaration was marked as being private to the module in which it was defined...
Definition: DeclBase.h:604
void propagateDLLAttrToBaseClassTemplate(CXXRecordDecl *Class, Attr *ClassAttr, ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc)
Perform propagation of DLL attributes from a derived class to a templated base class for MS compatibi...
bool isParameterPack() const
Whether this template template parameter is a template parameter pack.
TemplateNameKind
Specifies the kind of template name that an identifier refers to.
Definition: TemplateKinds.h:21
bool isExplicit() const
Whether this function is explicit.
Definition: DeclCXX.h:2438
QualType getType() const
Get the type for which this source info wrapper provides information.
Definition: TypeLoc.h:114
StorageClass
Storage classes.
Definition: Specifiers.h:202
static bool isEnableIf(NestedNameSpecifierLoc NNS, const IdentifierInfo &II, SourceRange &CondRange, Expr *&Cond)
Determine whether this failed name lookup should be treated as being disabled by a usage of std::enab...
TemplateDecl * AdjustDeclIfTemplate(Decl *&Decl)
AdjustDeclIfTemplate - If the given decl happens to be a template, reset the parameter D to reference...
A unary type transform, which is a type constructed from another.
Definition: Type.h:3708
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:1797
bool isFunctionOrMethod() const
Definition: DeclBase.h:1343
Declaration of an alias template.
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:1294
TemplateName getAsTemplateOrTemplatePattern() const
Retrieve the template argument as a template name; if the argument is a pack expansion, return the pattern as a template name.
Definition: TemplateBase.h:266
const TemplateArgument * data() const
Retrieve a pointer to the template argument list.
Definition: DeclTemplate.h:256
Data structure that captures multiple levels of template argument lists for use in template instantia...
Definition: Template.h:42
TemplateNameKind ActOnDependentTemplateName(Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext, TemplateTy &Template, bool AllowInjectedClassName=false)
Form a dependent template name.
void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl, MissingImportKind MIK, bool Recover=true)
Diagnose that the specified declaration needs to be visible but isn't, and suggest a module import th...
UnaryOperator - This represents the unary-expression's (except sizeof and alignof), the postinc/postdec operators from postfix-expression, and various extensions.
Definition: Expr.h:1714
Represents a GCC generic vector type.
Definition: Type.h:2797
void setLocation(SourceLocation L)
Definition: DeclBase.h:408
An lvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:2407
DeclarationName getDeclName() const
getDeclName - Get the actual, stored name of the declaration, which may be a special name...
Definition: Decl.h:258
TemplateTemplateParmDecl - Declares a template template parameter, e.g., "T" in.
DiagnosticsEngine & getDiagnostics() const
Definition: Sema.h:1170
Represents a reference to a non-type template parameter that has been substituted with a template arg...
Definition: ExprCXX.h:3751
Common base class for placeholders for types that get replaced by placeholder type deduction: C++11 a...
Definition: Type.h:4166
const TemplateArgumentLoc & getDefaultArgument() const
Retrieve the default argument, if any.
TemplateNameKind isTemplateName(Scope *S, CXXScopeSpec &SS, bool hasTemplateKeyword, UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext, TemplateTy &Template, bool &MemberOfUnknownSpecialization)
ValueDecl * getDecl()
Definition: Expr.h:1038
const Type * getAsType() const
Retrieve the type stored in this nested name specifier.
void setDescribedClassTemplate(ClassTemplateDecl *Template)
Definition: DeclCXX.cpp:1361
QualType getElementType() const
Definition: Type.h:2821
This template specialization was implicitly instantiated from a template.
Definition: Specifiers.h:148
NamedDecl * LookupSingleName(Scope *S, DeclarationName Name, SourceLocation Loc, LookupNameKind NameKind, RedeclarationKind Redecl=NotForRedeclaration)
Look up a name, looking for a single declaration.
bool hasNameForLinkage() const
Is this tag type named, either directly or via being defined in a typedef of this type...
Definition: Decl.h:3046
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:1943
SourceLocation getStorageClassSpecLoc() const
Definition: DeclSpec.h:457
RecordDecl * getDefinition() const
getDefinition - Returns the RecordDecl that actually defines this struct/union/class.
Definition: Decl.h:3473
bool isUnsignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is unsigned or an enumeration types whose underlying ...
Definition: Type.cpp:1800
static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef, const ParsedTemplateArgument &Arg)
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:661
QualType getReplacementType() const
Gets the type that was substituted for the template parameter.
Definition: Type.h:4083
SourceLocation getPointOfInstantiation() const
Get the point of instantiation (if any), or null if none.
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition: Decl.h:1944
TemplateName getQualifiedTemplateName(NestedNameSpecifier *NNS, bool TemplateKeyword, TemplateDecl *Template) const
Retrieve the template name that represents a qualified template name such as std::vector.
unsigned getDepth() const
Get the depth of this template parameter list in the set of template parameter lists.
static CXXRecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, CXXRecordDecl *PrevDecl=nullptr, bool DelayTypeCreation=false)
Definition: DeclCXX.cpp:100
const TypeClass * getTypePtr() const
Definition: TypeLoc.h:480
bool isLValueOnePastTheEnd() const
Definition: APValue.cpp:558
void translateTemplateArguments(const ASTTemplateArgsPtr &In, TemplateArgumentListInfo &Out)
Translates template arguments as provided by the parser into template arguments used by semantic anal...
bool isAmbiguous() const
Definition: Lookup.h:287
bool hasUnnamedOrLocalType() const
Whether this type is or contains a local or unnamed type.
Definition: Type.cpp:3426
NestedNameSpecifier * getScopeRep() const
Retrieve the representation of the nested-name-specifier.
Definition: DeclSpec.h:76
void addAttr(Attr *A)
Definition: DeclBase.h:472
static bool DiagnoseUnexpandedParameterPacks(Sema &S, TemplateTemplateParmDecl *TTP)
Check for unexpanded parameter packs within the template parameters of a template template parameter...
TypeSourceInfo * CreateTypeSourceInfo(QualType T, unsigned Size=0) const
Allocate an uninitialized TypeSourceInfo.
CanQualType OverloadTy
Definition: ASTContext.h:979
TemplateArgumentLoc getArgLoc(unsigned i) const
Definition: TypeLoc.h:1609
DeclContext * getEntity() const
Definition: Scope.h:313
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition: TypeLoc.h:222
ASTMatchFinder *const Finder
void makeDeclVisibleInContext(NamedDecl *D)
Makes a declaration visible within this context.
Definition: DeclBase.cpp:1679
#define false
Definition: stdbool.h:33
Assigning into this object requires the old value to be released and the new value to be retained...
Definition: Type.h:146
Kind
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition: Type.h:5956
decl_type * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
Definition: Redeclarable.h:197
void setLAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:2034
Represents the parsed form of a C++ template argument.
A stack object to be created when performing template instantiation.
Definition: Sema.h:7202
static ClassTemplateSpecializationDecl * Create(ASTContext &Context, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, ClassTemplateDecl *SpecializedTemplate, ArrayRef< TemplateArgument > Args, ClassTemplateSpecializationDecl *PrevDecl)
TypeSourceInfo * getDefaultArgumentInfo() const
Retrieves the default argument's source information, if any.
unsigned getNumLevels() const
Determine the number of levels in this template argument list.
Definition: Template.h:66
static bool isSameAsPrimaryTemplate(TemplateParameterList *Params, ArrayRef< TemplateArgument > Args)
Encodes a location in the source.
Expr * getAsExpr() const
Retrieve the non-type template argument's expression.
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:5489
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums...
Definition: Type.h:3810
TemplateName getAsTemplate() const
Retrieve the template name for a template name argument.
Definition: TemplateBase.h:259
QualType getElementType() const
Definition: Type.h:2176
bool InEnclosingNamespaceSetOf(const DeclContext *NS) const
Test if this context is part of the enclosing namespace set of the context NS, as defined in C++0x [n...
Definition: DeclBase.cpp:1661
Represents typeof(type), a GCC extension.
Definition: Type.h:3643
Interfaces are the core concept in Objective-C for object oriented design.
Definition: Type.h:5165
void setBraceRange(SourceRange R)
Definition: Decl.h:2936
An overloaded operator name, e.g., operator+.
Definition: DeclSpec.h:910
static bool CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn, TemplateArgument &Converted)
Checks whether the given template argument is the address of an object or function according to C++ [...
This names the __make_integer_seq BuiltinTemplateDecl.
Definition: Builtins.h:229
UnqualifiedId & getName()
Retrieve the name specified by this declarator.
Definition: DeclSpec.h:1868
bool isValid() const
Return true if this is a valid SourceLocation object.
SourceLocation getLParenLoc() const
Definition: TypeLoc.h:1389
void setExternLoc(SourceLocation Loc)
Sets the location of the extern keyword.
static void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS)
TagDecl - Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:2816
void referenceDLLExportedClassMethods()
NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const
Retrieve a nested-name-specifier with location information, copied into the given AST context...
Definition: DeclSpec.cpp:143
QualType CheckTypenameType(ElaboratedTypeKeyword Keyword, SourceLocation KeywordLoc, NestedNameSpecifierLoc QualifierLoc, const IdentifierInfo &II, SourceLocation IILoc)
Build the type that describes a C++ typename specifier, e.g., "typename T::type". ...
TemplateName getDependentTemplateName(NestedNameSpecifier *NNS, const IdentifierInfo *Name) const
Retrieve the template name that represents a dependent template name such as MetaFun::template apply...
bool isDeductionGuideName(Scope *S, const IdentifierInfo &Name, SourceLocation NameLoc, ParsedTemplateTy *Template=nullptr)
Determine whether a particular identifier might be the name in a C++1z deduction-guide declaration...
ASTContext & getASTContext() const LLVM_READONLY
Definition: DeclBase.cpp:346
bool isValid() const
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location, which defaults to the empty location.
ASTContext & getASTContext() const
Definition: Sema.h:1173
InheritableAttr * getDLLAttr(Decl *D)
Return a DLL attribute from the declaration.
Definition: SemaInternal.h:93
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, bool Canonical) const
Produce a unique representation of the given statement.
ValueKind getKind() const
Definition: APValue.h:181
Represents a dependent using declaration which was not marked with typename.
Definition: DeclCXX.h:3400
QualType getTemplateSpecializationType(TemplateName T, ArrayRef< TemplateArgument > Args, QualType Canon=QualType()) const
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:1903
unsigned getDepth() const
Retrieve the depth of the template parameter.
void print(const PrintingPolicy &Policy, raw_ostream &Out) const
Print this template argument to the given output stream.
SourceLocation getNameLoc() const
Definition: TypeLoc.h:502
Expr * getRequiresClause()
The constraint-expression of the associated requires-clause.
Definition: DeclTemplate.h:143
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
Expr * getDefaultArgument() const
Retrieve the default argument, if any.
bool isInvalid() const
An error occurred during parsing of the scope specifier.
Definition: DeclSpec.h:194
Name lookup found an unresolvable value declaration and cannot yet complete.
Definition: Lookup.h:54
static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized, NamedDecl *PrevDecl, SourceLocation Loc, bool IsPartialSpecialization)
Check whether a specialization is well-formed in the current context.
QualType getInjectedClassNameSpecialization()
Retrieve the template specialization type of the injected-class-name for this class template...
SourceLocation getConstexprSpecLoc() const
Definition: DeclSpec.h:709
bool isTemplateParamScope() const
isTemplateParamScope - Return true if this scope is a C++ template parameter scope.
Definition: Scope.h:365
void addDecl(NamedDecl *D)
Definition: UnresolvedSet.h:83
bool Matches
void setPointOfInstantiation(SourceLocation Loc)
A class for iterating through a result set and possibly filtering out results.
Definition: Lookup.h:602
SourceLocation getPointOfInstantiation() const
Get the point of instantiation (if any), or null if none.
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:1989
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition: Expr.h:2804
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs. ...
SourceLocation getBegin() const
bool isTypeDependent() const
isTypeDependent - Determines whether this expression is type-dependent (C++ [temp.dep.expr]), which means that its type could change from one template instantiation to the next.
Definition: Expr.h:166
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:6105
SourceLocation getBeginLoc() const
Definition: DeclSpec.h:72
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1507
No entity found met the criteria.
Definition: Lookup.h:36
This template specialization was instantiated from a template due to an explicit instantiation defini...
Definition: Specifiers.h:160
This template specialization was formed from a template-id but has not yet been declared, defined, or instantiated.
Definition: Specifiers.h:145
bool isFileContext() const
Definition: DeclBase.h:1360
PtrTy get() const
Definition: Ownership.h:74
A template type parameter, stored as a type.
VarDecl * getInstantiatedFromStaticDataMember() const
If this variable is an instantiated static data member of a class template specialization, returns the templated static data member from which it was instantiated.
Definition: Decl.cpp:2356
DeductionFailureInfo MakeDeductionFailureInfo(ASTContext &Context, Sema::TemplateDeductionResult TDK, sema::TemplateDeductionInfo &Info)
Convert from Sema's representation of template deduction information to the form used in overload-can...
Attr * clone(ASTContext &C) const
void checkPartialSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec)
We've found a use of a template specialization that would select a partial specialization.
NamedDecl * next()
Definition: Lookup.h:628
static TemplateArgumentLoc convertTypeTemplateArgumentToTemplate(TypeLoc TLoc)
Convert a template-argument that we parsed as a type into a template, if possible.
QualType getType() const
Return the type wrapped by this type source info.
Definition: Decl.h:70
void addArgument(const TemplateArgumentLoc &Loc)
Definition: TemplateBase.h:564
static ClassTemplateDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params, NamedDecl *Decl, Expr *AssociatedConstraints=nullptr)
Create a class template node.
ValueDecl * getAsDecl() const
Retrieve the declaration for a declaration non-type template argument.
Definition: TemplateBase.h:242
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:216
void UnmarkAsLateParsedTemplate(FunctionDecl *FD)
The injected class name of a C++ class template or class template partial specialization.
Definition: Type.h:4437
ClassTemplateDecl * getDescribedClassTemplate() const
Retrieves the class template that is described by this class declaration.
Definition: DeclCXX.cpp:1357
QualType getPointeeType() const
Definition: Type.h:2238
A qualified reference to a name whose declaration cannot yet be resolved.
Definition: ExprCXX.h:2775
Represents a pack expansion of types.
Definition: Type.h:4787
QualType getDependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, const IdentifierInfo *Name, QualType Canon=QualType()) const
A POD class for pairing a NamedDecl* with an access specifier.
void setLParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:1392
void setTemplateKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:1581
static void checkTemplatePartialSpecialization(Sema &S, PartialSpecDecl *Partial)
TypeResult ActOnTagTemplateIdType(TagUseKind TUK, TypeSpecifierType TagSpec, SourceLocation TagLoc, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, TemplateTy TemplateD, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn, SourceLocation RAngleLoc)
Parsed an elaborated-type-specifier that refers to a template-id, such as class T::template apply<U>...
SourceRange getSourceRange() const LLVM_READONLY
Get the source range that spans this declarator.
Definition: DeclSpec.h:1884
void setTemplateSpecializationKind(TemplateSpecializationKind TSK, SourceLocation PointOfInstantiation=SourceLocation())
For a static data member that was instantiated from a static data member of a class template...
Definition: Decl.cpp:2401
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
Decl * ActOnTemplateTemplateParameter(Scope *S, SourceLocation TmpLoc, TemplateParameterList *Params, SourceLocation EllipsisLoc, IdentifierInfo *ParamName, SourceLocation ParamNameLoc, unsigned Depth, unsigned Position, SourceLocation EqualLoc, ParsedTemplateArgument DefaultArg)
ActOnTemplateTemplateParameter - Called when a C++ template template parameter (e.g.
QualType getType() const
Definition: Expr.h:127
Represents a template argument.
Definition: TemplateBase.h:40
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine whether this particular class is a specialization or instantiation of a class template or m...
Definition: DeclCXX.cpp:1365
QualType getAsType() const
Retrieve the type for a type template argument.
Definition: TemplateBase.h:235
TagTypeKind
The kind of a tag type.
Definition: Type.h:4488
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition: Decl.cpp:3294
llvm::PointerUnion3< TemplateTypeParmDecl *, NonTypeTemplateParmDecl *, TemplateTemplateParmDecl * > TemplateParameter
Stores a template parameter of any kind.
Definition: DeclTemplate.h:40
The name does not refer to a template.
Definition: TemplateKinds.h:23
const CXXScopeSpec & getScopeSpec() const
Retrieve the nested-name-specifier that precedes the template name in a template template argument...
static ParmVarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S, Expr *DefArg)
Definition: Decl.cpp:2435
void setMemberSpecialization()
Note that this member template is a specialization.
bool RebuildTemplateParamsInCurrentInstantiation(TemplateParameterList *Params)
Rebuild the template parameters now that we know we're in a current instantiation.
void removeDefaultArgument()
Removes the default argument of this template parameter.
QualType getDecayedType(QualType T) const
Return the uniqued reference to the decayed version of the given type.
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition: Decl.cpp:3155
static NonTypeTemplateParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, unsigned D, unsigned P, IdentifierInfo *Id, QualType T, bool ParameterPack, TypeSourceInfo *TInfo)
UnaryOperatorKind
ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs)
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1215
CanQualType NullPtrTy
Definition: ASTContext.h:978
EvalResult is a struct with detailed info about an evaluated expression.
Definition: Expr.h:568
TemplateSpecializationKind getSpecializationKind() const
Determine the kind of specialization that this declaration represents.
StringRef Name
Definition: USRFinder.cpp:123
The base class of all kinds of template declarations (e.g., class, function, etc.).
Definition: DeclTemplate.h:378
Sema::LookupNameKind getLookupKind() const
Gets the kind of lookup to perform.
Definition: Lookup.h:259
ClassTemplateDecl * getInstantiatedFromMemberTemplate() const
bool isDependent() const
Determines whether this is a dependent template name.
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK=VK_RValue, const CXXCastPath *BasePath=nullptr, CheckedConversionKind CCK=CCK_ImplicitConversion)
ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
Definition: Sema.cpp:401
SourceLocation getLocStart() const LLVM_READONLY
Definition: TypeLoc.h:137
The template argument is a pack expansion of a template name that was provided for a template templat...
Definition: TemplateBase.h:63
SourceRange getSourceRange(const SourceRange &Range)
Returns the SourceRange of a SourceRange.
Definition: FixIt.h:34
CXXScopeSpec SS
The nested-name-specifier that precedes the template name.
SourceLocation RAngleLoc
The location of the '>' after the template argument list.
TemplateName getCanonicalTemplateName(TemplateName Name) const
Retrieves the "canonical" template name that refers to a given template.
bool isInvalidDecl() const
Definition: DeclBase.h:532
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition: Diagnostic.h:116
This is a scope that corresponds to the template parameters of a C++ template.
Definition: Scope.h:76
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition: Specifiers.h:156
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template specialization this is.
Definition: DeclTemplate.h:617
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
DeclarationName - The name of a declaration.
Expr * getDefaultArg()
Definition: Decl.cpp:2473
void setDependentTemplateSpecialization(ASTContext &Context, const UnresolvedSetImpl &Templates, const TemplateArgumentListInfo &TemplateArgs)
Specifies that this function declaration is actually a dependent function template specialization...
Definition: Decl.cpp:3355
Represents a C++11 pack expansion that produces a sequence of expressions.
Definition: ExprCXX.h:3565
std::string getAsString(ASTContext &Ctx, QualType Ty) const
Definition: APValue.cpp:545
bool isThisDeclarationADefinition() const
Returns whether this specific declaration of the function is also a definition that does not contain ...
Definition: Decl.h:1874
SourceLocation getLocStart() const LLVM_READONLY
Definition: Decl.h:683
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:792
static Expr * lookThroughRangesV3Condition(Preprocessor &PP, Expr *Cond)
bool isNull() const
Determine whether this template argument has no value.
Definition: TemplateBase.h:216
EnumDecl - Represents an enum.
Definition: Decl.h:3102
unsigned getFunctionScopeDepth() const
Definition: Decl.h:1481
detail::InMemoryDirectory::const_iterator E
bool inTemplateInstantiation() const
Determine whether we are currently performing template instantiation.
Definition: Sema.h:7328
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:2442
This names the __type_pack_element BuiltinTemplateDecl.
Definition: Builtins.h:232
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition: Specifiers.h:142
TemplateSpecCandidate & addCandidate()
Add a new candidate with NumConversions conversion sequence slots to the overload set...
bool isSingleResult() const
Determines if this names a single result which is not an unresolved value using decl.
Definition: Lookup.h:294
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2087
TypeResult ActOnTypenameType(Scope *S, SourceLocation TypenameLoc, const CXXScopeSpec &SS, const IdentifierInfo &II, SourceLocation IdLoc)
Called when the parser has parsed a C++ typename specifier, e.g., "typename T::type".
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspnd...
A type that was preceded by the 'template' keyword, stored as a Type*.
The name refers to a template whose specialization produces a type.
Definition: TemplateKinds.h:30
VarTemplateSpecializationDecl * findSpecialization(ArrayRef< TemplateArgument > Args, void *&InsertPos)
Return the specialization with the provided arguments if it exists, otherwise return the insertion po...
void CompleteMemberSpecialization(NamedDecl *Member, LookupResult &Previous)
void setObjectOfFriendDecl(bool PerformFriendInjection=false)
Changes the namespace of this declaration to reflect that it's the object of a friend declaration...
Definition: DeclBase.h:1031
Expr * IgnoreParenImpCasts() LLVM_READONLY
IgnoreParenImpCasts - Ignore parentheses and implicit casts.
Definition: Expr.cpp:2486
TemplateNameKindForDiagnostics getTemplateNameKindForDiagnostics(TemplateName Name)
Definition: SemaDecl.cpp:1155
bool isWideCharType() const
Definition: Type.cpp:1703
unsigned getDepth() const
Get the nesting depth of the template parameter.
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
Definition: Type.h:5662
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:1953
Represents a pointer to an Objective C object.
Definition: Type.h:5220
SourceRange getSourceRange() const LLVM_READONLY
Get the full source range.
Definition: TypeLoc.h:134
Pointer to a block type.
Definition: Type.h:2327
void setTemplateKeywordLoc(SourceLocation Loc)
Sets the location of the template keyword.
Name lookup found a single declaration that met the criteria.
Definition: Lookup.h:45
bool empty() const
Return true if no decls were found.
Definition: Lookup.h:325
bool isKeyword() const
static void completeMemberSpecializationImpl(Sema &S, DeclT *OrigD, SourceLocation Loc)
Complete the explicit specialization of a member of a class template by updating the instantiated mem...
NamedDecl * getCorrectionDecl() const
Gets the pointer to the declaration of the typo correction.
ArrayRef< LValuePathEntry > getLValuePath() const
Definition: APValue.cpp:573
bool isNotEmpty() const
A scope specifier is present, but may be valid or invalid.
Definition: DeclSpec.h:191
bool HasSideEffects
Whether the evaluated expression has side effects.
Definition: Expr.h:541
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:3784
Complex values, per C99 6.2.5p11.
Definition: Type.h:2164
Location wrapper for a TemplateArgument.
Definition: TemplateBase.h:428
VarDecl * getTemplatedDecl() const
Get the underlying variable declarations of the template.
Expr * getAssociatedConstraints() const
Definition: DeclTemplate.h:423
void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc)
Definition: Decl.cpp:3721
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:6042
void setTemplateSpecializationKind(TemplateSpecializationKind TSK, SourceLocation PointOfInstantiation=SourceLocation())
Determine what kind of template instantiation this function represents.
Definition: Decl.cpp:3415
CheckTemplateArgumentKind
Specifies the context in which a particular template argument is being checked.
Definition: Sema.h:6227
SourceLocation getPointOfInstantiation() const
Retrieve the first point of instantiation of this member.
Definition: DeclTemplate.h:635
This template specialization was declared or defined by an explicit specialization (C++ [temp...
Definition: Specifiers.h:152
static VarTemplatePartialSpecializationDecl * Create(ASTContext &Context, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, TemplateParameterList *Params, VarTemplateDecl *SpecializedTemplate, QualType T, TypeSourceInfo *TInfo, StorageClass S, ArrayRef< TemplateArgument > Args, const TemplateArgumentListInfo &ArgInfos)
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition: Decl.cpp:3398
ClassTemplatePartialSpecializationDecl * getInstantiatedFromMember() const
Retrieve the member class template partial specialization from which this particular class template p...
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
Definition: ASTContext.h:1281
static CStyleCastExpr * Create(const ASTContext &Context, QualType T, ExprValueKind VK, CastKind K, Expr *Op, const CXXCastPath *BasePath, TypeSourceInfo *WrittenTy, SourceLocation L, SourceLocation R)
Definition: Expr.cpp:1719
CanQualType DependentTy
Definition: ASTContext.h:979
QualType getIntegralType() const
Retrieve the type of the integral value.
Definition: TemplateBase.h:291
bool isNull() const
Determine whether this template name is NULL.
void setTypeSourceInfo(TypeSourceInfo *TI)
Definition: Decl.h:666
void setInstantiationOfStaticDataMember(VarDecl *VD, TemplateSpecializationKind TSK)
Specify that this variable is an instantiation of the static data member VD.
Definition: Decl.cpp:2424
bool isFunctionType() const
Definition: Type.h:5709
ExtVectorType - Extended vector type.
Definition: Type.h:2858
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:2360
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
Definition: DeclBase.cpp:1634
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1548
Wrapper for source info for record types.
Definition: TypeLoc.h:690
bool isInvalid() const
Determine whether the given template argument is invalid.
FriendObjectKind getFriendObjectKind() const
Determines whether this declaration is the object of a friend declaration and, if so...
Definition: DeclBase.h:1070
TypeSourceInfo * RebuildTypeInCurrentInstantiation(TypeSourceInfo *T, SourceLocation Loc, DeclarationName Name)
Rebuilds a type within the context of the current instantiation.
SourceRange getTemplateParamsRange(TemplateParameterList const *const *Params, unsigned NumParams)
Retrieves the range of the given template parameter lists.
DeclResult ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc, unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS, TemplateTy Template, SourceLocation TemplateNameLoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc, AttributeList *Attr)
The template argument is a type.
Definition: TemplateBase.h:48
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
Definition: Linkage.h:33
ActionResult< ParsedType > TypeResult
Definition: Ownership.h:254
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition: Diagnostic.h:90
const TypeClass * getTypePtr() const
Definition: TypeLoc.h:386
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream...
llvm::ArrayRef< TemplateArgumentLoc > arguments() const
Definition: TemplateBase.h:552
NestedNameSpecifier * getQualifier() const
Definition: Type.h:4725
bool isInlineSpecified() const
Definition: DeclSpec.h:562
The template argument is actually a parameter pack.
Definition: TemplateBase.h:72
A template-id, e.g., f<int>.
Definition: DeclSpec.h:922
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat]...
Definition: APValue.h:38
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition: Decl.h:1065
static QualType GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo=nullptr)
Definition: SemaType.cpp:2468
static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS)
Determine whether the given scope specifier has a template-id in it.
bool isConcept() const
Whether this is a (C++ Concepts TS) function or variable concept.
Definition: DeclTemplate.h:445
void checkClassLevelDLLAttribute(CXXRecordDecl *Class)
Check class-level dllimport/dllexport attribute.
void setInstantiationOf(VarTemplatePartialSpecializationDecl *PartialSpec, const TemplateArgumentList *TemplateArgs)
Note that this variable template specialization is actually an instantiation of the given variable te...
QualType getPointeeType() const
Definition: Type.h:2381
This is a scope that can contain a declaration.
Definition: Scope.h:58
IdentifierInfo * getIdentifier() const
Definition: DeclSpec.h:2114
void CheckTemplatePartialSpecialization(ClassTemplatePartialSpecializationDecl *Partial)
A template argument list.
Definition: DeclTemplate.h:195
DependentTemplateName * getAsDependentTemplateName() const
Retrieve the underlying dependent template name structure, if any.
const Type * getClass() const
Definition: Type.h:2475
static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial)
ExprResult SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs)
DeclarationName getCXXLiteralOperatorName(IdentifierInfo *II)
getCXXLiteralOperatorName - Get the name of the literal operator function with II as the identifier...
TypeResult ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc, TemplateTy Template, IdentifierInfo *TemplateII, SourceLocation TemplateIILoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc, bool IsCtorOrDtorName=false, bool IsClassName=false)
QualType CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI, SourceLocation Loc)
Check that the type of a non-type template parameter is well-formed.
bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T, UnexpandedParameterPackContext UPPC)
If the given type contains an unexpanded parameter pack, diagnose the error.
unsigned pack_size() const
The number of template arguments in the given template argument pack.
Definition: TemplateBase.h:336
SourceLocation getIdentifierLoc() const
Definition: DeclSpec.h:2120
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:5569
const LValueBase getLValueBase() const
Definition: APValue.cpp:553
Represents a C++ struct/union/class.
Definition: DeclCXX.h:267
BoundNodesTreeBuilder *const Builder
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:861
Represents a template specialization type whose template cannot be resolved, e.g. ...
Definition: Type.h:4695
A user-defined literal name, e.g., operator "" _i.
Definition: DeclSpec.h:914
The template argument is a template name that was provided for a template template parameter...
Definition: TemplateBase.h:60
Represents a C array with an unspecified size.
Definition: Type.h:2603
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template specialization this is.
Definition: DeclTemplate.h:540
bool isOutOfLine() const override
Determine whether this is or was instantiated from an out-of-line definition of a static data member...
Definition: Decl.cpp:2126
void setConstexpr(bool IC)
Definition: Decl.h:1945
bool isExpandedParameterPack() const
Whether this parameter is a template template parameter pack that has a known list of different templ...
void setParam(unsigned i, ParmVarDecl *VD)
Definition: TypeLoc.h:1432
Provides information a specialization of a member of a class template, which may be a member function...
Definition: DeclTemplate.h:595
NestedNameSpecifier * getNestedNameSpecifier() const
Retrieve the nested-name-specifier to which this instance refers.
A structure for storing the information associated with an overloaded template name.
Definition: TemplateName.h:93
ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs)
ClassTemplatePartialSpecializationDecl * findPartialSpecialization(ArrayRef< TemplateArgument > Args, void *&InsertPos)
Return the partial specialization with the provided arguments if it exists, otherwise return the inse...
SourceLocation getRParenLoc() const
Definition: TypeLoc.h:1396
Location information for a TemplateArgument.
Definition: TemplateBase.h:369
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:317
The "enum" keyword.
Definition: Type.h:4498
void DeclareImplicitDeductionGuides(TemplateDecl *Template, SourceLocation Loc)
Declare implicit deduction guides for a class template if we've not already done so.
static void collectConjunctionTerms(Expr *Clause, SmallVectorImpl< Expr * > &Terms)
Collect all of the separable terms in the given condition, which might be a conjunction.
Declaration of a class template.
DeclContext * getLookupParent()
Find the parent context of this context that will be used for unqualified name lookup.
Definition: DeclBase.cpp:978
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string...
Definition: Diagnostic.h:127
This class is used for builtin types like 'int'.
Definition: Type.h:2084
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Definition: DeclTemplate.h:410
LookupResultKind getResultKind() const
Definition: Lookup.h:307
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:245
bool isArrayType() const
Definition: Type.h:5751
DeclResult ActOnVarTemplateSpecialization(Scope *S, Declarator &D, TypeSourceInfo *DI, SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams, StorageClass SC, bool IsPartialSpecialization)
static TemplateArgumentListInfo makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId)
Convert the parser's template argument list representation into our form.
Defines the clang::TargetInfo interface.
QualType getPattern() const
Retrieve the pattern of this pack expansion, which is the type that will be repeatedly instantiated w...
Definition: Type.h:4814
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC...
Definition: DeclBase.h:1414
ArrayRef< ParmVarDecl * > getParams() const
Definition: TypeLoc.h:1417
void setRAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:1595
static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D, SourceLocation InstLoc, bool WasQualifiedName)
Check the scope of an explicit instantiation.
ExprResult ExprError()
Definition: Ownership.h:268
QualType getDeducedType() const
Get the type deduced for this placeholder type, or null if it's either not been deduced or was deduce...
Definition: Type.h:4192
StringRef getImmediateMacroName(SourceLocation Loc)
Retrieve the name of the immediate macro expansion.
static Decl::Kind getKind(const Decl *D)
Definition: DeclBase.cpp:897
CanQualType IntTy
Definition: ASTContext.h:971
bool isRecord() const
Definition: DeclBase.h:1368
bool IsQualificationConversion(QualType FromType, QualType ToType, bool CStyle, bool &ObjCLifetimeConversion)
IsQualificationConversion - Determines whether the conversion from an rvalue of type FromType to ToTy...
void LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS, QualType ObjectType, bool EnteringContext, bool &MemberOfUnknownSpecialization)
static Expr * formAssociatedConstraints(TemplateParameterList *Params, FunctionDecl *FD)
[temp.constr.decl]p2: A template's associated constraints are defined as a single constraint-expressi...
The name refers to a variable template whose specialization produces a variable.
Definition: TemplateKinds.h:33
bool hasEllipsis() const
Definition: DeclSpec.h:2392
bool isValid() const
A scope specifier is present, and it refers to a real scope.
Definition: DeclSpec.h:196
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:953
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition: Expr.h:402
bool isSet() const
Deprecated.
Definition: DeclSpec.h:209
Represents a type template specialization; the template must be a class template, a type alias templa...
Definition: Type.h:4297
NamedDecl * getMostRecentDecl()
Definition: Decl.h:391
SourceLocation getRAngleLoc() const
Definition: DeclTemplate.h:154
QualType getElementType() const
Definition: Type.h:2531
bool isPackExpansion() const
Whether this parameter pack is a pack expansion.
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition: Type.h:5564
void setMemberSpecialization()
Note that this member template is a specialization.
SourceLocation getInnerLocStart() const
getInnerLocStart - Return SourceLocation representing start of source range ignoring outer template d...
Definition: Decl.h:675
void setInheritedDefaultArgument(const ASTContext &C, TemplateTemplateParmDecl *Prev)
static bool diagnoseArityMismatch(Sema &S, TemplateDecl *Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs)
Diagnose an arity mismatch in the.
static std::pair< Expr *, std::string > findFailedEnableIfCondition(Sema &S, Expr *Cond)
Find the failed subexpression within enable_if, and describe it with a string.
TypeSourceInfo * SubstType(TypeSourceInfo *T, const MultiLevelTemplateArgumentList &TemplateArgs, SourceLocation Loc, DeclarationName Entity, bool AllowDeducedTST=false)
Perform substitution on the type T with a given set of template arguments.
void suppressDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup.
Definition: Lookup.h:568
AttributeList * getNext() const
An l-value expression is a reference to an object with independent storage.
Definition: Specifiers.h:110
static bool DependsOnTemplateParameters(QualType T, TemplateParameterList *Params)
Determines whether a given type depends on the given parameter list.
StringRef getKindName() const
Definition: Decl.h:3015
Wrapper for template type parameters.
Definition: TypeLoc.h:706
bool isInvalid() const
Determines whether we have exceeded the maximum recursive template instantiations.
Definition: Sema.h:7298
bool isParameterPack() const
Whether this declaration is a parameter pack.
Definition: DeclBase.cpp:192
A trivial tuple used to represent a source range.
static VarTemplateSpecializationDecl * Create(ASTContext &Context, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, VarTemplateDecl *SpecializedTemplate, QualType T, TypeSourceInfo *TInfo, StorageClass S, ArrayRef< TemplateArgument > Args)
SourceLocation getLocation() const
Definition: DeclBase.h:407
void setLexicalDeclContext(DeclContext *DC)
Definition: DeclBase.cpp:268
ASTContext & Context
Definition: Sema.h:305
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:2812
NamedDecl - This represents a decl with a name.
Definition: Decl.h:213
bool isInvalidType() const
Definition: DeclSpec.h:2381
A boolean literal, per ([C++ lex.bool] Boolean literals).
Definition: ExprCXX.h:486
FunctionDecl * getInstantiatedFromMemberFunction() const
If this function is an instantiation of a member function of a class template specialization, retrieves the function from which it was instantiated.
Definition: Decl.cpp:3171
void dropAttr()
Definition: DeclBase.h:494
SourceLocation getDefaultArgumentLoc() const
Retrieve the location of the default argument, if any.
void setAccess(AccessSpecifier AS)
Definition: DeclBase.h:446
A template template argument, stored as a template name.
Represents a C array with a specified size that is not an integer-constant-expression.
Definition: Type.h:2648
void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs, bool OnlyDeduced, unsigned Depth, llvm::SmallBitVector &Used)
Mark which template parameters can be deduced from a given template argument list.
void setTemplateNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:1616
No keyword precedes the qualified type name.
Definition: Type.h:4518
APSInt & getInt()
Definition: APValue.h:201
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:683
void setTypeAsWritten(TypeSourceInfo *T)
Sets the type of this specialization as it was written by the user.
unsigned NumArgs
NumArgs - The number of template arguments.
The global specifier '::'. There is no stored value.
static void noteNonDeducibleParameters(Sema &S, TemplateParameterList *TemplateParams, const llvm::SmallBitVector &DeducibleParams)
SourceLocation getLocStart() const LLVM_READONLY
Definition: Stmt.cpp:257
void setType(QualType newType)
Definition: Decl.h:590
const TemplateArgument & getArgument() const
Definition: TemplateBase.h:471
SourceRange getSourceRange() const LLVM_READONLY
Definition: DeclTemplate.h:156
void setDeletedAsWritten(bool D=true)
Definition: Decl.h:1981
Represents the canonical version of C arrays with a specified constant size.
Definition: Type.h:2553
Defines enum values for all the target-independent builtin functions.
Declaration of a template function.
Definition: DeclTemplate.h:939
void clear()
Clears out any current state.
Definition: Lookup.h:540
bool IsInsideALocalClassWithinATemplateFunction()
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:1876
const NamedDecl * Result
Definition: USRFinder.cpp:70
Attr - This represents one attribute.
Definition: Attr.h:43
ParsedAttributes & getAttributes()
Definition: DeclSpec.h:751
static bool diagnoseMissingArgument(Sema &S, SourceLocation Loc, TemplateDecl *TD, const TemplateParmDecl *D, TemplateArgumentListInfo &Args)
Diagnose a missing template argument.
std::vector< const ClassTemplatePartialSpecializationDecl * > PartialSpecs
llvm::FoldingSetVector< VarTemplatePartialSpecializationDecl > & getPartialSpecializations()
Retrieve the set of partial specializations of this class template.
ParsedTemplateTy Template
The declaration of the template corresponding to the template-name.
unsigned getIndex() const
Get the index of the template parameter within its parameter list.
const DeclSpec & getDeclSpec() const
getDeclSpec - Return the declaration-specifier that this declarator was declared with.
Definition: DeclSpec.h:1849
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
Definition: Preprocessor.h:98
AttributeList - Represents a syntactic attribute.
Definition: AttributeList.h:95
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:5516
bool isLValue() const
Definition: APValue.h:187
bool isPointerType() const
Definition: Type.h:5712
DeclarationName getCXXOperatorName(OverloadedOperatorKind Op)
getCXXOperatorName - Get the name of the overloadable C++ operator corresponding to Op...
A RAII object to temporarily push a declaration context.
Definition: Sema.h:684
QualType getDeducedTemplateSpecializationType(TemplateName Template, QualType DeducedType, bool IsDependent) const
C++1z deduced class template specialization type.
SourceLocation getTemplateLoc() const
Definition: DeclTemplate.h:152
bool isIncompleteOrObjectType() const
Return true if this is an incomplete or object type, in other words, not a function type...
Definition: Type.h:1605