clang  6.0.0svn
SemaTemplateInstantiate.cpp
Go to the documentation of this file.
1 //===------- SemaTemplateInstantiate.cpp - C++ Template Instantiation ------===/
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //===----------------------------------------------------------------------===/
8 //
9 // This file implements C++ template instantiation.
10 //
11 //===----------------------------------------------------------------------===/
12 
14 #include "TreeTransform.h"
15 #include "clang/AST/ASTConsumer.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTLambda.h"
19 #include "clang/AST/DeclTemplate.h"
20 #include "clang/AST/Expr.h"
22 #include "clang/Sema/DeclSpec.h"
24 #include "clang/Sema/Lookup.h"
26 #include "clang/Sema/Template.h"
28 
29 using namespace clang;
30 using namespace sema;
31 
32 //===----------------------------------------------------------------------===/
33 // Template Instantiation Support
34 //===----------------------------------------------------------------------===/
35 
36 /// \brief Retrieve the template argument list(s) that should be used to
37 /// instantiate the definition of the given declaration.
38 ///
39 /// \param D the declaration for which we are computing template instantiation
40 /// arguments.
41 ///
42 /// \param Innermost if non-NULL, the innermost template argument list.
43 ///
44 /// \param RelativeToPrimary true if we should get the template
45 /// arguments relative to the primary template, even when we're
46 /// dealing with a specialization. This is only relevant for function
47 /// template specializations.
48 ///
49 /// \param Pattern If non-NULL, indicates the pattern from which we will be
50 /// instantiating the definition of the given declaration, \p D. This is
51 /// used to determine the proper set of template instantiation arguments for
52 /// friend function template specializations.
55  const TemplateArgumentList *Innermost,
56  bool RelativeToPrimary,
57  const FunctionDecl *Pattern) {
58  // Accumulate the set of template argument lists in this structure.
60 
61  if (Innermost)
62  Result.addOuterTemplateArguments(Innermost);
63 
64  DeclContext *Ctx = dyn_cast<DeclContext>(D);
65  if (!Ctx) {
66  Ctx = D->getDeclContext();
67 
68  // Add template arguments from a variable template instantiation.
70  dyn_cast<VarTemplateSpecializationDecl>(D)) {
71  // We're done when we hit an explicit specialization.
72  if (Spec->getSpecializationKind() == TSK_ExplicitSpecialization &&
73  !isa<VarTemplatePartialSpecializationDecl>(Spec))
74  return Result;
75 
76  Result.addOuterTemplateArguments(&Spec->getTemplateInstantiationArgs());
77 
78  // If this variable template specialization was instantiated from a
79  // specialized member that is a variable template, we're done.
80  assert(Spec->getSpecializedTemplate() && "No variable template?");
81  llvm::PointerUnion<VarTemplateDecl*,
85  Specialized.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
86  if (Partial->isMemberSpecialization())
87  return Result;
88  } else {
89  VarTemplateDecl *Tmpl = Specialized.get<VarTemplateDecl *>();
90  if (Tmpl->isMemberSpecialization())
91  return Result;
92  }
93  }
94 
95  // If we have a template template parameter with translation unit context,
96  // then we're performing substitution into a default template argument of
97  // this template template parameter before we've constructed the template
98  // that will own this template template parameter. In this case, we
99  // use empty template parameter lists for all of the outer templates
100  // to avoid performing any substitutions.
101  if (Ctx->isTranslationUnit()) {
102  if (TemplateTemplateParmDecl *TTP
103  = dyn_cast<TemplateTemplateParmDecl>(D)) {
104  for (unsigned I = 0, N = TTP->getDepth() + 1; I != N; ++I)
105  Result.addOuterTemplateArguments(None);
106  return Result;
107  }
108  }
109  }
110 
111  while (!Ctx->isFileContext()) {
112  // Add template arguments from a class template instantiation.
114  = dyn_cast<ClassTemplateSpecializationDecl>(Ctx)) {
115  // We're done when we hit an explicit specialization.
116  if (Spec->getSpecializationKind() == TSK_ExplicitSpecialization &&
117  !isa<ClassTemplatePartialSpecializationDecl>(Spec))
118  break;
119 
120  Result.addOuterTemplateArguments(&Spec->getTemplateInstantiationArgs());
121 
122  // If this class template specialization was instantiated from a
123  // specialized member that is a class template, we're done.
124  assert(Spec->getSpecializedTemplate() && "No class template?");
125  if (Spec->getSpecializedTemplate()->isMemberSpecialization())
126  break;
127  }
128  // Add template arguments from a function template specialization.
129  else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Ctx)) {
130  if (!RelativeToPrimary &&
131  (Function->getTemplateSpecializationKind() ==
133  !Function->getClassScopeSpecializationPattern()))
134  break;
135 
136  if (const TemplateArgumentList *TemplateArgs
137  = Function->getTemplateSpecializationArgs()) {
138  // Add the template arguments for this specialization.
139  Result.addOuterTemplateArguments(TemplateArgs);
140 
141  // If this function was instantiated from a specialized member that is
142  // a function template, we're done.
143  assert(Function->getPrimaryTemplate() && "No function template?");
144  if (Function->getPrimaryTemplate()->isMemberSpecialization())
145  break;
146 
147  // If this function is a generic lambda specialization, we are done.
149  break;
150 
151  } else if (FunctionTemplateDecl *FunTmpl
152  = Function->getDescribedFunctionTemplate()) {
153  // Add the "injected" template arguments.
154  Result.addOuterTemplateArguments(FunTmpl->getInjectedTemplateArgs());
155  }
156 
157  // If this is a friend declaration and it declares an entity at
158  // namespace scope, take arguments from its lexical parent
159  // instead of its semantic parent, unless of course the pattern we're
160  // instantiating actually comes from the file's context!
161  if (Function->getFriendObjectKind() &&
162  Function->getDeclContext()->isFileContext() &&
163  (!Pattern || !Pattern->getLexicalDeclContext()->isFileContext())) {
164  Ctx = Function->getLexicalDeclContext();
165  RelativeToPrimary = false;
166  continue;
167  }
168  } else if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Ctx)) {
169  if (ClassTemplateDecl *ClassTemplate = Rec->getDescribedClassTemplate()) {
170  QualType T = ClassTemplate->getInjectedClassNameSpecialization();
171  const TemplateSpecializationType *TST =
172  cast<TemplateSpecializationType>(Context.getCanonicalType(T));
174  llvm::makeArrayRef(TST->getArgs(), TST->getNumArgs()));
175  if (ClassTemplate->isMemberSpecialization())
176  break;
177  }
178  }
179 
180  Ctx = Ctx->getParent();
181  RelativeToPrimary = false;
182  }
183 
184  return Result;
185 }
186 
188  switch (Kind) {
189  case TemplateInstantiation:
190  case ExceptionSpecInstantiation:
191  case DefaultTemplateArgumentInstantiation:
192  case DefaultFunctionArgumentInstantiation:
193  case ExplicitTemplateArgumentSubstitution:
194  case DeducedTemplateArgumentSubstitution:
195  case PriorTemplateArgumentSubstitution:
196  return true;
197 
198  case DefaultTemplateArgumentChecking:
199  case DeclaringSpecialMember:
200  case DefiningSynthesizedFunction:
201  return false;
202  }
203 
204  llvm_unreachable("Invalid SynthesisKind!");
205 }
206 
209  SourceLocation PointOfInstantiation, SourceRange InstantiationRange,
210  Decl *Entity, NamedDecl *Template, ArrayRef<TemplateArgument> TemplateArgs,
211  sema::TemplateDeductionInfo *DeductionInfo)
212  : SemaRef(SemaRef) {
213  // Don't allow further instantiation if a fatal error and an uncompilable
214  // error have occurred. Any diagnostics we might have raised will not be
215  // visible, and we do not need to construct a correct AST.
216  if (SemaRef.Diags.hasFatalErrorOccurred() &&
218  Invalid = true;
219  return;
220  }
221  Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
222  if (!Invalid) {
224  Inst.Kind = Kind;
225  Inst.PointOfInstantiation = PointOfInstantiation;
226  Inst.Entity = Entity;
227  Inst.Template = Template;
228  Inst.TemplateArgs = TemplateArgs.data();
229  Inst.NumTemplateArgs = TemplateArgs.size();
230  Inst.DeductionInfo = DeductionInfo;
231  Inst.InstantiationRange = InstantiationRange;
232  SemaRef.pushCodeSynthesisContext(Inst);
233 
234  AlreadyInstantiating =
236  .insert(std::make_pair(Inst.Entity->getCanonicalDecl(), Inst.Kind))
237  .second;
238  }
239 }
240 
242  Sema &SemaRef, SourceLocation PointOfInstantiation, Decl *Entity,
243  SourceRange InstantiationRange)
244  : InstantiatingTemplate(SemaRef,
245  CodeSynthesisContext::TemplateInstantiation,
246  PointOfInstantiation, InstantiationRange, Entity) {}
247 
249  Sema &SemaRef, SourceLocation PointOfInstantiation, FunctionDecl *Entity,
250  ExceptionSpecification, SourceRange InstantiationRange)
252  SemaRef, CodeSynthesisContext::ExceptionSpecInstantiation,
253  PointOfInstantiation, InstantiationRange, Entity) {}
254 
256  Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateParameter Param,
257  TemplateDecl *Template, ArrayRef<TemplateArgument> TemplateArgs,
258  SourceRange InstantiationRange)
260  SemaRef,
261  CodeSynthesisContext::DefaultTemplateArgumentInstantiation,
262  PointOfInstantiation, InstantiationRange, getAsNamedDecl(Param),
263  Template, TemplateArgs) {}
264 
266  Sema &SemaRef, SourceLocation PointOfInstantiation,
267  FunctionTemplateDecl *FunctionTemplate,
268  ArrayRef<TemplateArgument> TemplateArgs,
270  sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
271  : InstantiatingTemplate(SemaRef, Kind, PointOfInstantiation,
272  InstantiationRange, FunctionTemplate, nullptr,
273  TemplateArgs, &DeductionInfo) {
274  assert(
277 }
278 
280  Sema &SemaRef, SourceLocation PointOfInstantiation,
281  TemplateDecl *Template,
282  ArrayRef<TemplateArgument> TemplateArgs,
283  sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
285  SemaRef,
286  CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
287  PointOfInstantiation, InstantiationRange, Template, nullptr,
288  TemplateArgs, &DeductionInfo) {}
289 
291  Sema &SemaRef, SourceLocation PointOfInstantiation,
293  ArrayRef<TemplateArgument> TemplateArgs,
294  sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
296  SemaRef,
297  CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
298  PointOfInstantiation, InstantiationRange, PartialSpec, nullptr,
299  TemplateArgs, &DeductionInfo) {}
300 
302  Sema &SemaRef, SourceLocation PointOfInstantiation,
304  ArrayRef<TemplateArgument> TemplateArgs,
305  sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
307  SemaRef,
308  CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
309  PointOfInstantiation, InstantiationRange, PartialSpec, nullptr,
310  TemplateArgs, &DeductionInfo) {}
311 
313  Sema &SemaRef, SourceLocation PointOfInstantiation, ParmVarDecl *Param,
314  ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange)
316  SemaRef,
317  CodeSynthesisContext::DefaultFunctionArgumentInstantiation,
318  PointOfInstantiation, InstantiationRange, Param, nullptr,
319  TemplateArgs) {}
320 
322  Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template,
324  SourceRange InstantiationRange)
326  SemaRef,
327  CodeSynthesisContext::PriorTemplateArgumentSubstitution,
328  PointOfInstantiation, InstantiationRange, Param, Template,
329  TemplateArgs) {}
330 
332  Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template,
334  SourceRange InstantiationRange)
336  SemaRef,
337  CodeSynthesisContext::PriorTemplateArgumentSubstitution,
338  PointOfInstantiation, InstantiationRange, Param, Template,
339  TemplateArgs) {}
340 
342  Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Template,
343  NamedDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
344  SourceRange InstantiationRange)
346  SemaRef, CodeSynthesisContext::DefaultTemplateArgumentChecking,
347  PointOfInstantiation, InstantiationRange, Param, Template,
348  TemplateArgs) {}
349 
353 
354  CodeSynthesisContexts.push_back(Ctx);
355 
356  if (!Ctx.isInstantiationRecord())
358 }
359 
361  auto &Active = CodeSynthesisContexts.back();
362  if (!Active.isInstantiationRecord()) {
363  assert(NonInstantiationEntries > 0);
365  }
366 
367  InNonInstantiationSFINAEContext = Active.SavedInNonInstantiationSFINAEContext;
368 
369  // Name lookup no longer looks in this template's defining module.
370  assert(CodeSynthesisContexts.size() >=
372  "forgot to remove a lookup module for a template instantiation");
373  if (CodeSynthesisContexts.size() ==
376  LookupModulesCache.erase(M);
378  }
379 
380  // If we've left the code synthesis context for the current context stack,
381  // stop remembering that we've emitted that stack.
382  if (CodeSynthesisContexts.size() ==
385 
386  CodeSynthesisContexts.pop_back();
387 }
388 
390  if (!Invalid) {
391  if (!AlreadyInstantiating) {
392  auto &Active = SemaRef.CodeSynthesisContexts.back();
393  SemaRef.InstantiatingSpecializations.erase(
394  std::make_pair(Active.Entity, Active.Kind));
395  }
396 
397  SemaRef.popCodeSynthesisContext();
398 
399  Invalid = true;
400  }
401 }
402 
403 bool Sema::InstantiatingTemplate::CheckInstantiationDepth(
404  SourceLocation PointOfInstantiation,
405  SourceRange InstantiationRange) {
406  assert(SemaRef.NonInstantiationEntries <=
407  SemaRef.CodeSynthesisContexts.size());
408  if ((SemaRef.CodeSynthesisContexts.size() -
409  SemaRef.NonInstantiationEntries)
410  <= SemaRef.getLangOpts().InstantiationDepth)
411  return false;
412 
413  SemaRef.Diag(PointOfInstantiation,
414  diag::err_template_recursion_depth_exceeded)
415  << SemaRef.getLangOpts().InstantiationDepth
416  << InstantiationRange;
417  SemaRef.Diag(PointOfInstantiation, diag::note_template_recursion_depth)
418  << SemaRef.getLangOpts().InstantiationDepth;
419  return true;
420 }
421 
422 /// \brief Prints the current instantiation stack through a series of
423 /// notes.
425  // Determine which template instantiations to skip, if any.
426  unsigned SkipStart = CodeSynthesisContexts.size(), SkipEnd = SkipStart;
427  unsigned Limit = Diags.getTemplateBacktraceLimit();
428  if (Limit && Limit < CodeSynthesisContexts.size()) {
429  SkipStart = Limit / 2 + Limit % 2;
430  SkipEnd = CodeSynthesisContexts.size() - Limit / 2;
431  }
432 
433  // FIXME: In all of these cases, we need to show the template arguments
434  unsigned InstantiationIdx = 0;
436  Active = CodeSynthesisContexts.rbegin(),
437  ActiveEnd = CodeSynthesisContexts.rend();
438  Active != ActiveEnd;
439  ++Active, ++InstantiationIdx) {
440  // Skip this instantiation?
441  if (InstantiationIdx >= SkipStart && InstantiationIdx < SkipEnd) {
442  if (InstantiationIdx == SkipStart) {
443  // Note that we're skipping instantiations.
444  Diags.Report(Active->PointOfInstantiation,
445  diag::note_instantiation_contexts_suppressed)
446  << unsigned(CodeSynthesisContexts.size() - Limit);
447  }
448  continue;
449  }
450 
451  switch (Active->Kind) {
453  Decl *D = Active->Entity;
454  if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
455  unsigned DiagID = diag::note_template_member_class_here;
456  if (isa<ClassTemplateSpecializationDecl>(Record))
457  DiagID = diag::note_template_class_instantiation_here;
458  Diags.Report(Active->PointOfInstantiation, DiagID)
459  << Record << Active->InstantiationRange;
460  } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
461  unsigned DiagID;
462  if (Function->getPrimaryTemplate())
463  DiagID = diag::note_function_template_spec_here;
464  else
465  DiagID = diag::note_template_member_function_here;
466  Diags.Report(Active->PointOfInstantiation, DiagID)
467  << Function
468  << Active->InstantiationRange;
469  } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
470  Diags.Report(Active->PointOfInstantiation,
471  VD->isStaticDataMember()?
472  diag::note_template_static_data_member_def_here
473  : diag::note_template_variable_def_here)
474  << VD
475  << Active->InstantiationRange;
476  } else if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
477  Diags.Report(Active->PointOfInstantiation,
478  diag::note_template_enum_def_here)
479  << ED
480  << Active->InstantiationRange;
481  } else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
482  Diags.Report(Active->PointOfInstantiation,
483  diag::note_template_nsdmi_here)
484  << FD << Active->InstantiationRange;
485  } else {
486  Diags.Report(Active->PointOfInstantiation,
487  diag::note_template_type_alias_instantiation_here)
488  << cast<TypeAliasTemplateDecl>(D)
489  << Active->InstantiationRange;
490  }
491  break;
492  }
493 
495  TemplateDecl *Template = cast<TemplateDecl>(Active->Template);
496  SmallVector<char, 128> TemplateArgsStr;
497  llvm::raw_svector_ostream OS(TemplateArgsStr);
498  Template->printName(OS);
499  printTemplateArgumentList(OS, Active->template_arguments(),
501  Diags.Report(Active->PointOfInstantiation,
502  diag::note_default_arg_instantiation_here)
503  << OS.str()
504  << Active->InstantiationRange;
505  break;
506  }
507 
509  FunctionTemplateDecl *FnTmpl = cast<FunctionTemplateDecl>(Active->Entity);
510  Diags.Report(Active->PointOfInstantiation,
511  diag::note_explicit_template_arg_substitution_here)
512  << FnTmpl
514  Active->TemplateArgs,
515  Active->NumTemplateArgs)
516  << Active->InstantiationRange;
517  break;
518  }
519 
521  if (FunctionTemplateDecl *FnTmpl =
522  dyn_cast<FunctionTemplateDecl>(Active->Entity)) {
523  Diags.Report(Active->PointOfInstantiation,
524  diag::note_function_template_deduction_instantiation_here)
525  << FnTmpl
526  << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
527  Active->TemplateArgs,
528  Active->NumTemplateArgs)
529  << Active->InstantiationRange;
530  } else {
531  bool IsVar = isa<VarTemplateDecl>(Active->Entity) ||
532  isa<VarTemplateSpecializationDecl>(Active->Entity);
533  bool IsTemplate = false;
534  TemplateParameterList *Params;
535  if (auto *D = dyn_cast<TemplateDecl>(Active->Entity)) {
536  IsTemplate = true;
537  Params = D->getTemplateParameters();
538  } else if (auto *D = dyn_cast<ClassTemplatePartialSpecializationDecl>(
539  Active->Entity)) {
540  Params = D->getTemplateParameters();
541  } else if (auto *D = dyn_cast<VarTemplatePartialSpecializationDecl>(
542  Active->Entity)) {
543  Params = D->getTemplateParameters();
544  } else {
545  llvm_unreachable("unexpected template kind");
546  }
547 
548  Diags.Report(Active->PointOfInstantiation,
549  diag::note_deduced_template_arg_substitution_here)
550  << IsVar << IsTemplate << cast<NamedDecl>(Active->Entity)
551  << getTemplateArgumentBindingsText(Params, Active->TemplateArgs,
552  Active->NumTemplateArgs)
553  << Active->InstantiationRange;
554  }
555  break;
556  }
557 
559  ParmVarDecl *Param = cast<ParmVarDecl>(Active->Entity);
560  FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());
561 
562  SmallVector<char, 128> TemplateArgsStr;
563  llvm::raw_svector_ostream OS(TemplateArgsStr);
564  FD->printName(OS);
565  printTemplateArgumentList(OS, Active->template_arguments(),
567  Diags.Report(Active->PointOfInstantiation,
568  diag::note_default_function_arg_instantiation_here)
569  << OS.str()
570  << Active->InstantiationRange;
571  break;
572  }
573 
575  NamedDecl *Parm = cast<NamedDecl>(Active->Entity);
576  std::string Name;
577  if (!Parm->getName().empty())
578  Name = std::string(" '") + Parm->getName().str() + "'";
579 
580  TemplateParameterList *TemplateParams = nullptr;
581  if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
582  TemplateParams = Template->getTemplateParameters();
583  else
584  TemplateParams =
585  cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
586  ->getTemplateParameters();
587  Diags.Report(Active->PointOfInstantiation,
588  diag::note_prior_template_arg_substitution)
589  << isa<TemplateTemplateParmDecl>(Parm)
590  << Name
591  << getTemplateArgumentBindingsText(TemplateParams,
592  Active->TemplateArgs,
593  Active->NumTemplateArgs)
594  << Active->InstantiationRange;
595  break;
596  }
597 
599  TemplateParameterList *TemplateParams = nullptr;
600  if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
601  TemplateParams = Template->getTemplateParameters();
602  else
603  TemplateParams =
604  cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
605  ->getTemplateParameters();
606 
607  Diags.Report(Active->PointOfInstantiation,
608  diag::note_template_default_arg_checking)
609  << getTemplateArgumentBindingsText(TemplateParams,
610  Active->TemplateArgs,
611  Active->NumTemplateArgs)
612  << Active->InstantiationRange;
613  break;
614  }
615 
617  Diags.Report(Active->PointOfInstantiation,
618  diag::note_template_exception_spec_instantiation_here)
619  << cast<FunctionDecl>(Active->Entity)
620  << Active->InstantiationRange;
621  break;
622 
624  Diags.Report(Active->PointOfInstantiation,
625  diag::note_in_declaration_of_implicit_special_member)
626  << cast<CXXRecordDecl>(Active->Entity) << Active->SpecialMember;
627  break;
628 
630  // FIXME: For synthesized members other than special members, produce a note.
631  auto *MD = dyn_cast<CXXMethodDecl>(Active->Entity);
632  auto CSM = MD ? getSpecialMember(MD) : CXXInvalid;
633  if (CSM != CXXInvalid) {
634  Diags.Report(Active->PointOfInstantiation,
635  diag::note_member_synthesized_at)
636  << CSM << Context.getTagDeclType(MD->getParent());
637  }
638  break;
639  }
640  }
641 }
642 
645  return Optional<TemplateDeductionInfo *>(nullptr);
646 
648  Active = CodeSynthesisContexts.rbegin(),
649  ActiveEnd = CodeSynthesisContexts.rend();
650  Active != ActiveEnd;
651  ++Active)
652  {
653  switch (Active->Kind) {
655  // An instantiation of an alias template may or may not be a SFINAE
656  // context, depending on what else is on the stack.
657  if (isa<TypeAliasTemplateDecl>(Active->Entity))
658  break;
659  // Fall through.
662  // This is a template instantiation, so there is no SFINAE.
663  return None;
664 
668  // A default template argument instantiation and substitution into
669  // template parameters with arguments for prior parameters may or may
670  // not be a SFINAE context; look further up the stack.
671  break;
672 
675  // We're either substitution explicitly-specified template arguments
676  // or deduced template arguments, so SFINAE applies.
677  assert(Active->DeductionInfo && "Missing deduction info pointer");
678  return Active->DeductionInfo;
679 
682  // This happens in a context unrelated to template instantiation, so
683  // there is no SFINAE.
684  return None;
685  }
686 
687  // The inner context was transparent for SFINAE. If it occurred within a
688  // non-instantiation SFINAE context, then SFINAE applies.
689  if (Active->SavedInNonInstantiationSFINAEContext)
690  return Optional<TemplateDeductionInfo *>(nullptr);
691  }
692 
693  return None;
694 }
695 
696 /// \brief Retrieve the depth and index of a parameter pack.
697 static std::pair<unsigned, unsigned>
699  if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ND))
700  return std::make_pair(TTP->getDepth(), TTP->getIndex());
701 
702  if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND))
703  return std::make_pair(NTTP->getDepth(), NTTP->getIndex());
704 
705  TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(ND);
706  return std::make_pair(TTP->getDepth(), TTP->getIndex());
707 }
708 
709 //===----------------------------------------------------------------------===/
710 // Template Instantiation for Types
711 //===----------------------------------------------------------------------===/
712 namespace {
713  class TemplateInstantiator : public TreeTransform<TemplateInstantiator> {
714  const MultiLevelTemplateArgumentList &TemplateArgs;
715  SourceLocation Loc;
716  DeclarationName Entity;
717 
718  public:
719  typedef TreeTransform<TemplateInstantiator> inherited;
720 
721  TemplateInstantiator(Sema &SemaRef,
722  const MultiLevelTemplateArgumentList &TemplateArgs,
723  SourceLocation Loc,
724  DeclarationName Entity)
725  : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc),
726  Entity(Entity) { }
727 
728  /// \brief Determine whether the given type \p T has already been
729  /// transformed.
730  ///
731  /// For the purposes of template instantiation, a type has already been
732  /// transformed if it is NULL or if it is not dependent.
733  bool AlreadyTransformed(QualType T);
734 
735  /// \brief Returns the location of the entity being instantiated, if known.
736  SourceLocation getBaseLocation() { return Loc; }
737 
738  /// \brief Returns the name of the entity being instantiated, if any.
739  DeclarationName getBaseEntity() { return Entity; }
740 
741  /// \brief Sets the "base" location and entity when that
742  /// information is known based on another transformation.
743  void setBase(SourceLocation Loc, DeclarationName Entity) {
744  this->Loc = Loc;
745  this->Entity = Entity;
746  }
747 
748  bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
749  SourceRange PatternRange,
751  bool &ShouldExpand, bool &RetainExpansion,
752  Optional<unsigned> &NumExpansions) {
753  return getSema().CheckParameterPacksForExpansion(EllipsisLoc,
754  PatternRange, Unexpanded,
755  TemplateArgs,
756  ShouldExpand,
757  RetainExpansion,
758  NumExpansions);
759  }
760 
761  void ExpandingFunctionParameterPack(ParmVarDecl *Pack) {
763  }
764 
765  TemplateArgument ForgetPartiallySubstitutedPack() {
767  if (NamedDecl *PartialPack
769  MultiLevelTemplateArgumentList &TemplateArgs
770  = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
771  unsigned Depth, Index;
772  std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
773  if (TemplateArgs.hasTemplateArgument(Depth, Index)) {
774  Result = TemplateArgs(Depth, Index);
775  TemplateArgs.setArgument(Depth, Index, TemplateArgument());
776  }
777  }
778 
779  return Result;
780  }
781 
782  void RememberPartiallySubstitutedPack(TemplateArgument Arg) {
783  if (Arg.isNull())
784  return;
785 
786  if (NamedDecl *PartialPack
788  MultiLevelTemplateArgumentList &TemplateArgs
789  = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
790  unsigned Depth, Index;
791  std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
792  TemplateArgs.setArgument(Depth, Index, Arg);
793  }
794  }
795 
796  /// \brief Transform the given declaration by instantiating a reference to
797  /// this declaration.
798  Decl *TransformDecl(SourceLocation Loc, Decl *D);
799 
800  void transformAttrs(Decl *Old, Decl *New) {
801  SemaRef.InstantiateAttrs(TemplateArgs, Old, New);
802  }
803 
804  void transformedLocalDecl(Decl *Old, Decl *New) {
805  // If we've instantiated the call operator of a lambda or the call
806  // operator template of a generic lambda, update the "instantiation of"
807  // information.
808  auto *NewMD = dyn_cast<CXXMethodDecl>(New);
809  if (NewMD && isLambdaCallOperator(NewMD)) {
810  auto *OldMD = dyn_cast<CXXMethodDecl>(Old);
811  if (auto *NewTD = NewMD->getDescribedFunctionTemplate())
812  NewTD->setInstantiatedFromMemberTemplate(
813  OldMD->getDescribedFunctionTemplate());
814  else
817  }
818 
819  SemaRef.CurrentInstantiationScope->InstantiatedLocal(Old, New);
820 
821  // We recreated a local declaration, but not by instantiating it. There
822  // may be pending dependent diagnostics to produce.
823  if (auto *DC = dyn_cast<DeclContext>(Old))
824  SemaRef.PerformDependentDiagnostics(DC, TemplateArgs);
825  }
826 
827  /// \brief Transform the definition of the given declaration by
828  /// instantiating it.
829  Decl *TransformDefinition(SourceLocation Loc, Decl *D);
830 
831  /// \brief Transform the first qualifier within a scope by instantiating the
832  /// declaration.
833  NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc);
834 
835  /// \brief Rebuild the exception declaration and register the declaration
836  /// as an instantiated local.
837  VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
839  SourceLocation StartLoc,
840  SourceLocation NameLoc,
841  IdentifierInfo *Name);
842 
843  /// \brief Rebuild the Objective-C exception declaration and register the
844  /// declaration as an instantiated local.
845  VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
846  TypeSourceInfo *TSInfo, QualType T);
847 
848  /// \brief Check for tag mismatches when instantiating an
849  /// elaborated type.
850  QualType RebuildElaboratedType(SourceLocation KeywordLoc,
851  ElaboratedTypeKeyword Keyword,
852  NestedNameSpecifierLoc QualifierLoc,
853  QualType T);
854 
856  TransformTemplateName(CXXScopeSpec &SS, TemplateName Name,
857  SourceLocation NameLoc,
858  QualType ObjectType = QualType(),
859  NamedDecl *FirstQualifierInScope = nullptr,
860  bool AllowInjectedClassName = false);
861 
862  const LoopHintAttr *TransformLoopHintAttr(const LoopHintAttr *LH);
863 
864  ExprResult TransformPredefinedExpr(PredefinedExpr *E);
865  ExprResult TransformDeclRefExpr(DeclRefExpr *E);
866  ExprResult TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E);
867 
868  ExprResult TransformTemplateParmRefExpr(DeclRefExpr *E,
870  ExprResult TransformSubstNonTypeTemplateParmPackExpr(
872 
873  /// \brief Rebuild a DeclRefExpr for a ParmVarDecl reference.
874  ExprResult RebuildParmVarDeclRefExpr(ParmVarDecl *PD, SourceLocation Loc);
875 
876  /// \brief Transform a reference to a function parameter pack.
877  ExprResult TransformFunctionParmPackRefExpr(DeclRefExpr *E,
878  ParmVarDecl *PD);
879 
880  /// \brief Transform a FunctionParmPackExpr which was built when we couldn't
881  /// expand a function parameter pack reference which refers to an expanded
882  /// pack.
883  ExprResult TransformFunctionParmPackExpr(FunctionParmPackExpr *E);
884 
885  QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
887  // Call the base version; it will forward to our overridden version below.
888  return inherited::TransformFunctionProtoType(TLB, TL);
889  }
890 
891  template<typename Fn>
892  QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
894  CXXRecordDecl *ThisContext,
895  unsigned ThisTypeQuals,
896  Fn TransformExceptionSpec);
897 
898  ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm,
899  int indexAdjustment,
900  Optional<unsigned> NumExpansions,
901  bool ExpectParameterPack);
902 
903  /// \brief Transforms a template type parameter type by performing
904  /// substitution of the corresponding template type argument.
905  QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
907 
908  /// \brief Transforms an already-substituted template type parameter pack
909  /// into either itself (if we aren't substituting into its pack expansion)
910  /// or the appropriate substituted argument.
911  QualType TransformSubstTemplateTypeParmPackType(TypeLocBuilder &TLB,
913 
914  ExprResult TransformLambdaExpr(LambdaExpr *E) {
915  LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
917  }
918 
919  TemplateParameterList *TransformTemplateParameterList(
920  TemplateParameterList *OrigTPL) {
921  if (!OrigTPL || !OrigTPL->size()) return OrigTPL;
922 
923  DeclContext *Owner = OrigTPL->getParam(0)->getDeclContext();
924  TemplateDeclInstantiator DeclInstantiator(getSema(),
925  /* DeclContext *Owner */ Owner, TemplateArgs);
926  return DeclInstantiator.SubstTemplateParams(OrigTPL);
927  }
928  private:
929  ExprResult transformNonTypeTemplateParmRef(NonTypeTemplateParmDecl *parm,
930  SourceLocation loc,
931  TemplateArgument arg);
932  };
933 }
934 
935 bool TemplateInstantiator::AlreadyTransformed(QualType T) {
936  if (T.isNull())
937  return true;
938 
940  return false;
941 
942  getSema().MarkDeclarationsReferencedInType(Loc, T);
943  return true;
944 }
945 
946 static TemplateArgument
948  assert(S.ArgumentPackSubstitutionIndex >= 0);
949  assert(S.ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
951  if (Arg.isPackExpansion())
952  Arg = Arg.getPackExpansionPattern();
953  return Arg;
954 }
955 
956 Decl *TemplateInstantiator::TransformDecl(SourceLocation Loc, Decl *D) {
957  if (!D)
958  return nullptr;
959 
960  if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(D)) {
961  if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
962  // If the corresponding template argument is NULL or non-existent, it's
963  // because we are performing instantiation from explicitly-specified
964  // template arguments in a function template, but there were some
965  // arguments left unspecified.
966  if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
967  TTP->getPosition()))
968  return D;
969 
970  TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
971 
972  if (TTP->isParameterPack()) {
973  assert(Arg.getKind() == TemplateArgument::Pack &&
974  "Missing argument pack");
975  Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
976  }
977 
979  assert(!Template.isNull() && Template.getAsTemplateDecl() &&
980  "Wrong kind of template template argument");
981  return Template.getAsTemplateDecl();
982  }
983 
984  // Fall through to find the instantiated declaration for this template
985  // template parameter.
986  }
987 
988  return SemaRef.FindInstantiatedDecl(Loc, cast<NamedDecl>(D), TemplateArgs);
989 }
990 
991 Decl *TemplateInstantiator::TransformDefinition(SourceLocation Loc, Decl *D) {
992  Decl *Inst = getSema().SubstDecl(D, getSema().CurContext, TemplateArgs);
993  if (!Inst)
994  return nullptr;
995 
996  getSema().CurrentInstantiationScope->InstantiatedLocal(D, Inst);
997  return Inst;
998 }
999 
1000 NamedDecl *
1001 TemplateInstantiator::TransformFirstQualifierInScope(NamedDecl *D,
1002  SourceLocation Loc) {
1003  // If the first part of the nested-name-specifier was a template type
1004  // parameter, instantiate that type parameter down to a tag type.
1005  if (TemplateTypeParmDecl *TTPD = dyn_cast_or_null<TemplateTypeParmDecl>(D)) {
1006  const TemplateTypeParmType *TTP
1007  = cast<TemplateTypeParmType>(getSema().Context.getTypeDeclType(TTPD));
1008 
1009  if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1010  // FIXME: This needs testing w/ member access expressions.
1011  TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getIndex());
1012 
1013  if (TTP->isParameterPack()) {
1014  assert(Arg.getKind() == TemplateArgument::Pack &&
1015  "Missing argument pack");
1016 
1017  if (getSema().ArgumentPackSubstitutionIndex == -1)
1018  return nullptr;
1019 
1020  Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1021  }
1022 
1023  QualType T = Arg.getAsType();
1024  if (T.isNull())
1025  return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
1026 
1027  if (const TagType *Tag = T->getAs<TagType>())
1028  return Tag->getDecl();
1029 
1030  // The resulting type is not a tag; complain.
1031  getSema().Diag(Loc, diag::err_nested_name_spec_non_tag) << T;
1032  return nullptr;
1033  }
1034  }
1035 
1036  return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
1037 }
1038 
1039 VarDecl *
1040 TemplateInstantiator::RebuildExceptionDecl(VarDecl *ExceptionDecl,
1042  SourceLocation StartLoc,
1043  SourceLocation NameLoc,
1044  IdentifierInfo *Name) {
1045  VarDecl *Var = inherited::RebuildExceptionDecl(ExceptionDecl, Declarator,
1046  StartLoc, NameLoc, Name);
1047  if (Var)
1048  getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
1049  return Var;
1050 }
1051 
1052 VarDecl *TemplateInstantiator::RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
1053  TypeSourceInfo *TSInfo,
1054  QualType T) {
1055  VarDecl *Var = inherited::RebuildObjCExceptionDecl(ExceptionDecl, TSInfo, T);
1056  if (Var)
1057  getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
1058  return Var;
1059 }
1060 
1061 QualType
1062 TemplateInstantiator::RebuildElaboratedType(SourceLocation KeywordLoc,
1063  ElaboratedTypeKeyword Keyword,
1064  NestedNameSpecifierLoc QualifierLoc,
1065  QualType T) {
1066  if (const TagType *TT = T->getAs<TagType>()) {
1067  TagDecl* TD = TT->getDecl();
1068 
1069  SourceLocation TagLocation = KeywordLoc;
1070 
1071  IdentifierInfo *Id = TD->getIdentifier();
1072 
1073  // TODO: should we even warn on struct/class mismatches for this? Seems
1074  // like it's likely to produce a lot of spurious errors.
1075  if (Id && Keyword != ETK_None && Keyword != ETK_Typename) {
1077  if (!SemaRef.isAcceptableTagRedeclaration(TD, Kind, /*isDefinition*/false,
1078  TagLocation, Id)) {
1079  SemaRef.Diag(TagLocation, diag::err_use_with_wrong_tag)
1080  << Id
1081  << FixItHint::CreateReplacement(SourceRange(TagLocation),
1082  TD->getKindName());
1083  SemaRef.Diag(TD->getLocation(), diag::note_previous_use);
1084  }
1085  }
1086  }
1087 
1089  Keyword,
1090  QualifierLoc,
1091  T);
1092 }
1093 
1094 TemplateName TemplateInstantiator::TransformTemplateName(
1095  CXXScopeSpec &SS, TemplateName Name, SourceLocation NameLoc,
1096  QualType ObjectType, NamedDecl *FirstQualifierInScope,
1097  bool AllowInjectedClassName) {
1098  if (TemplateTemplateParmDecl *TTP
1099  = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl())) {
1100  if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1101  // If the corresponding template argument is NULL or non-existent, it's
1102  // because we are performing instantiation from explicitly-specified
1103  // template arguments in a function template, but there were some
1104  // arguments left unspecified.
1105  if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
1106  TTP->getPosition()))
1107  return Name;
1108 
1109  TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
1110 
1111  if (TTP->isParameterPack()) {
1112  assert(Arg.getKind() == TemplateArgument::Pack &&
1113  "Missing argument pack");
1114 
1115  if (getSema().ArgumentPackSubstitutionIndex == -1) {
1116  // We have the template argument pack to substitute, but we're not
1117  // actually expanding the enclosing pack expansion yet. So, just
1118  // keep the entire argument pack.
1119  return getSema().Context.getSubstTemplateTemplateParmPack(TTP, Arg);
1120  }
1121 
1122  Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1123  }
1124 
1125  TemplateName Template = Arg.getAsTemplate().getNameToSubstitute();
1126  assert(!Template.isNull() && "Null template template argument");
1127  assert(!Template.getAsQualifiedTemplateName() &&
1128  "template decl to substitute is qualified?");
1129 
1130  Template = getSema().Context.getSubstTemplateTemplateParm(TTP, Template);
1131  return Template;
1132  }
1133  }
1134 
1137  if (getSema().ArgumentPackSubstitutionIndex == -1)
1138  return Name;
1139 
1140  TemplateArgument Arg = SubstPack->getArgumentPack();
1141  Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1142  return Arg.getAsTemplate().getNameToSubstitute();
1143  }
1144 
1145  return inherited::TransformTemplateName(SS, Name, NameLoc, ObjectType,
1146  FirstQualifierInScope,
1147  AllowInjectedClassName);
1148 }
1149 
1150 ExprResult
1151 TemplateInstantiator::TransformPredefinedExpr(PredefinedExpr *E) {
1152  if (!E->isTypeDependent())
1153  return E;
1154 
1155  return getSema().BuildPredefinedExpr(E->getLocation(), E->getIdentType());
1156 }
1157 
1158 ExprResult
1159 TemplateInstantiator::TransformTemplateParmRefExpr(DeclRefExpr *E,
1160  NonTypeTemplateParmDecl *NTTP) {
1161  // If the corresponding template argument is NULL or non-existent, it's
1162  // because we are performing instantiation from explicitly-specified
1163  // template arguments in a function template, but there were some
1164  // arguments left unspecified.
1165  if (!TemplateArgs.hasTemplateArgument(NTTP->getDepth(),
1166  NTTP->getPosition()))
1167  return E;
1168 
1169  TemplateArgument Arg = TemplateArgs(NTTP->getDepth(), NTTP->getPosition());
1170 
1171  if (TemplateArgs.getNumLevels() != TemplateArgs.getNumSubstitutedLevels()) {
1172  // We're performing a partial substitution, so the substituted argument
1173  // could be dependent. As a result we can't create a SubstNonType*Expr
1174  // node now, since that represents a fully-substituted argument.
1175  // FIXME: We should have some AST representation for this.
1176  if (Arg.getKind() == TemplateArgument::Pack) {
1177  // FIXME: This won't work for alias templates.
1178  assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() &&
1179  "unexpected pack arguments in partial substitution");
1180  Arg = Arg.pack_begin()->getPackExpansionPattern();
1181  }
1182  assert(Arg.getKind() == TemplateArgument::Expression &&
1183  "unexpected nontype template argument kind in partial substitution");
1184  return Arg.getAsExpr();
1185  }
1186 
1187  if (NTTP->isParameterPack()) {
1188  assert(Arg.getKind() == TemplateArgument::Pack &&
1189  "Missing argument pack");
1190 
1191  if (getSema().ArgumentPackSubstitutionIndex == -1) {
1192  // We have an argument pack, but we can't select a particular argument
1193  // out of it yet. Therefore, we'll build an expression to hold on to that
1194  // argument pack.
1195  QualType TargetType = SemaRef.SubstType(NTTP->getType(), TemplateArgs,
1196  E->getLocation(),
1197  NTTP->getDeclName());
1198  if (TargetType.isNull())
1199  return ExprError();
1200 
1201  return new (SemaRef.Context) SubstNonTypeTemplateParmPackExpr(TargetType,
1202  NTTP,
1203  E->getLocation(),
1204  Arg);
1205  }
1206 
1207  Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1208  }
1209 
1210  return transformNonTypeTemplateParmRef(NTTP, E->getLocation(), Arg);
1211 }
1212 
1213 const LoopHintAttr *
1214 TemplateInstantiator::TransformLoopHintAttr(const LoopHintAttr *LH) {
1215  Expr *TransformedExpr = getDerived().TransformExpr(LH->getValue()).get();
1216 
1217  if (TransformedExpr == LH->getValue())
1218  return LH;
1219 
1220  // Generate error if there is a problem with the value.
1221  if (getSema().CheckLoopHintExpr(TransformedExpr, LH->getLocation()))
1222  return LH;
1223 
1224  // Create new LoopHintValueAttr with integral expression in place of the
1225  // non-type template parameter.
1226  return LoopHintAttr::CreateImplicit(
1227  getSema().Context, LH->getSemanticSpelling(), LH->getOption(),
1228  LH->getState(), TransformedExpr, LH->getRange());
1229 }
1230 
1231 ExprResult TemplateInstantiator::transformNonTypeTemplateParmRef(
1233  SourceLocation loc,
1234  TemplateArgument arg) {
1235  ExprResult result;
1236  QualType type;
1237 
1238  // The template argument itself might be an expression, in which
1239  // case we just return that expression.
1240  if (arg.getKind() == TemplateArgument::Expression) {
1241  Expr *argExpr = arg.getAsExpr();
1242  result = argExpr;
1243  type = argExpr->getType();
1244 
1245  } else if (arg.getKind() == TemplateArgument::Declaration ||
1247  ValueDecl *VD;
1248  if (arg.getKind() == TemplateArgument::Declaration) {
1249  VD = cast<ValueDecl>(arg.getAsDecl());
1250 
1251  // Find the instantiation of the template argument. This is
1252  // required for nested templates.
1253  VD = cast_or_null<ValueDecl>(
1254  getSema().FindInstantiatedDecl(loc, VD, TemplateArgs));
1255  if (!VD)
1256  return ExprError();
1257  } else {
1258  // Propagate NULL template argument.
1259  VD = nullptr;
1260  }
1261 
1262  // Derive the type we want the substituted decl to have. This had
1263  // better be non-dependent, or these checks will have serious problems.
1264  if (parm->isExpandedParameterPack()) {
1265  type = parm->getExpansionType(SemaRef.ArgumentPackSubstitutionIndex);
1266  } else if (parm->isParameterPack() &&
1267  isa<PackExpansionType>(parm->getType())) {
1268  type = SemaRef.SubstType(
1269  cast<PackExpansionType>(parm->getType())->getPattern(),
1270  TemplateArgs, loc, parm->getDeclName());
1271  } else {
1272  type = SemaRef.SubstType(VD ? arg.getParamTypeForDecl() : arg.getNullPtrType(),
1273  TemplateArgs, loc, parm->getDeclName());
1274  }
1275  assert(!type.isNull() && "type substitution failed for param type");
1276  assert(!type->isDependentType() && "param type still dependent");
1277  result = SemaRef.BuildExpressionFromDeclTemplateArgument(arg, type, loc);
1278 
1279  if (!result.isInvalid()) type = result.get()->getType();
1280  } else {
1281  result = SemaRef.BuildExpressionFromIntegralTemplateArgument(arg, loc);
1282 
1283  // Note that this type can be different from the type of 'result',
1284  // e.g. if it's an enum type.
1285  type = arg.getIntegralType();
1286  }
1287  if (result.isInvalid()) return ExprError();
1288 
1289  Expr *resultExpr = result.get();
1290  return new (SemaRef.Context) SubstNonTypeTemplateParmExpr(
1291  type, resultExpr->getValueKind(), loc, parm, resultExpr);
1292 }
1293 
1294 ExprResult
1295 TemplateInstantiator::TransformSubstNonTypeTemplateParmPackExpr(
1297  if (getSema().ArgumentPackSubstitutionIndex == -1) {
1298  // We aren't expanding the parameter pack, so just return ourselves.
1299  return E;
1300  }
1301 
1302  TemplateArgument Arg = E->getArgumentPack();
1303  Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1304  return transformNonTypeTemplateParmRef(E->getParameterPack(),
1306  Arg);
1307 }
1308 
1309 ExprResult
1310 TemplateInstantiator::RebuildParmVarDeclRefExpr(ParmVarDecl *PD,
1311  SourceLocation Loc) {
1312  DeclarationNameInfo NameInfo(PD->getDeclName(), Loc);
1313  return getSema().BuildDeclarationNameExpr(CXXScopeSpec(), NameInfo, PD);
1314 }
1315 
1316 ExprResult
1317 TemplateInstantiator::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {
1318  if (getSema().ArgumentPackSubstitutionIndex != -1) {
1319  // We can expand this parameter pack now.
1321  ValueDecl *VD = cast_or_null<ValueDecl>(TransformDecl(E->getExprLoc(), D));
1322  if (!VD)
1323  return ExprError();
1324  return RebuildParmVarDeclRefExpr(cast<ParmVarDecl>(VD), E->getExprLoc());
1325  }
1326 
1327  QualType T = TransformType(E->getType());
1328  if (T.isNull())
1329  return ExprError();
1330 
1331  // Transform each of the parameter expansions into the corresponding
1332  // parameters in the instantiation of the function decl.
1334  Parms.reserve(E->getNumExpansions());
1335  for (FunctionParmPackExpr::iterator I = E->begin(), End = E->end();
1336  I != End; ++I) {
1337  ParmVarDecl *D =
1338  cast_or_null<ParmVarDecl>(TransformDecl(E->getExprLoc(), *I));
1339  if (!D)
1340  return ExprError();
1341  Parms.push_back(D);
1342  }
1343 
1344  return FunctionParmPackExpr::Create(getSema().Context, T,
1345  E->getParameterPack(),
1346  E->getParameterPackLocation(), Parms);
1347 }
1348 
1349 ExprResult
1350 TemplateInstantiator::TransformFunctionParmPackRefExpr(DeclRefExpr *E,
1351  ParmVarDecl *PD) {
1352  typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
1353  llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
1354  = getSema().CurrentInstantiationScope->findInstantiationOf(PD);
1355  assert(Found && "no instantiation for parameter pack");
1356 
1357  Decl *TransformedDecl;
1358  if (DeclArgumentPack *Pack = Found->dyn_cast<DeclArgumentPack *>()) {
1359  // If this is a reference to a function parameter pack which we can
1360  // substitute but can't yet expand, build a FunctionParmPackExpr for it.
1361  if (getSema().ArgumentPackSubstitutionIndex == -1) {
1362  QualType T = TransformType(E->getType());
1363  if (T.isNull())
1364  return ExprError();
1365  return FunctionParmPackExpr::Create(getSema().Context, T, PD,
1366  E->getExprLoc(), *Pack);
1367  }
1368 
1369  TransformedDecl = (*Pack)[getSema().ArgumentPackSubstitutionIndex];
1370  } else {
1371  TransformedDecl = Found->get<Decl*>();
1372  }
1373 
1374  // We have either an unexpanded pack or a specific expansion.
1375  return RebuildParmVarDeclRefExpr(cast<ParmVarDecl>(TransformedDecl),
1376  E->getExprLoc());
1377 }
1378 
1379 ExprResult
1380 TemplateInstantiator::TransformDeclRefExpr(DeclRefExpr *E) {
1381  NamedDecl *D = E->getDecl();
1382 
1383  // Handle references to non-type template parameters and non-type template
1384  // parameter packs.
1385  if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) {
1386  if (NTTP->getDepth() < TemplateArgs.getNumLevels())
1387  return TransformTemplateParmRefExpr(E, NTTP);
1388 
1389  // We have a non-type template parameter that isn't fully substituted;
1390  // FindInstantiatedDecl will find it in the local instantiation scope.
1391  }
1392 
1393  // Handle references to function parameter packs.
1394  if (ParmVarDecl *PD = dyn_cast<ParmVarDecl>(D))
1395  if (PD->isParameterPack())
1396  return TransformFunctionParmPackRefExpr(E, PD);
1397 
1399 }
1400 
1401 ExprResult TemplateInstantiator::TransformCXXDefaultArgExpr(
1402  CXXDefaultArgExpr *E) {
1403  assert(!cast<FunctionDecl>(E->getParam()->getDeclContext())->
1404  getDescribedFunctionTemplate() &&
1405  "Default arg expressions are never formed in dependent cases.");
1406  return SemaRef.BuildCXXDefaultArgExpr(E->getUsedLocation(),
1407  cast<FunctionDecl>(E->getParam()->getDeclContext()),
1408  E->getParam());
1409 }
1410 
1411 template<typename Fn>
1412 QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB,
1414  CXXRecordDecl *ThisContext,
1415  unsigned ThisTypeQuals,
1416  Fn TransformExceptionSpec) {
1417  // We need a local instantiation scope for this function prototype.
1418  LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
1419  return inherited::TransformFunctionProtoType(
1420  TLB, TL, ThisContext, ThisTypeQuals, TransformExceptionSpec);
1421 }
1422 
1423 ParmVarDecl *
1424 TemplateInstantiator::TransformFunctionTypeParam(ParmVarDecl *OldParm,
1425  int indexAdjustment,
1426  Optional<unsigned> NumExpansions,
1427  bool ExpectParameterPack) {
1428  return SemaRef.SubstParmVarDecl(OldParm, TemplateArgs, indexAdjustment,
1429  NumExpansions, ExpectParameterPack);
1430 }
1431 
1432 QualType
1433 TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB,
1435  const TemplateTypeParmType *T = TL.getTypePtr();
1436  if (T->getDepth() < TemplateArgs.getNumLevels()) {
1437  // Replace the template type parameter with its corresponding
1438  // template argument.
1439 
1440  // If the corresponding template argument is NULL or doesn't exist, it's
1441  // because we are performing instantiation from explicitly-specified
1442  // template arguments in a function template class, but there were some
1443  // arguments left unspecified.
1444  if (!TemplateArgs.hasTemplateArgument(T->getDepth(), T->getIndex())) {
1446  = TLB.push<TemplateTypeParmTypeLoc>(TL.getType());
1447  NewTL.setNameLoc(TL.getNameLoc());
1448  return TL.getType();
1449  }
1450 
1451  TemplateArgument Arg = TemplateArgs(T->getDepth(), T->getIndex());
1452 
1453  if (T->isParameterPack()) {
1454  assert(Arg.getKind() == TemplateArgument::Pack &&
1455  "Missing argument pack");
1456 
1457  if (getSema().ArgumentPackSubstitutionIndex == -1) {
1458  // We have the template argument pack, but we're not expanding the
1459  // enclosing pack expansion yet. Just save the template argument
1460  // pack for later substitution.
1462  = getSema().Context.getSubstTemplateTypeParmPackType(T, Arg);
1465  NewTL.setNameLoc(TL.getNameLoc());
1466  return Result;
1467  }
1468 
1469  Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1470  }
1471 
1472  assert(Arg.getKind() == TemplateArgument::Type &&
1473  "Template argument kind mismatch");
1474 
1475  QualType Replacement = Arg.getAsType();
1476 
1477  // TODO: only do this uniquing once, at the start of instantiation.
1479  = getSema().Context.getSubstTemplateTypeParmType(T, Replacement);
1482  NewTL.setNameLoc(TL.getNameLoc());
1483  return Result;
1484  }
1485 
1486  // The template type parameter comes from an inner template (e.g.,
1487  // the template parameter list of a member template inside the
1488  // template we are instantiating). Create a new template type
1489  // parameter with the template "level" reduced by one.
1490  TemplateTypeParmDecl *NewTTPDecl = nullptr;
1491  if (TemplateTypeParmDecl *OldTTPDecl = T->getDecl())
1492  NewTTPDecl = cast_or_null<TemplateTypeParmDecl>(
1493  TransformDecl(TL.getNameLoc(), OldTTPDecl));
1494 
1495  QualType Result = getSema().Context.getTemplateTypeParmType(
1496  T->getDepth() - TemplateArgs.getNumSubstitutedLevels(), T->getIndex(),
1497  T->isParameterPack(), NewTTPDecl);
1499  NewTL.setNameLoc(TL.getNameLoc());
1500  return Result;
1501 }
1502 
1503 QualType
1504 TemplateInstantiator::TransformSubstTemplateTypeParmPackType(
1505  TypeLocBuilder &TLB,
1507  if (getSema().ArgumentPackSubstitutionIndex == -1) {
1508  // We aren't expanding the parameter pack, so just return ourselves.
1511  NewTL.setNameLoc(TL.getNameLoc());
1512  return TL.getType();
1513  }
1514 
1516  Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1517  QualType Result = Arg.getAsType();
1518 
1519  Result = getSema().Context.getSubstTemplateTypeParmType(
1521  Result);
1524  NewTL.setNameLoc(TL.getNameLoc());
1525  return Result;
1526 }
1527 
1528 /// \brief Perform substitution on the type T with a given set of template
1529 /// arguments.
1530 ///
1531 /// This routine substitutes the given template arguments into the
1532 /// type T and produces the instantiated type.
1533 ///
1534 /// \param T the type into which the template arguments will be
1535 /// substituted. If this type is not dependent, it will be returned
1536 /// immediately.
1537 ///
1538 /// \param Args the template arguments that will be
1539 /// substituted for the top-level template parameters within T.
1540 ///
1541 /// \param Loc the location in the source code where this substitution
1542 /// is being performed. It will typically be the location of the
1543 /// declarator (if we're instantiating the type of some declaration)
1544 /// or the location of the type in the source code (if, e.g., we're
1545 /// instantiating the type of a cast expression).
1546 ///
1547 /// \param Entity the name of the entity associated with a declaration
1548 /// being instantiated (if any). May be empty to indicate that there
1549 /// is no such entity (if, e.g., this is a type that occurs as part of
1550 /// a cast expression) or that the entity has no name (e.g., an
1551 /// unnamed function parameter).
1552 ///
1553 /// \param AllowDeducedTST Whether a DeducedTemplateSpecializationType is
1554 /// acceptable as the top level type of the result.
1555 ///
1556 /// \returns If the instantiation succeeds, the instantiated
1557 /// type. Otherwise, produces diagnostics and returns a NULL type.
1559  const MultiLevelTemplateArgumentList &Args,
1560  SourceLocation Loc,
1561  DeclarationName Entity,
1562  bool AllowDeducedTST) {
1563  assert(!CodeSynthesisContexts.empty() &&
1564  "Cannot perform an instantiation without some context on the "
1565  "instantiation stack");
1566 
1567  if (!T->getType()->isInstantiationDependentType() &&
1569  return T;
1570 
1571  TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1572  return AllowDeducedTST ? Instantiator.TransformTypeWithDeducedTST(T)
1573  : Instantiator.TransformType(T);
1574 }
1575 
1577  const MultiLevelTemplateArgumentList &Args,
1578  SourceLocation Loc,
1579  DeclarationName Entity) {
1580  assert(!CodeSynthesisContexts.empty() &&
1581  "Cannot perform an instantiation without some context on the "
1582  "instantiation stack");
1583 
1584  if (TL.getType().isNull())
1585  return nullptr;
1586 
1587  if (!TL.getType()->isInstantiationDependentType() &&
1588  !TL.getType()->isVariablyModifiedType()) {
1589  // FIXME: Make a copy of the TypeLoc data here, so that we can
1590  // return a new TypeSourceInfo. Inefficient!
1591  TypeLocBuilder TLB;
1592  TLB.pushFullCopy(TL);
1593  return TLB.getTypeSourceInfo(Context, TL.getType());
1594  }
1595 
1596  TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1597  TypeLocBuilder TLB;
1598  TLB.reserve(TL.getFullDataSize());
1599  QualType Result = Instantiator.TransformType(TLB, TL);
1600  if (Result.isNull())
1601  return nullptr;
1602 
1603  return TLB.getTypeSourceInfo(Context, Result);
1604 }
1605 
1606 /// Deprecated form of the above.
1608  const MultiLevelTemplateArgumentList &TemplateArgs,
1609  SourceLocation Loc, DeclarationName Entity) {
1610  assert(!CodeSynthesisContexts.empty() &&
1611  "Cannot perform an instantiation without some context on the "
1612  "instantiation stack");
1613 
1614  // If T is not a dependent type or a variably-modified type, there
1615  // is nothing to do.
1617  return T;
1618 
1619  TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity);
1620  return Instantiator.TransformType(T);
1621 }
1622 
1624  if (T->getType()->isInstantiationDependentType() ||
1626  return true;
1627 
1628  TypeLoc TL = T->getTypeLoc().IgnoreParens();
1629  if (!TL.getAs<FunctionProtoTypeLoc>())
1630  return false;
1631 
1633  for (ParmVarDecl *P : FP.getParams()) {
1634  // This must be synthesized from a typedef.
1635  if (!P) continue;
1636 
1637  // If there are any parameters, a new TypeSourceInfo that refers to the
1638  // instantiated parameters must be built.
1639  return true;
1640  }
1641 
1642  return false;
1643 }
1644 
1645 /// A form of SubstType intended specifically for instantiating the
1646 /// type of a FunctionDecl. Its purpose is solely to force the
1647 /// instantiation of default-argument expressions and to avoid
1648 /// instantiating an exception-specification.
1650  const MultiLevelTemplateArgumentList &Args,
1651  SourceLocation Loc,
1652  DeclarationName Entity,
1653  CXXRecordDecl *ThisContext,
1654  unsigned ThisTypeQuals) {
1655  assert(!CodeSynthesisContexts.empty() &&
1656  "Cannot perform an instantiation without some context on the "
1657  "instantiation stack");
1658 
1660  return T;
1661 
1662  TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1663 
1664  TypeLocBuilder TLB;
1665 
1666  TypeLoc TL = T->getTypeLoc();
1667  TLB.reserve(TL.getFullDataSize());
1668 
1669  QualType Result;
1670 
1671  if (FunctionProtoTypeLoc Proto =
1673  // Instantiate the type, other than its exception specification. The
1674  // exception specification is instantiated in InitFunctionInstantiation
1675  // once we've built the FunctionDecl.
1676  // FIXME: Set the exception specification to EST_Uninstantiated here,
1677  // instead of rebuilding the function type again later.
1678  Result = Instantiator.TransformFunctionProtoType(
1679  TLB, Proto, ThisContext, ThisTypeQuals,
1681  bool &Changed) { return false; });
1682  } else {
1683  Result = Instantiator.TransformType(TLB, TL);
1684  }
1685  if (Result.isNull())
1686  return nullptr;
1687 
1688  return TLB.getTypeSourceInfo(Context, Result);
1689 }
1690 
1693  SmallVectorImpl<QualType> &ExceptionStorage,
1694  const MultiLevelTemplateArgumentList &Args) {
1695  assert(ESI.Type != EST_Uninstantiated);
1696 
1697  bool Changed = false;
1698  TemplateInstantiator Instantiator(*this, Args, Loc, DeclarationName());
1699  return Instantiator.TransformExceptionSpec(Loc, ESI, ExceptionStorage,
1700  Changed);
1701 }
1702 
1704  const MultiLevelTemplateArgumentList &Args) {
1706  Proto->getExtProtoInfo().ExceptionSpec;
1707 
1708  SmallVector<QualType, 4> ExceptionStorage;
1710  ESI, ExceptionStorage, Args))
1711  // On error, recover by dropping the exception specification.
1712  ESI.Type = EST_None;
1713 
1714  UpdateExceptionSpec(New, ESI);
1715 }
1716 
1718  const MultiLevelTemplateArgumentList &TemplateArgs,
1719  int indexAdjustment,
1720  Optional<unsigned> NumExpansions,
1721  bool ExpectParameterPack) {
1722  TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
1723  TypeSourceInfo *NewDI = nullptr;
1724 
1725  TypeLoc OldTL = OldDI->getTypeLoc();
1726  if (PackExpansionTypeLoc ExpansionTL = OldTL.getAs<PackExpansionTypeLoc>()) {
1727 
1728  // We have a function parameter pack. Substitute into the pattern of the
1729  // expansion.
1730  NewDI = SubstType(ExpansionTL.getPatternLoc(), TemplateArgs,
1731  OldParm->getLocation(), OldParm->getDeclName());
1732  if (!NewDI)
1733  return nullptr;
1734 
1735  if (NewDI->getType()->containsUnexpandedParameterPack()) {
1736  // We still have unexpanded parameter packs, which means that
1737  // our function parameter is still a function parameter pack.
1738  // Therefore, make its type a pack expansion type.
1739  NewDI = CheckPackExpansion(NewDI, ExpansionTL.getEllipsisLoc(),
1740  NumExpansions);
1741  } else if (ExpectParameterPack) {
1742  // We expected to get a parameter pack but didn't (because the type
1743  // itself is not a pack expansion type), so complain. This can occur when
1744  // the substitution goes through an alias template that "loses" the
1745  // pack expansion.
1746  Diag(OldParm->getLocation(),
1747  diag::err_function_parameter_pack_without_parameter_packs)
1748  << NewDI->getType();
1749  return nullptr;
1750  }
1751  } else {
1752  NewDI = SubstType(OldDI, TemplateArgs, OldParm->getLocation(),
1753  OldParm->getDeclName());
1754  }
1755 
1756  if (!NewDI)
1757  return nullptr;
1758 
1759  if (NewDI->getType()->isVoidType()) {
1760  Diag(OldParm->getLocation(), diag::err_param_with_void_type);
1761  return nullptr;
1762  }
1763 
1765  OldParm->getInnerLocStart(),
1766  OldParm->getLocation(),
1767  OldParm->getIdentifier(),
1768  NewDI->getType(), NewDI,
1769  OldParm->getStorageClass());
1770  if (!NewParm)
1771  return nullptr;
1772 
1773  // Mark the (new) default argument as uninstantiated (if any).
1774  if (OldParm->hasUninstantiatedDefaultArg()) {
1775  Expr *Arg = OldParm->getUninstantiatedDefaultArg();
1776  NewParm->setUninstantiatedDefaultArg(Arg);
1777  } else if (OldParm->hasUnparsedDefaultArg()) {
1778  NewParm->setUnparsedDefaultArg();
1779  UnparsedDefaultArgInstantiations[OldParm].push_back(NewParm);
1780  } else if (Expr *Arg = OldParm->getDefaultArg()) {
1781  FunctionDecl *OwningFunc = cast<FunctionDecl>(OldParm->getDeclContext());
1782  if (OwningFunc->isLexicallyWithinFunctionOrMethod()) {
1783  // Instantiate default arguments for methods of local classes (DR1484)
1784  // and non-defining declarations.
1785  Sema::ContextRAII SavedContext(*this, OwningFunc);
1786  LocalInstantiationScope Local(*this, true);
1787  ExprResult NewArg = SubstExpr(Arg, TemplateArgs);
1788  if (NewArg.isUsable()) {
1789  // It would be nice if we still had this.
1790  SourceLocation EqualLoc = NewArg.get()->getLocStart();
1791  SetParamDefaultArgument(NewParm, NewArg.get(), EqualLoc);
1792  }
1793  } else {
1794  // FIXME: if we non-lazily instantiated non-dependent default args for
1795  // non-dependent parameter types we could remove a bunch of duplicate
1796  // conversion warnings for such arguments.
1797  NewParm->setUninstantiatedDefaultArg(Arg);
1798  }
1799  }
1800 
1802 
1803  if (OldParm->isParameterPack() && !NewParm->isParameterPack()) {
1804  // Add the new parameter to the instantiated parameter pack.
1806  } else {
1807  // Introduce an Old -> New mapping
1808  CurrentInstantiationScope->InstantiatedLocal(OldParm, NewParm);
1809  }
1810 
1811  // FIXME: OldParm may come from a FunctionProtoType, in which case CurContext
1812  // can be anything, is this right ?
1813  NewParm->setDeclContext(CurContext);
1814 
1815  NewParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
1816  OldParm->getFunctionScopeIndex() + indexAdjustment);
1817 
1818  InstantiateAttrs(TemplateArgs, OldParm, NewParm);
1819 
1820  return NewParm;
1821 }
1822 
1823 /// \brief Substitute the given template arguments into the given set of
1824 /// parameters, producing the set of parameter types that would be generated
1825 /// from such a substitution.
1828  const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
1829  const MultiLevelTemplateArgumentList &TemplateArgs,
1830  SmallVectorImpl<QualType> &ParamTypes,
1831  SmallVectorImpl<ParmVarDecl *> *OutParams,
1832  ExtParameterInfoBuilder &ParamInfos) {
1833  assert(!CodeSynthesisContexts.empty() &&
1834  "Cannot perform an instantiation without some context on the "
1835  "instantiation stack");
1836 
1837  TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
1838  DeclarationName());
1839  return Instantiator.TransformFunctionTypeParams(
1840  Loc, Params, nullptr, ExtParamInfos, ParamTypes, OutParams, ParamInfos);
1841 }
1842 
1843 /// \brief Perform substitution on the base class specifiers of the
1844 /// given class template specialization.
1845 ///
1846 /// Produces a diagnostic and returns true on error, returns false and
1847 /// attaches the instantiated base classes to the class template
1848 /// specialization if successful.
1849 bool
1851  CXXRecordDecl *Pattern,
1852  const MultiLevelTemplateArgumentList &TemplateArgs) {
1853  bool Invalid = false;
1854  SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases;
1855  for (const auto &Base : Pattern->bases()) {
1856  if (!Base.getType()->isDependentType()) {
1857  if (const CXXRecordDecl *RD = Base.getType()->getAsCXXRecordDecl()) {
1858  if (RD->isInvalidDecl())
1859  Instantiation->setInvalidDecl();
1860  }
1861  InstantiatedBases.push_back(new (Context) CXXBaseSpecifier(Base));
1862  continue;
1863  }
1864 
1865  SourceLocation EllipsisLoc;
1866  TypeSourceInfo *BaseTypeLoc;
1867  if (Base.isPackExpansion()) {
1868  // This is a pack expansion. See whether we should expand it now, or
1869  // wait until later.
1871  collectUnexpandedParameterPacks(Base.getTypeSourceInfo()->getTypeLoc(),
1872  Unexpanded);
1873  bool ShouldExpand = false;
1874  bool RetainExpansion = false;
1875  Optional<unsigned> NumExpansions;
1876  if (CheckParameterPacksForExpansion(Base.getEllipsisLoc(),
1877  Base.getSourceRange(),
1878  Unexpanded,
1879  TemplateArgs, ShouldExpand,
1880  RetainExpansion,
1881  NumExpansions)) {
1882  Invalid = true;
1883  continue;
1884  }
1885 
1886  // If we should expand this pack expansion now, do so.
1887  if (ShouldExpand) {
1888  for (unsigned I = 0; I != *NumExpansions; ++I) {
1889  Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
1890 
1891  TypeSourceInfo *BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
1892  TemplateArgs,
1893  Base.getSourceRange().getBegin(),
1894  DeclarationName());
1895  if (!BaseTypeLoc) {
1896  Invalid = true;
1897  continue;
1898  }
1899 
1900  if (CXXBaseSpecifier *InstantiatedBase
1901  = CheckBaseSpecifier(Instantiation,
1902  Base.getSourceRange(),
1903  Base.isVirtual(),
1904  Base.getAccessSpecifierAsWritten(),
1905  BaseTypeLoc,
1906  SourceLocation()))
1907  InstantiatedBases.push_back(InstantiatedBase);
1908  else
1909  Invalid = true;
1910  }
1911 
1912  continue;
1913  }
1914 
1915  // The resulting base specifier will (still) be a pack expansion.
1916  EllipsisLoc = Base.getEllipsisLoc();
1917  Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
1918  BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
1919  TemplateArgs,
1920  Base.getSourceRange().getBegin(),
1921  DeclarationName());
1922  } else {
1923  BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
1924  TemplateArgs,
1925  Base.getSourceRange().getBegin(),
1926  DeclarationName());
1927  }
1928 
1929  if (!BaseTypeLoc) {
1930  Invalid = true;
1931  continue;
1932  }
1933 
1934  if (CXXBaseSpecifier *InstantiatedBase
1935  = CheckBaseSpecifier(Instantiation,
1936  Base.getSourceRange(),
1937  Base.isVirtual(),
1938  Base.getAccessSpecifierAsWritten(),
1939  BaseTypeLoc,
1940  EllipsisLoc))
1941  InstantiatedBases.push_back(InstantiatedBase);
1942  else
1943  Invalid = true;
1944  }
1945 
1946  if (!Invalid && AttachBaseSpecifiers(Instantiation, InstantiatedBases))
1947  Invalid = true;
1948 
1949  return Invalid;
1950 }
1951 
1952 // Defined via #include from SemaTemplateInstantiateDecl.cpp
1953 namespace clang {
1954  namespace sema {
1956  const MultiLevelTemplateArgumentList &TemplateArgs);
1958  const Attr *At, ASTContext &C, Sema &S,
1959  const MultiLevelTemplateArgumentList &TemplateArgs);
1960  }
1961 }
1962 
1963 /// \brief Instantiate the definition of a class from a given pattern.
1964 ///
1965 /// \param PointOfInstantiation The point of instantiation within the
1966 /// source code.
1967 ///
1968 /// \param Instantiation is the declaration whose definition is being
1969 /// instantiated. This will be either a class template specialization
1970 /// or a member class of a class template specialization.
1971 ///
1972 /// \param Pattern is the pattern from which the instantiation
1973 /// occurs. This will be either the declaration of a class template or
1974 /// the declaration of a member class of a class template.
1975 ///
1976 /// \param TemplateArgs The template arguments to be substituted into
1977 /// the pattern.
1978 ///
1979 /// \param TSK the kind of implicit or explicit instantiation to perform.
1980 ///
1981 /// \param Complain whether to complain if the class cannot be instantiated due
1982 /// to the lack of a definition.
1983 ///
1984 /// \returns true if an error occurred, false otherwise.
1985 bool
1987  CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
1988  const MultiLevelTemplateArgumentList &TemplateArgs,
1990  bool Complain) {
1991  CXXRecordDecl *PatternDef
1992  = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
1993  if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
1994  Instantiation->getInstantiatedFromMemberClass(),
1995  Pattern, PatternDef, TSK, Complain))
1996  return true;
1997  Pattern = PatternDef;
1998 
1999  // \brief Record the point of instantiation.
2000  if (MemberSpecializationInfo *MSInfo
2001  = Instantiation->getMemberSpecializationInfo()) {
2002  MSInfo->setTemplateSpecializationKind(TSK);
2003  MSInfo->setPointOfInstantiation(PointOfInstantiation);
2004  } else if (ClassTemplateSpecializationDecl *Spec
2005  = dyn_cast<ClassTemplateSpecializationDecl>(Instantiation)) {
2006  Spec->setTemplateSpecializationKind(TSK);
2007  Spec->setPointOfInstantiation(PointOfInstantiation);
2008  }
2009 
2010  InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
2011  if (Inst.isInvalid())
2012  return true;
2013  assert(!Inst.isAlreadyInstantiating() && "should have been caught by caller");
2014  PrettyDeclStackTraceEntry CrashInfo(*this, Instantiation, SourceLocation(),
2015  "instantiating class definition");
2016 
2017  // Enter the scope of this instantiation. We don't use
2018  // PushDeclContext because we don't have a scope.
2019  ContextRAII SavedContext(*this, Instantiation);
2022 
2023  // If this is an instantiation of a local class, merge this local
2024  // instantiation scope with the enclosing scope. Otherwise, every
2025  // instantiation of a class has its own local instantiation scope.
2026  bool MergeWithParentScope = !Instantiation->isDefinedOutsideFunctionOrMethod();
2027  LocalInstantiationScope Scope(*this, MergeWithParentScope);
2028 
2029  // Some class state isn't processed immediately but delayed till class
2030  // instantiation completes. We may not be ready to handle any delayed state
2031  // already on the stack as it might correspond to a different class, so save
2032  // it now and put it back later.
2033  SavePendingParsedClassStateRAII SavedPendingParsedClassState(*this);
2034 
2035  // Pull attributes from the pattern onto the instantiation.
2036  InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
2037 
2038  // Start the definition of this instantiation.
2039  Instantiation->startDefinition();
2040 
2041  // The instantiation is visible here, even if it was first declared in an
2042  // unimported module.
2043  Instantiation->setVisibleDespiteOwningModule();
2044 
2045  // FIXME: This loses the as-written tag kind for an explicit instantiation.
2046  Instantiation->setTagKind(Pattern->getTagKind());
2047 
2048  // Do substitution on the base class specifiers.
2049  if (SubstBaseSpecifiers(Instantiation, Pattern, TemplateArgs))
2050  Instantiation->setInvalidDecl();
2051 
2052  TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
2053  SmallVector<Decl*, 4> Fields;
2054  // Delay instantiation of late parsed attributes.
2055  LateInstantiatedAttrVec LateAttrs;
2056  Instantiator.enableLateAttributeInstantiation(&LateAttrs);
2057 
2058  for (auto *Member : Pattern->decls()) {
2059  // Don't instantiate members not belonging in this semantic context.
2060  // e.g. for:
2061  // @code
2062  // template <int i> class A {
2063  // class B *g;
2064  // };
2065  // @endcode
2066  // 'class B' has the template as lexical context but semantically it is
2067  // introduced in namespace scope.
2068  if (Member->getDeclContext() != Pattern)
2069  continue;
2070 
2071  if (Member->isInvalidDecl()) {
2072  Instantiation->setInvalidDecl();
2073  continue;
2074  }
2075 
2076  Decl *NewMember = Instantiator.Visit(Member);
2077  if (NewMember) {
2078  if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember)) {
2079  Fields.push_back(Field);
2080  } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(NewMember)) {
2081  // C++11 [temp.inst]p1: The implicit instantiation of a class template
2082  // specialization causes the implicit instantiation of the definitions
2083  // of unscoped member enumerations.
2084  // Record a point of instantiation for this implicit instantiation.
2085  if (TSK == TSK_ImplicitInstantiation && !Enum->isScoped() &&
2086  Enum->isCompleteDefinition()) {
2087  MemberSpecializationInfo *MSInfo =Enum->getMemberSpecializationInfo();
2088  assert(MSInfo && "no spec info for member enum specialization");
2090  MSInfo->setPointOfInstantiation(PointOfInstantiation);
2091  }
2092  } else if (StaticAssertDecl *SA = dyn_cast<StaticAssertDecl>(NewMember)) {
2093  if (SA->isFailed()) {
2094  // A static_assert failed. Bail out; instantiating this
2095  // class is probably not meaningful.
2096  Instantiation->setInvalidDecl();
2097  break;
2098  }
2099  }
2100 
2101  if (NewMember->isInvalidDecl())
2102  Instantiation->setInvalidDecl();
2103  } else {
2104  // FIXME: Eventually, a NULL return will mean that one of the
2105  // instantiations was a semantic disaster, and we'll want to mark the
2106  // declaration invalid.
2107  // For now, we expect to skip some members that we can't yet handle.
2108  }
2109  }
2110 
2111  // Finish checking fields.
2112  ActOnFields(nullptr, Instantiation->getLocation(), Instantiation, Fields,
2113  SourceLocation(), SourceLocation(), nullptr);
2114  CheckCompletedCXXClass(Instantiation);
2115 
2116  // Default arguments are parsed, if not instantiated. We can go instantiate
2117  // default arg exprs for default constructors if necessary now.
2118  ActOnFinishCXXNonNestedClass(Instantiation);
2119 
2120  // Instantiate late parsed attributes, and attach them to their decls.
2121  // See Sema::InstantiateAttrs
2122  for (LateInstantiatedAttrVec::iterator I = LateAttrs.begin(),
2123  E = LateAttrs.end(); I != E; ++I) {
2124  assert(CurrentInstantiationScope == Instantiator.getStartingScope());
2125  CurrentInstantiationScope = I->Scope;
2126 
2127  // Allow 'this' within late-parsed attributes.
2128  NamedDecl *ND = dyn_cast<NamedDecl>(I->NewDecl);
2129  CXXRecordDecl *ThisContext =
2130  dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
2131  CXXThisScopeRAII ThisScope(*this, ThisContext, /*TypeQuals*/0,
2132  ND && ND->isCXXInstanceMember());
2133 
2134  Attr *NewAttr =
2135  instantiateTemplateAttribute(I->TmplAttr, Context, *this, TemplateArgs);
2136  I->NewDecl->addAttr(NewAttr);
2138  Instantiator.getStartingScope());
2139  }
2140  Instantiator.disableLateAttributeInstantiation();
2141  LateAttrs.clear();
2142 
2143  ActOnFinishDelayedMemberInitializers(Instantiation);
2144 
2145  // FIXME: We should do something similar for explicit instantiations so they
2146  // end up in the right module.
2147  if (TSK == TSK_ImplicitInstantiation) {
2148  Instantiation->setLocation(Pattern->getLocation());
2149  Instantiation->setLocStart(Pattern->getInnerLocStart());
2150  Instantiation->setBraceRange(Pattern->getBraceRange());
2151  }
2152 
2153  if (!Instantiation->isInvalidDecl()) {
2154  // Perform any dependent diagnostics from the pattern.
2155  PerformDependentDiagnostics(Pattern, TemplateArgs);
2156 
2157  // Instantiate any out-of-line class template partial
2158  // specializations now.
2160  P = Instantiator.delayed_partial_spec_begin(),
2161  PEnd = Instantiator.delayed_partial_spec_end();
2162  P != PEnd; ++P) {
2164  P->first, P->second)) {
2165  Instantiation->setInvalidDecl();
2166  break;
2167  }
2168  }
2169 
2170  // Instantiate any out-of-line variable template partial
2171  // specializations now.
2173  P = Instantiator.delayed_var_partial_spec_begin(),
2174  PEnd = Instantiator.delayed_var_partial_spec_end();
2175  P != PEnd; ++P) {
2177  P->first, P->second)) {
2178  Instantiation->setInvalidDecl();
2179  break;
2180  }
2181  }
2182  }
2183 
2184  // Exit the scope of this instantiation.
2185  SavedContext.pop();
2186 
2187  if (!Instantiation->isInvalidDecl()) {
2188  Consumer.HandleTagDeclDefinition(Instantiation);
2189 
2190  // Always emit the vtable for an explicit instantiation definition
2191  // of a polymorphic class template specialization.
2193  MarkVTableUsed(PointOfInstantiation, Instantiation, true);
2194  }
2195 
2196  return Instantiation->isInvalidDecl();
2197 }
2198 
2199 /// \brief Instantiate the definition of an enum from a given pattern.
2200 ///
2201 /// \param PointOfInstantiation The point of instantiation within the
2202 /// source code.
2203 /// \param Instantiation is the declaration whose definition is being
2204 /// instantiated. This will be a member enumeration of a class
2205 /// temploid specialization, or a local enumeration within a
2206 /// function temploid specialization.
2207 /// \param Pattern The templated declaration from which the instantiation
2208 /// occurs.
2209 /// \param TemplateArgs The template arguments to be substituted into
2210 /// the pattern.
2211 /// \param TSK The kind of implicit or explicit instantiation to perform.
2212 ///
2213 /// \return \c true if an error occurred, \c false otherwise.
2214 bool Sema::InstantiateEnum(SourceLocation PointOfInstantiation,
2215  EnumDecl *Instantiation, EnumDecl *Pattern,
2216  const MultiLevelTemplateArgumentList &TemplateArgs,
2218  EnumDecl *PatternDef = Pattern->getDefinition();
2219  if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
2220  Instantiation->getInstantiatedFromMemberEnum(),
2221  Pattern, PatternDef, TSK,/*Complain*/true))
2222  return true;
2223  Pattern = PatternDef;
2224 
2225  // Record the point of instantiation.
2226  if (MemberSpecializationInfo *MSInfo
2227  = Instantiation->getMemberSpecializationInfo()) {
2228  MSInfo->setTemplateSpecializationKind(TSK);
2229  MSInfo->setPointOfInstantiation(PointOfInstantiation);
2230  }
2231 
2232  InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
2233  if (Inst.isInvalid())
2234  return true;
2235  if (Inst.isAlreadyInstantiating())
2236  return false;
2237  PrettyDeclStackTraceEntry CrashInfo(*this, Instantiation, SourceLocation(),
2238  "instantiating enum definition");
2239 
2240  // The instantiation is visible here, even if it was first declared in an
2241  // unimported module.
2242  Instantiation->setVisibleDespiteOwningModule();
2243 
2244  // Enter the scope of this instantiation. We don't use
2245  // PushDeclContext because we don't have a scope.
2246  ContextRAII SavedContext(*this, Instantiation);
2249 
2250  LocalInstantiationScope Scope(*this, /*MergeWithParentScope*/true);
2251 
2252  // Pull attributes from the pattern onto the instantiation.
2253  InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
2254 
2255  TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
2256  Instantiator.InstantiateEnumDefinition(Instantiation, Pattern);
2257 
2258  // Exit the scope of this instantiation.
2259  SavedContext.pop();
2260 
2261  return Instantiation->isInvalidDecl();
2262 }
2263 
2264 
2265 /// \brief Instantiate the definition of a field from the given pattern.
2266 ///
2267 /// \param PointOfInstantiation The point of instantiation within the
2268 /// source code.
2269 /// \param Instantiation is the declaration whose definition is being
2270 /// instantiated. This will be a class of a class temploid
2271 /// specialization, or a local enumeration within a function temploid
2272 /// specialization.
2273 /// \param Pattern The templated declaration from which the instantiation
2274 /// occurs.
2275 /// \param TemplateArgs The template arguments to be substituted into
2276 /// the pattern.
2277 ///
2278 /// \return \c true if an error occurred, \c false otherwise.
2280  SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
2281  FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs) {
2282  // If there is no initializer, we don't need to do anything.
2283  if (!Pattern->hasInClassInitializer())
2284  return false;
2285 
2286  assert(Instantiation->getInClassInitStyle() ==
2287  Pattern->getInClassInitStyle() &&
2288  "pattern and instantiation disagree about init style");
2289 
2290  // Error out if we haven't parsed the initializer of the pattern yet because
2291  // we are waiting for the closing brace of the outer class.
2292  Expr *OldInit = Pattern->getInClassInitializer();
2293  if (!OldInit) {
2294  RecordDecl *PatternRD = Pattern->getParent();
2295  RecordDecl *OutermostClass = PatternRD->getOuterLexicalRecordContext();
2296  Diag(PointOfInstantiation,
2297  diag::err_in_class_initializer_not_yet_parsed)
2298  << OutermostClass << Pattern;
2299  Diag(Pattern->getLocEnd(), diag::note_in_class_initializer_not_yet_parsed);
2300  Instantiation->setInvalidDecl();
2301  return true;
2302  }
2303 
2304  InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
2305  if (Inst.isInvalid())
2306  return true;
2307  if (Inst.isAlreadyInstantiating()) {
2308  // Error out if we hit an instantiation cycle for this initializer.
2309  Diag(PointOfInstantiation, diag::err_in_class_initializer_cycle)
2310  << Instantiation;
2311  return true;
2312  }
2313  PrettyDeclStackTraceEntry CrashInfo(*this, Instantiation, SourceLocation(),
2314  "instantiating default member init");
2315 
2316  // Enter the scope of this instantiation. We don't use PushDeclContext because
2317  // we don't have a scope.
2318  ContextRAII SavedContext(*this, Instantiation->getParent());
2321 
2322  LocalInstantiationScope Scope(*this, true);
2323 
2324  // Instantiate the initializer.
2326  CXXThisScopeRAII ThisScope(*this, Instantiation->getParent(), /*TypeQuals=*/0);
2327 
2328  ExprResult NewInit = SubstInitializer(OldInit, TemplateArgs,
2329  /*CXXDirectInit=*/false);
2330  Expr *Init = NewInit.get();
2331  assert((!Init || !isa<ParenListExpr>(Init)) && "call-style init in class");
2333  Instantiation, Init ? Init->getLocStart() : SourceLocation(), Init);
2334 
2335  if (auto *L = getASTMutationListener())
2336  L->DefaultMemberInitializerInstantiated(Instantiation);
2337 
2338  // Return true if the in-class initializer is still missing.
2339  return !Instantiation->getInClassInitializer();
2340 }
2341 
2342 namespace {
2343  /// \brief A partial specialization whose template arguments have matched
2344  /// a given template-id.
2345  struct PartialSpecMatchResult {
2347  TemplateArgumentList *Args;
2348  };
2349 }
2350 
2352  SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec) {
2353  if (ClassTemplateSpec->getTemplateSpecializationKind() ==
2355  return true;
2356 
2358  ClassTemplateSpec->getSpecializedTemplate()
2359  ->getPartialSpecializations(PartialSpecs);
2360  for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
2361  TemplateDeductionInfo Info(Loc);
2362  if (!DeduceTemplateArguments(PartialSpecs[I],
2363  ClassTemplateSpec->getTemplateArgs(), Info))
2364  return true;
2365  }
2366 
2367  return false;
2368 }
2369 
2370 /// Get the instantiation pattern to use to instantiate the definition of a
2371 /// given ClassTemplateSpecializationDecl (either the pattern of the primary
2372 /// template or of a partial specialization).
2373 static CXXRecordDecl *
2375  Sema &S, SourceLocation PointOfInstantiation,
2376  ClassTemplateSpecializationDecl *ClassTemplateSpec,
2377  TemplateSpecializationKind TSK, bool Complain) {
2378  Sema::InstantiatingTemplate Inst(S, PointOfInstantiation, ClassTemplateSpec);
2379  if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
2380  return nullptr;
2381 
2382  ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
2383  CXXRecordDecl *Pattern = nullptr;
2384 
2385  // C++ [temp.class.spec.match]p1:
2386  // When a class template is used in a context that requires an
2387  // instantiation of the class, it is necessary to determine
2388  // whether the instantiation is to be generated using the primary
2389  // template or one of the partial specializations. This is done by
2390  // matching the template arguments of the class template
2391  // specialization with the template argument lists of the partial
2392  // specializations.
2393  typedef PartialSpecMatchResult MatchResult;
2396  Template->getPartialSpecializations(PartialSpecs);
2397  TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation);
2398  for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
2399  ClassTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
2400  TemplateDeductionInfo Info(FailedCandidates.getLocation());
2402  Partial, ClassTemplateSpec->getTemplateArgs(), Info)) {
2403  // Store the failed-deduction information for use in diagnostics, later.
2404  // TODO: Actually use the failed-deduction info?
2405  FailedCandidates.addCandidate().set(
2406  DeclAccessPair::make(Template, AS_public), Partial,
2408  (void)Result;
2409  } else {
2410  Matched.push_back(PartialSpecMatchResult());
2411  Matched.back().Partial = Partial;
2412  Matched.back().Args = Info.take();
2413  }
2414  }
2415 
2416  // If we're dealing with a member template where the template parameters
2417  // have been instantiated, this provides the original template parameters
2418  // from which the member template's parameters were instantiated.
2419 
2420  if (Matched.size() >= 1) {
2421  SmallVectorImpl<MatchResult>::iterator Best = Matched.begin();
2422  if (Matched.size() == 1) {
2423  // -- If exactly one matching specialization is found, the
2424  // instantiation is generated from that specialization.
2425  // We don't need to do anything for this.
2426  } else {
2427  // -- If more than one matching specialization is found, the
2428  // partial order rules (14.5.4.2) are used to determine
2429  // whether one of the specializations is more specialized
2430  // than the others. If none of the specializations is more
2431  // specialized than all of the other matching
2432  // specializations, then the use of the class template is
2433  // ambiguous and the program is ill-formed.
2434  for (SmallVectorImpl<MatchResult>::iterator P = Best + 1,
2435  PEnd = Matched.end();
2436  P != PEnd; ++P) {
2438  P->Partial, Best->Partial, PointOfInstantiation) == P->Partial)
2439  Best = P;
2440  }
2441 
2442  // Determine if the best partial specialization is more specialized than
2443  // the others.
2444  bool Ambiguous = false;
2445  for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
2446  PEnd = Matched.end();
2447  P != PEnd; ++P) {
2448  if (P != Best &&
2449  S.getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
2450  PointOfInstantiation) !=
2451  Best->Partial) {
2452  Ambiguous = true;
2453  break;
2454  }
2455  }
2456 
2457  if (Ambiguous) {
2458  // Partial ordering did not produce a clear winner. Complain.
2459  Inst.Clear();
2460  ClassTemplateSpec->setInvalidDecl();
2461  S.Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
2462  << ClassTemplateSpec;
2463 
2464  // Print the matching partial specializations.
2465  for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
2466  PEnd = Matched.end();
2467  P != PEnd; ++P)
2468  S.Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
2470  P->Partial->getTemplateParameters(), *P->Args);
2471 
2472  return nullptr;
2473  }
2474  }
2475 
2476  // Instantiate using the best class template partial specialization.
2477  ClassTemplatePartialSpecializationDecl *OrigPartialSpec = Best->Partial;
2478  while (OrigPartialSpec->getInstantiatedFromMember()) {
2479  // If we've found an explicit specialization of this class template,
2480  // stop here and use that as the pattern.
2481  if (OrigPartialSpec->isMemberSpecialization())
2482  break;
2483 
2484  OrigPartialSpec = OrigPartialSpec->getInstantiatedFromMember();
2485  }
2486 
2487  Pattern = OrigPartialSpec;
2488  ClassTemplateSpec->setInstantiationOf(Best->Partial, Best->Args);
2489  } else {
2490  // -- If no matches are found, the instantiation is generated
2491  // from the primary template.
2492  ClassTemplateDecl *OrigTemplate = Template;
2493  while (OrigTemplate->getInstantiatedFromMemberTemplate()) {
2494  // If we've found an explicit specialization of this class template,
2495  // stop here and use that as the pattern.
2496  if (OrigTemplate->isMemberSpecialization())
2497  break;
2498 
2499  OrigTemplate = OrigTemplate->getInstantiatedFromMemberTemplate();
2500  }
2501 
2502  Pattern = OrigTemplate->getTemplatedDecl();
2503  }
2504 
2505  return Pattern;
2506 }
2507 
2509  SourceLocation PointOfInstantiation,
2510  ClassTemplateSpecializationDecl *ClassTemplateSpec,
2511  TemplateSpecializationKind TSK, bool Complain) {
2512  // Perform the actual instantiation on the canonical declaration.
2513  ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>(
2514  ClassTemplateSpec->getCanonicalDecl());
2515  if (ClassTemplateSpec->isInvalidDecl())
2516  return true;
2517 
2519  *this, PointOfInstantiation, ClassTemplateSpec, TSK, Complain);
2520  if (!Pattern)
2521  return true;
2522 
2523  return InstantiateClass(PointOfInstantiation, ClassTemplateSpec, Pattern,
2524  getTemplateInstantiationArgs(ClassTemplateSpec), TSK,
2525  Complain);
2526 }
2527 
2528 /// \brief Instantiates the definitions of all of the member
2529 /// of the given class, which is an instantiation of a class template
2530 /// or a member class of a template.
2531 void
2533  CXXRecordDecl *Instantiation,
2534  const MultiLevelTemplateArgumentList &TemplateArgs,
2536  // FIXME: We need to notify the ASTMutationListener that we did all of these
2537  // things, in case we have an explicit instantiation definition in a PCM, a
2538  // module, or preamble, and the declaration is in an imported AST.
2539  assert(
2542  (TSK == TSK_ImplicitInstantiation && Instantiation->isLocalClass())) &&
2543  "Unexpected template specialization kind!");
2544  for (auto *D : Instantiation->decls()) {
2545  bool SuppressNew = false;
2546  if (auto *Function = dyn_cast<FunctionDecl>(D)) {
2547  if (FunctionDecl *Pattern
2548  = Function->getInstantiatedFromMemberFunction()) {
2549  MemberSpecializationInfo *MSInfo
2550  = Function->getMemberSpecializationInfo();
2551  assert(MSInfo && "No member specialization information?");
2552  if (MSInfo->getTemplateSpecializationKind()
2554  continue;
2555 
2556  if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2557  Function,
2559  MSInfo->getPointOfInstantiation(),
2560  SuppressNew) ||
2561  SuppressNew)
2562  continue;
2563 
2564  // C++11 [temp.explicit]p8:
2565  // An explicit instantiation definition that names a class template
2566  // specialization explicitly instantiates the class template
2567  // specialization and is only an explicit instantiation definition
2568  // of members whose definition is visible at the point of
2569  // instantiation.
2570  if (TSK == TSK_ExplicitInstantiationDefinition && !Pattern->isDefined())
2571  continue;
2572 
2573  Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2574 
2575  if (Function->isDefined()) {
2576  // Let the ASTConsumer know that this function has been explicitly
2577  // instantiated now, and its linkage might have changed.
2579  } else if (TSK == TSK_ExplicitInstantiationDefinition) {
2580  InstantiateFunctionDefinition(PointOfInstantiation, Function);
2581  } else if (TSK == TSK_ImplicitInstantiation) {
2583  std::make_pair(Function, PointOfInstantiation));
2584  }
2585  }
2586  } else if (auto *Var = dyn_cast<VarDecl>(D)) {
2587  if (isa<VarTemplateSpecializationDecl>(Var))
2588  continue;
2589 
2590  if (Var->isStaticDataMember()) {
2591  MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
2592  assert(MSInfo && "No member specialization information?");
2593  if (MSInfo->getTemplateSpecializationKind()
2595  continue;
2596 
2597  if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2598  Var,
2600  MSInfo->getPointOfInstantiation(),
2601  SuppressNew) ||
2602  SuppressNew)
2603  continue;
2604 
2606  // C++0x [temp.explicit]p8:
2607  // An explicit instantiation definition that names a class template
2608  // specialization explicitly instantiates the class template
2609  // specialization and is only an explicit instantiation definition
2610  // of members whose definition is visible at the point of
2611  // instantiation.
2612  if (!Var->getInstantiatedFromStaticDataMember()->getDefinition())
2613  continue;
2614 
2615  Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2616  InstantiateVariableDefinition(PointOfInstantiation, Var);
2617  } else {
2618  Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2619  }
2620  }
2621  } else if (auto *Record = dyn_cast<CXXRecordDecl>(D)) {
2622  // Always skip the injected-class-name, along with any
2623  // redeclarations of nested classes, since both would cause us
2624  // to try to instantiate the members of a class twice.
2625  // Skip closure types; they'll get instantiated when we instantiate
2626  // the corresponding lambda-expression.
2627  if (Record->isInjectedClassName() || Record->getPreviousDecl() ||
2628  Record->isLambda())
2629  continue;
2630 
2631  MemberSpecializationInfo *MSInfo = Record->getMemberSpecializationInfo();
2632  assert(MSInfo && "No member specialization information?");
2633 
2634  if (MSInfo->getTemplateSpecializationKind()
2636  continue;
2637 
2639  Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment()) &&
2641  // In MSVC and Windows Itanium mode, explicit instantiation decl of the
2642  // outer class doesn't affect the inner class.
2643  continue;
2644  }
2645 
2646  if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2647  Record,
2649  MSInfo->getPointOfInstantiation(),
2650  SuppressNew) ||
2651  SuppressNew)
2652  continue;
2653 
2654  CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
2655  assert(Pattern && "Missing instantiated-from-template information");
2656 
2657  if (!Record->getDefinition()) {
2658  if (!Pattern->getDefinition()) {
2659  // C++0x [temp.explicit]p8:
2660  // An explicit instantiation definition that names a class template
2661  // specialization explicitly instantiates the class template
2662  // specialization and is only an explicit instantiation definition
2663  // of members whose definition is visible at the point of
2664  // instantiation.
2666  MSInfo->setTemplateSpecializationKind(TSK);
2667  MSInfo->setPointOfInstantiation(PointOfInstantiation);
2668  }
2669 
2670  continue;
2671  }
2672 
2673  InstantiateClass(PointOfInstantiation, Record, Pattern,
2674  TemplateArgs,
2675  TSK);
2676  } else {
2678  Record->getTemplateSpecializationKind() ==
2680  Record->setTemplateSpecializationKind(TSK);
2681  MarkVTableUsed(PointOfInstantiation, Record, true);
2682  }
2683  }
2684 
2685  Pattern = cast_or_null<CXXRecordDecl>(Record->getDefinition());
2686  if (Pattern)
2687  InstantiateClassMembers(PointOfInstantiation, Pattern, TemplateArgs,
2688  TSK);
2689  } else if (auto *Enum = dyn_cast<EnumDecl>(D)) {
2690  MemberSpecializationInfo *MSInfo = Enum->getMemberSpecializationInfo();
2691  assert(MSInfo && "No member specialization information?");
2692 
2693  if (MSInfo->getTemplateSpecializationKind()
2695  continue;
2696 
2698  PointOfInstantiation, TSK, Enum,
2700  MSInfo->getPointOfInstantiation(), SuppressNew) ||
2701  SuppressNew)
2702  continue;
2703 
2704  if (Enum->getDefinition())
2705  continue;
2706 
2707  EnumDecl *Pattern = Enum->getTemplateInstantiationPattern();
2708  assert(Pattern && "Missing instantiated-from-template information");
2709 
2711  if (!Pattern->getDefinition())
2712  continue;
2713 
2714  InstantiateEnum(PointOfInstantiation, Enum, Pattern, TemplateArgs, TSK);
2715  } else {
2716  MSInfo->setTemplateSpecializationKind(TSK);
2717  MSInfo->setPointOfInstantiation(PointOfInstantiation);
2718  }
2719  } else if (auto *Field = dyn_cast<FieldDecl>(D)) {
2720  // No need to instantiate in-class initializers during explicit
2721  // instantiation.
2722  if (Field->hasInClassInitializer() && TSK == TSK_ImplicitInstantiation) {
2723  CXXRecordDecl *ClassPattern =
2724  Instantiation->getTemplateInstantiationPattern();
2726  ClassPattern->lookup(Field->getDeclName());
2727  FieldDecl *Pattern = cast<FieldDecl>(Lookup.front());
2728  InstantiateInClassInitializer(PointOfInstantiation, Field, Pattern,
2729  TemplateArgs);
2730  }
2731  }
2732  }
2733 }
2734 
2735 /// \brief Instantiate the definitions of all of the members of the
2736 /// given class template specialization, which was named as part of an
2737 /// explicit instantiation.
2738 void
2740  SourceLocation PointOfInstantiation,
2741  ClassTemplateSpecializationDecl *ClassTemplateSpec,
2743  // C++0x [temp.explicit]p7:
2744  // An explicit instantiation that names a class template
2745  // specialization is an explicit instantion of the same kind
2746  // (declaration or definition) of each of its members (not
2747  // including members inherited from base classes) that has not
2748  // been previously explicitly specialized in the translation unit
2749  // containing the explicit instantiation, except as described
2750  // below.
2751  InstantiateClassMembers(PointOfInstantiation, ClassTemplateSpec,
2752  getTemplateInstantiationArgs(ClassTemplateSpec),
2753  TSK);
2754 }
2755 
2756 StmtResult
2758  if (!S)
2759  return S;
2760 
2761  TemplateInstantiator Instantiator(*this, TemplateArgs,
2762  SourceLocation(),
2763  DeclarationName());
2764  return Instantiator.TransformStmt(S);
2765 }
2766 
2767 ExprResult
2769  if (!E)
2770  return E;
2771 
2772  TemplateInstantiator Instantiator(*this, TemplateArgs,
2773  SourceLocation(),
2774  DeclarationName());
2775  return Instantiator.TransformExpr(E);
2776 }
2777 
2779  const MultiLevelTemplateArgumentList &TemplateArgs,
2780  bool CXXDirectInit) {
2781  TemplateInstantiator Instantiator(*this, TemplateArgs,
2782  SourceLocation(),
2783  DeclarationName());
2784  return Instantiator.TransformInitializer(Init, CXXDirectInit);
2785 }
2786 
2787 bool Sema::SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
2788  const MultiLevelTemplateArgumentList &TemplateArgs,
2789  SmallVectorImpl<Expr *> &Outputs) {
2790  if (Exprs.empty())
2791  return false;
2792 
2793  TemplateInstantiator Instantiator(*this, TemplateArgs,
2794  SourceLocation(),
2795  DeclarationName());
2796  return Instantiator.TransformExprs(Exprs.data(), Exprs.size(),
2797  IsCall, Outputs);
2798 }
2799 
2802  const MultiLevelTemplateArgumentList &TemplateArgs) {
2803  if (!NNS)
2804  return NestedNameSpecifierLoc();
2805 
2806  TemplateInstantiator Instantiator(*this, TemplateArgs, NNS.getBeginLoc(),
2807  DeclarationName());
2808  return Instantiator.TransformNestedNameSpecifierLoc(NNS);
2809 }
2810 
2811 /// \brief Do template substitution on declaration name info.
2814  const MultiLevelTemplateArgumentList &TemplateArgs) {
2815  TemplateInstantiator Instantiator(*this, TemplateArgs, NameInfo.getLoc(),
2816  NameInfo.getName());
2817  return Instantiator.TransformDeclarationNameInfo(NameInfo);
2818 }
2819 
2822  TemplateName Name, SourceLocation Loc,
2823  const MultiLevelTemplateArgumentList &TemplateArgs) {
2824  TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
2825  DeclarationName());
2826  CXXScopeSpec SS;
2827  SS.Adopt(QualifierLoc);
2828  return Instantiator.TransformTemplateName(SS, Name, Loc);
2829 }
2830 
2831 bool Sema::Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
2833  const MultiLevelTemplateArgumentList &TemplateArgs) {
2834  TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
2835  DeclarationName());
2836 
2837  return Instantiator.TransformTemplateArguments(Args, NumArgs, Result);
2838 }
2839 
2840 static const Decl *getCanonicalParmVarDecl(const Decl *D) {
2841  // When storing ParmVarDecls in the local instantiation scope, we always
2842  // want to use the ParmVarDecl from the canonical function declaration,
2843  // since the map is then valid for any redeclaration or definition of that
2844  // function.
2845  if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(D)) {
2846  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
2847  unsigned i = PV->getFunctionScopeIndex();
2848  // This parameter might be from a freestanding function type within the
2849  // function and isn't necessarily referring to one of FD's parameters.
2850  if (FD->getParamDecl(i) == PV)
2851  return FD->getCanonicalDecl()->getParamDecl(i);
2852  }
2853  }
2854  return D;
2855 }
2856 
2857 
2858 llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> *
2860  D = getCanonicalParmVarDecl(D);
2861  for (LocalInstantiationScope *Current = this; Current;
2862  Current = Current->Outer) {
2863 
2864  // Check if we found something within this scope.
2865  const Decl *CheckD = D;
2866  do {
2867  LocalDeclsMap::iterator Found = Current->LocalDecls.find(CheckD);
2868  if (Found != Current->LocalDecls.end())
2869  return &Found->second;
2870 
2871  // If this is a tag declaration, it's possible that we need to look for
2872  // a previous declaration.
2873  if (const TagDecl *Tag = dyn_cast<TagDecl>(CheckD))
2874  CheckD = Tag->getPreviousDecl();
2875  else
2876  CheckD = nullptr;
2877  } while (CheckD);
2878 
2879  // If we aren't combined with our outer scope, we're done.
2880  if (!Current->CombineWithOuterScope)
2881  break;
2882  }
2883 
2884  // If we're performing a partial substitution during template argument
2885  // deduction, we may not have values for template parameters yet.
2886  if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
2887  isa<TemplateTemplateParmDecl>(D))
2888  return nullptr;
2889 
2890  // Local types referenced prior to definition may require instantiation.
2891  if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
2892  if (RD->isLocalClass())
2893  return nullptr;
2894 
2895  // Enumeration types referenced prior to definition may appear as a result of
2896  // error recovery.
2897  if (isa<EnumDecl>(D))
2898  return nullptr;
2899 
2900  // If we didn't find the decl, then we either have a sema bug, or we have a
2901  // forward reference to a label declaration. Return null to indicate that
2902  // we have an uninstantiated label.
2903  assert(isa<LabelDecl>(D) && "declaration not instantiated in this scope");
2904  return nullptr;
2905 }
2906 
2908  D = getCanonicalParmVarDecl(D);
2909  llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
2910  if (Stored.isNull()) {
2911 #ifndef NDEBUG
2912  // It should not be present in any surrounding scope either.
2913  LocalInstantiationScope *Current = this;
2914  while (Current->CombineWithOuterScope && Current->Outer) {
2915  Current = Current->Outer;
2916  assert(Current->LocalDecls.find(D) == Current->LocalDecls.end() &&
2917  "Instantiated local in inner and outer scopes");
2918  }
2919 #endif
2920  Stored = Inst;
2921  } else if (DeclArgumentPack *Pack = Stored.dyn_cast<DeclArgumentPack *>()) {
2922  Pack->push_back(cast<ParmVarDecl>(Inst));
2923  } else {
2924  assert(Stored.get<Decl *>() == Inst && "Already instantiated this local");
2925  }
2926 }
2927 
2929  ParmVarDecl *Inst) {
2930  D = getCanonicalParmVarDecl(D);
2931  DeclArgumentPack *Pack = LocalDecls[D].get<DeclArgumentPack *>();
2932  Pack->push_back(Inst);
2933 }
2934 
2936 #ifndef NDEBUG
2937  // This should be the first time we've been told about this decl.
2938  for (LocalInstantiationScope *Current = this;
2939  Current && Current->CombineWithOuterScope; Current = Current->Outer)
2940  assert(Current->LocalDecls.find(D) == Current->LocalDecls.end() &&
2941  "Creating local pack after instantiation of local");
2942 #endif
2943 
2944  D = getCanonicalParmVarDecl(D);
2945  llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
2946  DeclArgumentPack *Pack = new DeclArgumentPack;
2947  Stored = Pack;
2948  ArgumentPacks.push_back(Pack);
2949 }
2950 
2952  const TemplateArgument *ExplicitArgs,
2953  unsigned NumExplicitArgs) {
2954  assert((!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack) &&
2955  "Already have a partially-substituted pack");
2956  assert((!PartiallySubstitutedPack
2957  || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) &&
2958  "Wrong number of arguments in partially-substituted pack");
2959  PartiallySubstitutedPack = Pack;
2960  ArgsInPartiallySubstitutedPack = ExplicitArgs;
2961  NumArgsInPartiallySubstitutedPack = NumExplicitArgs;
2962 }
2963 
2965  const TemplateArgument **ExplicitArgs,
2966  unsigned *NumExplicitArgs) const {
2967  if (ExplicitArgs)
2968  *ExplicitArgs = nullptr;
2969  if (NumExplicitArgs)
2970  *NumExplicitArgs = 0;
2971 
2972  for (const LocalInstantiationScope *Current = this; Current;
2973  Current = Current->Outer) {
2974  if (Current->PartiallySubstitutedPack) {
2975  if (ExplicitArgs)
2976  *ExplicitArgs = Current->ArgsInPartiallySubstitutedPack;
2977  if (NumExplicitArgs)
2978  *NumExplicitArgs = Current->NumArgsInPartiallySubstitutedPack;
2979 
2980  return Current->PartiallySubstitutedPack;
2981  }
2982 
2983  if (!Current->CombineWithOuterScope)
2984  break;
2985  }
2986 
2987  return nullptr;
2988 }
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:484
void ActOnFinishDelayedMemberInitializers(Decl *Record)
void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex)
Definition: Decl.h:1547
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:7104
FunctionDecl - An instance of this class is created to represent a function declaration or definition...
Definition: Decl.h:1698
delayed_var_partial_spec_iterator delayed_var_partial_spec_begin()
Definition: Template.h:497
no exception specification
const TypeClass * getTypePtr() const
Definition: TypeLoc.h:497
if(T->getSizeExpr()) TRY_TO(TraverseStmt(T -> getSizeExpr()))
SourceLocation getUsedLocation() const
Retrieve the location where this default argument was actually used.
Definition: ExprCXX.h:1086
A (possibly-)qualified type.
Definition: Type.h:653
ASTConsumer & Consumer
Definition: Sema.h:317
TemplateDeductionResult
Describes the result of template argument deduction.
Definition: Sema.h:6832
void InstantiatedLocal(const Decl *D, Decl *Inst)
base_class_range bases()
Definition: DeclCXX.h:773
void UpdateExceptionSpec(FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI)
llvm::PointerUnion3< TemplateTypeParmDecl *, NonTypeTemplateParmDecl *, TemplateTemplateParmDecl * > TemplateParameter
Stores a template parameter of any kind.
Definition: DeclTemplate.h:62
A stack-allocated class that identifies which local variable declaration instantiations are present i...
Definition: Template.h:202
SourceRange getBraceRange() const
Definition: Decl.h:3066
InClassInitStyle getInClassInitStyle() const
Get the kind of (C++11) default member initializer that this field has.
Definition: Decl.h:2584
void addOuterTemplateArguments(const TemplateArgumentList *TemplateArgs)
Add a new outermost level to the multi-level template argument list.
Definition: Template.h:111
Decl * Entity
The entity that is being synthesized.
Definition: Sema.h:7114
bool isMemberSpecialization()
Determines whether this class template partial specialization template was a specialization of a memb...
Stmt - This represents one statement.
Definition: Stmt.h:66
bool isGenericLambdaCallOperatorSpecialization(const CXXMethodDecl *MD)
Definition: ASTLambda.h:39
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:790
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition: Decl.h:1010
ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param)
BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating the default expr if needed...
Definition: SemaExpr.cpp:4590
The template argument is an expression, and we&#39;ve not resolved it to one of the other forms yet...
Definition: TemplateBase.h:87
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:1270
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
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:7162
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:948
SmallVector< Module *, 16 > CodeSynthesisContextLookupModules
Extra modules inspected when performing a lookup during a template instantiation. ...
Definition: Sema.h:7173
const RecordDecl * getParent() const
getParent - Returns the parent of this field declaration, which is the struct in which this field is ...
Definition: Decl.h:2642
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:7564
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
Definition: Diagnostic.h:1207
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:64
NamedDecl * getParam(unsigned Idx)
Definition: DeclTemplate.h:133
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:671
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...
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:7068
VarTemplatePartialSpecializationDecl * InstantiateVarTemplatePartialSpecialization(VarTemplateDecl *VarTemplate, VarTemplatePartialSpecializationDecl *PartialSpec)
Instantiate the declaration of a variable template partial specialization.
TemplateTypeParmDecl * getDecl() const
Definition: Type.h:4224
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:7203
bool hasInClassInitializer() const
Determine whether this member has a C++11 default member initializer.
Definition: Decl.h:2591
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.
LocalInstantiationScope * getStartingScope() const
Definition: Template.h:477
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:125
unsigned getDepth() const
Get the nesting depth of the template parameter.
void InstantiatedLocalPackArg(const Decl *D, ParmVarDecl *Inst)
RAII object that enters a new expression evaluation context.
Definition: Sema.h:10631
VarDecl - An instance of this class is created to represent a variable declaration or definition...
Definition: Decl.h:807
Information about one declarator, including the parsed type information and the identifier.
Definition: DeclSpec.h:1720
DiagnosticsEngine & Diags
Definition: Sema.h:318
const T * getAs() const
Member-template getAs<specific type>&#39;.
Definition: Type.h:6307
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy.
Definition: Sema.h:2128
TypeSourceInfo * SubstFunctionDeclType(TypeSourceInfo *T, const MultiLevelTemplateArgumentList &TemplateArgs, SourceLocation Loc, DeclarationName Entity, CXXRecordDecl *ThisContext, unsigned ThisTypeQuals)
A form of SubstType intended specifically for instantiating the type of a FunctionDecl.
bool hasInheritedDefaultArg() const
Definition: Decl.h:1642
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition: DeclBase.h:1576
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:5040
SmallVectorImpl< std::pair< ClassTemplateDecl *, ClassTemplatePartialSpecializationDecl * > >::iterator delayed_partial_spec_iterator
Definition: Template.h:483
reference front() const
Definition: DeclBase.h:1226
bool isInvalidDecl() const
Definition: DeclBase.h:546
Stores a list of template parameters for a TemplateDecl and its derived classes.
Definition: DeclTemplate.h:68
A context in which code is being synthesized (where a source location alone is not sufficient to iden...
Definition: Sema.h:7056
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template specialization this is.
Definition: DeclTemplate.h:629
ParmVarDecl - Represents a parameter to a function.
Definition: Decl.h:1514
QualType getIntegralType() const
Retrieve the type of the integral value.
Definition: TemplateBase.h:315
iterator begin() const
Definition: ExprCXX.h:3994
const TemplateArgument * TemplateArgs
The list of template arguments we are substituting, if they are not part of the entity.
Definition: Sema.h:7123
const FunctionDecl * isLocalClass() const
If the class is a local class [class.local], returns the enclosing function declaration.
Definition: DeclCXX.h:1572
void setTemplateSpecializationKind(TemplateSpecializationKind TSK)
Set the kind of specialization or template instantiation this is.
Definition: DeclCXX.cpp:1398
IdentifierInfo * getIdentifier() const
getIdentifier - Get the identifier that names this declaration, if there is one.
Definition: Decl.h:265
bool isLexicallyWithinFunctionOrMethod() const
Returns true if this declaration lexically is inside a function.
Definition: DeclBase.cpp:324
Base wrapper for a particular "section" of type source info.
Definition: TypeLoc.h:56
RecordDecl - Represents a struct/union/class.
Definition: Decl.h:3482
A semantic tree transformation that allows one to transform one abstract syntax tree into another...
Definition: TreeTransform.h:96
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
getDeclName - Get the actual, stored name of the declaration, which may be a special name...
Definition: Decl.h:291
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...
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:859
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition: Sema.h:7484
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:330
void setUninstantiatedDefaultArg(Expr *arg)
Definition: Decl.cpp:2526
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:149
A C++ nested-name-specifier augmented with source location information.
NestedNameSpecifierLoc SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS, const MultiLevelTemplateArgumentList &TemplateArgs)
The results of name lookup within a DeclContext.
Definition: DeclBase.h:1178
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.
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:12914
FieldDecl - An instance of this class is created by Sema::ActOnField to represent a member of a struc...
Definition: Decl.h:2461
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:100
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:1567
void setVisibleDespiteOwningModule()
Set that this declaration is globally visible, even if it came from a module that is not visible...
Definition: DeclBase.h:772
NamedDecl * Template
The template (or partial specialization) in which we are performing the instantiation, for substitutions of prior template arguments.
Definition: Sema.h:7119
void startDefinition()
Starts the definition of this tag declaration.
Definition: Decl.cpp:3702
bool usesPartialOrExplicitSpecialization(SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec)
Interesting information about a specific parameter that can&#39;t simply be reflected in parameter&#39;s type...
Definition: Type.h:3291
bool isDefinedOutsideFunctionOrMethod() const
isDefinedOutsideFunctionOrMethod - This predicate returns true if this scoped decl is defined outside...
Definition: DeclBase.h:843
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:3894
delayed_var_partial_spec_iterator delayed_var_partial_spec_end()
Definition: Template.h:509
QualType getParamTypeForDecl() const
Definition: TemplateBase.h:269
Describes a module or submodule.
Definition: Module.h:65
We are instantiating the exception specification for a function template which was deferred until it ...
Definition: Sema.h:7097
unsigned getNumExpansions() const
Get the number of parameters in this parameter pack.
Definition: ExprCXX.h:3998
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:522
PtrTy get() const
Definition: Ownership.h:162
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
TemplateArgument getArgumentPack() const
Retrieve the template argument pack containing the substituted template arguments.
Definition: ExprCXX.cpp:1341
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:3845
TagKind getTagKind() const
Definition: Decl.h:3150
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:3924
A convenient class for passing around template argument information.
Definition: TemplateBase.h:546
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:869
QualType getNullPtrType() const
Retrieve the type for null non-type template argument.
Definition: TemplateBase.h:275
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition: Expr.h:405
Wrapper for substituted template type parameters.
Definition: TypeLoc.h:839
llvm::DenseSet< Module * > LookupModulesCache
Cache of additional modules that should be used for name lookup within the current template instantia...
Definition: Sema.h:7178
bool containsUnexpandedParameterPack() const
Whether this type is or contains an unexpanded parameter pack, used to support C++0x variadic templat...
Definition: Type.h:1635
Wrapper for substituted template type parameters.
Definition: TypeLoc.h:832
unsigned LastEmittedCodeSynthesisContextDepth
The depth of the context stack at the point when the most recent error or warning was produced...
Definition: Sema.h:7211
SourceLocation PointOfInstantiation
The point of instantiation or synthesis within the source code.
Definition: Sema.h:7111
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this enumeration is an instantiation of a member enumeration of a class template specialization...
Definition: Decl.h:3463
void setInstantiationOf(ClassTemplatePartialSpecializationDecl *PartialSpec, const TemplateArgumentList *TemplateArgs)
Note that this class template specialization is actually an instantiation of the given class template...
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:39
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:705
const TemplateArgument * getArgs() const
Retrieve the template arguments.
Definition: Type.h:4568
bool hasUnparsedDefaultArg() const
hasUnparsedDefaultArg - Determines whether this parameter has a default argument that has not yet bee...
Definition: Decl.h:1625
CXXBaseSpecifier * CheckBaseSpecifier(CXXRecordDecl *Class, SourceRange SpecifierRange, bool Virtual, AccessSpecifier Access, TypeSourceInfo *TInfo, SourceLocation EllipsisLoc)
ActOnBaseSpecifier - Parsed a base specifier.
unsigned getIndex() const
Get the index of the template parameter within its parameter list.
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:820
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:1580
const LangOptions & getLangOpts() const
Definition: Sema.h:1193
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:167
bool isLambdaCallOperator(const CXXMethodDecl *MD)
Definition: ASTLambda.h:28
CXXRecordDecl * getTemplatedDecl() const
Get the underlying class declarations of the template.
A default argument (C++ [dcl.fct.default]).
Definition: ExprCXX.h:1042
void setLocStart(SourceLocation L)
Definition: Decl.h:2782
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:865
RAII object used to change the argument pack substitution index within a Sema object.
Definition: Sema.h:7225
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:7589
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1521
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:7077
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:274
Represents a prototype with parameter type info, e.g.
Definition: Type.h:3270
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:1386
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:1049
We are instantiating a template declaration.
Definition: Sema.h:7061
ValueDecl * getAsDecl() const
Retrieve the declaration for a declaration non-type template argument.
Definition: TemplateBase.h:264
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:493
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Definition: DeclTemplate.h:432
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:1561
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...
ValueDecl - Represent the declaration of a variable (in which case it is an lvalue) a function (in wh...
Definition: Decl.h:628
Expr - This represents one expression.
Definition: Expr.h:106
Defines the clang::LangOptions interface.
StringRef getKindName() const
Definition: Decl.h:3146
SourceLocation End
The "typename" keyword precedes the qualified type name, e.g., typename T::type.
Definition: Type.h:4725
int Id
Definition: ASTDiff.cpp:191
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:666
const FunctionProtoType * T
Declaration of a template type parameter.
unsigned getIndex() const
Definition: Type.h:4221
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:7358
We are substituting template argument determined as part of template argument deduction for either a ...
Definition: Sema.h:7084
ElaboratedTypeKeyword
The elaboration keyword that precedes a qualified type name or introduces an elaborated-type-specifie...
Definition: Type.h:4707
The template argument is a null pointer or null pointer to member that was provided for a non-type te...
Definition: TemplateBase.h:68
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:1413
bool InNonInstantiationSFINAEContext
Whether we are in a SFINAE context that is not associated with template instantiation.
Definition: Sema.h:7194
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:1397
ParmVarDecl * SubstParmVarDecl(ParmVarDecl *D, const MultiLevelTemplateArgumentList &TemplateArgs, int indexAdjustment, Optional< unsigned > NumExpansions, bool ExpectParameterPack)
DeclContext * getDeclContext()
Definition: DeclBase.h:425
CXXRecordDecl * getDefinition() const
Definition: DeclCXX.h:731
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:178
EnumDecl * getDefinition() const
Definition: Decl.h:3303
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:191
QualType getType() const
Definition: Expr.h:128
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:1331
Data structure that captures multiple levels of template argument lists for use in template instantia...
Definition: Template.h:42
bool isInvalid() const
Definition: Ownership.h:158
void setLocation(SourceLocation L)
Definition: DeclBase.h:417
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:1364
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:3838
ClassTemplatePartialSpecializationDecl * getInstantiatedFromMember() const
Retrieve the member class template partial specialization from which this particular class template p...
bool isPackExpansion() const
Determine whether this template argument is a pack expansion.
ValueDecl * getDecl()
Definition: Expr.h:1041
SourceLocation getLocation() const
Definition: Expr.h:1217
bool isUsable() const
Definition: Ownership.h:159
The result type of a method or function.
This template specialization was implicitly instantiated from a template.
Definition: Specifiers.h:149
SourceLocation getLocEnd() const LLVM_READONLY
Definition: TypeLoc.h:155
ParmVarDecl *const * iterator
Iterators over the parameters which the parameter pack expanded into.
Definition: ExprCXX.h:3993
bool isNull() const
Return true if this QualType doesn&#39;t point to a type yet.
Definition: Type.h:719
void setDeclContext(DeclContext *DC)
setDeclContext - Set both the semantic and lexical DeclContext to DC.
Definition: DeclBase.cpp:284
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:3871
static void deleteScopes(LocalInstantiationScope *Scope, LocalInstantiationScope *Outermost)
deletes the given scope, and all otuer scopes, down to the given outermost scope. ...
Definition: Template.h:338
virtual void printName(raw_ostream &os) const
Definition: Decl.cpp:1467
void ActOnStartCXXInClassMemberInitializer()
Enter a new C++ default initializer scope.
void pushCodeSynthesisContext(CodeSynthesisContext Ctx)
We are declaring an implicit special member function.
Definition: Sema.h:7100
Kind
ActionResult - This structure is used while parsing/acting on expressions, stmts, etc...
Definition: Ownership.h:144
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition: Type.h:3367
TypeLoc IgnoreParens() const
Definition: TypeLoc.h:1196
A stack object to be created when performing template instantiation.
Definition: Sema.h:7262
Attr * instantiateTemplateAttributeForDecl(const Attr *At, ASTContext &C, Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs)
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:3502
bool Subst(const TemplateArgumentLoc *Args, unsigned NumArgs, TemplateArgumentListInfo &Result, const MultiLevelTemplateArgumentList &TemplateArgs)
Encodes a location in the source.
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition: Type.h:1876
void setBraceRange(SourceRange R)
Definition: Decl.h:3067
sema::TemplateDeductionInfo * DeductionInfo
The template deduction info object associated with the substitution or checking of explicit or deduce...
Definition: Sema.h:7142
A structure for storing an already-substituted template template parameter pack.
Definition: TemplateName.h:121
SmallVectorImpl< std::pair< VarTemplateDecl *, VarTemplatePartialSpecializationDecl * > >::iterator delayed_var_partial_spec_iterator
Definition: Template.h:487
DeclarationName getName() const
getName - Returns the embedded declaration name.
TagDecl - Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:2938
TemplateArgument getArgumentPack() const
Definition: Type.cpp:3175
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:2598
SynthesisKind
The kind of template instantiation we are performing.
Definition: Sema.h:7058
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:1964
We are checking the validity of a default template argument that has been used when naming a template...
Definition: Sema.h:7093
bool isParameterPack() const
Definition: Type.h:4222
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:360
const TemplateTypeParmType * getReplacedParameter() const
Gets the template parameter that was substituted for.
Definition: Type.h:4335
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:3154
void InstantiateEnumDefinition(EnumDecl *Enum, EnumDecl *Pattern)
llvm::DenseSet< std::pair< Decl *, unsigned > > InstantiatingSpecializations
Specializations whose definitions are currently being instantiated.
Definition: Sema.h:7165
bool hasUninstantiatedDefaultArg() const
Definition: Decl.h:1629
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:161
IdentType getIdentType() const
Definition: Expr.h:1215
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:1462
unsigned getFullDataSize() const
Returns the size of the type source info data block.
Definition: TypeLoc.h:163
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:87
static TagTypeKind getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword)
Converts an elaborated type keyword into a TagTypeKind.
Definition: Type.cpp:2477
ParmVarDecl * getExpansion(unsigned I) const
Get an expansion of the parameter pack by index.
Definition: ExprCXX.h:4001
void setHasInheritedDefaultArg(bool I=true)
Definition: Decl.h:1646
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition: Type.h:1866
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:216
CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD)
getSpecialMember - get the special member enum for a method.
Definition: SemaDecl.cpp:2804
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 that has been substituted but not yet expanded...
Definition: ExprCXX.h:3957
Represents a template argument.
Definition: TemplateBase.h:51
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:4688
bool isNull() const
Determine whether this template name is NULL.
Dataflow Directional Tag Classes.
int ArgumentPackSubstitutionIndex
The current index into pack expansion arguments that will be used for substitution of parameter packs...
Definition: Sema.h:7219
unsigned NumTemplateArgs
The number of template arguments in TemplateArgs.
Definition: Sema.h:7129
[C99 6.4.2.2] - A predefined identifier such as func.
Definition: Expr.h:1188
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1252
The base class of all kinds of template declarations (e.g., class, function, etc.).
Definition: DeclTemplate.h:399
ASTMutationListener * getASTMutationListener() const
Definition: Sema.cpp:390
NonTypeTemplateParmDecl * getParameterPack() const
Retrieve the non-type template parameter pack being substituted.
Definition: ExprCXX.h:3921
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:7073
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:505
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition: Specifiers.h:157
RecordDecl * getOuterLexicalRecordContext()
Retrieve the outermost lexically enclosing record context.
Definition: DeclBase.cpp:1664
DeclarationName - The name of a declaration.
Expr * getDefaultArg()
Definition: Decl.cpp:2489
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:2306
SourceRange InstantiationRange
The source range that covers the construct that cause the instantiation, e.g., the template-id that c...
Definition: Sema.h:7147
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:1357
EnumDecl - Represents an enum.
Definition: Decl.h:3233
SourceLocation getParameterPackLocation() const
Get the location of the parameter pack.
Definition: ExprCXX.h:3989
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition: Specifiers.h:143
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:340
ParmVarDecl * CheckParameter(DeclContext *DC, SourceLocation StartLoc, SourceLocation NameLoc, IdentifierInfo *Name, QualType T, TypeSourceInfo *TSInfo, StorageClass SC)
Definition: SemaDecl.cpp:11719
bool isNull() const
Determine whether this template argument has no value.
Definition: TemplateBase.h:238
iterator end() const
Definition: ExprCXX.h:3995
Location wrapper for a TemplateArgument.
Definition: TemplateBase.h:450
RetTy Visit(PTR(Decl) D)
Definition: DeclVisitor.h:41
unsigned getNumArgs() const
Retrieve the number of template arguments.
Definition: Type.h:4573
void setUnparsedDefaultArg()
setUnparsedDefaultArg - Specify that this parameter has an unparsed default argument.
Definition: Decl.h:1638
Expr * getUninstantiatedDefaultArg()
Definition: Decl.cpp:2531
This template specialization was declared or defined by an explicit specialization (C++ [temp...
Definition: Specifiers.h:153
static std::pair< unsigned, unsigned > getDepthAndIndex(NamedDecl *ND)
Retrieve the depth and index of a parameter pack.
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:708
UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations
A mapping from parameters with unparsed default arguments to the set of instantiations of each parame...
Definition: Sema.h:1089
The template argument is a type.
Definition: TemplateBase.h:60
void SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto, const MultiLevelTemplateArgumentList &Args)
The template argument is actually a parameter pack.
Definition: TemplateBase.h:91
Represents a base class of a C++ class.
Definition: DeclCXX.h:191
const Expr * Replacement
Definition: AttributeList.h:59
bool SavedInNonInstantiationSFINAEContext
Was the enclosing context a non-instantiation SFINAE context?
Definition: Sema.h:7108
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2174
bool isAlreadyInstantiating() const
Determine whether we are already instantiating this specialization in some surrounding active instant...
Definition: Sema.h:7362
A template argument list.
Definition: DeclTemplate.h:210
bool hasFatalErrorOccurred() const
Definition: Diagnostic.h:669
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition: TypeLoc.h:239
ExprResult SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs)
ArgKind getKind() const
Return the kind of stored template argument.
Definition: TemplateBase.h:235
unsigned getDepth() const
Definition: Type.h:4220
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:989
Represents a C++ struct/union/class.
Definition: DeclCXX.h:299
bool isVoidType() const
Definition: Type.h:6171
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:466
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
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:328
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:127
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Definition: TargetCXXABI.h:154
SourceLocation getNameLoc() const
Definition: TypeLoc.h:518
We are substituting prior template arguments into a new template parameter.
Definition: Sema.h:7089
StringRef getName() const
getName - Get the name of identifier for this declaration as a StringRef.
Definition: Decl.h:270
ExprResult ExprError()
Definition: Ownership.h:267
ClassTemplatePartialSpecializationDecl * getMoreSpecializedPartialSpecialization(ClassTemplatePartialSpecializationDecl *PS1, ClassTemplatePartialSpecializationDecl *PS2, SourceLocation Loc)
Returns the more specialized class template partial specialization according to the rules of partial ...
static FunctionParmPackExpr * Create(const ASTContext &Context, QualType T, ParmVarDecl *ParamPack, SourceLocation NameLoc, ArrayRef< ParmVarDecl *> Params)
Definition: ExprCXX.cpp:1358
const ParmVarDecl * getParam() const
Definition: ExprCXX.h:1073
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:1860
QualType getAsType() const
Retrieve the type for a type template argument.
Definition: TemplateBase.h:257
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:956
Represents a type template specialization; the template must be a class template, a type alias templa...
Definition: Type.h:4495
virtual bool HandleTopLevelDecl(DeclGroupRef D)
HandleTopLevelDecl - Handle the specified top-level declaration.
Definition: ASTConsumer.cpp:19
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.
SourceLocation getInnerLocStart() const
getInnerLocStart - Return SourceLocation representing start of source range ignoring outer template d...
Definition: Decl.h:3071
QualType getType() const
Definition: Decl.h:639
ParmVarDecl * getParameterPack() const
Get the parameter pack which this expression refers to.
Definition: ExprCXX.h:3986
Wrapper for template type parameters.
Definition: TypeLoc.h:733
A trivial tuple used to represent a source range.
ASTContext & Context
Definition: Sema.h:316
NamedDecl - This represents a decl with a name.
Definition: Decl.h:245
bool isTranslationUnit() const
Definition: DeclBase.h:1401
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)
No keyword precedes the qualified type name.
Definition: Type.h:4728
TemplateName getAsTemplate() const
Retrieve the template name for a template name argument.
Definition: TemplateBase.h:281
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
void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl, ArrayRef< Decl *> Fields, SourceLocation LBrac, SourceLocation RBrac, AttributeList *AttrList)
Definition: SemaDecl.cpp:14781
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 getLocStart() const LLVM_READONLY
Definition: Stmt.cpp:277
SourceLocation getInnerLocStart() const
getInnerLocStart - Return SourceLocation representing start of source range ignoring outer template d...
Definition: Decl.h:723
bool isParameterPack() const
Determine whether this parameter is actually a function parameter pack.
Definition: Decl.cpp:2545
ExceptionSpecInfo ExceptionSpec
Definition: Type.h:3395
Declaration of a template function.
Definition: DeclTemplate.h:958
Attr - This represents one attribute.
Definition: Attr.h:43
SourceLocation getLocation() const
Definition: DeclBase.h:416
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:73
bool isCXXInstanceMember() const
Determine whether the given declaration is an instance member of a C++ class.
Definition: Decl.cpp:1685
A RAII object to temporarily push a declaration context.
Definition: Sema.h:705
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...