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