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