clang  10.0.0svn
SemaTemplateInstantiate.cpp
Go to the documentation of this file.
1 //===------- SemaTemplateInstantiate.cpp - C++ Template Instantiation ------===/
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 C++ template instantiation.
9 //
10 //===----------------------------------------------------------------------===/
11 
13 #include "TreeTransform.h"
14 #include "clang/AST/ASTConsumer.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTLambda.h"
18 #include "clang/AST/DeclTemplate.h"
19 #include "clang/AST/Expr.h"
22 #include "clang/Basic/Stack.h"
23 #include "clang/Sema/DeclSpec.h"
25 #include "clang/Sema/Lookup.h"
26 #include "clang/Sema/Template.h"
29 #include "llvm/Support/TimeProfiler.h"
30 
31 using namespace clang;
32 using namespace sema;
33 
34 //===----------------------------------------------------------------------===/
35 // Template Instantiation Support
36 //===----------------------------------------------------------------------===/
37 
38 /// Retrieve the template argument list(s) that should be used to
39 /// instantiate the definition of the given declaration.
40 ///
41 /// \param D the declaration for which we are computing template instantiation
42 /// arguments.
43 ///
44 /// \param Innermost if non-NULL, the innermost template argument list.
45 ///
46 /// \param RelativeToPrimary true if we should get the template
47 /// arguments relative to the primary template, even when we're
48 /// dealing with a specialization. This is only relevant for function
49 /// template specializations.
50 ///
51 /// \param Pattern If non-NULL, indicates the pattern from which we will be
52 /// instantiating the definition of the given declaration, \p D. This is
53 /// used to determine the proper set of template instantiation arguments for
54 /// friend function template specializations.
57  const TemplateArgumentList *Innermost,
58  bool RelativeToPrimary,
59  const FunctionDecl *Pattern) {
60  // Accumulate the set of template argument lists in this structure.
62 
63  if (Innermost)
64  Result.addOuterTemplateArguments(Innermost);
65 
66  DeclContext *Ctx = dyn_cast<DeclContext>(D);
67  if (!Ctx) {
68  Ctx = D->getDeclContext();
69 
70  // Add template arguments from a variable template instantiation. For a
71  // class-scope explicit specialization, there are no template arguments
72  // at this level, but there may be enclosing template arguments.
74  dyn_cast<VarTemplateSpecializationDecl>(D);
75  if (Spec && !Spec->isClassScopeExplicitSpecialization()) {
76  // We're done when we hit an explicit specialization.
78  !isa<VarTemplatePartialSpecializationDecl>(Spec))
79  return Result;
80 
82 
83  // If this variable template specialization was instantiated from a
84  // specialized member that is a variable template, we're done.
85  assert(Spec->getSpecializedTemplate() && "No variable template?");
86  llvm::PointerUnion<VarTemplateDecl*,
90  Specialized.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
91  if (Partial->isMemberSpecialization())
92  return Result;
93  } else {
94  VarTemplateDecl *Tmpl = Specialized.get<VarTemplateDecl *>();
95  if (Tmpl->isMemberSpecialization())
96  return Result;
97  }
98  }
99 
100  // If we have a template template parameter with translation unit context,
101  // then we're performing substitution into a default template argument of
102  // this template template parameter before we've constructed the template
103  // that will own this template template parameter. In this case, we
104  // use empty template parameter lists for all of the outer templates
105  // to avoid performing any substitutions.
106  if (Ctx->isTranslationUnit()) {
107  if (TemplateTemplateParmDecl *TTP
108  = dyn_cast<TemplateTemplateParmDecl>(D)) {
109  for (unsigned I = 0, N = TTP->getDepth() + 1; I != N; ++I)
110  Result.addOuterTemplateArguments(None);
111  return Result;
112  }
113  }
114  }
115 
116  while (!Ctx->isFileContext()) {
117  // Add template arguments from a class template instantiation.
119  = dyn_cast<ClassTemplateSpecializationDecl>(Ctx);
120  if (Spec && !Spec->isClassScopeExplicitSpecialization()) {
121  // We're done when we hit an explicit specialization.
123  !isa<ClassTemplatePartialSpecializationDecl>(Spec))
124  break;
125 
127 
128  // If this class template specialization was instantiated from a
129  // specialized member that is a class template, we're done.
130  assert(Spec->getSpecializedTemplate() && "No class template?");
132  break;
133  }
134  // Add template arguments from a function template specialization.
135  else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Ctx)) {
136  if (!RelativeToPrimary &&
137  Function->getTemplateSpecializationKindForInstantiation() ==
139  break;
140 
141  if (const TemplateArgumentList *TemplateArgs
142  = Function->getTemplateSpecializationArgs()) {
143  // Add the template arguments for this specialization.
144  Result.addOuterTemplateArguments(TemplateArgs);
145 
146  // If this function was instantiated from a specialized member that is
147  // a function template, we're done.
148  assert(Function->getPrimaryTemplate() && "No function template?");
149  if (Function->getPrimaryTemplate()->isMemberSpecialization())
150  break;
151 
152  // If this function is a generic lambda specialization, we are done.
154  break;
155 
156  } else if (FunctionTemplateDecl *FunTmpl
157  = Function->getDescribedFunctionTemplate()) {
158  // Add the "injected" template arguments.
159  Result.addOuterTemplateArguments(FunTmpl->getInjectedTemplateArgs());
160  }
161 
162  // If this is a friend declaration and it declares an entity at
163  // namespace scope, take arguments from its lexical parent
164  // instead of its semantic parent, unless of course the pattern we're
165  // instantiating actually comes from the file's context!
166  if (Function->getFriendObjectKind() &&
167  Function->getDeclContext()->isFileContext() &&
168  (!Pattern || !Pattern->getLexicalDeclContext()->isFileContext())) {
169  Ctx = Function->getLexicalDeclContext();
170  RelativeToPrimary = false;
171  continue;
172  }
173  } else if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Ctx)) {
174  if (ClassTemplateDecl *ClassTemplate = Rec->getDescribedClassTemplate()) {
175  QualType T = ClassTemplate->getInjectedClassNameSpecialization();
176  const TemplateSpecializationType *TST =
177  cast<TemplateSpecializationType>(Context.getCanonicalType(T));
179  llvm::makeArrayRef(TST->getArgs(), TST->getNumArgs()));
180  if (ClassTemplate->isMemberSpecialization())
181  break;
182  }
183  }
184 
185  Ctx = Ctx->getParent();
186  RelativeToPrimary = false;
187  }
188 
189  return Result;
190 }
191 
193  switch (Kind) {
194  case TemplateInstantiation:
195  case ExceptionSpecInstantiation:
196  case DefaultTemplateArgumentInstantiation:
197  case DefaultFunctionArgumentInstantiation:
198  case ExplicitTemplateArgumentSubstitution:
199  case DeducedTemplateArgumentSubstitution:
200  case PriorTemplateArgumentSubstitution:
201  case ConstraintsCheck:
202  return true;
203 
204  case DefaultTemplateArgumentChecking:
205  case DeclaringSpecialMember:
206  case DefiningSynthesizedFunction:
207  case ExceptionSpecEvaluation:
208  case ConstraintSubstitution:
209  case RewritingOperatorAsSpaceship:
210  return false;
211 
212  // This function should never be called when Kind's value is Memoization.
213  case Memoization:
214  break;
215  }
216 
217  llvm_unreachable("Invalid SynthesisKind!");
218 }
219 
222  SourceLocation PointOfInstantiation, SourceRange InstantiationRange,
223  Decl *Entity, NamedDecl *Template, ArrayRef<TemplateArgument> TemplateArgs,
224  sema::TemplateDeductionInfo *DeductionInfo)
225  : SemaRef(SemaRef) {
226  // Don't allow further instantiation if a fatal error and an uncompilable
227  // error have occurred. Any diagnostics we might have raised will not be
228  // visible, and we do not need to construct a correct AST.
229  if (SemaRef.Diags.hasFatalErrorOccurred() &&
231  Invalid = true;
232  return;
233  }
234  Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
235  if (!Invalid) {
237  Inst.Kind = Kind;
238  Inst.PointOfInstantiation = PointOfInstantiation;
239  Inst.Entity = Entity;
240  Inst.Template = Template;
241  Inst.TemplateArgs = TemplateArgs.data();
242  Inst.NumTemplateArgs = TemplateArgs.size();
243  Inst.DeductionInfo = DeductionInfo;
244  Inst.InstantiationRange = InstantiationRange;
245  SemaRef.pushCodeSynthesisContext(Inst);
246 
247  AlreadyInstantiating =
249  .insert(std::make_pair(Inst.Entity->getCanonicalDecl(), Inst.Kind))
250  .second;
251  atTemplateBegin(SemaRef.TemplateInstCallbacks, SemaRef, Inst);
252  }
253 }
254 
256  Sema &SemaRef, SourceLocation PointOfInstantiation, Decl *Entity,
257  SourceRange InstantiationRange)
258  : InstantiatingTemplate(SemaRef,
259  CodeSynthesisContext::TemplateInstantiation,
260  PointOfInstantiation, InstantiationRange, Entity) {}
261 
263  Sema &SemaRef, SourceLocation PointOfInstantiation, FunctionDecl *Entity,
264  ExceptionSpecification, SourceRange InstantiationRange)
266  SemaRef, CodeSynthesisContext::ExceptionSpecInstantiation,
267  PointOfInstantiation, InstantiationRange, Entity) {}
268 
270  Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateParameter Param,
271  TemplateDecl *Template, ArrayRef<TemplateArgument> TemplateArgs,
272  SourceRange InstantiationRange)
274  SemaRef,
275  CodeSynthesisContext::DefaultTemplateArgumentInstantiation,
276  PointOfInstantiation, InstantiationRange, getAsNamedDecl(Param),
277  Template, TemplateArgs) {}
278 
280  Sema &SemaRef, SourceLocation PointOfInstantiation,
281  FunctionTemplateDecl *FunctionTemplate,
282  ArrayRef<TemplateArgument> TemplateArgs,
284  sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
285  : InstantiatingTemplate(SemaRef, Kind, PointOfInstantiation,
286  InstantiationRange, FunctionTemplate, nullptr,
287  TemplateArgs, &DeductionInfo) {
288  assert(
291 }
292 
294  Sema &SemaRef, SourceLocation PointOfInstantiation,
295  TemplateDecl *Template,
296  ArrayRef<TemplateArgument> TemplateArgs,
297  sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
299  SemaRef,
300  CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
301  PointOfInstantiation, InstantiationRange, Template, nullptr,
302  TemplateArgs, &DeductionInfo) {}
303 
305  Sema &SemaRef, SourceLocation PointOfInstantiation,
307  ArrayRef<TemplateArgument> TemplateArgs,
308  sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
310  SemaRef,
311  CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
312  PointOfInstantiation, InstantiationRange, PartialSpec, nullptr,
313  TemplateArgs, &DeductionInfo) {}
314 
316  Sema &SemaRef, SourceLocation PointOfInstantiation,
318  ArrayRef<TemplateArgument> TemplateArgs,
319  sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
321  SemaRef,
322  CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
323  PointOfInstantiation, InstantiationRange, PartialSpec, nullptr,
324  TemplateArgs, &DeductionInfo) {}
325 
327  Sema &SemaRef, SourceLocation PointOfInstantiation, ParmVarDecl *Param,
328  ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange)
330  SemaRef,
331  CodeSynthesisContext::DefaultFunctionArgumentInstantiation,
332  PointOfInstantiation, InstantiationRange, Param, nullptr,
333  TemplateArgs) {}
334 
336  Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template,
338  SourceRange InstantiationRange)
340  SemaRef,
341  CodeSynthesisContext::PriorTemplateArgumentSubstitution,
342  PointOfInstantiation, InstantiationRange, Param, Template,
343  TemplateArgs) {}
344 
346  Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template,
348  SourceRange InstantiationRange)
350  SemaRef,
351  CodeSynthesisContext::PriorTemplateArgumentSubstitution,
352  PointOfInstantiation, InstantiationRange, Param, Template,
353  TemplateArgs) {}
354 
356  Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Template,
357  NamedDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
358  SourceRange InstantiationRange)
360  SemaRef, CodeSynthesisContext::DefaultTemplateArgumentChecking,
361  PointOfInstantiation, InstantiationRange, Param, Template,
362  TemplateArgs) {}
363 
365  Sema &SemaRef, SourceLocation PointOfInstantiation,
366  ConstraintsCheck, TemplateDecl *Template,
367  ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange)
370  PointOfInstantiation, InstantiationRange, Template, nullptr,
371  TemplateArgs) {}
372 
374  Sema &SemaRef, SourceLocation PointOfInstantiation,
376  sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
379  PointOfInstantiation, InstantiationRange, Template, nullptr,
380  {}, &DeductionInfo) {}
381 
385 
386  CodeSynthesisContexts.push_back(Ctx);
387 
388  if (!Ctx.isInstantiationRecord())
390 
391  // Check to see if we're low on stack space. We can't do anything about this
392  // from here, but we can at least warn the user.
395 }
396 
398  auto &Active = CodeSynthesisContexts.back();
399  if (!Active.isInstantiationRecord()) {
400  assert(NonInstantiationEntries > 0);
402  }
403 
404  InNonInstantiationSFINAEContext = Active.SavedInNonInstantiationSFINAEContext;
405 
406  // Name lookup no longer looks in this template's defining module.
407  assert(CodeSynthesisContexts.size() >=
409  "forgot to remove a lookup module for a template instantiation");
410  if (CodeSynthesisContexts.size() ==
413  LookupModulesCache.erase(M);
415  }
416 
417  // If we've left the code synthesis context for the current context stack,
418  // stop remembering that we've emitted that stack.
419  if (CodeSynthesisContexts.size() ==
422 
423  CodeSynthesisContexts.pop_back();
424 }
425 
427  if (!Invalid) {
428  if (!AlreadyInstantiating) {
429  auto &Active = SemaRef.CodeSynthesisContexts.back();
430  SemaRef.InstantiatingSpecializations.erase(
431  std::make_pair(Active.Entity, Active.Kind));
432  }
433 
434  atTemplateEnd(SemaRef.TemplateInstCallbacks, SemaRef,
435  SemaRef.CodeSynthesisContexts.back());
436 
437  SemaRef.popCodeSynthesisContext();
438  Invalid = true;
439  }
440 }
441 
442 bool Sema::InstantiatingTemplate::CheckInstantiationDepth(
443  SourceLocation PointOfInstantiation,
444  SourceRange InstantiationRange) {
445  assert(SemaRef.NonInstantiationEntries <=
446  SemaRef.CodeSynthesisContexts.size());
447  if ((SemaRef.CodeSynthesisContexts.size() -
448  SemaRef.NonInstantiationEntries)
449  <= SemaRef.getLangOpts().InstantiationDepth)
450  return false;
451 
452  SemaRef.Diag(PointOfInstantiation,
453  diag::err_template_recursion_depth_exceeded)
454  << SemaRef.getLangOpts().InstantiationDepth
455  << InstantiationRange;
456  SemaRef.Diag(PointOfInstantiation, diag::note_template_recursion_depth)
457  << SemaRef.getLangOpts().InstantiationDepth;
458  return true;
459 }
460 
461 /// Prints the current instantiation stack through a series of
462 /// notes.
464  // Determine which template instantiations to skip, if any.
465  unsigned SkipStart = CodeSynthesisContexts.size(), SkipEnd = SkipStart;
466  unsigned Limit = Diags.getTemplateBacktraceLimit();
467  if (Limit && Limit < CodeSynthesisContexts.size()) {
468  SkipStart = Limit / 2 + Limit % 2;
469  SkipEnd = CodeSynthesisContexts.size() - Limit / 2;
470  }
471 
472  // FIXME: In all of these cases, we need to show the template arguments
473  unsigned InstantiationIdx = 0;
475  Active = CodeSynthesisContexts.rbegin(),
476  ActiveEnd = CodeSynthesisContexts.rend();
477  Active != ActiveEnd;
478  ++Active, ++InstantiationIdx) {
479  // Skip this instantiation?
480  if (InstantiationIdx >= SkipStart && InstantiationIdx < SkipEnd) {
481  if (InstantiationIdx == SkipStart) {
482  // Note that we're skipping instantiations.
483  Diags.Report(Active->PointOfInstantiation,
484  diag::note_instantiation_contexts_suppressed)
485  << unsigned(CodeSynthesisContexts.size() - Limit);
486  }
487  continue;
488  }
489 
490  switch (Active->Kind) {
492  Decl *D = Active->Entity;
493  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
494  unsigned DiagID = diag::note_template_member_class_here;
495  if (isa<ClassTemplateSpecializationDecl>(Record))
496  DiagID = diag::note_template_class_instantiation_here;
497  Diags.Report(Active->PointOfInstantiation, DiagID)
498  << Record << Active->InstantiationRange;
499  } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
500  unsigned DiagID;
501  if (Function->getPrimaryTemplate())
502  DiagID = diag::note_function_template_spec_here;
503  else
504  DiagID = diag::note_template_member_function_here;
505  Diags.Report(Active->PointOfInstantiation, DiagID)
506  << Function
507  << Active->InstantiationRange;
508  } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
509  Diags.Report(Active->PointOfInstantiation,
510  VD->isStaticDataMember()?
511  diag::note_template_static_data_member_def_here
512  : diag::note_template_variable_def_here)
513  << VD
514  << Active->InstantiationRange;
515  } else if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
516  Diags.Report(Active->PointOfInstantiation,
517  diag::note_template_enum_def_here)
518  << ED
519  << Active->InstantiationRange;
520  } else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
521  Diags.Report(Active->PointOfInstantiation,
522  diag::note_template_nsdmi_here)
523  << FD << Active->InstantiationRange;
524  } else {
525  Diags.Report(Active->PointOfInstantiation,
526  diag::note_template_type_alias_instantiation_here)
527  << cast<TypeAliasTemplateDecl>(D)
528  << Active->InstantiationRange;
529  }
530  break;
531  }
532 
534  TemplateDecl *Template = cast<TemplateDecl>(Active->Template);
535  SmallVector<char, 128> TemplateArgsStr;
536  llvm::raw_svector_ostream OS(TemplateArgsStr);
537  Template->printName(OS);
538  printTemplateArgumentList(OS, Active->template_arguments(),
540  Diags.Report(Active->PointOfInstantiation,
541  diag::note_default_arg_instantiation_here)
542  << OS.str()
543  << Active->InstantiationRange;
544  break;
545  }
546 
548  FunctionTemplateDecl *FnTmpl = cast<FunctionTemplateDecl>(Active->Entity);
549  Diags.Report(Active->PointOfInstantiation,
550  diag::note_explicit_template_arg_substitution_here)
551  << FnTmpl
553  Active->TemplateArgs,
554  Active->NumTemplateArgs)
555  << Active->InstantiationRange;
556  break;
557  }
558 
560  if (FunctionTemplateDecl *FnTmpl =
561  dyn_cast<FunctionTemplateDecl>(Active->Entity)) {
562  Diags.Report(Active->PointOfInstantiation,
563  diag::note_function_template_deduction_instantiation_here)
564  << FnTmpl
565  << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
566  Active->TemplateArgs,
567  Active->NumTemplateArgs)
568  << Active->InstantiationRange;
569  } else {
570  bool IsVar = isa<VarTemplateDecl>(Active->Entity) ||
571  isa<VarTemplateSpecializationDecl>(Active->Entity);
572  bool IsTemplate = false;
573  TemplateParameterList *Params;
574  if (auto *D = dyn_cast<TemplateDecl>(Active->Entity)) {
575  IsTemplate = true;
576  Params = D->getTemplateParameters();
577  } else if (auto *D = dyn_cast<ClassTemplatePartialSpecializationDecl>(
578  Active->Entity)) {
579  Params = D->getTemplateParameters();
580  } else if (auto *D = dyn_cast<VarTemplatePartialSpecializationDecl>(
581  Active->Entity)) {
582  Params = D->getTemplateParameters();
583  } else {
584  llvm_unreachable("unexpected template kind");
585  }
586 
587  Diags.Report(Active->PointOfInstantiation,
588  diag::note_deduced_template_arg_substitution_here)
589  << IsVar << IsTemplate << cast<NamedDecl>(Active->Entity)
590  << getTemplateArgumentBindingsText(Params, Active->TemplateArgs,
591  Active->NumTemplateArgs)
592  << Active->InstantiationRange;
593  }
594  break;
595  }
596 
598  ParmVarDecl *Param = cast<ParmVarDecl>(Active->Entity);
599  FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());
600 
601  SmallVector<char, 128> TemplateArgsStr;
602  llvm::raw_svector_ostream OS(TemplateArgsStr);
603  FD->printName(OS);
604  printTemplateArgumentList(OS, Active->template_arguments(),
606  Diags.Report(Active->PointOfInstantiation,
607  diag::note_default_function_arg_instantiation_here)
608  << OS.str()
609  << Active->InstantiationRange;
610  break;
611  }
612 
614  NamedDecl *Parm = cast<NamedDecl>(Active->Entity);
615  std::string Name;
616  if (!Parm->getName().empty())
617  Name = std::string(" '") + Parm->getName().str() + "'";
618 
619  TemplateParameterList *TemplateParams = nullptr;
620  if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
621  TemplateParams = Template->getTemplateParameters();
622  else
623  TemplateParams =
624  cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
625  ->getTemplateParameters();
626  Diags.Report(Active->PointOfInstantiation,
627  diag::note_prior_template_arg_substitution)
628  << isa<TemplateTemplateParmDecl>(Parm)
629  << Name
630  << getTemplateArgumentBindingsText(TemplateParams,
631  Active->TemplateArgs,
632  Active->NumTemplateArgs)
633  << Active->InstantiationRange;
634  break;
635  }
636 
638  TemplateParameterList *TemplateParams = nullptr;
639  if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
640  TemplateParams = Template->getTemplateParameters();
641  else
642  TemplateParams =
643  cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
644  ->getTemplateParameters();
645 
646  Diags.Report(Active->PointOfInstantiation,
647  diag::note_template_default_arg_checking)
648  << getTemplateArgumentBindingsText(TemplateParams,
649  Active->TemplateArgs,
650  Active->NumTemplateArgs)
651  << Active->InstantiationRange;
652  break;
653  }
654 
656  Diags.Report(Active->PointOfInstantiation,
657  diag::note_evaluating_exception_spec_here)
658  << cast<FunctionDecl>(Active->Entity);
659  break;
660 
662  Diags.Report(Active->PointOfInstantiation,
663  diag::note_template_exception_spec_instantiation_here)
664  << cast<FunctionDecl>(Active->Entity)
665  << Active->InstantiationRange;
666  break;
667 
669  Diags.Report(Active->PointOfInstantiation,
670  diag::note_in_declaration_of_implicit_special_member)
671  << cast<CXXRecordDecl>(Active->Entity) << Active->SpecialMember;
672  break;
673 
675  // FIXME: For synthesized members other than special members, produce a note.
676  auto *MD = dyn_cast<CXXMethodDecl>(Active->Entity);
677  auto CSM = MD ? getSpecialMember(MD) : CXXInvalid;
678  if (CSM != CXXInvalid) {
679  Diags.Report(Active->PointOfInstantiation,
680  diag::note_member_synthesized_at)
681  << CSM << Context.getTagDeclType(MD->getParent());
682  }
683  break;
684  }
685 
687  Diags.Report(Active->Entity->getLocation(),
688  diag::note_rewriting_operator_as_spaceship);
689  break;
690 
692  break;
693 
695  if (auto *CD = dyn_cast<ConceptDecl>(Active->Entity)) {
696  SmallVector<char, 128> TemplateArgsStr;
697  llvm::raw_svector_ostream OS(TemplateArgsStr);
698  CD->printName(OS);
699  printTemplateArgumentList(OS, Active->template_arguments(),
701  Diags.Report(Active->PointOfInstantiation,
702  diag::note_concept_specialization_here)
703  << OS.str()
704  << Active->InstantiationRange;
705  break;
706  }
707  // TODO: Concepts - implement this for constrained templates and partial
708  // specializations.
709  llvm_unreachable("only concept constraints are supported right now");
710  break;
711 
713  Diags.Report(Active->PointOfInstantiation,
714  diag::note_constraint_substitution_here)
715  << Active->InstantiationRange;
716  break;
717  }
718  }
719 }
720 
723  return Optional<TemplateDeductionInfo *>(nullptr);
724 
726  Active = CodeSynthesisContexts.rbegin(),
727  ActiveEnd = CodeSynthesisContexts.rend();
728  Active != ActiveEnd;
729  ++Active)
730  {
731  switch (Active->Kind) {
733  // An instantiation of an alias template may or may not be a SFINAE
734  // context, depending on what else is on the stack.
735  if (isa<TypeAliasTemplateDecl>(Active->Entity))
736  break;
737  LLVM_FALLTHROUGH;
741  // This is a template instantiation, so there is no SFINAE.
742  return None;
743 
747  // A default template argument instantiation and substitution into
748  // template parameters with arguments for prior parameters may or may
749  // not be a SFINAE context; look further up the stack.
750  break;
751 
755  // We're either substituting explicitly-specified template arguments
756  // or deduced template arguments or a constraint expression, so SFINAE
757  // applies.
758  assert(Active->DeductionInfo && "Missing deduction info pointer");
759  return Active->DeductionInfo;
760 
764  // This happens in a context unrelated to template instantiation, so
765  // there is no SFINAE.
766  return None;
767 
769  // FIXME: This should not be treated as a SFINAE context, because
770  // we will cache an incorrect exception specification. However, clang
771  // bootstrap relies this! See PR31692.
772  break;
773 
775  break;
776  }
777 
778  // The inner context was transparent for SFINAE. If it occurred within a
779  // non-instantiation SFINAE context, then SFINAE applies.
780  if (Active->SavedInNonInstantiationSFINAEContext)
781  return Optional<TemplateDeductionInfo *>(nullptr);
782  }
783 
784  return None;
785 }
786 
787 //===----------------------------------------------------------------------===/
788 // Template Instantiation for Types
789 //===----------------------------------------------------------------------===/
790 namespace {
791  class TemplateInstantiator : public TreeTransform<TemplateInstantiator> {
792  const MultiLevelTemplateArgumentList &TemplateArgs;
793  SourceLocation Loc;
794  DeclarationName Entity;
795 
796  public:
797  typedef TreeTransform<TemplateInstantiator> inherited;
798 
799  TemplateInstantiator(Sema &SemaRef,
800  const MultiLevelTemplateArgumentList &TemplateArgs,
801  SourceLocation Loc,
802  DeclarationName Entity)
803  : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc),
804  Entity(Entity) { }
805 
806  /// Determine whether the given type \p T has already been
807  /// transformed.
808  ///
809  /// For the purposes of template instantiation, a type has already been
810  /// transformed if it is NULL or if it is not dependent.
811  bool AlreadyTransformed(QualType T);
812 
813  /// Returns the location of the entity being instantiated, if known.
814  SourceLocation getBaseLocation() { return Loc; }
815 
816  /// Returns the name of the entity being instantiated, if any.
817  DeclarationName getBaseEntity() { return Entity; }
818 
819  /// Sets the "base" location and entity when that
820  /// information is known based on another transformation.
821  void setBase(SourceLocation Loc, DeclarationName Entity) {
822  this->Loc = Loc;
823  this->Entity = Entity;
824  }
825 
826  bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
827  SourceRange PatternRange,
829  bool &ShouldExpand, bool &RetainExpansion,
830  Optional<unsigned> &NumExpansions) {
831  return getSema().CheckParameterPacksForExpansion(EllipsisLoc,
832  PatternRange, Unexpanded,
833  TemplateArgs,
834  ShouldExpand,
835  RetainExpansion,
836  NumExpansions);
837  }
838 
839  void ExpandingFunctionParameterPack(ParmVarDecl *Pack) {
841  }
842 
843  TemplateArgument ForgetPartiallySubstitutedPack() {
845  if (NamedDecl *PartialPack
847  MultiLevelTemplateArgumentList &TemplateArgs
848  = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
849  unsigned Depth, Index;
850  std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
851  if (TemplateArgs.hasTemplateArgument(Depth, Index)) {
852  Result = TemplateArgs(Depth, Index);
853  TemplateArgs.setArgument(Depth, Index, TemplateArgument());
854  }
855  }
856 
857  return Result;
858  }
859 
860  void RememberPartiallySubstitutedPack(TemplateArgument Arg) {
861  if (Arg.isNull())
862  return;
863 
864  if (NamedDecl *PartialPack
866  MultiLevelTemplateArgumentList &TemplateArgs
867  = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
868  unsigned Depth, Index;
869  std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
870  TemplateArgs.setArgument(Depth, Index, Arg);
871  }
872  }
873 
874  /// Transform the given declaration by instantiating a reference to
875  /// this declaration.
876  Decl *TransformDecl(SourceLocation Loc, Decl *D);
877 
878  void transformAttrs(Decl *Old, Decl *New) {
879  SemaRef.InstantiateAttrs(TemplateArgs, Old, New);
880  }
881 
882  void transformedLocalDecl(Decl *Old, ArrayRef<Decl *> NewDecls) {
883  if (Old->isParameterPack()) {
885  for (auto *New : NewDecls)
887  Old, cast<VarDecl>(New));
888  return;
889  }
890 
891  assert(NewDecls.size() == 1 &&
892  "should only have multiple expansions for a pack");
893  Decl *New = NewDecls.front();
894 
895  // If we've instantiated the call operator of a lambda or the call
896  // operator template of a generic lambda, update the "instantiation of"
897  // information.
898  auto *NewMD = dyn_cast<CXXMethodDecl>(New);
899  if (NewMD && isLambdaCallOperator(NewMD)) {
900  auto *OldMD = dyn_cast<CXXMethodDecl>(Old);
901  if (auto *NewTD = NewMD->getDescribedFunctionTemplate())
902  NewTD->setInstantiatedFromMemberTemplate(
903  OldMD->getDescribedFunctionTemplate());
904  else
907  }
908 
909  SemaRef.CurrentInstantiationScope->InstantiatedLocal(Old, New);
910 
911  // We recreated a local declaration, but not by instantiating it. There
912  // may be pending dependent diagnostics to produce.
913  if (auto *DC = dyn_cast<DeclContext>(Old))
914  SemaRef.PerformDependentDiagnostics(DC, TemplateArgs);
915  }
916 
917  /// Transform the definition of the given declaration by
918  /// instantiating it.
919  Decl *TransformDefinition(SourceLocation Loc, Decl *D);
920 
921  /// Transform the first qualifier within a scope by instantiating the
922  /// declaration.
923  NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc);
924 
925  /// Rebuild the exception declaration and register the declaration
926  /// as an instantiated local.
927  VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
929  SourceLocation StartLoc,
930  SourceLocation NameLoc,
931  IdentifierInfo *Name);
932 
933  /// Rebuild the Objective-C exception declaration and register the
934  /// declaration as an instantiated local.
935  VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
936  TypeSourceInfo *TSInfo, QualType T);
937 
938  /// Check for tag mismatches when instantiating an
939  /// elaborated type.
940  QualType RebuildElaboratedType(SourceLocation KeywordLoc,
941  ElaboratedTypeKeyword Keyword,
942  NestedNameSpecifierLoc QualifierLoc,
943  QualType T);
944 
946  TransformTemplateName(CXXScopeSpec &SS, TemplateName Name,
947  SourceLocation NameLoc,
948  QualType ObjectType = QualType(),
949  NamedDecl *FirstQualifierInScope = nullptr,
950  bool AllowInjectedClassName = false);
951 
952  const LoopHintAttr *TransformLoopHintAttr(const LoopHintAttr *LH);
953 
954  ExprResult TransformPredefinedExpr(PredefinedExpr *E);
955  ExprResult TransformDeclRefExpr(DeclRefExpr *E);
956  ExprResult TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E);
957 
958  ExprResult TransformTemplateParmRefExpr(DeclRefExpr *E,
960  ExprResult TransformSubstNonTypeTemplateParmPackExpr(
962 
963  /// Rebuild a DeclRefExpr for a VarDecl reference.
964  ExprResult RebuildVarDeclRefExpr(VarDecl *PD, SourceLocation Loc);
965 
966  /// Transform a reference to a function or init-capture parameter pack.
967  ExprResult TransformFunctionParmPackRefExpr(DeclRefExpr *E, VarDecl *PD);
968 
969  /// Transform a FunctionParmPackExpr which was built when we couldn't
970  /// expand a function parameter pack reference which refers to an expanded
971  /// pack.
972  ExprResult TransformFunctionParmPackExpr(FunctionParmPackExpr *E);
973 
974  QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
976  // Call the base version; it will forward to our overridden version below.
977  return inherited::TransformFunctionProtoType(TLB, TL);
978  }
979 
980  template<typename Fn>
981  QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
983  CXXRecordDecl *ThisContext,
984  Qualifiers ThisTypeQuals,
985  Fn TransformExceptionSpec);
986 
987  ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm,
988  int indexAdjustment,
989  Optional<unsigned> NumExpansions,
990  bool ExpectParameterPack);
991 
992  /// Transforms a template type parameter type by performing
993  /// substitution of the corresponding template type argument.
994  QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
996 
997  /// Transforms an already-substituted template type parameter pack
998  /// into either itself (if we aren't substituting into its pack expansion)
999  /// or the appropriate substituted argument.
1000  QualType TransformSubstTemplateTypeParmPackType(TypeLocBuilder &TLB,
1002 
1003  ExprResult TransformLambdaExpr(LambdaExpr *E) {
1004  LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
1006  }
1007 
1008  TemplateParameterList *TransformTemplateParameterList(
1009  TemplateParameterList *OrigTPL) {
1010  if (!OrigTPL || !OrigTPL->size()) return OrigTPL;
1011 
1012  DeclContext *Owner = OrigTPL->getParam(0)->getDeclContext();
1013  TemplateDeclInstantiator DeclInstantiator(getSema(),
1014  /* DeclContext *Owner */ Owner, TemplateArgs);
1015  return DeclInstantiator.SubstTemplateParams(OrigTPL);
1016  }
1017  private:
1018  ExprResult transformNonTypeTemplateParmRef(NonTypeTemplateParmDecl *parm,
1019  SourceLocation loc,
1020  TemplateArgument arg);
1021  };
1022 }
1023 
1024 bool TemplateInstantiator::AlreadyTransformed(QualType T) {
1025  if (T.isNull())
1026  return true;
1027 
1029  return false;
1030 
1031  getSema().MarkDeclarationsReferencedInType(Loc, T);
1032  return true;
1033 }
1034 
1035 static TemplateArgument
1037  assert(S.ArgumentPackSubstitutionIndex >= 0);
1038  assert(S.ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
1040  if (Arg.isPackExpansion())
1041  Arg = Arg.getPackExpansionPattern();
1042  return Arg;
1043 }
1044 
1045 Decl *TemplateInstantiator::TransformDecl(SourceLocation Loc, Decl *D) {
1046  if (!D)
1047  return nullptr;
1048 
1049  if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(D)) {
1050  if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1051  // If the corresponding template argument is NULL or non-existent, it's
1052  // because we are performing instantiation from explicitly-specified
1053  // template arguments in a function template, but there were some
1054  // arguments left unspecified.
1055  if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
1056  TTP->getPosition()))
1057  return D;
1058 
1059  TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
1060 
1061  if (TTP->isParameterPack()) {
1062  assert(Arg.getKind() == TemplateArgument::Pack &&
1063  "Missing argument pack");
1064  Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1065  }
1066 
1067  TemplateName Template = Arg.getAsTemplate().getNameToSubstitute();
1068  assert(!Template.isNull() && Template.getAsTemplateDecl() &&
1069  "Wrong kind of template template argument");
1070  return Template.getAsTemplateDecl();
1071  }
1072 
1073  // Fall through to find the instantiated declaration for this template
1074  // template parameter.
1075  }
1076 
1077  return SemaRef.FindInstantiatedDecl(Loc, cast<NamedDecl>(D), TemplateArgs);
1078 }
1079 
1080 Decl *TemplateInstantiator::TransformDefinition(SourceLocation Loc, Decl *D) {
1081  Decl *Inst = getSema().SubstDecl(D, getSema().CurContext, TemplateArgs);
1082  if (!Inst)
1083  return nullptr;
1084 
1085  getSema().CurrentInstantiationScope->InstantiatedLocal(D, Inst);
1086  return Inst;
1087 }
1088 
1089 NamedDecl *
1090 TemplateInstantiator::TransformFirstQualifierInScope(NamedDecl *D,
1091  SourceLocation Loc) {
1092  // If the first part of the nested-name-specifier was a template type
1093  // parameter, instantiate that type parameter down to a tag type.
1094  if (TemplateTypeParmDecl *TTPD = dyn_cast_or_null<TemplateTypeParmDecl>(D)) {
1095  const TemplateTypeParmType *TTP
1096  = cast<TemplateTypeParmType>(getSema().Context.getTypeDeclType(TTPD));
1097 
1098  if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1099  // FIXME: This needs testing w/ member access expressions.
1100  TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getIndex());
1101 
1102  if (TTP->isParameterPack()) {
1103  assert(Arg.getKind() == TemplateArgument::Pack &&
1104  "Missing argument pack");
1105 
1106  if (getSema().ArgumentPackSubstitutionIndex == -1)
1107  return nullptr;
1108 
1109  Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1110  }
1111 
1112  QualType T = Arg.getAsType();
1113  if (T.isNull())
1114  return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
1115 
1116  if (const TagType *Tag = T->getAs<TagType>())
1117  return Tag->getDecl();
1118 
1119  // The resulting type is not a tag; complain.
1120  getSema().Diag(Loc, diag::err_nested_name_spec_non_tag) << T;
1121  return nullptr;
1122  }
1123  }
1124 
1125  return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
1126 }
1127 
1128 VarDecl *
1129 TemplateInstantiator::RebuildExceptionDecl(VarDecl *ExceptionDecl,
1131  SourceLocation StartLoc,
1132  SourceLocation NameLoc,
1133  IdentifierInfo *Name) {
1134  VarDecl *Var = inherited::RebuildExceptionDecl(ExceptionDecl, Declarator,
1135  StartLoc, NameLoc, Name);
1136  if (Var)
1137  getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
1138  return Var;
1139 }
1140 
1141 VarDecl *TemplateInstantiator::RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
1142  TypeSourceInfo *TSInfo,
1143  QualType T) {
1144  VarDecl *Var = inherited::RebuildObjCExceptionDecl(ExceptionDecl, TSInfo, T);
1145  if (Var)
1146  getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
1147  return Var;
1148 }
1149 
1150 QualType
1151 TemplateInstantiator::RebuildElaboratedType(SourceLocation KeywordLoc,
1152  ElaboratedTypeKeyword Keyword,
1153  NestedNameSpecifierLoc QualifierLoc,
1154  QualType T) {
1155  if (const TagType *TT = T->getAs<TagType>()) {
1156  TagDecl* TD = TT->getDecl();
1157 
1158  SourceLocation TagLocation = KeywordLoc;
1159 
1160  IdentifierInfo *Id = TD->getIdentifier();
1161 
1162  // TODO: should we even warn on struct/class mismatches for this? Seems
1163  // like it's likely to produce a lot of spurious errors.
1164  if (Id && Keyword != ETK_None && Keyword != ETK_Typename) {
1166  if (!SemaRef.isAcceptableTagRedeclaration(TD, Kind, /*isDefinition*/false,
1167  TagLocation, Id)) {
1168  SemaRef.Diag(TagLocation, diag::err_use_with_wrong_tag)
1169  << Id
1170  << FixItHint::CreateReplacement(SourceRange(TagLocation),
1171  TD->getKindName());
1172  SemaRef.Diag(TD->getLocation(), diag::note_previous_use);
1173  }
1174  }
1175  }
1176 
1178  Keyword,
1179  QualifierLoc,
1180  T);
1181 }
1182 
1183 TemplateName TemplateInstantiator::TransformTemplateName(
1184  CXXScopeSpec &SS, TemplateName Name, SourceLocation NameLoc,
1185  QualType ObjectType, NamedDecl *FirstQualifierInScope,
1186  bool AllowInjectedClassName) {
1187  if (TemplateTemplateParmDecl *TTP
1188  = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl())) {
1189  if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1190  // If the corresponding template argument is NULL or non-existent, it's
1191  // because we are performing instantiation from explicitly-specified
1192  // template arguments in a function template, but there were some
1193  // arguments left unspecified.
1194  if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
1195  TTP->getPosition()))
1196  return Name;
1197 
1198  TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
1199 
1200  if (TTP->isParameterPack()) {
1201  assert(Arg.getKind() == TemplateArgument::Pack &&
1202  "Missing argument pack");
1203 
1204  if (getSema().ArgumentPackSubstitutionIndex == -1) {
1205  // We have the template argument pack to substitute, but we're not
1206  // actually expanding the enclosing pack expansion yet. So, just
1207  // keep the entire argument pack.
1208  return getSema().Context.getSubstTemplateTemplateParmPack(TTP, Arg);
1209  }
1210 
1211  Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1212  }
1213 
1214  TemplateName Template = Arg.getAsTemplate().getNameToSubstitute();
1215  assert(!Template.isNull() && "Null template template argument");
1216  assert(!Template.getAsQualifiedTemplateName() &&
1217  "template decl to substitute is qualified?");
1218 
1219  Template = getSema().Context.getSubstTemplateTemplateParm(TTP, Template);
1220  return Template;
1221  }
1222  }
1223 
1226  if (getSema().ArgumentPackSubstitutionIndex == -1)
1227  return Name;
1228 
1229  TemplateArgument Arg = SubstPack->getArgumentPack();
1230  Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1231  return Arg.getAsTemplate().getNameToSubstitute();
1232  }
1233 
1234  return inherited::TransformTemplateName(SS, Name, NameLoc, ObjectType,
1235  FirstQualifierInScope,
1236  AllowInjectedClassName);
1237 }
1238 
1239 ExprResult
1240 TemplateInstantiator::TransformPredefinedExpr(PredefinedExpr *E) {
1241  if (!E->isTypeDependent())
1242  return E;
1243 
1244  return getSema().BuildPredefinedExpr(E->getLocation(), E->getIdentKind());
1245 }
1246 
1247 ExprResult
1248 TemplateInstantiator::TransformTemplateParmRefExpr(DeclRefExpr *E,
1249  NonTypeTemplateParmDecl *NTTP) {
1250  // If the corresponding template argument is NULL or non-existent, it's
1251  // because we are performing instantiation from explicitly-specified
1252  // template arguments in a function template, but there were some
1253  // arguments left unspecified.
1254  if (!TemplateArgs.hasTemplateArgument(NTTP->getDepth(),
1255  NTTP->getPosition()))
1256  return E;
1257 
1258  TemplateArgument Arg = TemplateArgs(NTTP->getDepth(), NTTP->getPosition());
1259 
1260  if (TemplateArgs.getNumLevels() != TemplateArgs.getNumSubstitutedLevels()) {
1261  // We're performing a partial substitution, so the substituted argument
1262  // could be dependent. As a result we can't create a SubstNonType*Expr
1263  // node now, since that represents a fully-substituted argument.
1264  // FIXME: We should have some AST representation for this.
1265  if (Arg.getKind() == TemplateArgument::Pack) {
1266  // FIXME: This won't work for alias templates.
1267  assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() &&
1268  "unexpected pack arguments in partial substitution");
1269  Arg = Arg.pack_begin()->getPackExpansionPattern();
1270  }
1271  assert(Arg.getKind() == TemplateArgument::Expression &&
1272  "unexpected nontype template argument kind in partial substitution");
1273  return Arg.getAsExpr();
1274  }
1275 
1276  if (NTTP->isParameterPack()) {
1277  assert(Arg.getKind() == TemplateArgument::Pack &&
1278  "Missing argument pack");
1279 
1280  if (getSema().ArgumentPackSubstitutionIndex == -1) {
1281  // We have an argument pack, but we can't select a particular argument
1282  // out of it yet. Therefore, we'll build an expression to hold on to that
1283  // argument pack.
1284  QualType TargetType = SemaRef.SubstType(NTTP->getType(), TemplateArgs,
1285  E->getLocation(),
1286  NTTP->getDeclName());
1287  if (TargetType.isNull())
1288  return ExprError();
1289 
1290  return new (SemaRef.Context) SubstNonTypeTemplateParmPackExpr(
1291  TargetType.getNonLValueExprType(SemaRef.Context),
1292  TargetType->isReferenceType() ? VK_LValue : VK_RValue, NTTP,
1293  E->getLocation(), Arg);
1294  }
1295 
1296  Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1297  }
1298 
1299  return transformNonTypeTemplateParmRef(NTTP, E->getLocation(), Arg);
1300 }
1301 
1302 const LoopHintAttr *
1303 TemplateInstantiator::TransformLoopHintAttr(const LoopHintAttr *LH) {
1304  Expr *TransformedExpr = getDerived().TransformExpr(LH->getValue()).get();
1305 
1306  if (TransformedExpr == LH->getValue())
1307  return LH;
1308 
1309  // Generate error if there is a problem with the value.
1310  if (getSema().CheckLoopHintExpr(TransformedExpr, LH->getLocation()))
1311  return LH;
1312 
1313  // Create new LoopHintValueAttr with integral expression in place of the
1314  // non-type template parameter.
1315  return LoopHintAttr::CreateImplicit(getSema().Context, LH->getOption(),
1316  LH->getState(), TransformedExpr, *LH);
1317 }
1318 
1319 ExprResult TemplateInstantiator::transformNonTypeTemplateParmRef(
1321  SourceLocation loc,
1322  TemplateArgument arg) {
1323  ExprResult result;
1324  QualType type;
1325 
1326  // The template argument itself might be an expression, in which
1327  // case we just return that expression.
1328  if (arg.getKind() == TemplateArgument::Expression) {
1329  Expr *argExpr = arg.getAsExpr();
1330  result = argExpr;
1331  type = argExpr->getType();
1332 
1333  } else if (arg.getKind() == TemplateArgument::Declaration ||
1335  ValueDecl *VD;
1336  if (arg.getKind() == TemplateArgument::Declaration) {
1337  VD = arg.getAsDecl();
1338 
1339  // Find the instantiation of the template argument. This is
1340  // required for nested templates.
1341  VD = cast_or_null<ValueDecl>(
1342  getSema().FindInstantiatedDecl(loc, VD, TemplateArgs));
1343  if (!VD)
1344  return ExprError();
1345  } else {
1346  // Propagate NULL template argument.
1347  VD = nullptr;
1348  }
1349 
1350  // Derive the type we want the substituted decl to have. This had
1351  // better be non-dependent, or these checks will have serious problems.
1352  if (parm->isExpandedParameterPack()) {
1353  type = parm->getExpansionType(SemaRef.ArgumentPackSubstitutionIndex);
1354  } else if (parm->isParameterPack() &&
1355  isa<PackExpansionType>(parm->getType())) {
1356  type = SemaRef.SubstType(
1357  cast<PackExpansionType>(parm->getType())->getPattern(),
1358  TemplateArgs, loc, parm->getDeclName());
1359  } else {
1360  type = SemaRef.SubstType(VD ? arg.getParamTypeForDecl() : arg.getNullPtrType(),
1361  TemplateArgs, loc, parm->getDeclName());
1362  }
1363  assert(!type.isNull() && "type substitution failed for param type");
1364  assert(!type->isDependentType() && "param type still dependent");
1365  result = SemaRef.BuildExpressionFromDeclTemplateArgument(arg, type, loc);
1366 
1367  if (!result.isInvalid()) type = result.get()->getType();
1368  } else {
1369  result = SemaRef.BuildExpressionFromIntegralTemplateArgument(arg, loc);
1370 
1371  // Note that this type can be different from the type of 'result',
1372  // e.g. if it's an enum type.
1373  type = arg.getIntegralType();
1374  }
1375  if (result.isInvalid()) return ExprError();
1376 
1377  Expr *resultExpr = result.get();
1378  return new (SemaRef.Context) SubstNonTypeTemplateParmExpr(
1379  type, resultExpr->getValueKind(), loc, parm, resultExpr);
1380 }
1381 
1382 ExprResult
1383 TemplateInstantiator::TransformSubstNonTypeTemplateParmPackExpr(
1385  if (getSema().ArgumentPackSubstitutionIndex == -1) {
1386  // We aren't expanding the parameter pack, so just return ourselves.
1387  return E;
1388  }
1389 
1390  TemplateArgument Arg = E->getArgumentPack();
1391  Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1392  return transformNonTypeTemplateParmRef(E->getParameterPack(),
1394  Arg);
1395 }
1396 
1397 ExprResult TemplateInstantiator::RebuildVarDeclRefExpr(VarDecl *PD,
1398  SourceLocation Loc) {
1399  DeclarationNameInfo NameInfo(PD->getDeclName(), Loc);
1400  return getSema().BuildDeclarationNameExpr(CXXScopeSpec(), NameInfo, PD);
1401 }
1402 
1403 ExprResult
1404 TemplateInstantiator::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {
1405  if (getSema().ArgumentPackSubstitutionIndex != -1) {
1406  // We can expand this parameter pack now.
1408  VarDecl *VD = cast_or_null<VarDecl>(TransformDecl(E->getExprLoc(), D));
1409  if (!VD)
1410  return ExprError();
1411  return RebuildVarDeclRefExpr(VD, E->getExprLoc());
1412  }
1413 
1414  QualType T = TransformType(E->getType());
1415  if (T.isNull())
1416  return ExprError();
1417 
1418  // Transform each of the parameter expansions into the corresponding
1419  // parameters in the instantiation of the function decl.
1421  Vars.reserve(E->getNumExpansions());
1422  for (FunctionParmPackExpr::iterator I = E->begin(), End = E->end();
1423  I != End; ++I) {
1424  VarDecl *D = cast_or_null<VarDecl>(TransformDecl(E->getExprLoc(), *I));
1425  if (!D)
1426  return ExprError();
1427  Vars.push_back(D);
1428  }
1429 
1430  auto *PackExpr =
1432  E->getParameterPackLocation(), Vars);
1433  getSema().MarkFunctionParmPackReferenced(PackExpr);
1434  return PackExpr;
1435 }
1436 
1437 ExprResult
1438 TemplateInstantiator::TransformFunctionParmPackRefExpr(DeclRefExpr *E,
1439  VarDecl *PD) {
1440  typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
1441  llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
1442  = getSema().CurrentInstantiationScope->findInstantiationOf(PD);
1443  assert(Found && "no instantiation for parameter pack");
1444 
1445  Decl *TransformedDecl;
1446  if (DeclArgumentPack *Pack = Found->dyn_cast<DeclArgumentPack *>()) {
1447  // If this is a reference to a function parameter pack which we can
1448  // substitute but can't yet expand, build a FunctionParmPackExpr for it.
1449  if (getSema().ArgumentPackSubstitutionIndex == -1) {
1450  QualType T = TransformType(E->getType());
1451  if (T.isNull())
1452  return ExprError();
1453  auto *PackExpr = FunctionParmPackExpr::Create(getSema().Context, T, PD,
1454  E->getExprLoc(), *Pack);
1455  getSema().MarkFunctionParmPackReferenced(PackExpr);
1456  return PackExpr;
1457  }
1458 
1459  TransformedDecl = (*Pack)[getSema().ArgumentPackSubstitutionIndex];
1460  } else {
1461  TransformedDecl = Found->get<Decl*>();
1462  }
1463 
1464  // We have either an unexpanded pack or a specific expansion.
1465  return RebuildVarDeclRefExpr(cast<VarDecl>(TransformedDecl), E->getExprLoc());
1466 }
1467 
1468 ExprResult
1469 TemplateInstantiator::TransformDeclRefExpr(DeclRefExpr *E) {
1470  NamedDecl *D = E->getDecl();
1471 
1472  // Handle references to non-type template parameters and non-type template
1473  // parameter packs.
1474  if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) {
1475  if (NTTP->getDepth() < TemplateArgs.getNumLevels())
1476  return TransformTemplateParmRefExpr(E, NTTP);
1477 
1478  // We have a non-type template parameter that isn't fully substituted;
1479  // FindInstantiatedDecl will find it in the local instantiation scope.
1480  }
1481 
1482  // Handle references to function parameter packs.
1483  if (VarDecl *PD = dyn_cast<VarDecl>(D))
1484  if (PD->isParameterPack())
1485  return TransformFunctionParmPackRefExpr(E, PD);
1486 
1488 }
1489 
1490 ExprResult TemplateInstantiator::TransformCXXDefaultArgExpr(
1491  CXXDefaultArgExpr *E) {
1492  assert(!cast<FunctionDecl>(E->getParam()->getDeclContext())->
1493  getDescribedFunctionTemplate() &&
1494  "Default arg expressions are never formed in dependent cases.");
1495  return SemaRef.BuildCXXDefaultArgExpr(E->getUsedLocation(),
1496  cast<FunctionDecl>(E->getParam()->getDeclContext()),
1497  E->getParam());
1498 }
1499 
1500 template<typename Fn>
1501 QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB,
1503  CXXRecordDecl *ThisContext,
1504  Qualifiers ThisTypeQuals,
1505  Fn TransformExceptionSpec) {
1506  // We need a local instantiation scope for this function prototype.
1507  LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
1508  return inherited::TransformFunctionProtoType(
1509  TLB, TL, ThisContext, ThisTypeQuals, TransformExceptionSpec);
1510 }
1511 
1512 ParmVarDecl *
1513 TemplateInstantiator::TransformFunctionTypeParam(ParmVarDecl *OldParm,
1514  int indexAdjustment,
1515  Optional<unsigned> NumExpansions,
1516  bool ExpectParameterPack) {
1517  return SemaRef.SubstParmVarDecl(OldParm, TemplateArgs, indexAdjustment,
1518  NumExpansions, ExpectParameterPack);
1519 }
1520 
1521 QualType
1522 TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB,
1524  const TemplateTypeParmType *T = TL.getTypePtr();
1525  if (T->getDepth() < TemplateArgs.getNumLevels()) {
1526  // Replace the template type parameter with its corresponding
1527  // template argument.
1528 
1529  // If the corresponding template argument is NULL or doesn't exist, it's
1530  // because we are performing instantiation from explicitly-specified
1531  // template arguments in a function template class, but there were some
1532  // arguments left unspecified.
1533  if (!TemplateArgs.hasTemplateArgument(T->getDepth(), T->getIndex())) {
1535  = TLB.push<TemplateTypeParmTypeLoc>(TL.getType());
1536  NewTL.setNameLoc(TL.getNameLoc());
1537  return TL.getType();
1538  }
1539 
1540  TemplateArgument Arg = TemplateArgs(T->getDepth(), T->getIndex());
1541 
1542  if (T->isParameterPack()) {
1543  assert(Arg.getKind() == TemplateArgument::Pack &&
1544  "Missing argument pack");
1545 
1546  if (getSema().ArgumentPackSubstitutionIndex == -1) {
1547  // We have the template argument pack, but we're not expanding the
1548  // enclosing pack expansion yet. Just save the template argument
1549  // pack for later substitution.
1551  = getSema().Context.getSubstTemplateTypeParmPackType(T, Arg);
1554  NewTL.setNameLoc(TL.getNameLoc());
1555  return Result;
1556  }
1557 
1558  Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1559  }
1560 
1561  assert(Arg.getKind() == TemplateArgument::Type &&
1562  "Template argument kind mismatch");
1563 
1564  QualType Replacement = Arg.getAsType();
1565 
1566  // TODO: only do this uniquing once, at the start of instantiation.
1568  = getSema().Context.getSubstTemplateTypeParmType(T, Replacement);
1571  NewTL.setNameLoc(TL.getNameLoc());
1572  return Result;
1573  }
1574 
1575  // The template type parameter comes from an inner template (e.g.,
1576  // the template parameter list of a member template inside the
1577  // template we are instantiating). Create a new template type
1578  // parameter with the template "level" reduced by one.
1579  TemplateTypeParmDecl *NewTTPDecl = nullptr;
1580  if (TemplateTypeParmDecl *OldTTPDecl = T->getDecl())
1581  NewTTPDecl = cast_or_null<TemplateTypeParmDecl>(
1582  TransformDecl(TL.getNameLoc(), OldTTPDecl));
1583 
1584  QualType Result = getSema().Context.getTemplateTypeParmType(
1585  T->getDepth() - TemplateArgs.getNumSubstitutedLevels(), T->getIndex(),
1586  T->isParameterPack(), NewTTPDecl);
1588  NewTL.setNameLoc(TL.getNameLoc());
1589  return Result;
1590 }
1591 
1592 QualType
1593 TemplateInstantiator::TransformSubstTemplateTypeParmPackType(
1594  TypeLocBuilder &TLB,
1596  if (getSema().ArgumentPackSubstitutionIndex == -1) {
1597  // We aren't expanding the parameter pack, so just return ourselves.
1600  NewTL.setNameLoc(TL.getNameLoc());
1601  return TL.getType();
1602  }
1603 
1605  Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1606  QualType Result = Arg.getAsType();
1607 
1608  Result = getSema().Context.getSubstTemplateTypeParmType(
1610  Result);
1613  NewTL.setNameLoc(TL.getNameLoc());
1614  return Result;
1615 }
1616 
1617 /// Perform substitution on the type T with a given set of template
1618 /// arguments.
1619 ///
1620 /// This routine substitutes the given template arguments into the
1621 /// type T and produces the instantiated type.
1622 ///
1623 /// \param T the type into which the template arguments will be
1624 /// substituted. If this type is not dependent, it will be returned
1625 /// immediately.
1626 ///
1627 /// \param Args the template arguments that will be
1628 /// substituted for the top-level template parameters within T.
1629 ///
1630 /// \param Loc the location in the source code where this substitution
1631 /// is being performed. It will typically be the location of the
1632 /// declarator (if we're instantiating the type of some declaration)
1633 /// or the location of the type in the source code (if, e.g., we're
1634 /// instantiating the type of a cast expression).
1635 ///
1636 /// \param Entity the name of the entity associated with a declaration
1637 /// being instantiated (if any). May be empty to indicate that there
1638 /// is no such entity (if, e.g., this is a type that occurs as part of
1639 /// a cast expression) or that the entity has no name (e.g., an
1640 /// unnamed function parameter).
1641 ///
1642 /// \param AllowDeducedTST Whether a DeducedTemplateSpecializationType is
1643 /// acceptable as the top level type of the result.
1644 ///
1645 /// \returns If the instantiation succeeds, the instantiated
1646 /// type. Otherwise, produces diagnostics and returns a NULL type.
1648  const MultiLevelTemplateArgumentList &Args,
1649  SourceLocation Loc,
1650  DeclarationName Entity,
1651  bool AllowDeducedTST) {
1652  assert(!CodeSynthesisContexts.empty() &&
1653  "Cannot perform an instantiation without some context on the "
1654  "instantiation stack");
1655 
1656  if (!T->getType()->isInstantiationDependentType() &&
1658  return T;
1659 
1660  TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1661  return AllowDeducedTST ? Instantiator.TransformTypeWithDeducedTST(T)
1662  : Instantiator.TransformType(T);
1663 }
1664 
1666  const MultiLevelTemplateArgumentList &Args,
1667  SourceLocation Loc,
1668  DeclarationName Entity) {
1669  assert(!CodeSynthesisContexts.empty() &&
1670  "Cannot perform an instantiation without some context on the "
1671  "instantiation stack");
1672 
1673  if (TL.getType().isNull())
1674  return nullptr;
1675 
1676  if (!TL.getType()->isInstantiationDependentType() &&
1677  !TL.getType()->isVariablyModifiedType()) {
1678  // FIXME: Make a copy of the TypeLoc data here, so that we can
1679  // return a new TypeSourceInfo. Inefficient!
1680  TypeLocBuilder TLB;
1681  TLB.pushFullCopy(TL);
1682  return TLB.getTypeSourceInfo(Context, TL.getType());
1683  }
1684 
1685  TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1686  TypeLocBuilder TLB;
1687  TLB.reserve(TL.getFullDataSize());
1688  QualType Result = Instantiator.TransformType(TLB, TL);
1689  if (Result.isNull())
1690  return nullptr;
1691 
1692  return TLB.getTypeSourceInfo(Context, Result);
1693 }
1694 
1695 /// Deprecated form of the above.
1697  const MultiLevelTemplateArgumentList &TemplateArgs,
1698  SourceLocation Loc, DeclarationName Entity) {
1699  assert(!CodeSynthesisContexts.empty() &&
1700  "Cannot perform an instantiation without some context on the "
1701  "instantiation stack");
1702 
1703  // If T is not a dependent type or a variably-modified type, there
1704  // is nothing to do.
1706  return T;
1707 
1708  TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity);
1709  return Instantiator.TransformType(T);
1710 }
1711 
1713  if (T->getType()->isInstantiationDependentType() ||
1715  return true;
1716 
1717  TypeLoc TL = T->getTypeLoc().IgnoreParens();
1718  if (!TL.getAs<FunctionProtoTypeLoc>())
1719  return false;
1720 
1722  for (ParmVarDecl *P : FP.getParams()) {
1723  // This must be synthesized from a typedef.
1724  if (!P) continue;
1725 
1726  // If there are any parameters, a new TypeSourceInfo that refers to the
1727  // instantiated parameters must be built.
1728  return true;
1729  }
1730 
1731  return false;
1732 }
1733 
1734 /// A form of SubstType intended specifically for instantiating the
1735 /// type of a FunctionDecl. Its purpose is solely to force the
1736 /// instantiation of default-argument expressions and to avoid
1737 /// instantiating an exception-specification.
1739  const MultiLevelTemplateArgumentList &Args,
1740  SourceLocation Loc,
1741  DeclarationName Entity,
1742  CXXRecordDecl *ThisContext,
1743  Qualifiers ThisTypeQuals) {
1744  assert(!CodeSynthesisContexts.empty() &&
1745  "Cannot perform an instantiation without some context on the "
1746  "instantiation stack");
1747 
1749  return T;
1750 
1751  TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1752 
1753  TypeLocBuilder TLB;
1754 
1755  TypeLoc TL = T->getTypeLoc();
1756  TLB.reserve(TL.getFullDataSize());
1757 
1758  QualType Result;
1759 
1760  if (FunctionProtoTypeLoc Proto =
1762  // Instantiate the type, other than its exception specification. The
1763  // exception specification is instantiated in InitFunctionInstantiation
1764  // once we've built the FunctionDecl.
1765  // FIXME: Set the exception specification to EST_Uninstantiated here,
1766  // instead of rebuilding the function type again later.
1767  Result = Instantiator.TransformFunctionProtoType(
1768  TLB, Proto, ThisContext, ThisTypeQuals,
1770  bool &Changed) { return false; });
1771  } else {
1772  Result = Instantiator.TransformType(TLB, TL);
1773  }
1774  if (Result.isNull())
1775  return nullptr;
1776 
1777  return TLB.getTypeSourceInfo(Context, Result);
1778 }
1779 
1782  SmallVectorImpl<QualType> &ExceptionStorage,
1783  const MultiLevelTemplateArgumentList &Args) {
1784  assert(ESI.Type != EST_Uninstantiated);
1785 
1786  bool Changed = false;
1787  TemplateInstantiator Instantiator(*this, Args, Loc, DeclarationName());
1788  return Instantiator.TransformExceptionSpec(Loc, ESI, ExceptionStorage,
1789  Changed);
1790 }
1791 
1793  const MultiLevelTemplateArgumentList &Args) {
1795  Proto->getExtProtoInfo().ExceptionSpec;
1796 
1797  SmallVector<QualType, 4> ExceptionStorage;
1799  ESI, ExceptionStorage, Args))
1800  // On error, recover by dropping the exception specification.
1801  ESI.Type = EST_None;
1802 
1803  UpdateExceptionSpec(New, ESI);
1804 }
1805 
1807  const MultiLevelTemplateArgumentList &TemplateArgs,
1808  int indexAdjustment,
1809  Optional<unsigned> NumExpansions,
1810  bool ExpectParameterPack) {
1811  TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
1812  TypeSourceInfo *NewDI = nullptr;
1813 
1814  TypeLoc OldTL = OldDI->getTypeLoc();
1815  if (PackExpansionTypeLoc ExpansionTL = OldTL.getAs<PackExpansionTypeLoc>()) {
1816 
1817  // We have a function parameter pack. Substitute into the pattern of the
1818  // expansion.
1819  NewDI = SubstType(ExpansionTL.getPatternLoc(), TemplateArgs,
1820  OldParm->getLocation(), OldParm->getDeclName());
1821  if (!NewDI)
1822  return nullptr;
1823 
1824  if (NewDI->getType()->containsUnexpandedParameterPack()) {
1825  // We still have unexpanded parameter packs, which means that
1826  // our function parameter is still a function parameter pack.
1827  // Therefore, make its type a pack expansion type.
1828  NewDI = CheckPackExpansion(NewDI, ExpansionTL.getEllipsisLoc(),
1829  NumExpansions);
1830  } else if (ExpectParameterPack) {
1831  // We expected to get a parameter pack but didn't (because the type
1832  // itself is not a pack expansion type), so complain. This can occur when
1833  // the substitution goes through an alias template that "loses" the
1834  // pack expansion.
1835  Diag(OldParm->getLocation(),
1836  diag::err_function_parameter_pack_without_parameter_packs)
1837  << NewDI->getType();
1838  return nullptr;
1839  }
1840  } else {
1841  NewDI = SubstType(OldDI, TemplateArgs, OldParm->getLocation(),
1842  OldParm->getDeclName());
1843  }
1844 
1845  if (!NewDI)
1846  return nullptr;
1847 
1848  if (NewDI->getType()->isVoidType()) {
1849  Diag(OldParm->getLocation(), diag::err_param_with_void_type);
1850  return nullptr;
1851  }
1852 
1854  OldParm->getInnerLocStart(),
1855  OldParm->getLocation(),
1856  OldParm->getIdentifier(),
1857  NewDI->getType(), NewDI,
1858  OldParm->getStorageClass());
1859  if (!NewParm)
1860  return nullptr;
1861 
1862  // Mark the (new) default argument as uninstantiated (if any).
1863  if (OldParm->hasUninstantiatedDefaultArg()) {
1864  Expr *Arg = OldParm->getUninstantiatedDefaultArg();
1865  NewParm->setUninstantiatedDefaultArg(Arg);
1866  } else if (OldParm->hasUnparsedDefaultArg()) {
1867  NewParm->setUnparsedDefaultArg();
1868  UnparsedDefaultArgInstantiations[OldParm].push_back(NewParm);
1869  } else if (Expr *Arg = OldParm->getDefaultArg()) {
1870  FunctionDecl *OwningFunc = cast<FunctionDecl>(OldParm->getDeclContext());
1871  if (OwningFunc->isLexicallyWithinFunctionOrMethod()) {
1872  // Instantiate default arguments for methods of local classes (DR1484)
1873  // and non-defining declarations.
1874  Sema::ContextRAII SavedContext(*this, OwningFunc);
1875  LocalInstantiationScope Local(*this, true);
1876  ExprResult NewArg = SubstExpr(Arg, TemplateArgs);
1877  if (NewArg.isUsable()) {
1878  // It would be nice if we still had this.
1879  SourceLocation EqualLoc = NewArg.get()->getBeginLoc();
1880  SetParamDefaultArgument(NewParm, NewArg.get(), EqualLoc);
1881  }
1882  } else {
1883  // FIXME: if we non-lazily instantiated non-dependent default args for
1884  // non-dependent parameter types we could remove a bunch of duplicate
1885  // conversion warnings for such arguments.
1886  NewParm->setUninstantiatedDefaultArg(Arg);
1887  }
1888  }
1889 
1891 
1892  if (OldParm->isParameterPack() && !NewParm->isParameterPack()) {
1893  // Add the new parameter to the instantiated parameter pack.
1895  } else {
1896  // Introduce an Old -> New mapping
1897  CurrentInstantiationScope->InstantiatedLocal(OldParm, NewParm);
1898  }
1899 
1900  // FIXME: OldParm may come from a FunctionProtoType, in which case CurContext
1901  // can be anything, is this right ?
1902  NewParm->setDeclContext(CurContext);
1903 
1904  NewParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
1905  OldParm->getFunctionScopeIndex() + indexAdjustment);
1906 
1907  InstantiateAttrs(TemplateArgs, OldParm, NewParm);
1908 
1909  return NewParm;
1910 }
1911 
1912 /// Substitute the given template arguments into the given set of
1913 /// parameters, producing the set of parameter types that would be generated
1914 /// from such a substitution.
1917  const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
1918  const MultiLevelTemplateArgumentList &TemplateArgs,
1919  SmallVectorImpl<QualType> &ParamTypes,
1920  SmallVectorImpl<ParmVarDecl *> *OutParams,
1921  ExtParameterInfoBuilder &ParamInfos) {
1922  assert(!CodeSynthesisContexts.empty() &&
1923  "Cannot perform an instantiation without some context on the "
1924  "instantiation stack");
1925 
1926  TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
1927  DeclarationName());
1928  return Instantiator.TransformFunctionTypeParams(
1929  Loc, Params, nullptr, ExtParamInfos, ParamTypes, OutParams, ParamInfos);
1930 }
1931 
1932 /// Perform substitution on the base class specifiers of the
1933 /// given class template specialization.
1934 ///
1935 /// Produces a diagnostic and returns true on error, returns false and
1936 /// attaches the instantiated base classes to the class template
1937 /// specialization if successful.
1938 bool
1940  CXXRecordDecl *Pattern,
1941  const MultiLevelTemplateArgumentList &TemplateArgs) {
1942  bool Invalid = false;
1943  SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases;
1944  for (const auto &Base : Pattern->bases()) {
1945  if (!Base.getType()->isDependentType()) {
1946  if (const CXXRecordDecl *RD = Base.getType()->getAsCXXRecordDecl()) {
1947  if (RD->isInvalidDecl())
1948  Instantiation->setInvalidDecl();
1949  }
1950  InstantiatedBases.push_back(new (Context) CXXBaseSpecifier(Base));
1951  continue;
1952  }
1953 
1954  SourceLocation EllipsisLoc;
1955  TypeSourceInfo *BaseTypeLoc;
1956  if (Base.isPackExpansion()) {
1957  // This is a pack expansion. See whether we should expand it now, or
1958  // wait until later.
1960  collectUnexpandedParameterPacks(Base.getTypeSourceInfo()->getTypeLoc(),
1961  Unexpanded);
1962  bool ShouldExpand = false;
1963  bool RetainExpansion = false;
1964  Optional<unsigned> NumExpansions;
1965  if (CheckParameterPacksForExpansion(Base.getEllipsisLoc(),
1966  Base.getSourceRange(),
1967  Unexpanded,
1968  TemplateArgs, ShouldExpand,
1969  RetainExpansion,
1970  NumExpansions)) {
1971  Invalid = true;
1972  continue;
1973  }
1974 
1975  // If we should expand this pack expansion now, do so.
1976  if (ShouldExpand) {
1977  for (unsigned I = 0; I != *NumExpansions; ++I) {
1978  Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
1979 
1980  TypeSourceInfo *BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
1981  TemplateArgs,
1982  Base.getSourceRange().getBegin(),
1983  DeclarationName());
1984  if (!BaseTypeLoc) {
1985  Invalid = true;
1986  continue;
1987  }
1988 
1989  if (CXXBaseSpecifier *InstantiatedBase
1990  = CheckBaseSpecifier(Instantiation,
1991  Base.getSourceRange(),
1992  Base.isVirtual(),
1993  Base.getAccessSpecifierAsWritten(),
1994  BaseTypeLoc,
1995  SourceLocation()))
1996  InstantiatedBases.push_back(InstantiatedBase);
1997  else
1998  Invalid = true;
1999  }
2000 
2001  continue;
2002  }
2003 
2004  // The resulting base specifier will (still) be a pack expansion.
2005  EllipsisLoc = Base.getEllipsisLoc();
2006  Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
2007  BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
2008  TemplateArgs,
2009  Base.getSourceRange().getBegin(),
2010  DeclarationName());
2011  } else {
2012  BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
2013  TemplateArgs,
2014  Base.getSourceRange().getBegin(),
2015  DeclarationName());
2016  }
2017 
2018  if (!BaseTypeLoc) {
2019  Invalid = true;
2020  continue;
2021  }
2022 
2023  if (CXXBaseSpecifier *InstantiatedBase
2024  = CheckBaseSpecifier(Instantiation,
2025  Base.getSourceRange(),
2026  Base.isVirtual(),
2027  Base.getAccessSpecifierAsWritten(),
2028  BaseTypeLoc,
2029  EllipsisLoc))
2030  InstantiatedBases.push_back(InstantiatedBase);
2031  else
2032  Invalid = true;
2033  }
2034 
2035  if (!Invalid && AttachBaseSpecifiers(Instantiation, InstantiatedBases))
2036  Invalid = true;
2037 
2038  return Invalid;
2039 }
2040 
2041 // Defined via #include from SemaTemplateInstantiateDecl.cpp
2042 namespace clang {
2043  namespace sema {
2045  const MultiLevelTemplateArgumentList &TemplateArgs);
2047  const Attr *At, ASTContext &C, Sema &S,
2048  const MultiLevelTemplateArgumentList &TemplateArgs);
2049  }
2050 }
2051 
2052 /// Instantiate the definition of a class from a given pattern.
2053 ///
2054 /// \param PointOfInstantiation The point of instantiation within the
2055 /// source code.
2056 ///
2057 /// \param Instantiation is the declaration whose definition is being
2058 /// instantiated. This will be either a class template specialization
2059 /// or a member class of a class template specialization.
2060 ///
2061 /// \param Pattern is the pattern from which the instantiation
2062 /// occurs. This will be either the declaration of a class template or
2063 /// the declaration of a member class of a class template.
2064 ///
2065 /// \param TemplateArgs The template arguments to be substituted into
2066 /// the pattern.
2067 ///
2068 /// \param TSK the kind of implicit or explicit instantiation to perform.
2069 ///
2070 /// \param Complain whether to complain if the class cannot be instantiated due
2071 /// to the lack of a definition.
2072 ///
2073 /// \returns true if an error occurred, false otherwise.
2074 bool
2076  CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
2077  const MultiLevelTemplateArgumentList &TemplateArgs,
2079  bool Complain) {
2080  CXXRecordDecl *PatternDef
2081  = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
2082  if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
2083  Instantiation->getInstantiatedFromMemberClass(),
2084  Pattern, PatternDef, TSK, Complain))
2085  return true;
2086 
2087  llvm::TimeTraceScope TimeScope("InstantiateClass", [&]() {
2088  std::string Name;
2089  llvm::raw_string_ostream OS(Name);
2090  Instantiation->getNameForDiagnostic(OS, getPrintingPolicy(),
2091  /*Qualified=*/true);
2092  return Name;
2093  });
2094 
2095  Pattern = PatternDef;
2096 
2097  // Record the point of instantiation.
2098  if (MemberSpecializationInfo *MSInfo
2099  = Instantiation->getMemberSpecializationInfo()) {
2100  MSInfo->setTemplateSpecializationKind(TSK);
2101  MSInfo->setPointOfInstantiation(PointOfInstantiation);
2102  } else if (ClassTemplateSpecializationDecl *Spec
2103  = dyn_cast<ClassTemplateSpecializationDecl>(Instantiation)) {
2104  Spec->setTemplateSpecializationKind(TSK);
2105  Spec->setPointOfInstantiation(PointOfInstantiation);
2106  }
2107 
2108  InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
2109  if (Inst.isInvalid())
2110  return true;
2111  assert(!Inst.isAlreadyInstantiating() && "should have been caught by caller");
2112  PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
2113  "instantiating class definition");
2114 
2115  // Enter the scope of this instantiation. We don't use
2116  // PushDeclContext because we don't have a scope.
2117  ContextRAII SavedContext(*this, Instantiation);
2120 
2121  // If this is an instantiation of a local class, merge this local
2122  // instantiation scope with the enclosing scope. Otherwise, every
2123  // instantiation of a class has its own local instantiation scope.
2124  bool MergeWithParentScope = !Instantiation->isDefinedOutsideFunctionOrMethod();
2125  LocalInstantiationScope Scope(*this, MergeWithParentScope);
2126 
2127  // Some class state isn't processed immediately but delayed till class
2128  // instantiation completes. We may not be ready to handle any delayed state
2129  // already on the stack as it might correspond to a different class, so save
2130  // it now and put it back later.
2131  SavePendingParsedClassStateRAII SavedPendingParsedClassState(*this);
2132 
2133  // Pull attributes from the pattern onto the instantiation.
2134  InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
2135 
2136  // Start the definition of this instantiation.
2137  Instantiation->startDefinition();
2138 
2139  // The instantiation is visible here, even if it was first declared in an
2140  // unimported module.
2141  Instantiation->setVisibleDespiteOwningModule();
2142 
2143  // FIXME: This loses the as-written tag kind for an explicit instantiation.
2144  Instantiation->setTagKind(Pattern->getTagKind());
2145 
2146  // Do substitution on the base class specifiers.
2147  if (SubstBaseSpecifiers(Instantiation, Pattern, TemplateArgs))
2148  Instantiation->setInvalidDecl();
2149 
2150  TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
2151  SmallVector<Decl*, 4> Fields;
2152  // Delay instantiation of late parsed attributes.
2153  LateInstantiatedAttrVec LateAttrs;
2154  Instantiator.enableLateAttributeInstantiation(&LateAttrs);
2155 
2156  bool MightHaveConstexprVirtualFunctions = false;
2157  for (auto *Member : Pattern->decls()) {
2158  // Don't instantiate members not belonging in this semantic context.
2159  // e.g. for:
2160  // @code
2161  // template <int i> class A {
2162  // class B *g;
2163  // };
2164  // @endcode
2165  // 'class B' has the template as lexical context but semantically it is
2166  // introduced in namespace scope.
2167  if (Member->getDeclContext() != Pattern)
2168  continue;
2169 
2170  // BlockDecls can appear in a default-member-initializer. They must be the
2171  // child of a BlockExpr, so we only know how to instantiate them from there.
2172  if (isa<BlockDecl>(Member))
2173  continue;
2174 
2175  if (Member->isInvalidDecl()) {
2176  Instantiation->setInvalidDecl();
2177  continue;
2178  }
2179 
2180  Decl *NewMember = Instantiator.Visit(Member);
2181  if (NewMember) {
2182  if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember)) {
2183  Fields.push_back(Field);
2184  } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(NewMember)) {
2185  // C++11 [temp.inst]p1: The implicit instantiation of a class template
2186  // specialization causes the implicit instantiation of the definitions
2187  // of unscoped member enumerations.
2188  // Record a point of instantiation for this implicit instantiation.
2189  if (TSK == TSK_ImplicitInstantiation && !Enum->isScoped() &&
2190  Enum->isCompleteDefinition()) {
2191  MemberSpecializationInfo *MSInfo =Enum->getMemberSpecializationInfo();
2192  assert(MSInfo && "no spec info for member enum specialization");
2194  MSInfo->setPointOfInstantiation(PointOfInstantiation);
2195  }
2196  } else if (StaticAssertDecl *SA = dyn_cast<StaticAssertDecl>(NewMember)) {
2197  if (SA->isFailed()) {
2198  // A static_assert failed. Bail out; instantiating this
2199  // class is probably not meaningful.
2200  Instantiation->setInvalidDecl();
2201  break;
2202  }
2203  } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewMember)) {
2204  if (MD->isConstexpr() && !MD->getFriendObjectKind() &&
2205  (MD->isVirtualAsWritten() || Instantiation->getNumBases()))
2206  MightHaveConstexprVirtualFunctions = true;
2207  }
2208 
2209  if (NewMember->isInvalidDecl())
2210  Instantiation->setInvalidDecl();
2211  } else {
2212  // FIXME: Eventually, a NULL return will mean that one of the
2213  // instantiations was a semantic disaster, and we'll want to mark the
2214  // declaration invalid.
2215  // For now, we expect to skip some members that we can't yet handle.
2216  }
2217  }
2218 
2219  // Finish checking fields.
2220  ActOnFields(nullptr, Instantiation->getLocation(), Instantiation, Fields,
2222  CheckCompletedCXXClass(Instantiation);
2223 
2224  // Default arguments are parsed, if not instantiated. We can go instantiate
2225  // default arg exprs for default constructors if necessary now.
2226  ActOnFinishCXXNonNestedClass(Instantiation);
2227 
2228  // Instantiate late parsed attributes, and attach them to their decls.
2229  // See Sema::InstantiateAttrs
2230  for (LateInstantiatedAttrVec::iterator I = LateAttrs.begin(),
2231  E = LateAttrs.end(); I != E; ++I) {
2232  assert(CurrentInstantiationScope == Instantiator.getStartingScope());
2233  CurrentInstantiationScope = I->Scope;
2234 
2235  // Allow 'this' within late-parsed attributes.
2236  NamedDecl *ND = dyn_cast<NamedDecl>(I->NewDecl);
2237  CXXRecordDecl *ThisContext =
2238  dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
2239  CXXThisScopeRAII ThisScope(*this, ThisContext, Qualifiers(),
2240  ND && ND->isCXXInstanceMember());
2241 
2242  Attr *NewAttr =
2243  instantiateTemplateAttribute(I->TmplAttr, Context, *this, TemplateArgs);
2244  I->NewDecl->addAttr(NewAttr);
2246  Instantiator.getStartingScope());
2247  }
2248  Instantiator.disableLateAttributeInstantiation();
2249  LateAttrs.clear();
2250 
2251  ActOnFinishDelayedMemberInitializers(Instantiation);
2252 
2253  // FIXME: We should do something similar for explicit instantiations so they
2254  // end up in the right module.
2255  if (TSK == TSK_ImplicitInstantiation) {
2256  Instantiation->setLocation(Pattern->getLocation());
2257  Instantiation->setLocStart(Pattern->getInnerLocStart());
2258  Instantiation->setBraceRange(Pattern->getBraceRange());
2259  }
2260 
2261  if (!Instantiation->isInvalidDecl()) {
2262  // Perform any dependent diagnostics from the pattern.
2263  PerformDependentDiagnostics(Pattern, TemplateArgs);
2264 
2265  // Instantiate any out-of-line class template partial
2266  // specializations now.
2268  P = Instantiator.delayed_partial_spec_begin(),
2269  PEnd = Instantiator.delayed_partial_spec_end();
2270  P != PEnd; ++P) {
2272  P->first, P->second)) {
2273  Instantiation->setInvalidDecl();
2274  break;
2275  }
2276  }
2277 
2278  // Instantiate any out-of-line variable template partial
2279  // specializations now.
2281  P = Instantiator.delayed_var_partial_spec_begin(),
2282  PEnd = Instantiator.delayed_var_partial_spec_end();
2283  P != PEnd; ++P) {
2285  P->first, P->second)) {
2286  Instantiation->setInvalidDecl();
2287  break;
2288  }
2289  }
2290  }
2291 
2292  // Exit the scope of this instantiation.
2293  SavedContext.pop();
2294 
2295  if (!Instantiation->isInvalidDecl()) {
2296  Consumer.HandleTagDeclDefinition(Instantiation);
2297 
2298  // Always emit the vtable for an explicit instantiation definition
2299  // of a polymorphic class template specialization. Otherwise, eagerly
2300  // instantiate only constexpr virtual functions in preparation for their use
2301  // in constant evaluation.
2303  MarkVTableUsed(PointOfInstantiation, Instantiation, true);
2304  else if (MightHaveConstexprVirtualFunctions)
2305  MarkVirtualMembersReferenced(PointOfInstantiation, Instantiation,
2306  /*ConstexprOnly*/ true);
2307  }
2308 
2309  return Instantiation->isInvalidDecl();
2310 }
2311 
2312 /// Instantiate the definition of an enum from a given pattern.
2313 ///
2314 /// \param PointOfInstantiation The point of instantiation within the
2315 /// source code.
2316 /// \param Instantiation is the declaration whose definition is being
2317 /// instantiated. This will be a member enumeration of a class
2318 /// temploid specialization, or a local enumeration within a
2319 /// function temploid specialization.
2320 /// \param Pattern The templated declaration from which the instantiation
2321 /// occurs.
2322 /// \param TemplateArgs The template arguments to be substituted into
2323 /// the pattern.
2324 /// \param TSK The kind of implicit or explicit instantiation to perform.
2325 ///
2326 /// \return \c true if an error occurred, \c false otherwise.
2327 bool Sema::InstantiateEnum(SourceLocation PointOfInstantiation,
2328  EnumDecl *Instantiation, EnumDecl *Pattern,
2329  const MultiLevelTemplateArgumentList &TemplateArgs,
2331  EnumDecl *PatternDef = Pattern->getDefinition();
2332  if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
2333  Instantiation->getInstantiatedFromMemberEnum(),
2334  Pattern, PatternDef, TSK,/*Complain*/true))
2335  return true;
2336  Pattern = PatternDef;
2337 
2338  // Record the point of instantiation.
2339  if (MemberSpecializationInfo *MSInfo
2340  = Instantiation->getMemberSpecializationInfo()) {
2341  MSInfo->setTemplateSpecializationKind(TSK);
2342  MSInfo->setPointOfInstantiation(PointOfInstantiation);
2343  }
2344 
2345  InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
2346  if (Inst.isInvalid())
2347  return true;
2348  if (Inst.isAlreadyInstantiating())
2349  return false;
2350  PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
2351  "instantiating enum definition");
2352 
2353  // The instantiation is visible here, even if it was first declared in an
2354  // unimported module.
2355  Instantiation->setVisibleDespiteOwningModule();
2356 
2357  // Enter the scope of this instantiation. We don't use
2358  // PushDeclContext because we don't have a scope.
2359  ContextRAII SavedContext(*this, Instantiation);
2362 
2363  LocalInstantiationScope Scope(*this, /*MergeWithParentScope*/true);
2364 
2365  // Pull attributes from the pattern onto the instantiation.
2366  InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
2367 
2368  TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
2369  Instantiator.InstantiateEnumDefinition(Instantiation, Pattern);
2370 
2371  // Exit the scope of this instantiation.
2372  SavedContext.pop();
2373 
2374  return Instantiation->isInvalidDecl();
2375 }
2376 
2377 
2378 /// Instantiate the definition of a field from the given pattern.
2379 ///
2380 /// \param PointOfInstantiation The point of instantiation within the
2381 /// source code.
2382 /// \param Instantiation is the declaration whose definition is being
2383 /// instantiated. This will be a class of a class temploid
2384 /// specialization, or a local enumeration within a function temploid
2385 /// specialization.
2386 /// \param Pattern The templated declaration from which the instantiation
2387 /// occurs.
2388 /// \param TemplateArgs The template arguments to be substituted into
2389 /// the pattern.
2390 ///
2391 /// \return \c true if an error occurred, \c false otherwise.
2393  SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
2394  FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs) {
2395  // If there is no initializer, we don't need to do anything.
2396  if (!Pattern->hasInClassInitializer())
2397  return false;
2398 
2399  assert(Instantiation->getInClassInitStyle() ==
2400  Pattern->getInClassInitStyle() &&
2401  "pattern and instantiation disagree about init style");
2402 
2403  // Error out if we haven't parsed the initializer of the pattern yet because
2404  // we are waiting for the closing brace of the outer class.
2405  Expr *OldInit = Pattern->getInClassInitializer();
2406  if (!OldInit) {
2407  RecordDecl *PatternRD = Pattern->getParent();
2408  RecordDecl *OutermostClass = PatternRD->getOuterLexicalRecordContext();
2409  Diag(PointOfInstantiation,
2410  diag::err_in_class_initializer_not_yet_parsed)
2411  << OutermostClass << Pattern;
2412  Diag(Pattern->getEndLoc(), diag::note_in_class_initializer_not_yet_parsed);
2413  Instantiation->setInvalidDecl();
2414  return true;
2415  }
2416 
2417  InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
2418  if (Inst.isInvalid())
2419  return true;
2420  if (Inst.isAlreadyInstantiating()) {
2421  // Error out if we hit an instantiation cycle for this initializer.
2422  Diag(PointOfInstantiation, diag::err_in_class_initializer_cycle)
2423  << Instantiation;
2424  return true;
2425  }
2426  PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
2427  "instantiating default member init");
2428 
2429  // Enter the scope of this instantiation. We don't use PushDeclContext because
2430  // we don't have a scope.
2431  ContextRAII SavedContext(*this, Instantiation->getParent());
2434 
2435  LocalInstantiationScope Scope(*this, true);
2436 
2437  // Instantiate the initializer.
2439  CXXThisScopeRAII ThisScope(*this, Instantiation->getParent(), Qualifiers());
2440 
2441  ExprResult NewInit = SubstInitializer(OldInit, TemplateArgs,
2442  /*CXXDirectInit=*/false);
2443  Expr *Init = NewInit.get();
2444  assert((!Init || !isa<ParenListExpr>(Init)) && "call-style init in class");
2446  Instantiation, Init ? Init->getBeginLoc() : SourceLocation(), Init);
2447 
2448  if (auto *L = getASTMutationListener())
2449  L->DefaultMemberInitializerInstantiated(Instantiation);
2450 
2451  // Return true if the in-class initializer is still missing.
2452  return !Instantiation->getInClassInitializer();
2453 }
2454 
2455 namespace {
2456  /// A partial specialization whose template arguments have matched
2457  /// a given template-id.
2458  struct PartialSpecMatchResult {
2460  TemplateArgumentList *Args;
2461  };
2462 }
2463 
2465  SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec) {
2466  if (ClassTemplateSpec->getTemplateSpecializationKind() ==
2468  return true;
2469 
2471  ClassTemplateSpec->getSpecializedTemplate()
2472  ->getPartialSpecializations(PartialSpecs);
2473  for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
2474  TemplateDeductionInfo Info(Loc);
2475  if (!DeduceTemplateArguments(PartialSpecs[I],
2476  ClassTemplateSpec->getTemplateArgs(), Info))
2477  return true;
2478  }
2479 
2480  return false;
2481 }
2482 
2483 /// Get the instantiation pattern to use to instantiate the definition of a
2484 /// given ClassTemplateSpecializationDecl (either the pattern of the primary
2485 /// template or of a partial specialization).
2486 static CXXRecordDecl *
2488  Sema &S, SourceLocation PointOfInstantiation,
2489  ClassTemplateSpecializationDecl *ClassTemplateSpec,
2490  TemplateSpecializationKind TSK, bool Complain) {
2491  Sema::InstantiatingTemplate Inst(S, PointOfInstantiation, ClassTemplateSpec);
2492  if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
2493  return nullptr;
2494 
2495  llvm::PointerUnion<ClassTemplateDecl *,
2497  Specialized = ClassTemplateSpec->getSpecializedTemplateOrPartial();
2498  if (!Specialized.is<ClassTemplatePartialSpecializationDecl *>()) {
2499  // Find best matching specialization.
2500  ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
2501 
2502  // C++ [temp.class.spec.match]p1:
2503  // When a class template is used in a context that requires an
2504  // instantiation of the class, it is necessary to determine
2505  // whether the instantiation is to be generated using the primary
2506  // template or one of the partial specializations. This is done by
2507  // matching the template arguments of the class template
2508  // specialization with the template argument lists of the partial
2509  // specializations.
2510  typedef PartialSpecMatchResult MatchResult;
2513  Template->getPartialSpecializations(PartialSpecs);
2514  TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation);
2515  for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
2516  ClassTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
2517  TemplateDeductionInfo Info(FailedCandidates.getLocation());
2519  Partial, ClassTemplateSpec->getTemplateArgs(), Info)) {
2520  // Store the failed-deduction information for use in diagnostics, later.
2521  // TODO: Actually use the failed-deduction info?
2522  FailedCandidates.addCandidate().set(
2523  DeclAccessPair::make(Template, AS_public), Partial,
2525  (void)Result;
2526  } else {
2527  Matched.push_back(PartialSpecMatchResult());
2528  Matched.back().Partial = Partial;
2529  Matched.back().Args = Info.take();
2530  }
2531  }
2532 
2533  // If we're dealing with a member template where the template parameters
2534  // have been instantiated, this provides the original template parameters
2535  // from which the member template's parameters were instantiated.
2536 
2537  if (Matched.size() >= 1) {
2538  SmallVectorImpl<MatchResult>::iterator Best = Matched.begin();
2539  if (Matched.size() == 1) {
2540  // -- If exactly one matching specialization is found, the
2541  // instantiation is generated from that specialization.
2542  // We don't need to do anything for this.
2543  } else {
2544  // -- If more than one matching specialization is found, the
2545  // partial order rules (14.5.4.2) are used to determine
2546  // whether one of the specializations is more specialized
2547  // than the others. If none of the specializations is more
2548  // specialized than all of the other matching
2549  // specializations, then the use of the class template is
2550  // ambiguous and the program is ill-formed.
2551  for (SmallVectorImpl<MatchResult>::iterator P = Best + 1,
2552  PEnd = Matched.end();
2553  P != PEnd; ++P) {
2555  P->Partial, Best->Partial, PointOfInstantiation) ==
2556  P->Partial)
2557  Best = P;
2558  }
2559 
2560  // Determine if the best partial specialization is more specialized than
2561  // the others.
2562  bool Ambiguous = false;
2563  for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
2564  PEnd = Matched.end();
2565  P != PEnd; ++P) {
2566  if (P != Best && S.getMoreSpecializedPartialSpecialization(
2567  P->Partial, Best->Partial,
2568  PointOfInstantiation) != Best->Partial) {
2569  Ambiguous = true;
2570  break;
2571  }
2572  }
2573 
2574  if (Ambiguous) {
2575  // Partial ordering did not produce a clear winner. Complain.
2576  Inst.Clear();
2577  ClassTemplateSpec->setInvalidDecl();
2578  S.Diag(PointOfInstantiation,
2579  diag::err_partial_spec_ordering_ambiguous)
2580  << ClassTemplateSpec;
2581 
2582  // Print the matching partial specializations.
2583  for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
2584  PEnd = Matched.end();
2585  P != PEnd; ++P)
2586  S.Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
2588  P->Partial->getTemplateParameters(), *P->Args);
2589 
2590  return nullptr;
2591  }
2592  }
2593 
2594  ClassTemplateSpec->setInstantiationOf(Best->Partial, Best->Args);
2595  } else {
2596  // -- If no matches are found, the instantiation is generated
2597  // from the primary template.
2598  }
2599  }
2600 
2601  CXXRecordDecl *Pattern = nullptr;
2602  Specialized = ClassTemplateSpec->getSpecializedTemplateOrPartial();
2603  if (auto *PartialSpec =
2604  Specialized.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
2605  // Instantiate using the best class template partial specialization.
2606  while (PartialSpec->getInstantiatedFromMember()) {
2607  // If we've found an explicit specialization of this class template,
2608  // stop here and use that as the pattern.
2609  if (PartialSpec->isMemberSpecialization())
2610  break;
2611 
2612  PartialSpec = PartialSpec->getInstantiatedFromMember();
2613  }
2614  Pattern = PartialSpec;
2615  } else {
2616  ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
2617  while (Template->getInstantiatedFromMemberTemplate()) {
2618  // If we've found an explicit specialization of this class template,
2619  // stop here and use that as the pattern.
2620  if (Template->isMemberSpecialization())
2621  break;
2622 
2623  Template = Template->getInstantiatedFromMemberTemplate();
2624  }
2625  Pattern = Template->getTemplatedDecl();
2626  }
2627 
2628  return Pattern;
2629 }
2630 
2632  SourceLocation PointOfInstantiation,
2633  ClassTemplateSpecializationDecl *ClassTemplateSpec,
2634  TemplateSpecializationKind TSK, bool Complain) {
2635  // Perform the actual instantiation on the canonical declaration.
2636  ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>(
2637  ClassTemplateSpec->getCanonicalDecl());
2638  if (ClassTemplateSpec->isInvalidDecl())
2639  return true;
2640 
2642  *this, PointOfInstantiation, ClassTemplateSpec, TSK, Complain);
2643  if (!Pattern)
2644  return true;
2645 
2646  return InstantiateClass(PointOfInstantiation, ClassTemplateSpec, Pattern,
2647  getTemplateInstantiationArgs(ClassTemplateSpec), TSK,
2648  Complain);
2649 }
2650 
2651 /// Instantiates the definitions of all of the member
2652 /// of the given class, which is an instantiation of a class template
2653 /// or a member class of a template.
2654 void
2656  CXXRecordDecl *Instantiation,
2657  const MultiLevelTemplateArgumentList &TemplateArgs,
2659  // FIXME: We need to notify the ASTMutationListener that we did all of these
2660  // things, in case we have an explicit instantiation definition in a PCM, a
2661  // module, or preamble, and the declaration is in an imported AST.
2662  assert(
2665  (TSK == TSK_ImplicitInstantiation && Instantiation->isLocalClass())) &&
2666  "Unexpected template specialization kind!");
2667  for (auto *D : Instantiation->decls()) {
2668  bool SuppressNew = false;
2669  if (auto *Function = dyn_cast<FunctionDecl>(D)) {
2670  if (FunctionDecl *Pattern =
2671  Function->getInstantiatedFromMemberFunction()) {
2672 
2673  if (Function->hasAttr<ExcludeFromExplicitInstantiationAttr>())
2674  continue;
2675 
2676  MemberSpecializationInfo *MSInfo =
2677  Function->getMemberSpecializationInfo();
2678  assert(MSInfo && "No member specialization information?");
2679  if (MSInfo->getTemplateSpecializationKind()
2681  continue;
2682 
2683  if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2684  Function,
2686  MSInfo->getPointOfInstantiation(),
2687  SuppressNew) ||
2688  SuppressNew)
2689  continue;
2690 
2691  // C++11 [temp.explicit]p8:
2692  // An explicit instantiation definition that names a class template
2693  // specialization explicitly instantiates the class template
2694  // specialization and is only an explicit instantiation definition
2695  // of members whose definition is visible at the point of
2696  // instantiation.
2697  if (TSK == TSK_ExplicitInstantiationDefinition && !Pattern->isDefined())
2698  continue;
2699 
2700  Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2701 
2702  if (Function->isDefined()) {
2703  // Let the ASTConsumer know that this function has been explicitly
2704  // instantiated now, and its linkage might have changed.
2706  } else if (TSK == TSK_ExplicitInstantiationDefinition) {
2707  InstantiateFunctionDefinition(PointOfInstantiation, Function);
2708  } else if (TSK == TSK_ImplicitInstantiation) {
2710  std::make_pair(Function, PointOfInstantiation));
2711  }
2712  }
2713  } else if (auto *Var = dyn_cast<VarDecl>(D)) {
2714  if (isa<VarTemplateSpecializationDecl>(Var))
2715  continue;
2716 
2717  if (Var->isStaticDataMember()) {
2718  if (Var->hasAttr<ExcludeFromExplicitInstantiationAttr>())
2719  continue;
2720 
2721  MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
2722  assert(MSInfo && "No member specialization information?");
2723  if (MSInfo->getTemplateSpecializationKind()
2725  continue;
2726 
2727  if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2728  Var,
2730  MSInfo->getPointOfInstantiation(),
2731  SuppressNew) ||
2732  SuppressNew)
2733  continue;
2734 
2736  // C++0x [temp.explicit]p8:
2737  // An explicit instantiation definition that names a class template
2738  // specialization explicitly instantiates the class template
2739  // specialization and is only an explicit instantiation definition
2740  // of members whose definition is visible at the point of
2741  // instantiation.
2742  if (!Var->getInstantiatedFromStaticDataMember()->getDefinition())
2743  continue;
2744 
2745  Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2746  InstantiateVariableDefinition(PointOfInstantiation, Var);
2747  } else {
2748  Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2749  }
2750  }
2751  } else if (auto *Record = dyn_cast<CXXRecordDecl>(D)) {
2752  if (Record->hasAttr<ExcludeFromExplicitInstantiationAttr>())
2753  continue;
2754 
2755  // Always skip the injected-class-name, along with any
2756  // redeclarations of nested classes, since both would cause us
2757  // to try to instantiate the members of a class twice.
2758  // Skip closure types; they'll get instantiated when we instantiate
2759  // the corresponding lambda-expression.
2760  if (Record->isInjectedClassName() || Record->getPreviousDecl() ||
2761  Record->isLambda())
2762  continue;
2763 
2764  MemberSpecializationInfo *MSInfo = Record->getMemberSpecializationInfo();
2765  assert(MSInfo && "No member specialization information?");
2766 
2767  if (MSInfo->getTemplateSpecializationKind()
2769  continue;
2770 
2771  if (Context.getTargetInfo().getTriple().isOSWindows() &&
2773  // On Windows, explicit instantiation decl of the outer class doesn't
2774  // affect the inner class. Typically extern template declarations are
2775  // used in combination with dll import/export annotations, but those
2776  // are not propagated from the outer class templates to inner classes.
2777  // Therefore, do not instantiate inner classes on this platform, so
2778  // that users don't end up with undefined symbols during linking.
2779  continue;
2780  }
2781 
2782  if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2783  Record,
2785  MSInfo->getPointOfInstantiation(),
2786  SuppressNew) ||
2787  SuppressNew)
2788  continue;
2789 
2790  CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
2791  assert(Pattern && "Missing instantiated-from-template information");
2792 
2793  if (!Record->getDefinition()) {
2794  if (!Pattern->getDefinition()) {
2795  // C++0x [temp.explicit]p8:
2796  // An explicit instantiation definition that names a class template
2797  // specialization explicitly instantiates the class template
2798  // specialization and is only an explicit instantiation definition
2799  // of members whose definition is visible at the point of
2800  // instantiation.
2802  MSInfo->setTemplateSpecializationKind(TSK);
2803  MSInfo->setPointOfInstantiation(PointOfInstantiation);
2804  }
2805 
2806  continue;
2807  }
2808 
2809  InstantiateClass(PointOfInstantiation, Record, Pattern,
2810  TemplateArgs,
2811  TSK);
2812  } else {
2814  Record->getTemplateSpecializationKind() ==
2816  Record->setTemplateSpecializationKind(TSK);
2817  MarkVTableUsed(PointOfInstantiation, Record, true);
2818  }
2819  }
2820 
2821  Pattern = cast_or_null<CXXRecordDecl>(Record->getDefinition());
2822  if (Pattern)
2823  InstantiateClassMembers(PointOfInstantiation, Pattern, TemplateArgs,
2824  TSK);
2825  } else if (auto *Enum = dyn_cast<EnumDecl>(D)) {
2826  MemberSpecializationInfo *MSInfo = Enum->getMemberSpecializationInfo();
2827  assert(MSInfo && "No member specialization information?");
2828 
2829  if (MSInfo->getTemplateSpecializationKind()
2831  continue;
2832 
2834  PointOfInstantiation, TSK, Enum,
2836  MSInfo->getPointOfInstantiation(), SuppressNew) ||
2837  SuppressNew)
2838  continue;
2839 
2840  if (Enum->getDefinition())
2841  continue;
2842 
2843  EnumDecl *Pattern = Enum->getTemplateInstantiationPattern();
2844  assert(Pattern && "Missing instantiated-from-template information");
2845 
2847  if (!Pattern->getDefinition())
2848  continue;
2849 
2850  InstantiateEnum(PointOfInstantiation, Enum, Pattern, TemplateArgs, TSK);
2851  } else {
2852  MSInfo->setTemplateSpecializationKind(TSK);
2853  MSInfo->setPointOfInstantiation(PointOfInstantiation);
2854  }
2855  } else if (auto *Field = dyn_cast<FieldDecl>(D)) {
2856  // No need to instantiate in-class initializers during explicit
2857  // instantiation.
2858  if (Field->hasInClassInitializer() && TSK == TSK_ImplicitInstantiation) {
2859  CXXRecordDecl *ClassPattern =
2860  Instantiation->getTemplateInstantiationPattern();
2862  ClassPattern->lookup(Field->getDeclName());
2863  FieldDecl *Pattern = cast<FieldDecl>(Lookup.front());
2864  InstantiateInClassInitializer(PointOfInstantiation, Field, Pattern,
2865  TemplateArgs);
2866  }
2867  }
2868  }
2869 }
2870 
2871 /// Instantiate the definitions of all of the members of the
2872 /// given class template specialization, which was named as part of an
2873 /// explicit instantiation.
2874 void
2876  SourceLocation PointOfInstantiation,
2877  ClassTemplateSpecializationDecl *ClassTemplateSpec,
2879  // C++0x [temp.explicit]p7:
2880  // An explicit instantiation that names a class template
2881  // specialization is an explicit instantion of the same kind
2882  // (declaration or definition) of each of its members (not
2883  // including members inherited from base classes) that has not
2884  // been previously explicitly specialized in the translation unit
2885  // containing the explicit instantiation, except as described
2886  // below.
2887  InstantiateClassMembers(PointOfInstantiation, ClassTemplateSpec,
2888  getTemplateInstantiationArgs(ClassTemplateSpec),
2889  TSK);
2890 }
2891 
2892 StmtResult
2894  if (!S)
2895  return S;
2896 
2897  TemplateInstantiator Instantiator(*this, TemplateArgs,
2898  SourceLocation(),
2899  DeclarationName());
2900  return Instantiator.TransformStmt(S);
2901 }
2902 
2903 ExprResult
2905  if (!E)
2906  return E;
2907 
2908  TemplateInstantiator Instantiator(*this, TemplateArgs,
2909  SourceLocation(),
2910  DeclarationName());
2911  return Instantiator.TransformExpr(E);
2912 }
2913 
2915  const MultiLevelTemplateArgumentList &TemplateArgs,
2916  bool CXXDirectInit) {
2917  TemplateInstantiator Instantiator(*this, TemplateArgs,
2918  SourceLocation(),
2919  DeclarationName());
2920  return Instantiator.TransformInitializer(Init, CXXDirectInit);
2921 }
2922 
2923 bool Sema::SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
2924  const MultiLevelTemplateArgumentList &TemplateArgs,
2925  SmallVectorImpl<Expr *> &Outputs) {
2926  if (Exprs.empty())
2927  return false;
2928 
2929  TemplateInstantiator Instantiator(*this, TemplateArgs,
2930  SourceLocation(),
2931  DeclarationName());
2932  return Instantiator.TransformExprs(Exprs.data(), Exprs.size(),
2933  IsCall, Outputs);
2934 }
2935 
2938  const MultiLevelTemplateArgumentList &TemplateArgs) {
2939  if (!NNS)
2940  return NestedNameSpecifierLoc();
2941 
2942  TemplateInstantiator Instantiator(*this, TemplateArgs, NNS.getBeginLoc(),
2943  DeclarationName());
2944  return Instantiator.TransformNestedNameSpecifierLoc(NNS);
2945 }
2946 
2947 /// Do template substitution on declaration name info.
2950  const MultiLevelTemplateArgumentList &TemplateArgs) {
2951  TemplateInstantiator Instantiator(*this, TemplateArgs, NameInfo.getLoc(),
2952  NameInfo.getName());
2953  return Instantiator.TransformDeclarationNameInfo(NameInfo);
2954 }
2955 
2958  TemplateName Name, SourceLocation Loc,
2959  const MultiLevelTemplateArgumentList &TemplateArgs) {
2960  TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
2961  DeclarationName());
2962  CXXScopeSpec SS;
2963  SS.Adopt(QualifierLoc);
2964  return Instantiator.TransformTemplateName(SS, Name, Loc);
2965 }
2966 
2967 bool Sema::Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
2969  const MultiLevelTemplateArgumentList &TemplateArgs) {
2970  TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
2971  DeclarationName());
2972 
2973  return Instantiator.TransformTemplateArguments(Args, NumArgs, Result);
2974 }
2975 
2976 static const Decl *getCanonicalParmVarDecl(const Decl *D) {
2977  // When storing ParmVarDecls in the local instantiation scope, we always
2978  // want to use the ParmVarDecl from the canonical function declaration,
2979  // since the map is then valid for any redeclaration or definition of that
2980  // function.
2981  if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(D)) {
2982  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
2983  unsigned i = PV->getFunctionScopeIndex();
2984  // This parameter might be from a freestanding function type within the
2985  // function and isn't necessarily referring to one of FD's parameters.
2986  if (i < FD->getNumParams() && FD->getParamDecl(i) == PV)
2987  return FD->getCanonicalDecl()->getParamDecl(i);
2988  }
2989  }
2990  return D;
2991 }
2992 
2993 
2994 llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> *
2996  D = getCanonicalParmVarDecl(D);
2997  for (LocalInstantiationScope *Current = this; Current;
2998  Current = Current->Outer) {
2999 
3000  // Check if we found something within this scope.
3001  const Decl *CheckD = D;
3002  do {
3003  LocalDeclsMap::iterator Found = Current->LocalDecls.find(CheckD);
3004  if (Found != Current->LocalDecls.end())
3005  return &Found->second;
3006 
3007  // If this is a tag declaration, it's possible that we need to look for
3008  // a previous declaration.
3009  if (const TagDecl *Tag = dyn_cast<TagDecl>(CheckD))
3010  CheckD = Tag->getPreviousDecl();
3011  else
3012  CheckD = nullptr;
3013  } while (CheckD);
3014 
3015  // If we aren't combined with our outer scope, we're done.
3016  if (!Current->CombineWithOuterScope)
3017  break;
3018  }
3019 
3020  // If we're performing a partial substitution during template argument
3021  // deduction, we may not have values for template parameters yet.
3022  if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
3023  isa<TemplateTemplateParmDecl>(D))
3024  return nullptr;
3025 
3026  // Local types referenced prior to definition may require instantiation.
3027  if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
3028  if (RD->isLocalClass())
3029  return nullptr;
3030 
3031  // Enumeration types referenced prior to definition may appear as a result of
3032  // error recovery.
3033  if (isa<EnumDecl>(D))
3034  return nullptr;
3035 
3036  // If we didn't find the decl, then we either have a sema bug, or we have a
3037  // forward reference to a label declaration. Return null to indicate that
3038  // we have an uninstantiated label.
3039  assert(isa<LabelDecl>(D) && "declaration not instantiated in this scope");
3040  return nullptr;
3041 }
3042 
3044  D = getCanonicalParmVarDecl(D);
3045  llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
3046  if (Stored.isNull()) {
3047 #ifndef NDEBUG
3048  // It should not be present in any surrounding scope either.
3049  LocalInstantiationScope *Current = this;
3050  while (Current->CombineWithOuterScope && Current->Outer) {
3051  Current = Current->Outer;
3052  assert(Current->LocalDecls.find(D) == Current->LocalDecls.end() &&
3053  "Instantiated local in inner and outer scopes");
3054  }
3055 #endif
3056  Stored = Inst;
3057  } else if (DeclArgumentPack *Pack = Stored.dyn_cast<DeclArgumentPack *>()) {
3058  Pack->push_back(cast<VarDecl>(Inst));
3059  } else {
3060  assert(Stored.get<Decl *>() == Inst && "Already instantiated this local");
3061  }
3062 }
3063 
3065  VarDecl *Inst) {
3066  D = getCanonicalParmVarDecl(D);
3067  DeclArgumentPack *Pack = LocalDecls[D].get<DeclArgumentPack *>();
3068  Pack->push_back(Inst);
3069 }
3070 
3072 #ifndef NDEBUG
3073  // This should be the first time we've been told about this decl.
3074  for (LocalInstantiationScope *Current = this;
3075  Current && Current->CombineWithOuterScope; Current = Current->Outer)
3076  assert(Current->LocalDecls.find(D) == Current->LocalDecls.end() &&
3077  "Creating local pack after instantiation of local");
3078 #endif
3079 
3080  D = getCanonicalParmVarDecl(D);
3081  llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
3082  DeclArgumentPack *Pack = new DeclArgumentPack;
3083  Stored = Pack;
3084  ArgumentPacks.push_back(Pack);
3085 }
3086 
3088  const TemplateArgument *ExplicitArgs,
3089  unsigned NumExplicitArgs) {
3090  assert((!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack) &&
3091  "Already have a partially-substituted pack");
3092  assert((!PartiallySubstitutedPack
3093  || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) &&
3094  "Wrong number of arguments in partially-substituted pack");
3095  PartiallySubstitutedPack = Pack;
3096  ArgsInPartiallySubstitutedPack = ExplicitArgs;
3097  NumArgsInPartiallySubstitutedPack = NumExplicitArgs;
3098 }
3099 
3101  const TemplateArgument **ExplicitArgs,
3102  unsigned *NumExplicitArgs) const {
3103  if (ExplicitArgs)
3104  *ExplicitArgs = nullptr;
3105  if (NumExplicitArgs)
3106  *NumExplicitArgs = 0;
3107 
3108  for (const LocalInstantiationScope *Current = this; Current;
3109  Current = Current->Outer) {
3110  if (Current->PartiallySubstitutedPack) {
3111  if (ExplicitArgs)
3112  *ExplicitArgs = Current->ArgsInPartiallySubstitutedPack;
3113  if (NumExplicitArgs)
3114  *NumExplicitArgs = Current->NumArgsInPartiallySubstitutedPack;
3115 
3116  return Current->PartiallySubstitutedPack;
3117  }
3118 
3119  if (!Current->CombineWithOuterScope)
3120  break;
3121  }
3122 
3123  return nullptr;
3124 }
SourceLocation getLoc() const
getLoc - Returns the main location of the declaration name.
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
ExprResult BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg, SourceLocation Loc)
Construct a new expression that refers to the given integral template argument with the given source-...
Defines the clang::ASTContext interface.
unsigned getTemplateBacktraceLimit() const
Retrieve the maximum number of template instantiation notes to emit along with a given diagnostic...
Definition: Diagnostic.h:569
void ActOnFinishDelayedMemberInitializers(Decl *Record)
void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex)
Definition: Decl.h:1633
void InstantiateClassMembers(SourceLocation PointOfInstantiation, CXXRecordDecl *Instantiation, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateSpecializationKind TSK)
Instantiates the definitions of all of the member of the given class, which is an instantiation of a ...
We are defining a synthesized function (such as a defaulted special member).
Definition: Sema.h:7672
Represents a function declaration or definition.
Definition: Decl.h:1784
delayed_var_partial_spec_iterator delayed_var_partial_spec_begin()
Definition: Template.h:515
no exception specification
const TypeClass * getTypePtr() const
Definition: TypeLoc.h:498
if(T->getSizeExpr()) TRY_TO(TraverseStmt(T -> getSizeExpr()))
SourceLocation getUsedLocation() const
Retrieve the location where this default argument was actually used.
Definition: ExprCXX.h:1248
A (possibly-)qualified type.
Definition: Type.h:643
ASTConsumer & Consumer
Definition: Sema.h:378
TemplateDeductionResult
Describes the result of template argument deduction.
Definition: Sema.h:7393
void InstantiatedLocal(const Decl *D, Decl *Inst)
base_class_range bases()
Definition: DeclCXX.h:589
void UpdateExceptionSpec(FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI)
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition: DeclCXX.h:583
llvm::PointerUnion3< TemplateTypeParmDecl *, NonTypeTemplateParmDecl *, TemplateTemplateParmDecl * > TemplateParameter
Stores a template parameter of any kind.
Definition: DeclTemplate.h:61
A stack-allocated class that identifies which local variable declaration instantiations are present i...
Definition: Template.h:227
std::vector< std::unique_ptr< TemplateInstantiationCallback > > TemplateInstCallbacks
The template instantiation callbacks to trace or track instantiations (objects can be chained)...
Definition: Sema.h:7807
VarDecl * getParameterPack() const
Get the parameter pack which this expression refers to.
Definition: ExprCXX.h:4366
InClassInitStyle getInClassInitStyle() const
Get the kind of (C++11) default member initializer that this field has.
Definition: Decl.h:2776
void addOuterTemplateArguments(const TemplateArgumentList *TemplateArgs)
Add a new outermost level to the multi-level template argument list.
Definition: Template.h:133
Decl * Entity
The entity that is being synthesized.
Definition: Sema.h:7700
Stmt - This represents one statement.
Definition: Stmt.h:66
bool isGenericLambdaCallOperatorSpecialization(const CXXMethodDecl *MD)
Definition: ASTLambda.h:38
ExprResult SubstInitializer(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs, bool CXXDirectInit)
Provides information about an attempted template argument deduction, whose success or failure was des...
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:991
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition: Decl.h:1034
ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param)
BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating the default expr if needed...
Definition: SemaExpr.cpp:4929
The template argument is an expression, and we&#39;ve not resolved it to one of the other forms yet...
Definition: TemplateBase.h:86
std::string getTemplateArgumentBindingsText(const TemplateParameterList *Params, const TemplateArgumentList &Args)
Produces a formatted string that describes the binding of template parameters to template arguments...
bool isInstantiationRecord() const
Determines whether this template is an actual instantiation that should be counted toward the maximum...
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition: Sema.h:1375
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:88
llvm::PointerUnion< Decl *, DeclArgumentPack * > * findInstantiationOf(const Decl *D)
Find the instantiation of the declaration D within the current instantiation scope.
Defines the C++ template declaration subclasses.
StringRef P
SmallVector< CodeSynthesisContext, 16 > CodeSynthesisContexts
List of active code synthesis contexts.
Definition: Sema.h:7750
Decl * getPreviousDecl()
Retrieve the previous declaration that declares the same entity as this declaration, or NULL if there is no previous declaration.
Definition: DeclBase.h:960
SmallVector< Module *, 16 > CodeSynthesisContextLookupModules
Extra modules inspected when performing a lookup during a template instantiation. ...
Definition: Sema.h:7761
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined...
Definition: Decl.h:2832
bool InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation, ClassTemplateSpecializationDecl *ClassTemplateSpec, TemplateSpecializationKind TSK, bool Complain=true)
std::deque< PendingImplicitInstantiation > PendingLocalImplicitInstantiations
The queue of implicit template instantiations that are required and must be performed within the curr...
Definition: Sema.h:8181
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
Definition: Diagnostic.h:1290
Declaration of a variable template.
The template argument is a declaration that was provided for a pointer, reference, or pointer to member non-type template parameter.
Definition: TemplateBase.h:63
NamedDecl * getParam(unsigned Idx)
Definition: DeclTemplate.h:132
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:706
A container of type source information.
Definition: Decl.h:86
bool SubstExprs(ArrayRef< Expr *> Exprs, bool IsCall, const MultiLevelTemplateArgumentList &TemplateArgs, SmallVectorImpl< Expr *> &Outputs)
Substitute the given template arguments into a list of expressions, expanding pack expansions if requ...
IdentKind getIdentKind() const
Definition: Expr.h:1926
bool isStackNearlyExhausted()
Determine whether the stack is nearly exhausted.
Definition: Stack.cpp:46
bool DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation, NamedDecl *Instantiation, bool InstantiatedFromMember, const NamedDecl *Pattern, const NamedDecl *PatternDef, TemplateSpecializationKind TSK, bool Complain=true)
Determine whether we would be unable to instantiate this template (because it either has no definitio...
We are instantiating a default argument for a template parameter.
Definition: Sema.h:7632
VarTemplatePartialSpecializationDecl * InstantiateVarTemplatePartialSpecialization(VarTemplateDecl *VarTemplate, VarTemplatePartialSpecializationDecl *PartialSpec)
Instantiate the declaration of a variable template partial specialization.
TemplateTypeParmDecl * getDecl() const
Definition: Type.h:4643
void SetPartiallySubstitutedPack(NamedDecl *Pack, const TemplateArgument *ExplicitArgs, unsigned NumExplicitArgs)
Note that the given parameter pack has been partially substituted via explicit specification of templ...
TemplateName SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name, SourceLocation Loc, const MultiLevelTemplateArgumentList &TemplateArgs)
unsigned NonInstantiationEntries
The number of CodeSynthesisContexts that are not template instantiations and, therefore, should not be counted as part of the instantiation depth.
Definition: Sema.h:7791
bool hasInClassInitializer() const
Determine whether this member has a C++11 default member initializer.
Definition: Decl.h:2783
void InstantiateVariableDefinition(SourceLocation PointOfInstantiation, VarDecl *Var, bool Recursive=false, bool DefinitionRequired=false, bool AtEndOfTU=false)
Instantiate the definition of the given variable from its template.
SourceLocation getEndLoc() const
Get the end source location.
Definition: TypeLoc.cpp:226
LocalInstantiationScope * getStartingScope() const
Definition: Template.h:499
void ActOnFinishCXXNonNestedClass(Decl *D)
This file provides some common utility functions for processing Lambda related AST Constructs...
void Adopt(NestedNameSpecifierLoc Other)
Adopt an existing nested-name-specifier (with source-range information).
Definition: DeclSpec.cpp:124
unsigned getDepth() const
Get the nesting depth of the template parameter.
RAII object that enters a new expression evaluation context.
Definition: Sema.h:11557
Represents a variable declaration or definition.
Definition: Decl.h:827
Information about one declarator, including the parsed type information and the identifier.
Definition: DeclSpec.h:1775
MatchFinder::MatchResult MatchResult
DiagnosticsEngine & Diags
Definition: Sema.h:379
const T * getAs() const
Member-template getAs<specific type>&#39;.
Definition: Type.h:6858
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
Definition: Sema.h:2422
bool hasInheritedDefaultArg() const
Definition: Decl.h:1726
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition: DeclBase.h:2028
QualifiedTemplateName * getAsQualifiedTemplateName() const
Retrieve the underlying qualified template name structure, if any.
Represents a variable template specialization, which refers to a variable template with a given set o...
RAII object used to temporarily allow the C++ &#39;this&#39; expression to be used, with the given qualifiers...
Definition: Sema.h:5474
reference front() const
Definition: DeclBase.h:1242
bool isInvalidDecl() const
Definition: DeclBase.h:553
Stores a list of template parameters for a TemplateDecl and its derived classes.
Definition: DeclTemplate.h:67
A context in which code is being synthesized (where a source location alone is not sufficient to iden...
Definition: Sema.h:7620
bool isParameterPack() const
Whether this declaration is a parameter pack.
Definition: DeclBase.cpp:211
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template specialization this is.
Definition: DeclTemplate.h:629
Represents a parameter to a function.
Definition: Decl.h:1600
QualType getIntegralType() const
Retrieve the type of the integral value.
Definition: TemplateBase.h:314
iterator begin() const
Definition: ExprCXX.h:4374
const TemplateArgument * TemplateArgs
The list of template arguments we are substituting, if they are not part of the entity.
Definition: Sema.h:7709
The collection of all-type qualifiers we support.
Definition: Type.h:137
const FunctionDecl * isLocalClass() const
If the class is a local class [class.local], returns the enclosing function declaration.
Definition: DeclCXX.h:1441
void setTemplateSpecializationKind(TemplateSpecializationKind TSK)
Set the kind of specialization or template instantiation this is.
Definition: DeclCXX.cpp:1706
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:269
bool isLexicallyWithinFunctionOrMethod() const
Returns true if this declaration lexically is inside a function.
Definition: DeclBase.cpp:335
Base wrapper for a particular "section" of type source info.
Definition: TypeLoc.h:56
Represents a struct/union/class.
Definition: Decl.h:3662
A semantic tree transformation that allows one to transform one abstract syntax tree into another...
Definition: TreeTransform.h:95
enum clang::Sema::CodeSynthesisContext::SynthesisKind Kind
llvm::PointerUnion< VarTemplateDecl *, VarTemplatePartialSpecializationDecl * > getSpecializedTemplateOrPartial() const
Retrieve the variable template or variable template partial specialization which was specialized by t...
const TemplateArgumentList & getTemplateArgs() const
Retrieve the template arguments of the class template specialization.
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:297
void PrintInstantiationStack()
Prints the current instantiation stack through a series of notes.
One of these records is kept for each identifier that is lexed.
Represents a class template specialization, which refers to a class template with a given set of temp...
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition: Sema.h:8097
TemplateArgument getPackExpansionPattern() const
When the template argument is a pack expansion, returns the pattern of the pack expansion.
TemplateName getNameToSubstitute() const
Get the template name to substitute when this template name is used as a template template argument...
Expr * getAsExpr() const
Retrieve the template argument as an expression.
Definition: TemplateBase.h:329
void setUninstantiatedDefaultArg(Expr *arg)
Definition: Decl.cpp:2732
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:160
A C++ nested-name-specifier augmented with source location information.
NestedNameSpecifierLoc SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS, const MultiLevelTemplateArgumentList &TemplateArgs)
TemplateSpecializationKind getSpecializationKind() const
Determine the kind of specialization that this declaration represents.
The results of name lookup within a DeclContext.
Definition: DeclBase.h:1195
TemplateDecl * getAsTemplateDecl() const
Retrieve the underlying template declaration that this template name refers to, if known...
NamedDecl * getPartiallySubstitutedPack(const TemplateArgument **ExplicitArgs=nullptr, unsigned *NumExplicitArgs=nullptr) const
Retrieve the partially-substitued template parameter pack.
TypeSourceInfo * getTypeSourceInfo(ASTContext &Context, QualType T)
Creates a TypeSourceInfo for the given type.
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:274
bool isAcceptableTagRedeclaration(const TagDecl *Previous, TagTypeKind NewTag, bool isDefinition, SourceLocation NewTagLoc, const IdentifierInfo *Name)
Determine whether a tag with a given kind is acceptable as a redeclaration of the given tag declarati...
Definition: SemaDecl.cpp:14526
Represents a member of a struct/union/class.
Definition: Decl.h:2643
The current expression is potentially evaluated at run time, which means that code may be generated t...
void setArgument(unsigned Depth, unsigned Index, TemplateArgument Arg)
Clear out a specific template argument.
Definition: Template.h:122
SubstTemplateTemplateParmPackStorage * getAsSubstTemplateTemplateParmPack() const
Retrieve the substituted template template parameter pack, if known.
unsigned getFunctionScopeIndex() const
Returns the index of this parameter in its prototype or method scope.
Definition: Decl.h:1653
void setVisibleDespiteOwningModule()
Set that this declaration is globally visible, even if it came from a module that is not visible...
Definition: DeclBase.h:780
NamedDecl * Template
The template (or partial specialization) in which we are performing the instantiation, for substitutions of prior template arguments.
Definition: Sema.h:7705
void startDefinition()
Starts the definition of this tag declaration.
Definition: Decl.cpp:4072
bool usesPartialOrExplicitSpecialization(SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec)
bool isReferenceType() const
Definition: Type.h:6403
bool isDefinedOutsideFunctionOrMethod() const
isDefinedOutsideFunctionOrMethod - This predicate returns true if this scoped decl is defined outside...
Definition: DeclBase.h:855
unsigned getPosition() const
Get the position of the template parameter within its parameter list.
bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc, SourceRange PatternRange, ArrayRef< UnexpandedParameterPack > Unexpanded, const MultiLevelTemplateArgumentList &TemplateArgs, bool &ShouldExpand, bool &RetainExpansion, Optional< unsigned > &NumExpansions)
Determine whether we could expand a pack expansion with the given set of parameter packs into separat...
DeclarationNameInfo SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo, const MultiLevelTemplateArgumentList &TemplateArgs)
Do template substitution on declaration name info.
void set(DeclAccessPair Found, Decl *Spec, DeductionFailureInfo Info)
Represents a reference to a non-type template parameter pack that has been substituted with a non-tem...
Definition: ExprCXX.h:4269
delayed_var_partial_spec_iterator delayed_var_partial_spec_end()
Definition: Template.h:527
QualType getParamTypeForDecl() const
Definition: TemplateBase.h:268
Describes a module or submodule.
Definition: Module.h:64
An r-value expression (a pr-value in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:125
We are instantiating the exception specification for a function template which was deferred until it ...
Definition: Sema.h:7665
unsigned getNumExpansions() const
Get the number of parameters in this parameter pack.
Definition: ExprCXX.h:4378
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:523
PtrTy get() const
Definition: Ownership.h:170
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
TemplateArgument getArgumentPack() const
Retrieve the template argument pack containing the substituted template arguments.
Definition: ExprCXX.cpp:1625
void setTemplateSpecializationKind(TemplateSpecializationKind TSK, SourceLocation PointOfInstantiation=SourceLocation())
For an enumeration member that was instantiated from a member enumeration of a templated class...
Definition: Decl.cpp:4230
TemplateSpecCandidateSet - A set of generalized overload candidates, used in template specializations...
SourceLocation getParameterPackLocation() const
Retrieve the location of the parameter pack name.
Definition: ExprCXX.h:4300
A convenient class for passing around template argument information.
Definition: TemplateBase.h:554
static TemplateArgument getPackSubstitutedTemplateArgument(Sema &S, TemplateArgument Arg)
StmtResult SubstStmt(Stmt *S, const MultiLevelTemplateArgumentList &TemplateArgs)
bool isMemberSpecialization() const
Determines whether this template was a specialization of a member template.
Definition: DeclTemplate.h:872
QualType getNullPtrType() const
Retrieve the type for null non-type template argument.
Definition: TemplateBase.h:274
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition: Expr.h:414
Wrapper for substituted template type parameters.
Definition: TypeLoc.h:840
llvm::DenseSet< Module * > LookupModulesCache
Cache of additional modules that should be used for name lookup within the current template instantia...
Definition: Sema.h:7766
bool containsUnexpandedParameterPack() const
Whether this type is or contains an unexpanded parameter pack, used to support C++0x variadic templat...
Definition: Type.h:1871
Wrapper for substituted template type parameters.
Definition: TypeLoc.h:833
unsigned LastEmittedCodeSynthesisContextDepth
The depth of the context stack at the point when the most recent error or warning was produced...
Definition: Sema.h:7799
SourceLocation PointOfInstantiation
The point of instantiation or synthesis within the source code.
Definition: Sema.h:7697
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this enumeration is an instantiation of a member enumeration of a class template specialization...
Definition: Decl.h:3643
void setInstantiationOf(ClassTemplatePartialSpecializationDecl *PartialSpec, const TemplateArgumentList *TemplateArgs)
Note that this class template specialization is actually an instantiation of the given class template...
VarTemplateDecl * getSpecializedTemplate() const
Retrieve the template that this specialization specializes.
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:40
bool SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg, SourceLocation EqualLoc)
InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, Decl *Entity, SourceRange InstantiationRange=SourceRange())
Note that we are instantiating a class template, function template, variable template, alias template, or a member thereof.
CXXRecordDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:494
const TemplateArgument * getArgs() const
Retrieve the template arguments.
Definition: Type.h:4983
bool hasUnparsedDefaultArg() const
Determines whether this parameter has a default argument that has not yet been parsed.
Definition: Decl.h:1710
CXXBaseSpecifier * CheckBaseSpecifier(CXXRecordDecl *Class, SourceRange SpecifierRange, bool Virtual, AccessSpecifier Access, TypeSourceInfo *TInfo, SourceLocation EllipsisLoc)
ActOnBaseSpecifier - Parsed a base specifier.
Represents a C++ nested-name-specifier or a global scope specifier.
Definition: DeclSpec.h:63
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC)...
Definition: DeclBase.h:828
QualType getExpansionType(unsigned I) const
Retrieve a particular expansion type within an expanded parameter pack.
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
Definition: ExprCXX.h:1818
const LangOptions & getLangOpts() const
Definition: Sema.h:1288
bool isTypeDependent() const
isTypeDependent - Determines whether this expression is type-dependent (C++ [temp.dep.expr]), which means that its type could change from one template instantiation to the next.
Definition: Expr.h:176
bool isLambdaCallOperator(const CXXMethodDecl *MD)
Definition: ASTLambda.h:27
CXXRecordDecl * getTemplatedDecl() const
Get the underlying class declarations of the template.
A default argument (C++ [dcl.fct.default]).
Definition: ExprCXX.h:1202
void setLocStart(SourceLocation L)
Definition: Decl.h:2971
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:877
RAII object used to change the argument pack substitution index within a Sema object.
Definition: Sema.h:7821
void warnStackExhausted(SourceLocation Loc)
Warn that the stack is nearly exhausted.
Definition: Sema.cpp:389
TyLocType push(QualType T)
Pushes space for a new TypeLoc of the given type.
void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation, FunctionDecl *Function, bool Recursive=false, bool DefinitionRequired=false, bool AtEndOfTU=false)
Instantiate the definition of the given function from its template.
A helper class for building up ExtParameterInfos.
Definition: Sema.h:8206
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1609
bool isExpandedParameterPack() const
Whether this parameter is a non-type template parameter pack that has a known list of different types...
bool SubstBaseSpecifiers(CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs)
Perform substitution on the base class specifiers of the given class template specialization.
We are substituting explicit template arguments provided for a function template. ...
Definition: Sema.h:7641
TypeSourceInfo * SubstFunctionDeclType(TypeSourceInfo *T, const MultiLevelTemplateArgumentList &TemplateArgs, SourceLocation Loc, DeclarationName Entity, CXXRecordDecl *ThisContext, Qualifiers ThisTypeQuals)
A form of SubstType intended specifically for instantiating the type of a FunctionDecl.
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:331
Represents a prototype with parameter type info, e.g.
Definition: Type.h:3725
bool InstantiateEnum(SourceLocation PointOfInstantiation, EnumDecl *Instantiation, EnumDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateSpecializationKind TSK)
Instantiate the definition of an enum from a given pattern.
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine whether this particular class is a specialization or instantiation of a class template or m...
Definition: DeclCXX.cpp:1695
std::pair< unsigned, unsigned > getDepthAndIndex(NamedDecl *ND)
Retrieve the depth and index of a template parameter.
Definition: SemaInternal.h:65
static FunctionParmPackExpr * Create(const ASTContext &Context, QualType T, VarDecl *ParamPack, SourceLocation NameLoc, ArrayRef< VarDecl *> Params)
Definition: ExprCXX.cpp:1642
bool CheckSpecializationInstantiationRedecl(SourceLocation NewLoc, TemplateSpecializationKind NewTSK, NamedDecl *PrevDecl, TemplateSpecializationKind PrevTSK, SourceLocation PrevPtOfInstantiation, bool &SuppressNew)
Diagnose cases where we have an explicit template specialization before/after an explicit template in...
bool isParameterPack() const
Whether this parameter is a non-type template parameter pack.
SourceLocation getLocation() const
Definition: Expr.h:1230
void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl, ArrayRef< Decl *> Fields, SourceLocation LBrac, SourceLocation RBrac, const ParsedAttributesView &AttrList)
Definition: SemaDecl.cpp:16422
We are instantiating a template declaration.
Definition: Sema.h:7625
ValueDecl * getAsDecl() const
Retrieve the declaration for a declaration non-type template argument.
Definition: TemplateBase.h:263
Added for Template instantiation observation.
Definition: Sema.h:7690
bool InstantiateInClassInitializer(SourceLocation PointOfInstantiation, FieldDecl *Instantiation, FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs)
Instantiate the definition of a field from the given pattern.
delayed_partial_spec_iterator delayed_partial_spec_begin()
Return an iterator to the beginning of the set of "delayed" partial specializations, which must be passed to InstantiateClassTemplatePartialSpecialization once the class definition has been completed.
Definition: Template.h:511
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Definition: DeclTemplate.h:406
TypeSourceInfo * CheckPackExpansion(TypeSourceInfo *Pattern, SourceLocation EllipsisLoc, Optional< unsigned > NumExpansions)
Construct a pack expansion type from the pattern of the pack expansion.
unsigned getFunctionScopeDepth() const
Definition: Decl.h:1647
MultiLevelTemplateArgumentList getTemplateInstantiationArgs(NamedDecl *D, const TemplateArgumentList *Innermost=nullptr, bool RelativeToPrimary=false, const FunctionDecl *Pattern=nullptr)
Retrieve the template argument list(s) that should be used to instantiate the definition of the given...
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:644
This represents one expression.
Definition: Expr.h:108
Defines the clang::LangOptions interface.
StringRef getKindName() const
Definition: Decl.h:3308
SourceLocation End
The "typename" keyword precedes the qualified type name, e.g., typename T::type.
Definition: Type.h:5144
int Id
Definition: ASTDiff.cpp:190
void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs, const Decl *Pattern, Decl *Inst, LateInstantiatedAttrVec *LateAttrs=nullptr, LocalInstantiationScope *OuterMostScope=nullptr)
bool hasUncompilableErrorOccurred() const
Errors that actually prevent compilation, not those that are upgraded from a warning by -Werror...
Definition: Diagnostic.h:751
Declaration of a template type parameter.
unsigned getIndex() const
Definition: Type.h:4640
ClassTemplatePartialSpecializationDecl * InstantiateClassTemplatePartialSpecialization(ClassTemplateDecl *ClassTemplate, ClassTemplatePartialSpecializationDecl *PartialSpec)
Instantiate the declaration of a class template partial specialization.
void PerformDependentDiagnostics(const DeclContext *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs)
This file defines the classes used to store parsed information about declaration-specifiers and decla...
bool isInvalid() const
Determines whether we have exceeded the maximum recursive template instantiations.
Definition: Sema.h:7971
We are substituting template argument determined as part of template argument deduction for either a ...
Definition: Sema.h:7648
ElaboratedTypeKeyword
The elaboration keyword that precedes a qualified type name or introduces an elaborated-type-specifie...
Definition: Type.h:5126
The template argument is a null pointer or null pointer to member that was provided for a non-type te...
Definition: TemplateBase.h:67
SourceLocation getBeginLoc() const
Retrieve the location of the beginning of this nested-name-specifier.
ExprResult BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc)
Given a non-type template argument that refers to a declaration and the type of its corresponding non...
T getAs() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition: TypeLoc.h:86
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition: DeclBase.cpp:132
const CXXRecordDecl * getTemplateInstantiationPattern() const
Retrieve the record declaration from which this record could be instantiated.
Definition: DeclCXX.cpp:1720
bool InNonInstantiationSFINAEContext
Whether we are in a SFINAE context that is not associated with template instantiation.
Definition: Sema.h:7782
QualType getTagDeclType(const TagDecl *Decl) const
Return the unique reference to the type for the specified TagDecl (struct/union/class/enum) decl...
ClassTemplateDecl * getSpecializedTemplate() const
Retrieve the template that this specialization specializes.
bool isFileContext() const
Definition: DeclBase.h:1849
ParmVarDecl * SubstParmVarDecl(ParmVarDecl *D, const MultiLevelTemplateArgumentList &TemplateArgs, int indexAdjustment, Optional< unsigned > NumExpansions, bool ExpectParameterPack)
DeclContext * getDeclContext()
Definition: DeclBase.h:438
CXXRecordDecl * getDefinition() const
Definition: DeclCXX.h:535
void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl, SourceLocation EqualLoc, Expr *Init)
This is invoked after parsing an in-class initializer for a non-static C++ class member, and after instantiating an in-class initializer in a class template.
NonTypeTemplateParmDecl - Declares a non-type template parameter, e.g., "Size" in.
Represents a C++ template name within the type system.
Definition: TemplateName.h:187
EnumDecl * getDefinition() const
Definition: Decl.h:3496
llvm::PointerUnion< ClassTemplateDecl *, ClassTemplatePartialSpecializationDecl * > getSpecializedTemplateOrPartial() const
Retrieve the class template or class template partial specialization which was specialized by this...
void printTemplateArgumentList(raw_ostream &OS, ArrayRef< TemplateArgument > Args, const PrintingPolicy &Policy)
Print a template argument list, including the &#39;<&#39; and &#39;>&#39; enclosing the template arguments.
int Depth
Definition: ASTDiff.cpp:190
QualType getType() const
Definition: Expr.h:137
void CheckCompletedCXXClass(CXXRecordDecl *Record)
Perform semantic checks on a class definition that has been completing, introducing implicitly-declar...
llvm::FoldingSetVector< ClassTemplatePartialSpecializationDecl > & getPartialSpecializations()
Retrieve the set of partial specializations of this class template.
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:1779
Data structure that captures multiple levels of template argument lists for use in template instantia...
Definition: Template.h:64
bool isInvalid() const
Definition: Ownership.h:166
void setLocation(SourceLocation L)
Definition: DeclBase.h:430
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this class is an instantiation of a member class of a class template specialization, retrieves the member specialization information.
Definition: DeclCXX.cpp:1673
TemplateTemplateParmDecl - Declares a template template parameter, e.g., "T" in.
Represents a reference to a non-type template parameter that has been substituted with a template arg...
Definition: ExprCXX.h:4209
bool isPackExpansion() const
Determine whether this template argument is a pack expansion.
ValueDecl * getDecl()
Definition: Expr.h:1222
SourceLocation getLocation() const
Definition: Expr.h:1930
bool isUsable() const
Definition: Ownership.h:167
The result type of a method or function.
This template specialization was implicitly instantiated from a template.
Definition: Specifiers.h:181
bool isNull() const
Return true if this QualType doesn&#39;t point to a type yet.
Definition: Type.h:708
void setDeclContext(DeclContext *DC)
setDeclContext - Set both the semantic and lexical DeclContext to DC.
Definition: DeclBase.cpp:295
NamedDecl * FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D, const MultiLevelTemplateArgumentList &TemplateArgs, bool FindingInstantiatedContext=false)
Find the instantiation of the given declaration within the current instantiation. ...
PrettyDeclStackTraceEntry - If a crash occurs in the parser while parsing something related to a decl...
Attr * instantiateTemplateAttribute(const Attr *At, ASTContext &C, Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs)
ClassTemplateDecl * getInstantiatedFromMemberTemplate() const
EnumDecl * getInstantiatedFromMemberEnum() const
Returns the enumeration (declared within the template) from which this enumeration type was instantia...
Definition: Decl.cpp:4256
static void deleteScopes(LocalInstantiationScope *Scope, LocalInstantiationScope *Outermost)
deletes the given scope, and all otuer scopes, down to the given outermost scope. ...
Definition: Template.h:360
virtual void printName(raw_ostream &os) const
Definition: Decl.cpp:1546
void ActOnStartCXXInClassMemberInitializer()
Enter a new C++ default initializer scope.
void pushCodeSynthesisContext(CodeSynthesisContext Ctx)
We are declaring an implicit special member function.
Definition: Sema.h:7668
Kind
ActionResult - This structure is used while parsing/acting on expressions, stmts, etc...
Definition: Ownership.h:153
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition: Type.h:3781
TypeLoc IgnoreParens() const
Definition: TypeLoc.h:1162
A stack object to be created when performing template instantiation.
Definition: Sema.h:7858
Attr * instantiateTemplateAttributeForDecl(const Attr *At, ASTContext &C, Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs)
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:3938
bool Subst(const TemplateArgumentLoc *Args, unsigned NumArgs, TemplateArgumentListInfo &Result, const MultiLevelTemplateArgumentList &TemplateArgs)
Encodes a location in the source.
We are computing the exception specification for a defaulted special member function.
Definition: Sema.h:7661
void atTemplateBegin(TemplateInstantiationCallbackPtrs &Callbacks, const Sema &TheSema, const Sema::CodeSynthesisContext &Inst)
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition: Type.h:2137
void setBraceRange(SourceRange R)
Definition: Decl.h:3215
sema::TemplateDeductionInfo * DeductionInfo
The template deduction info object associated with the substitution or checking of explicit or deduce...
Definition: Sema.h:7728
A structure for storing an already-substituted template template parameter pack.
Definition: TemplateName.h:130
DeclarationName getName() const
getName - Returns the embedded declaration name.
Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:3133
TemplateArgument getArgumentPack() const
Definition: Type.cpp:3400
TemplateParameterList * SubstTemplateParams(TemplateParameterList *List)
Instantiates a nested template parameter list in the current instantiation context.
Expr * getInClassInitializer() const
Get the C++11 default member initializer for this member, or null if one has not been set...
Definition: Decl.h:2790
SynthesisKind
The kind of template instantiation we are performing.
Definition: Sema.h:7622
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:1905
VarDecl * getExpansion(unsigned I) const
Get an expansion of the parameter pack by index.
Definition: ExprCXX.h:4381
We are checking the validity of a default template argument that has been used when naming a template...
Definition: Sema.h:7657
bool isParameterPack() const
Definition: Type.h:4641
void reserve(size_t Requested)
Ensures that this buffer has at least as much capacity as described.
unsigned pack_size() const
The number of template arguments in the given template argument pack.
Definition: TemplateBase.h:359
const TemplateTypeParmType * getReplacedParameter() const
Gets the template parameter that was substituted for.
Definition: Type.h:4751
TemplateSpecializationKind getSpecializationKind() const
Determine the kind of specialization that this declaration represents.
static const Decl * getCanonicalParmVarDecl(const Decl *D)
TemplateDeductionResult DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial, const TemplateArgumentList &TemplateArgs, sema::TemplateDeductionInfo &Info)
Perform template argument deduction to determine whether the given template arguments match the given...
void setTagKind(TagKind TK)
Definition: Decl.h:3316
void InstantiateEnumDefinition(EnumDecl *Enum, EnumDecl *Pattern)
llvm::DenseSet< std::pair< Decl *, unsigned > > InstantiatingSpecializations
Specializations whose definitions are currently being instantiated.
Definition: Sema.h:7753
bool hasUninstantiatedDefaultArg() const
Definition: Decl.h:1714
void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, bool DefinitionRequired=false)
Note that the vtable for the given class was used at the given location.
This template specialization was instantiated from a template due to an explicit instantiation defini...
Definition: Specifiers.h:193
Represents a C++11 static_assert declaration.
Definition: DeclCXX.h:3669
DeductionFailureInfo MakeDeductionFailureInfo(ASTContext &Context, Sema::TemplateDeductionResult TDK, sema::TemplateDeductionInfo &Info)
Convert from Sema&#39;s representation of template deduction information to the form used in overload-can...
ArrayRef< ParmVarDecl * > getParams() const
Definition: TypeLoc.h:1428
unsigned getFullDataSize() const
Returns the size of the type source info data block.
Definition: TypeLoc.h:161
bool hasTemplateArgument(unsigned Depth, unsigned Index) const
Determine whether there is a non-NULL template argument at the given depth and index.
Definition: Template.h:109
static TagTypeKind getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword)
Converts an elaborated type keyword into a TagTypeKind.
Definition: Type.cpp:2660
void InstantiatedLocalPackArg(const Decl *D, VarDecl *Inst)
void setHasInheritedDefaultArg(bool I=true)
Definition: Decl.h:1730
const TemplateArgumentList & getTemplateInstantiationArgs() const
Retrieve the set of template arguments that should be used to instantiate the initializer of the vari...
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition: Type.h:2127
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:221
CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD)
getSpecialMember - get the special member enum for a method.
Definition: SemaDecl.cpp:2997
void setTemplateSpecializationKind(TemplateSpecializationKind TSK)
Set the template specialization kind.
Definition: DeclTemplate.h:638
SourceLocation getLocation() const
void InstantiateClassTemplateSpecializationMembers(SourceLocation PointOfInstantiation, ClassTemplateSpecializationDecl *ClassTemplateSpec, TemplateSpecializationKind TSK)
Instantiate the definitions of all of the members of the given class template specialization, which was named as part of an explicit instantiation.
Represents a reference to a function parameter pack or init-capture pack that has been substituted bu...
Definition: ExprCXX.h:4337
Represents a template argument.
Definition: TemplateBase.h:50
void collectUnexpandedParameterPacks(TemplateArgument Arg, SmallVectorImpl< UnexpandedParameterPack > &Unexpanded)
Collect the set of unexpanded parameter packs within the given template argument. ...
TagTypeKind
The kind of a tag type.
Definition: Type.h:5107
bool isNull() const
Determine whether this template name is NULL.
Dataflow Directional Tag Classes.
virtual void getNameForDiagnostic(raw_ostream &OS, const PrintingPolicy &Policy, bool Qualified) const
Appends a human-readable name for this declaration into the given stream.
Definition: Decl.cpp:1667
int ArgumentPackSubstitutionIndex
The current index into pack expansion arguments that will be used for substitution of parameter packs...
Definition: Sema.h:7815
unsigned NumTemplateArgs
The number of template arguments in TemplateArgs.
Definition: Sema.h:7715
[C99 6.4.2.2] - A predefined identifier such as func.
Definition: Expr.h:1878
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1271
The base class of all kinds of template declarations (e.g., class, function, etc.).
Definition: DeclTemplate.h:387
ASTMutationListener * getASTMutationListener() const
Definition: Sema.cpp:427
NonTypeTemplateParmDecl * getParameterPack() const
Retrieve the non-type template parameter pack being substituted.
Definition: ExprCXX.h:4297
QualType getType() const
Get the type for which this source info wrapper provides information.
Definition: TypeLoc.h:130
We are instantiating a default argument for a function.
Definition: Sema.h:7637
QualType RebuildElaboratedType(SourceLocation KeywordLoc, ElaboratedTypeKeyword Keyword, NestedNameSpecifierLoc QualifierLoc, QualType Named)
Build a new qualified name type.
delayed_partial_spec_iterator delayed_partial_spec_end()
Return an iterator to the end of the set of "delayed" partial specializations, which must be passed t...
Definition: Template.h:523
Interesting information about a specific parameter that can&#39;t simply be reflected in parameter&#39;s type...
Definition: Type.h:3419
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition: Specifiers.h:189
RecordDecl * getOuterLexicalRecordContext()
Retrieve the outermost lexically enclosing record context.
Definition: DeclBase.cpp:1770
VarDecl *const * iterator
Iterators over the parameters which the parameter pack expanded into.
Definition: ExprCXX.h:4373
The name of a declaration.
Expr * getDefaultArg()
Definition: Decl.cpp:2695
bool InstantiateClass(SourceLocation PointOfInstantiation, CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateSpecializationKind TSK, bool Complain=true)
Instantiate the definition of a class from a given pattern.
void setInstantiationOfMemberFunction(FunctionDecl *FD, TemplateSpecializationKind TSK)
Specify that this record is an instantiation of the member function FD.
Definition: Decl.h:2480
SourceRange InstantiationRange
The source range that covers the construct that cause the instantiation, e.g., the template-id that c...
Definition: Sema.h:7733
CXXRecordDecl * getInstantiatedFromMemberClass() const
If this record is an instantiation of a member class, retrieves the member class from which it was in...
Definition: DeclCXX.cpp:1666
bool isClassScopeExplicitSpecialization() const
Is this an explicit specialization at class scope (within the class that owns the primary template)...
Represents an enum.
Definition: Decl.h:3395
bool isParameterPack() const
Determine whether this variable is actually a function parameter pack or init-capture pack...
Definition: Decl.cpp:2449
SourceLocation getParameterPackLocation() const
Get the location of the parameter pack.
Definition: ExprCXX.h:4369
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition: Specifiers.h:175
TemplateSpecCandidate & addCandidate()
Add a new candidate with NumConversions conversion sequence slots to the overload set...
Optional< sema::TemplateDeductionInfo * > isSFINAEContext() const
Determines whether we are currently in a context where template argument substitution failures are no...
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspnd...
pack_iterator pack_begin() const
Iterator referencing the first argument of a template argument pack.
Definition: TemplateBase.h:339
ParmVarDecl * CheckParameter(DeclContext *DC, SourceLocation StartLoc, SourceLocation NameLoc, IdentifierInfo *Name, QualType T, TypeSourceInfo *TSInfo, StorageClass SC)
Definition: SemaDecl.cpp:13166
bool isNull() const
Determine whether this template argument has no value.
Definition: TemplateBase.h:237
iterator end() const
Definition: ExprCXX.h:4375
Location wrapper for a TemplateArgument.
Definition: TemplateBase.h:449
RetTy Visit(PTR(Decl) D)
Definition: DeclVisitor.h:37
unsigned getNumArgs() const
Retrieve the number of template arguments.
Definition: Type.h:4988
void setUnparsedDefaultArg()
Specify that this parameter has an unparsed default argument.
Definition: Decl.h:1722
Expr * getUninstantiatedDefaultArg()
Definition: Decl.cpp:2737
void MarkVirtualMembersReferenced(SourceLocation Loc, const CXXRecordDecl *RD, bool ConstexprOnly=false)
MarkVirtualMembersReferenced - Will mark all members of the given CXXRecordDecl referenced.
This template specialization was declared or defined by an explicit specialization (C++ [temp...
Definition: Specifiers.h:185
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:723
UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations
A mapping from parameters with unparsed default arguments to the set of instantiations of each parame...
Definition: Sema.h:1177
The template argument is a type.
Definition: TemplateBase.h:59
Holds information about the various types of exception specification.
Definition: Type.h:3779
SmallVectorImpl< std::pair< VarTemplateDecl *, VarTemplatePartialSpecializationDecl * > >::iterator delayed_var_partial_spec_iterator
Definition: Template.h:505
void SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto, const MultiLevelTemplateArgumentList &Args)
The template argument is actually a parameter pack.
Definition: TemplateBase.h:90
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type...
Definition: Type.cpp:2918
Represents a base class of a C++ class.
Definition: DeclCXX.h:147
bool SavedInNonInstantiationSFINAEContext
Was the enclosing context a non-instantiation SFINAE context?
Definition: Sema.h:7694
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2289
bool isAlreadyInstantiating() const
Determine whether we are already instantiating this specialization in some surrounding active instant...
Definition: Sema.h:7975
A template argument list.
Definition: DeclTemplate.h:224
bool hasFatalErrorOccurred() const
Definition: Diagnostic.h:754
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition: TypeLoc.h:240
ExprResult SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs)
ArgKind getKind() const
Return the kind of stored template argument.
Definition: TemplateBase.h:234
unsigned getDepth() const
Definition: Type.h:4639
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:1008
Represents a C++ struct/union/class.
Definition: DeclCXX.h:255
bool isVoidType() const
Definition: Type.h:6650
static bool NeedsInstantiationAsFunctionType(TypeSourceInfo *T)
bool AttachBaseSpecifiers(CXXRecordDecl *Class, MutableArrayRef< CXXBaseSpecifier *> Bases)
Performs the actual work of attaching the given base class specifiers to a C++ class.
void enableLateAttributeInstantiation(Sema::LateInstantiatedAttrVec *LA)
Definition: Template.h:488
void Clear()
Note that we have finished instantiating this template.
Provides information a specialization of a member of a class template, which may be a member function...
Definition: DeclTemplate.h:607
void atTemplateEnd(TemplateInstantiationCallbackPtrs &Callbacks, const Sema &TheSema, const Sema::CodeSynthesisContext &Inst)
SmallVectorImpl< std::pair< ClassTemplateDecl *, ClassTemplatePartialSpecializationDecl * > >::iterator delayed_partial_spec_iterator
Definition: Template.h:502
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:389
Declaration of a class template.
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string...
Definition: Diagnostic.h:129
We are rewriting a comparison operator in terms of an operator<=>.
Definition: Sema.h:7684
SourceLocation getNameLoc() const
Definition: TypeLoc.h:519
We are substituting prior template arguments into a new template parameter.
Definition: Sema.h:7653
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition: Decl.h:275
ExprResult ExprError()
Definition: Ownership.h:279
ClassTemplatePartialSpecializationDecl * getMoreSpecializedPartialSpecialization(ClassTemplatePartialSpecializationDecl *PS1, ClassTemplatePartialSpecializationDecl *PS2, SourceLocation Loc)
Returns the more specialized class template partial specialization according to the rules of partial ...
const ParmVarDecl * getParam() const
Definition: ExprCXX.h:1237
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2121
QualType getAsType() const
Retrieve the type for a type template argument.
Definition: TemplateBase.h:256
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1146
Represents a type template specialization; the template must be a class template, a type alias templa...
Definition: Type.h:4917
Defines utilities for dealing with stack allocation and stack space.
virtual bool HandleTopLevelDecl(DeclGroupRef D)
HandleTopLevelDecl - Handle the specified top-level declaration.
Definition: ASTConsumer.cpp:18
TypeSourceInfo * SubstType(TypeSourceInfo *T, const MultiLevelTemplateArgumentList &TemplateArgs, SourceLocation Loc, DeclarationName Entity, bool AllowDeducedTST=false)
Perform substitution on the type T with a given set of template arguments.
QualType getType() const
Definition: Decl.h:655
An l-value expression is a reference to an object with independent storage.
Definition: Specifiers.h:129
Wrapper for template type parameters.
Definition: TypeLoc.h:734
A trivial tuple used to represent a source range.
ASTContext & Context
Definition: Sema.h:377
This represents a decl that may have a name.
Definition: Decl.h:248
bool isTranslationUnit() const
Definition: DeclBase.h:1854
T castAs() const
Convert to the specified TypeLoc type, asserting that this TypeLoc is of the desired type...
Definition: TypeLoc.h:75
NamedDecl * getAsNamedDecl(TemplateParameter P)
const TemplateArgumentList & getTemplateInstantiationArgs() const
Retrieve the set of template arguments that should be used to instantiate members of the class templa...
No keyword precedes the qualified type name.
Definition: Type.h:5147
TemplateName getAsTemplate() const
Retrieve the template name for a template name argument.
Definition: TemplateBase.h:280
SourceLocation getPointOfInstantiation() const
Retrieve the first point of instantiation of this member.
Definition: DeclTemplate.h:647
void setPointOfInstantiation(SourceLocation POI)
Set the first point of instantiation.
Definition: DeclTemplate.h:652
bool SubstParmTypes(SourceLocation Loc, ArrayRef< ParmVarDecl *> Params, const FunctionProtoType::ExtParameterInfo *ExtParamInfos, const MultiLevelTemplateArgumentList &TemplateArgs, SmallVectorImpl< QualType > &ParamTypes, SmallVectorImpl< ParmVarDecl *> *OutParams, ExtParameterInfoBuilder &ParamInfos)
Substitute the given template arguments into the given set of parameters, producing the set of parame...
void pushFullCopy(TypeLoc L)
Pushes a copy of the given TypeLoc onto this builder.
SourceLocation getInnerLocStart() const
Return start of source range ignoring outer template declarations.
Definition: Decl.h:737
ExceptionSpecInfo ExceptionSpec
Definition: Type.h:3811
Declaration of a template function.
Definition: DeclTemplate.h:961
Attr - This represents one attribute.
Definition: Attr.h:45
SourceLocation getLocation() const
Definition: DeclBase.h:429
QualType getType() const
Return the type wrapped by this type source info.
Definition: Decl.h:97
virtual void HandleTagDeclDefinition(TagDecl *D)
HandleTagDeclDefinition - This callback is invoked each time a TagDecl (e.g.
Definition: ASTConsumer.h:72
bool isCXXInstanceMember() const
Determine whether the given declaration is an instance member of a C++ class.
Definition: Decl.cpp:1785
A RAII object to temporarily push a declaration context.
Definition: Sema.h:779
static CXXRecordDecl * getPatternForClassTemplateSpecialization(Sema &S, SourceLocation PointOfInstantiation, ClassTemplateSpecializationDecl *ClassTemplateSpec, TemplateSpecializationKind TSK, bool Complain)
Get the instantiation pattern to use to instantiate the definition of a given ClassTemplateSpecializa...