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