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