1 //===------- SemaTemplateInstantiate.cpp - C++ Template Instantiation ------===/
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //===----------------------------------------------------------------------===/
9 // This file implements C++ template instantiation.
11 //===----------------------------------------------------------------------===/
13 #include "clang/Sema/SemaInternal.h"
14 #include "TreeTransform.h"
15 #include "clang/AST/ASTConsumer.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/DeclTemplate.h"
18 #include "clang/AST/Expr.h"
19 #include "clang/Basic/LangOptions.h"
20 #include "clang/Sema/DeclSpec.h"
21 #include "clang/Sema/Initialization.h"
22 #include "clang/Sema/Lookup.h"
23 #include "clang/Sema/Template.h"
24 #include "clang/Sema/TemplateDeduction.h"
26 using namespace clang;
29 //===----------------------------------------------------------------------===/
30 // Template Instantiation Support
31 //===----------------------------------------------------------------------===/
33 /// \brief Retrieve the template argument list(s) that should be used to
34 /// instantiate the definition of the given declaration.
36 /// \param D the declaration for which we are computing template instantiation
39 /// \param Innermost if non-NULL, the innermost template argument list.
41 /// \param RelativeToPrimary true if we should get the template
42 /// arguments relative to the primary template, even when we're
43 /// dealing with a specialization. This is only relevant for function
44 /// template specializations.
46 /// \param Pattern If non-NULL, indicates the pattern from which we will be
47 /// instantiating the definition of the given declaration, \p D. This is
48 /// used to determine the proper set of template instantiation arguments for
49 /// friend function template specializations.
50 MultiLevelTemplateArgumentList
51 Sema::getTemplateInstantiationArgs(NamedDecl *D,
52 const TemplateArgumentList *Innermost,
53 bool RelativeToPrimary,
54 const FunctionDecl *Pattern) {
55 // Accumulate the set of template argument lists in this structure.
56 MultiLevelTemplateArgumentList Result;
59 Result.addOuterTemplateArguments(Innermost);
61 DeclContext *Ctx = dyn_cast<DeclContext>(D);
63 Ctx = D->getDeclContext();
65 // If we have a template template parameter with translation unit context,
66 // then we're performing substitution into a default template argument of
67 // this template template parameter before we've constructed the template
68 // that will own this template template parameter. In this case, we
69 // use empty template parameter lists for all of the outer templates
70 // to avoid performing any substitutions.
71 if (Ctx->isTranslationUnit()) {
72 if (TemplateTemplateParmDecl *TTP
73 = dyn_cast<TemplateTemplateParmDecl>(D)) {
74 for (unsigned I = 0, N = TTP->getDepth() + 1; I != N; ++I)
75 Result.addOuterTemplateArguments(0, 0);
81 while (!Ctx->isFileContext()) {
82 // Add template arguments from a class template instantiation.
83 if (ClassTemplateSpecializationDecl *Spec
84 = dyn_cast<ClassTemplateSpecializationDecl>(Ctx)) {
85 // We're done when we hit an explicit specialization.
86 if (Spec->getSpecializationKind() == TSK_ExplicitSpecialization &&
87 !isa<ClassTemplatePartialSpecializationDecl>(Spec))
90 Result.addOuterTemplateArguments(&Spec->getTemplateInstantiationArgs());
92 // If this class template specialization was instantiated from a
93 // specialized member that is a class template, we're done.
94 assert(Spec->getSpecializedTemplate() && "No class template?");
95 if (Spec->getSpecializedTemplate()->isMemberSpecialization())
98 // Add template arguments from a function template specialization.
99 else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Ctx)) {
100 if (!RelativeToPrimary &&
101 (Function->getTemplateSpecializationKind() ==
102 TSK_ExplicitSpecialization &&
103 !Function->getClassScopeSpecializationPattern()))
106 if (const TemplateArgumentList *TemplateArgs
107 = Function->getTemplateSpecializationArgs()) {
108 // Add the template arguments for this specialization.
109 Result.addOuterTemplateArguments(TemplateArgs);
111 // If this function was instantiated from a specialized member that is
112 // a function template, we're done.
113 assert(Function->getPrimaryTemplate() && "No function template?");
114 if (Function->getPrimaryTemplate()->isMemberSpecialization())
116 } else if (FunctionTemplateDecl *FunTmpl
117 = Function->getDescribedFunctionTemplate()) {
118 // Add the "injected" template arguments.
119 std::pair<const TemplateArgument *, unsigned>
120 Injected = FunTmpl->getInjectedTemplateArgs();
121 Result.addOuterTemplateArguments(Injected.first, Injected.second);
124 // If this is a friend declaration and it declares an entity at
125 // namespace scope, take arguments from its lexical parent
126 // instead of its semantic parent, unless of course the pattern we're
127 // instantiating actually comes from the file's context!
128 if (Function->getFriendObjectKind() &&
129 Function->getDeclContext()->isFileContext() &&
130 (!Pattern || !Pattern->getLexicalDeclContext()->isFileContext())) {
131 Ctx = Function->getLexicalDeclContext();
132 RelativeToPrimary = false;
135 } else if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Ctx)) {
136 if (ClassTemplateDecl *ClassTemplate = Rec->getDescribedClassTemplate()) {
137 QualType T = ClassTemplate->getInjectedClassNameSpecialization();
138 const TemplateSpecializationType *TST
139 = cast<TemplateSpecializationType>(Context.getCanonicalType(T));
140 Result.addOuterTemplateArguments(TST->getArgs(), TST->getNumArgs());
141 if (ClassTemplate->isMemberSpecialization())
146 Ctx = Ctx->getParent();
147 RelativeToPrimary = false;
153 bool Sema::ActiveTemplateInstantiation::isInstantiationRecord() const {
155 case TemplateInstantiation:
156 case ExceptionSpecInstantiation:
157 case DefaultTemplateArgumentInstantiation:
158 case DefaultFunctionArgumentInstantiation:
159 case ExplicitTemplateArgumentSubstitution:
160 case DeducedTemplateArgumentSubstitution:
161 case PriorTemplateArgumentSubstitution:
164 case DefaultTemplateArgumentChecking:
168 llvm_unreachable("Invalid InstantiationKind!");
171 Sema::InstantiatingTemplate::
172 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
174 SourceRange InstantiationRange)
176 SavedInNonInstantiationSFINAEContext(
177 SemaRef.InNonInstantiationSFINAEContext)
179 Invalid = CheckInstantiationDepth(PointOfInstantiation,
182 ActiveTemplateInstantiation Inst;
183 Inst.Kind = ActiveTemplateInstantiation::TemplateInstantiation;
184 Inst.PointOfInstantiation = PointOfInstantiation;
185 Inst.Entity = Entity;
186 Inst.TemplateArgs = 0;
187 Inst.NumTemplateArgs = 0;
188 Inst.InstantiationRange = InstantiationRange;
189 SemaRef.InNonInstantiationSFINAEContext = false;
190 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
194 Sema::InstantiatingTemplate::
195 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
196 FunctionDecl *Entity, ExceptionSpecification,
197 SourceRange InstantiationRange)
199 SavedInNonInstantiationSFINAEContext(
200 SemaRef.InNonInstantiationSFINAEContext)
202 Invalid = CheckInstantiationDepth(PointOfInstantiation,
205 ActiveTemplateInstantiation Inst;
206 Inst.Kind = ActiveTemplateInstantiation::ExceptionSpecInstantiation;
207 Inst.PointOfInstantiation = PointOfInstantiation;
208 Inst.Entity = Entity;
209 Inst.TemplateArgs = 0;
210 Inst.NumTemplateArgs = 0;
211 Inst.InstantiationRange = InstantiationRange;
212 SemaRef.InNonInstantiationSFINAEContext = false;
213 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
217 Sema::InstantiatingTemplate::
218 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
219 TemplateDecl *Template,
220 ArrayRef<TemplateArgument> TemplateArgs,
221 SourceRange InstantiationRange)
223 SavedInNonInstantiationSFINAEContext(
224 SemaRef.InNonInstantiationSFINAEContext)
226 Invalid = CheckInstantiationDepth(PointOfInstantiation,
229 ActiveTemplateInstantiation Inst;
231 = ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation;
232 Inst.PointOfInstantiation = PointOfInstantiation;
233 Inst.Entity = Template;
234 Inst.TemplateArgs = TemplateArgs.data();
235 Inst.NumTemplateArgs = TemplateArgs.size();
236 Inst.InstantiationRange = InstantiationRange;
237 SemaRef.InNonInstantiationSFINAEContext = false;
238 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
242 Sema::InstantiatingTemplate::
243 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
244 FunctionTemplateDecl *FunctionTemplate,
245 ArrayRef<TemplateArgument> TemplateArgs,
246 ActiveTemplateInstantiation::InstantiationKind Kind,
247 sema::TemplateDeductionInfo &DeductionInfo,
248 SourceRange InstantiationRange)
250 SavedInNonInstantiationSFINAEContext(
251 SemaRef.InNonInstantiationSFINAEContext)
253 Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
255 ActiveTemplateInstantiation Inst;
257 Inst.PointOfInstantiation = PointOfInstantiation;
258 Inst.Entity = FunctionTemplate;
259 Inst.TemplateArgs = TemplateArgs.data();
260 Inst.NumTemplateArgs = TemplateArgs.size();
261 Inst.DeductionInfo = &DeductionInfo;
262 Inst.InstantiationRange = InstantiationRange;
263 SemaRef.InNonInstantiationSFINAEContext = false;
264 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
266 if (!Inst.isInstantiationRecord())
267 ++SemaRef.NonInstantiationEntries;
271 Sema::InstantiatingTemplate::
272 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
273 ClassTemplatePartialSpecializationDecl *PartialSpec,
274 ArrayRef<TemplateArgument> TemplateArgs,
275 sema::TemplateDeductionInfo &DeductionInfo,
276 SourceRange InstantiationRange)
278 SavedInNonInstantiationSFINAEContext(
279 SemaRef.InNonInstantiationSFINAEContext)
281 Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
283 ActiveTemplateInstantiation Inst;
284 Inst.Kind = ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution;
285 Inst.PointOfInstantiation = PointOfInstantiation;
286 Inst.Entity = PartialSpec;
287 Inst.TemplateArgs = TemplateArgs.data();
288 Inst.NumTemplateArgs = TemplateArgs.size();
289 Inst.DeductionInfo = &DeductionInfo;
290 Inst.InstantiationRange = InstantiationRange;
291 SemaRef.InNonInstantiationSFINAEContext = false;
292 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
296 Sema::InstantiatingTemplate::
297 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
299 ArrayRef<TemplateArgument> TemplateArgs,
300 SourceRange InstantiationRange)
302 SavedInNonInstantiationSFINAEContext(
303 SemaRef.InNonInstantiationSFINAEContext)
305 Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
307 ActiveTemplateInstantiation Inst;
309 = ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
310 Inst.PointOfInstantiation = PointOfInstantiation;
312 Inst.TemplateArgs = TemplateArgs.data();
313 Inst.NumTemplateArgs = TemplateArgs.size();
314 Inst.InstantiationRange = InstantiationRange;
315 SemaRef.InNonInstantiationSFINAEContext = false;
316 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
320 Sema::InstantiatingTemplate::
321 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
322 NamedDecl *Template, NonTypeTemplateParmDecl *Param,
323 ArrayRef<TemplateArgument> TemplateArgs,
324 SourceRange InstantiationRange)
326 SavedInNonInstantiationSFINAEContext(
327 SemaRef.InNonInstantiationSFINAEContext)
329 Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
331 ActiveTemplateInstantiation Inst;
332 Inst.Kind = ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution;
333 Inst.PointOfInstantiation = PointOfInstantiation;
334 Inst.Template = Template;
336 Inst.TemplateArgs = TemplateArgs.data();
337 Inst.NumTemplateArgs = TemplateArgs.size();
338 Inst.InstantiationRange = InstantiationRange;
339 SemaRef.InNonInstantiationSFINAEContext = false;
340 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
344 Sema::InstantiatingTemplate::
345 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
346 NamedDecl *Template, TemplateTemplateParmDecl *Param,
347 ArrayRef<TemplateArgument> TemplateArgs,
348 SourceRange InstantiationRange)
350 SavedInNonInstantiationSFINAEContext(
351 SemaRef.InNonInstantiationSFINAEContext)
353 Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
355 ActiveTemplateInstantiation Inst;
356 Inst.Kind = ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution;
357 Inst.PointOfInstantiation = PointOfInstantiation;
358 Inst.Template = Template;
360 Inst.TemplateArgs = TemplateArgs.data();
361 Inst.NumTemplateArgs = TemplateArgs.size();
362 Inst.InstantiationRange = InstantiationRange;
363 SemaRef.InNonInstantiationSFINAEContext = false;
364 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
368 Sema::InstantiatingTemplate::
369 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
370 TemplateDecl *Template, NamedDecl *Param,
371 ArrayRef<TemplateArgument> TemplateArgs,
372 SourceRange InstantiationRange)
374 SavedInNonInstantiationSFINAEContext(
375 SemaRef.InNonInstantiationSFINAEContext)
379 ActiveTemplateInstantiation Inst;
380 Inst.Kind = ActiveTemplateInstantiation::DefaultTemplateArgumentChecking;
381 Inst.PointOfInstantiation = PointOfInstantiation;
382 Inst.Template = Template;
384 Inst.TemplateArgs = TemplateArgs.data();
385 Inst.NumTemplateArgs = TemplateArgs.size();
386 Inst.InstantiationRange = InstantiationRange;
387 SemaRef.InNonInstantiationSFINAEContext = false;
388 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
390 assert(!Inst.isInstantiationRecord());
391 ++SemaRef.NonInstantiationEntries;
394 void Sema::InstantiatingTemplate::Clear() {
396 if (!SemaRef.ActiveTemplateInstantiations.back().isInstantiationRecord()) {
397 assert(SemaRef.NonInstantiationEntries > 0);
398 --SemaRef.NonInstantiationEntries;
400 SemaRef.InNonInstantiationSFINAEContext
401 = SavedInNonInstantiationSFINAEContext;
402 SemaRef.ActiveTemplateInstantiations.pop_back();
407 bool Sema::InstantiatingTemplate::CheckInstantiationDepth(
408 SourceLocation PointOfInstantiation,
409 SourceRange InstantiationRange) {
410 assert(SemaRef.NonInstantiationEntries <=
411 SemaRef.ActiveTemplateInstantiations.size());
412 if ((SemaRef.ActiveTemplateInstantiations.size() -
413 SemaRef.NonInstantiationEntries)
414 <= SemaRef.getLangOpts().InstantiationDepth)
417 SemaRef.Diag(PointOfInstantiation,
418 diag::err_template_recursion_depth_exceeded)
419 << SemaRef.getLangOpts().InstantiationDepth
420 << InstantiationRange;
421 SemaRef.Diag(PointOfInstantiation, diag::note_template_recursion_depth)
422 << SemaRef.getLangOpts().InstantiationDepth;
426 /// \brief Prints the current instantiation stack through a series of
428 void Sema::PrintInstantiationStack() {
429 // Determine which template instantiations to skip, if any.
430 unsigned SkipStart = ActiveTemplateInstantiations.size(), SkipEnd = SkipStart;
431 unsigned Limit = Diags.getTemplateBacktraceLimit();
432 if (Limit && Limit < ActiveTemplateInstantiations.size()) {
433 SkipStart = Limit / 2 + Limit % 2;
434 SkipEnd = ActiveTemplateInstantiations.size() - Limit / 2;
437 // FIXME: In all of these cases, we need to show the template arguments
438 unsigned InstantiationIdx = 0;
439 for (SmallVector<ActiveTemplateInstantiation, 16>::reverse_iterator
440 Active = ActiveTemplateInstantiations.rbegin(),
441 ActiveEnd = ActiveTemplateInstantiations.rend();
443 ++Active, ++InstantiationIdx) {
444 // Skip this instantiation?
445 if (InstantiationIdx >= SkipStart && InstantiationIdx < SkipEnd) {
446 if (InstantiationIdx == SkipStart) {
447 // Note that we're skipping instantiations.
448 Diags.Report(Active->PointOfInstantiation,
449 diag::note_instantiation_contexts_suppressed)
450 << unsigned(ActiveTemplateInstantiations.size() - Limit);
455 switch (Active->Kind) {
456 case ActiveTemplateInstantiation::TemplateInstantiation: {
457 Decl *D = Active->Entity;
458 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
459 unsigned DiagID = diag::note_template_member_class_here;
460 if (isa<ClassTemplateSpecializationDecl>(Record))
461 DiagID = diag::note_template_class_instantiation_here;
462 Diags.Report(Active->PointOfInstantiation, DiagID)
463 << Context.getTypeDeclType(Record)
464 << Active->InstantiationRange;
465 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
467 if (Function->getPrimaryTemplate())
468 DiagID = diag::note_function_template_spec_here;
470 DiagID = diag::note_template_member_function_here;
471 Diags.Report(Active->PointOfInstantiation, DiagID)
473 << Active->InstantiationRange;
474 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
475 Diags.Report(Active->PointOfInstantiation,
476 diag::note_template_static_data_member_def_here)
478 << Active->InstantiationRange;
479 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
480 Diags.Report(Active->PointOfInstantiation,
481 diag::note_template_enum_def_here)
483 << Active->InstantiationRange;
485 Diags.Report(Active->PointOfInstantiation,
486 diag::note_template_type_alias_instantiation_here)
487 << cast<TypeAliasTemplateDecl>(D)
488 << Active->InstantiationRange;
493 case ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation: {
494 TemplateDecl *Template = cast<TemplateDecl>(Active->Entity);
495 SmallVector<char, 128> TemplateArgsStr;
496 llvm::raw_svector_ostream OS(TemplateArgsStr);
497 Template->printName(OS);
498 TemplateSpecializationType::PrintTemplateArgumentList(OS,
499 Active->TemplateArgs,
500 Active->NumTemplateArgs,
501 getPrintingPolicy());
502 Diags.Report(Active->PointOfInstantiation,
503 diag::note_default_arg_instantiation_here)
505 << Active->InstantiationRange;
509 case ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution: {
510 FunctionTemplateDecl *FnTmpl = cast<FunctionTemplateDecl>(Active->Entity);
511 Diags.Report(Active->PointOfInstantiation,
512 diag::note_explicit_template_arg_substitution_here)
514 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
515 Active->TemplateArgs,
516 Active->NumTemplateArgs)
517 << Active->InstantiationRange;
521 case ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution:
522 if (ClassTemplatePartialSpecializationDecl *PartialSpec =
523 dyn_cast<ClassTemplatePartialSpecializationDecl>(Active->Entity)) {
524 Diags.Report(Active->PointOfInstantiation,
525 diag::note_partial_spec_deduct_instantiation_here)
526 << Context.getTypeDeclType(PartialSpec)
527 << getTemplateArgumentBindingsText(
528 PartialSpec->getTemplateParameters(),
529 Active->TemplateArgs,
530 Active->NumTemplateArgs)
531 << Active->InstantiationRange;
533 FunctionTemplateDecl *FnTmpl
534 = cast<FunctionTemplateDecl>(Active->Entity);
535 Diags.Report(Active->PointOfInstantiation,
536 diag::note_function_template_deduction_instantiation_here)
538 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
539 Active->TemplateArgs,
540 Active->NumTemplateArgs)
541 << Active->InstantiationRange;
545 case ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation: {
546 ParmVarDecl *Param = cast<ParmVarDecl>(Active->Entity);
547 FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());
549 SmallVector<char, 128> TemplateArgsStr;
550 llvm::raw_svector_ostream OS(TemplateArgsStr);
552 TemplateSpecializationType::PrintTemplateArgumentList(OS,
553 Active->TemplateArgs,
554 Active->NumTemplateArgs,
555 getPrintingPolicy());
556 Diags.Report(Active->PointOfInstantiation,
557 diag::note_default_function_arg_instantiation_here)
559 << Active->InstantiationRange;
563 case ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution: {
564 NamedDecl *Parm = cast<NamedDecl>(Active->Entity);
566 if (!Parm->getName().empty())
567 Name = std::string(" '") + Parm->getName().str() + "'";
569 TemplateParameterList *TemplateParams = 0;
570 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
571 TemplateParams = Template->getTemplateParameters();
574 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
575 ->getTemplateParameters();
576 Diags.Report(Active->PointOfInstantiation,
577 diag::note_prior_template_arg_substitution)
578 << isa<TemplateTemplateParmDecl>(Parm)
580 << getTemplateArgumentBindingsText(TemplateParams,
581 Active->TemplateArgs,
582 Active->NumTemplateArgs)
583 << Active->InstantiationRange;
587 case ActiveTemplateInstantiation::DefaultTemplateArgumentChecking: {
588 TemplateParameterList *TemplateParams = 0;
589 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
590 TemplateParams = Template->getTemplateParameters();
593 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
594 ->getTemplateParameters();
596 Diags.Report(Active->PointOfInstantiation,
597 diag::note_template_default_arg_checking)
598 << getTemplateArgumentBindingsText(TemplateParams,
599 Active->TemplateArgs,
600 Active->NumTemplateArgs)
601 << Active->InstantiationRange;
605 case ActiveTemplateInstantiation::ExceptionSpecInstantiation:
606 Diags.Report(Active->PointOfInstantiation,
607 diag::note_template_exception_spec_instantiation_here)
608 << cast<FunctionDecl>(Active->Entity)
609 << Active->InstantiationRange;
615 Optional<TemplateDeductionInfo *> Sema::isSFINAEContext() const {
616 if (InNonInstantiationSFINAEContext)
617 return Optional<TemplateDeductionInfo *>(0);
619 for (SmallVector<ActiveTemplateInstantiation, 16>::const_reverse_iterator
620 Active = ActiveTemplateInstantiations.rbegin(),
621 ActiveEnd = ActiveTemplateInstantiations.rend();
625 switch(Active->Kind) {
626 case ActiveTemplateInstantiation::TemplateInstantiation:
627 // An instantiation of an alias template may or may not be a SFINAE
628 // context, depending on what else is on the stack.
629 if (isa<TypeAliasTemplateDecl>(Active->Entity))
632 case ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation:
633 case ActiveTemplateInstantiation::ExceptionSpecInstantiation:
634 // This is a template instantiation, so there is no SFINAE.
637 case ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation:
638 case ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution:
639 case ActiveTemplateInstantiation::DefaultTemplateArgumentChecking:
640 // A default template argument instantiation and substitution into
641 // template parameters with arguments for prior parameters may or may
642 // not be a SFINAE context; look further up the stack.
645 case ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution:
646 case ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution:
647 // We're either substitution explicitly-specified template arguments
648 // or deduced template arguments, so SFINAE applies.
649 assert(Active->DeductionInfo && "Missing deduction info pointer");
650 return Active->DeductionInfo;
657 /// \brief Retrieve the depth and index of a parameter pack.
658 static std::pair<unsigned, unsigned>
659 getDepthAndIndex(NamedDecl *ND) {
660 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ND))
661 return std::make_pair(TTP->getDepth(), TTP->getIndex());
663 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND))
664 return std::make_pair(NTTP->getDepth(), NTTP->getIndex());
666 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(ND);
667 return std::make_pair(TTP->getDepth(), TTP->getIndex());
670 //===----------------------------------------------------------------------===/
671 // Template Instantiation for Types
672 //===----------------------------------------------------------------------===/
674 class TemplateInstantiator : public TreeTransform<TemplateInstantiator> {
675 const MultiLevelTemplateArgumentList &TemplateArgs;
677 DeclarationName Entity;
680 typedef TreeTransform<TemplateInstantiator> inherited;
682 TemplateInstantiator(Sema &SemaRef,
683 const MultiLevelTemplateArgumentList &TemplateArgs,
685 DeclarationName Entity)
686 : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc),
689 /// \brief Determine whether the given type \p T has already been
692 /// For the purposes of template instantiation, a type has already been
693 /// transformed if it is NULL or if it is not dependent.
694 bool AlreadyTransformed(QualType T);
696 /// \brief Returns the location of the entity being instantiated, if known.
697 SourceLocation getBaseLocation() { return Loc; }
699 /// \brief Returns the name of the entity being instantiated, if any.
700 DeclarationName getBaseEntity() { return Entity; }
702 /// \brief Sets the "base" location and entity when that
703 /// information is known based on another transformation.
704 void setBase(SourceLocation Loc, DeclarationName Entity) {
706 this->Entity = Entity;
709 bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
710 SourceRange PatternRange,
711 llvm::ArrayRef<UnexpandedParameterPack> Unexpanded,
713 bool &RetainExpansion,
714 Optional<unsigned> &NumExpansions) {
715 return getSema().CheckParameterPacksForExpansion(EllipsisLoc,
716 PatternRange, Unexpanded,
723 void ExpandingFunctionParameterPack(ParmVarDecl *Pack) {
724 SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(Pack);
727 TemplateArgument ForgetPartiallySubstitutedPack() {
728 TemplateArgument Result;
729 if (NamedDecl *PartialPack
730 = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
731 MultiLevelTemplateArgumentList &TemplateArgs
732 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
733 unsigned Depth, Index;
734 llvm::tie(Depth, Index) = getDepthAndIndex(PartialPack);
735 if (TemplateArgs.hasTemplateArgument(Depth, Index)) {
736 Result = TemplateArgs(Depth, Index);
737 TemplateArgs.setArgument(Depth, Index, TemplateArgument());
744 void RememberPartiallySubstitutedPack(TemplateArgument Arg) {
748 if (NamedDecl *PartialPack
749 = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
750 MultiLevelTemplateArgumentList &TemplateArgs
751 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
752 unsigned Depth, Index;
753 llvm::tie(Depth, Index) = getDepthAndIndex(PartialPack);
754 TemplateArgs.setArgument(Depth, Index, Arg);
758 /// \brief Transform the given declaration by instantiating a reference to
759 /// this declaration.
760 Decl *TransformDecl(SourceLocation Loc, Decl *D);
762 void transformAttrs(Decl *Old, Decl *New) {
763 SemaRef.InstantiateAttrs(TemplateArgs, Old, New);
766 void transformedLocalDecl(Decl *Old, Decl *New) {
767 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Old, New);
770 /// \brief Transform the definition of the given declaration by
771 /// instantiating it.
772 Decl *TransformDefinition(SourceLocation Loc, Decl *D);
774 /// \brief Transform the first qualifier within a scope by instantiating the
776 NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc);
778 /// \brief Rebuild the exception declaration and register the declaration
779 /// as an instantiated local.
780 VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
781 TypeSourceInfo *Declarator,
782 SourceLocation StartLoc,
783 SourceLocation NameLoc,
784 IdentifierInfo *Name);
786 /// \brief Rebuild the Objective-C exception declaration and register the
787 /// declaration as an instantiated local.
788 VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
789 TypeSourceInfo *TSInfo, QualType T);
791 /// \brief Check for tag mismatches when instantiating an
793 QualType RebuildElaboratedType(SourceLocation KeywordLoc,
794 ElaboratedTypeKeyword Keyword,
795 NestedNameSpecifierLoc QualifierLoc,
798 TemplateName TransformTemplateName(CXXScopeSpec &SS,
800 SourceLocation NameLoc,
801 QualType ObjectType = QualType(),
802 NamedDecl *FirstQualifierInScope = 0);
804 ExprResult TransformPredefinedExpr(PredefinedExpr *E);
805 ExprResult TransformDeclRefExpr(DeclRefExpr *E);
806 ExprResult TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E);
808 ExprResult TransformTemplateParmRefExpr(DeclRefExpr *E,
809 NonTypeTemplateParmDecl *D);
810 ExprResult TransformSubstNonTypeTemplateParmPackExpr(
811 SubstNonTypeTemplateParmPackExpr *E);
813 /// \brief Rebuild a DeclRefExpr for a ParmVarDecl reference.
814 ExprResult RebuildParmVarDeclRefExpr(ParmVarDecl *PD, SourceLocation Loc);
816 /// \brief Transform a reference to a function parameter pack.
817 ExprResult TransformFunctionParmPackRefExpr(DeclRefExpr *E,
820 /// \brief Transform a FunctionParmPackExpr which was built when we couldn't
821 /// expand a function parameter pack reference which refers to an expanded
823 ExprResult TransformFunctionParmPackExpr(FunctionParmPackExpr *E);
825 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
826 FunctionProtoTypeLoc TL);
827 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
828 FunctionProtoTypeLoc TL,
829 CXXRecordDecl *ThisContext,
830 unsigned ThisTypeQuals);
832 ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm,
834 Optional<unsigned> NumExpansions,
835 bool ExpectParameterPack);
837 /// \brief Transforms a template type parameter type by performing
838 /// substitution of the corresponding template type argument.
839 QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
840 TemplateTypeParmTypeLoc TL);
842 /// \brief Transforms an already-substituted template type parameter pack
843 /// into either itself (if we aren't substituting into its pack expansion)
844 /// or the appropriate substituted argument.
845 QualType TransformSubstTemplateTypeParmPackType(TypeLocBuilder &TLB,
846 SubstTemplateTypeParmPackTypeLoc TL);
848 ExprResult TransformCallExpr(CallExpr *CE) {
849 getSema().CallsUndergoingInstantiation.push_back(CE);
851 TreeTransform<TemplateInstantiator>::TransformCallExpr(CE);
852 getSema().CallsUndergoingInstantiation.pop_back();
856 ExprResult TransformLambdaExpr(LambdaExpr *E) {
857 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
858 return TreeTransform<TemplateInstantiator>::TransformLambdaExpr(E);
861 ExprResult TransformLambdaScope(LambdaExpr *E,
862 CXXMethodDecl *CallOperator) {
863 CallOperator->setInstantiationOfMemberFunction(E->getCallOperator(),
864 TSK_ImplicitInstantiation);
865 return TreeTransform<TemplateInstantiator>::
866 TransformLambdaScope(E, CallOperator);
870 ExprResult transformNonTypeTemplateParmRef(NonTypeTemplateParmDecl *parm,
872 TemplateArgument arg);
876 bool TemplateInstantiator::AlreadyTransformed(QualType T) {
880 if (T->isInstantiationDependentType() || T->isVariablyModifiedType())
883 getSema().MarkDeclarationsReferencedInType(Loc, T);
887 Decl *TemplateInstantiator::TransformDecl(SourceLocation Loc, Decl *D) {
891 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(D)) {
892 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
893 // If the corresponding template argument is NULL or non-existent, it's
894 // because we are performing instantiation from explicitly-specified
895 // template arguments in a function template, but there were some
896 // arguments left unspecified.
897 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
901 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
903 if (TTP->isParameterPack()) {
904 assert(Arg.getKind() == TemplateArgument::Pack &&
905 "Missing argument pack");
907 assert(getSema().ArgumentPackSubstitutionIndex >= 0);
908 assert(getSema().ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
909 Arg = Arg.pack_begin()[getSema().ArgumentPackSubstitutionIndex];
912 TemplateName Template = Arg.getAsTemplate();
913 assert(!Template.isNull() && Template.getAsTemplateDecl() &&
914 "Wrong kind of template template argument");
915 return Template.getAsTemplateDecl();
918 // Fall through to find the instantiated declaration for this template
919 // template parameter.
922 return SemaRef.FindInstantiatedDecl(Loc, cast<NamedDecl>(D), TemplateArgs);
925 Decl *TemplateInstantiator::TransformDefinition(SourceLocation Loc, Decl *D) {
926 Decl *Inst = getSema().SubstDecl(D, getSema().CurContext, TemplateArgs);
930 getSema().CurrentInstantiationScope->InstantiatedLocal(D, Inst);
935 TemplateInstantiator::TransformFirstQualifierInScope(NamedDecl *D,
936 SourceLocation Loc) {
937 // If the first part of the nested-name-specifier was a template type
938 // parameter, instantiate that type parameter down to a tag type.
939 if (TemplateTypeParmDecl *TTPD = dyn_cast_or_null<TemplateTypeParmDecl>(D)) {
940 const TemplateTypeParmType *TTP
941 = cast<TemplateTypeParmType>(getSema().Context.getTypeDeclType(TTPD));
943 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
944 // FIXME: This needs testing w/ member access expressions.
945 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getIndex());
947 if (TTP->isParameterPack()) {
948 assert(Arg.getKind() == TemplateArgument::Pack &&
949 "Missing argument pack");
951 if (getSema().ArgumentPackSubstitutionIndex == -1)
954 assert(getSema().ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
955 Arg = Arg.pack_begin()[getSema().ArgumentPackSubstitutionIndex];
958 QualType T = Arg.getAsType();
960 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
962 if (const TagType *Tag = T->getAs<TagType>())
963 return Tag->getDecl();
965 // The resulting type is not a tag; complain.
966 getSema().Diag(Loc, diag::err_nested_name_spec_non_tag) << T;
971 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
975 TemplateInstantiator::RebuildExceptionDecl(VarDecl *ExceptionDecl,
976 TypeSourceInfo *Declarator,
977 SourceLocation StartLoc,
978 SourceLocation NameLoc,
979 IdentifierInfo *Name) {
980 VarDecl *Var = inherited::RebuildExceptionDecl(ExceptionDecl, Declarator,
981 StartLoc, NameLoc, Name);
983 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
987 VarDecl *TemplateInstantiator::RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
988 TypeSourceInfo *TSInfo,
990 VarDecl *Var = inherited::RebuildObjCExceptionDecl(ExceptionDecl, TSInfo, T);
992 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
997 TemplateInstantiator::RebuildElaboratedType(SourceLocation KeywordLoc,
998 ElaboratedTypeKeyword Keyword,
999 NestedNameSpecifierLoc QualifierLoc,
1001 if (const TagType *TT = T->getAs<TagType>()) {
1002 TagDecl* TD = TT->getDecl();
1004 SourceLocation TagLocation = KeywordLoc;
1006 IdentifierInfo *Id = TD->getIdentifier();
1008 // TODO: should we even warn on struct/class mismatches for this? Seems
1009 // like it's likely to produce a lot of spurious errors.
1010 if (Id && Keyword != ETK_None && Keyword != ETK_Typename) {
1011 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForKeyword(Keyword);
1012 if (!SemaRef.isAcceptableTagRedeclaration(TD, Kind, /*isDefinition*/false,
1013 TagLocation, *Id)) {
1014 SemaRef.Diag(TagLocation, diag::err_use_with_wrong_tag)
1016 << FixItHint::CreateReplacement(SourceRange(TagLocation),
1018 SemaRef.Diag(TD->getLocation(), diag::note_previous_use);
1023 return TreeTransform<TemplateInstantiator>::RebuildElaboratedType(KeywordLoc,
1029 TemplateName TemplateInstantiator::TransformTemplateName(CXXScopeSpec &SS,
1031 SourceLocation NameLoc,
1032 QualType ObjectType,
1033 NamedDecl *FirstQualifierInScope) {
1034 if (TemplateTemplateParmDecl *TTP
1035 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl())) {
1036 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1037 // If the corresponding template argument is NULL or non-existent, it's
1038 // because we are performing instantiation from explicitly-specified
1039 // template arguments in a function template, but there were some
1040 // arguments left unspecified.
1041 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
1042 TTP->getPosition()))
1045 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
1047 if (TTP->isParameterPack()) {
1048 assert(Arg.getKind() == TemplateArgument::Pack &&
1049 "Missing argument pack");
1051 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1052 // We have the template argument pack to substitute, but we're not
1053 // actually expanding the enclosing pack expansion yet. So, just
1054 // keep the entire argument pack.
1055 return getSema().Context.getSubstTemplateTemplateParmPack(TTP, Arg);
1058 assert(getSema().ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
1059 Arg = Arg.pack_begin()[getSema().ArgumentPackSubstitutionIndex];
1062 TemplateName Template = Arg.getAsTemplate();
1063 assert(!Template.isNull() && "Null template template argument");
1065 // We don't ever want to substitute for a qualified template name, since
1066 // the qualifier is handled separately. So, look through the qualified
1067 // template name to its underlying declaration.
1068 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
1069 Template = TemplateName(QTN->getTemplateDecl());
1071 Template = getSema().Context.getSubstTemplateTemplateParm(TTP, Template);
1076 if (SubstTemplateTemplateParmPackStorage *SubstPack
1077 = Name.getAsSubstTemplateTemplateParmPack()) {
1078 if (getSema().ArgumentPackSubstitutionIndex == -1)
1081 const TemplateArgument &ArgPack = SubstPack->getArgumentPack();
1082 assert(getSema().ArgumentPackSubstitutionIndex < (int)ArgPack.pack_size() &&
1083 "Pack substitution index out-of-range");
1084 return ArgPack.pack_begin()[getSema().ArgumentPackSubstitutionIndex]
1088 return inherited::TransformTemplateName(SS, Name, NameLoc, ObjectType,
1089 FirstQualifierInScope);
1093 TemplateInstantiator::TransformPredefinedExpr(PredefinedExpr *E) {
1094 if (!E->isTypeDependent())
1095 return SemaRef.Owned(E);
1097 FunctionDecl *currentDecl = getSema().getCurFunctionDecl();
1098 assert(currentDecl && "Must have current function declaration when "
1101 PredefinedExpr::IdentType IT = E->getIdentType();
1103 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
1105 llvm::APInt LengthI(32, Length + 1);
1107 if (IT == PredefinedExpr::LFunction)
1108 ResTy = getSema().Context.WCharTy.withConst();
1110 ResTy = getSema().Context.CharTy.withConst();
1111 ResTy = getSema().Context.getConstantArrayType(ResTy, LengthI,
1112 ArrayType::Normal, 0);
1113 PredefinedExpr *PE =
1114 new (getSema().Context) PredefinedExpr(E->getLocation(), ResTy, IT);
1115 return getSema().Owned(PE);
1119 TemplateInstantiator::TransformTemplateParmRefExpr(DeclRefExpr *E,
1120 NonTypeTemplateParmDecl *NTTP) {
1121 // If the corresponding template argument is NULL or non-existent, it's
1122 // because we are performing instantiation from explicitly-specified
1123 // template arguments in a function template, but there were some
1124 // arguments left unspecified.
1125 if (!TemplateArgs.hasTemplateArgument(NTTP->getDepth(),
1126 NTTP->getPosition()))
1127 return SemaRef.Owned(E);
1129 TemplateArgument Arg = TemplateArgs(NTTP->getDepth(), NTTP->getPosition());
1130 if (NTTP->isParameterPack()) {
1131 assert(Arg.getKind() == TemplateArgument::Pack &&
1132 "Missing argument pack");
1134 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1135 // We have an argument pack, but we can't select a particular argument
1136 // out of it yet. Therefore, we'll build an expression to hold on to that
1138 QualType TargetType = SemaRef.SubstType(NTTP->getType(), TemplateArgs,
1140 NTTP->getDeclName());
1141 if (TargetType.isNull())
1144 return new (SemaRef.Context) SubstNonTypeTemplateParmPackExpr(TargetType,
1150 assert(getSema().ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
1151 Arg = Arg.pack_begin()[getSema().ArgumentPackSubstitutionIndex];
1154 return transformNonTypeTemplateParmRef(NTTP, E->getLocation(), Arg);
1157 ExprResult TemplateInstantiator::transformNonTypeTemplateParmRef(
1158 NonTypeTemplateParmDecl *parm,
1160 TemplateArgument arg) {
1164 // If the argument is a pack expansion, the parameter must actually be a
1165 // parameter pack, and we should substitute the pattern itself, producing
1166 // an expression which contains an unexpanded parameter pack.
1167 if (arg.isPackExpansion()) {
1168 assert(parm->isParameterPack() && "pack expansion for non-pack");
1169 arg = arg.getPackExpansionPattern();
1172 // The template argument itself might be an expression, in which
1173 // case we just return that expression.
1174 if (arg.getKind() == TemplateArgument::Expression) {
1175 Expr *argExpr = arg.getAsExpr();
1176 result = SemaRef.Owned(argExpr);
1177 type = argExpr->getType();
1179 } else if (arg.getKind() == TemplateArgument::Declaration ||
1180 arg.getKind() == TemplateArgument::NullPtr) {
1182 if (arg.getKind() == TemplateArgument::Declaration) {
1183 VD = cast<ValueDecl>(arg.getAsDecl());
1185 // Find the instantiation of the template argument. This is
1186 // required for nested templates.
1187 VD = cast_or_null<ValueDecl>(
1188 getSema().FindInstantiatedDecl(loc, VD, TemplateArgs));
1192 // Propagate NULL template argument.
1196 // Derive the type we want the substituted decl to have. This had
1197 // better be non-dependent, or these checks will have serious problems.
1198 if (parm->isExpandedParameterPack()) {
1199 type = parm->getExpansionType(SemaRef.ArgumentPackSubstitutionIndex);
1200 } else if (parm->isParameterPack() &&
1201 isa<PackExpansionType>(parm->getType())) {
1202 type = SemaRef.SubstType(
1203 cast<PackExpansionType>(parm->getType())->getPattern(),
1204 TemplateArgs, loc, parm->getDeclName());
1206 type = SemaRef.SubstType(parm->getType(), TemplateArgs,
1207 loc, parm->getDeclName());
1209 assert(!type.isNull() && "type substitution failed for param type");
1210 assert(!type->isDependentType() && "param type still dependent");
1211 result = SemaRef.BuildExpressionFromDeclTemplateArgument(arg, type, loc);
1213 if (!result.isInvalid()) type = result.get()->getType();
1215 result = SemaRef.BuildExpressionFromIntegralTemplateArgument(arg, loc);
1217 // Note that this type can be different from the type of 'result',
1218 // e.g. if it's an enum type.
1219 type = arg.getIntegralType();
1221 if (result.isInvalid()) return ExprError();
1223 Expr *resultExpr = result.take();
1224 return SemaRef.Owned(new (SemaRef.Context)
1225 SubstNonTypeTemplateParmExpr(type,
1226 resultExpr->getValueKind(),
1227 loc, parm, resultExpr));
1231 TemplateInstantiator::TransformSubstNonTypeTemplateParmPackExpr(
1232 SubstNonTypeTemplateParmPackExpr *E) {
1233 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1234 // We aren't expanding the parameter pack, so just return ourselves.
1235 return getSema().Owned(E);
1238 const TemplateArgument &ArgPack = E->getArgumentPack();
1239 unsigned Index = (unsigned)getSema().ArgumentPackSubstitutionIndex;
1240 assert(Index < ArgPack.pack_size() && "Substitution index out-of-range");
1242 const TemplateArgument &Arg = ArgPack.pack_begin()[Index];
1243 return transformNonTypeTemplateParmRef(E->getParameterPack(),
1244 E->getParameterPackLocation(),
1249 TemplateInstantiator::RebuildParmVarDeclRefExpr(ParmVarDecl *PD,
1250 SourceLocation Loc) {
1251 DeclarationNameInfo NameInfo(PD->getDeclName(), Loc);
1252 return getSema().BuildDeclarationNameExpr(CXXScopeSpec(), NameInfo, PD);
1256 TemplateInstantiator::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {
1257 if (getSema().ArgumentPackSubstitutionIndex != -1) {
1258 // We can expand this parameter pack now.
1259 ParmVarDecl *D = E->getExpansion(getSema().ArgumentPackSubstitutionIndex);
1260 ValueDecl *VD = cast_or_null<ValueDecl>(TransformDecl(E->getExprLoc(), D));
1263 return RebuildParmVarDeclRefExpr(cast<ParmVarDecl>(VD), E->getExprLoc());
1266 QualType T = TransformType(E->getType());
1270 // Transform each of the parameter expansions into the corresponding
1271 // parameters in the instantiation of the function decl.
1272 SmallVector<Decl *, 8> Parms;
1273 Parms.reserve(E->getNumExpansions());
1274 for (FunctionParmPackExpr::iterator I = E->begin(), End = E->end();
1277 cast_or_null<ParmVarDecl>(TransformDecl(E->getExprLoc(), *I));
1283 return FunctionParmPackExpr::Create(getSema().Context, T,
1284 E->getParameterPack(),
1285 E->getParameterPackLocation(), Parms);
1289 TemplateInstantiator::TransformFunctionParmPackRefExpr(DeclRefExpr *E,
1291 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
1292 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
1293 = getSema().CurrentInstantiationScope->findInstantiationOf(PD);
1294 assert(Found && "no instantiation for parameter pack");
1296 Decl *TransformedDecl;
1297 if (DeclArgumentPack *Pack = Found->dyn_cast<DeclArgumentPack *>()) {
1298 // If this is a reference to a function parameter pack which we can substitute
1299 // but can't yet expand, build a FunctionParmPackExpr for it.
1300 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1301 QualType T = TransformType(E->getType());
1304 return FunctionParmPackExpr::Create(getSema().Context, T, PD,
1305 E->getExprLoc(), *Pack);
1308 TransformedDecl = (*Pack)[getSema().ArgumentPackSubstitutionIndex];
1310 TransformedDecl = Found->get<Decl*>();
1313 // We have either an unexpanded pack or a specific expansion.
1314 return RebuildParmVarDeclRefExpr(cast<ParmVarDecl>(TransformedDecl),
1319 TemplateInstantiator::TransformDeclRefExpr(DeclRefExpr *E) {
1320 NamedDecl *D = E->getDecl();
1322 // Handle references to non-type template parameters and non-type template
1324 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) {
1325 if (NTTP->getDepth() < TemplateArgs.getNumLevels())
1326 return TransformTemplateParmRefExpr(E, NTTP);
1328 // We have a non-type template parameter that isn't fully substituted;
1329 // FindInstantiatedDecl will find it in the local instantiation scope.
1332 // Handle references to function parameter packs.
1333 if (ParmVarDecl *PD = dyn_cast<ParmVarDecl>(D))
1334 if (PD->isParameterPack())
1335 return TransformFunctionParmPackRefExpr(E, PD);
1337 return TreeTransform<TemplateInstantiator>::TransformDeclRefExpr(E);
1340 ExprResult TemplateInstantiator::TransformCXXDefaultArgExpr(
1341 CXXDefaultArgExpr *E) {
1342 assert(!cast<FunctionDecl>(E->getParam()->getDeclContext())->
1343 getDescribedFunctionTemplate() &&
1344 "Default arg expressions are never formed in dependent cases.");
1345 return SemaRef.BuildCXXDefaultArgExpr(E->getUsedLocation(),
1346 cast<FunctionDecl>(E->getParam()->getDeclContext()),
1350 QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB,
1351 FunctionProtoTypeLoc TL) {
1352 // We need a local instantiation scope for this function prototype.
1353 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
1354 return inherited::TransformFunctionProtoType(TLB, TL);
1357 QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB,
1358 FunctionProtoTypeLoc TL,
1359 CXXRecordDecl *ThisContext,
1360 unsigned ThisTypeQuals) {
1361 // We need a local instantiation scope for this function prototype.
1362 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
1363 return inherited::TransformFunctionProtoType(TLB, TL, ThisContext,
1368 TemplateInstantiator::TransformFunctionTypeParam(ParmVarDecl *OldParm,
1369 int indexAdjustment,
1370 Optional<unsigned> NumExpansions,
1371 bool ExpectParameterPack) {
1372 return SemaRef.SubstParmVarDecl(OldParm, TemplateArgs, indexAdjustment,
1373 NumExpansions, ExpectParameterPack);
1377 TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB,
1378 TemplateTypeParmTypeLoc TL) {
1379 const TemplateTypeParmType *T = TL.getTypePtr();
1380 if (T->getDepth() < TemplateArgs.getNumLevels()) {
1381 // Replace the template type parameter with its corresponding
1382 // template argument.
1384 // If the corresponding template argument is NULL or doesn't exist, it's
1385 // because we are performing instantiation from explicitly-specified
1386 // template arguments in a function template class, but there were some
1387 // arguments left unspecified.
1388 if (!TemplateArgs.hasTemplateArgument(T->getDepth(), T->getIndex())) {
1389 TemplateTypeParmTypeLoc NewTL
1390 = TLB.push<TemplateTypeParmTypeLoc>(TL.getType());
1391 NewTL.setNameLoc(TL.getNameLoc());
1392 return TL.getType();
1395 TemplateArgument Arg = TemplateArgs(T->getDepth(), T->getIndex());
1397 if (T->isParameterPack()) {
1398 assert(Arg.getKind() == TemplateArgument::Pack &&
1399 "Missing argument pack");
1401 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1402 // We have the template argument pack, but we're not expanding the
1403 // enclosing pack expansion yet. Just save the template argument
1404 // pack for later substitution.
1406 = getSema().Context.getSubstTemplateTypeParmPackType(T, Arg);
1407 SubstTemplateTypeParmPackTypeLoc NewTL
1408 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(Result);
1409 NewTL.setNameLoc(TL.getNameLoc());
1413 assert(getSema().ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
1414 Arg = Arg.pack_begin()[getSema().ArgumentPackSubstitutionIndex];
1417 assert(Arg.getKind() == TemplateArgument::Type &&
1418 "Template argument kind mismatch");
1420 QualType Replacement = Arg.getAsType();
1422 // TODO: only do this uniquing once, at the start of instantiation.
1424 = getSema().Context.getSubstTemplateTypeParmType(T, Replacement);
1425 SubstTemplateTypeParmTypeLoc NewTL
1426 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
1427 NewTL.setNameLoc(TL.getNameLoc());
1431 // The template type parameter comes from an inner template (e.g.,
1432 // the template parameter list of a member template inside the
1433 // template we are instantiating). Create a new template type
1434 // parameter with the template "level" reduced by one.
1435 TemplateTypeParmDecl *NewTTPDecl = 0;
1436 if (TemplateTypeParmDecl *OldTTPDecl = T->getDecl())
1437 NewTTPDecl = cast_or_null<TemplateTypeParmDecl>(
1438 TransformDecl(TL.getNameLoc(), OldTTPDecl));
1441 = getSema().Context.getTemplateTypeParmType(T->getDepth()
1442 - TemplateArgs.getNumLevels(),
1444 T->isParameterPack(),
1446 TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result);
1447 NewTL.setNameLoc(TL.getNameLoc());
1452 TemplateInstantiator::TransformSubstTemplateTypeParmPackType(
1453 TypeLocBuilder &TLB,
1454 SubstTemplateTypeParmPackTypeLoc TL) {
1455 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1456 // We aren't expanding the parameter pack, so just return ourselves.
1457 SubstTemplateTypeParmPackTypeLoc NewTL
1458 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(TL.getType());
1459 NewTL.setNameLoc(TL.getNameLoc());
1460 return TL.getType();
1463 const TemplateArgument &ArgPack = TL.getTypePtr()->getArgumentPack();
1464 unsigned Index = (unsigned)getSema().ArgumentPackSubstitutionIndex;
1465 assert(Index < ArgPack.pack_size() && "Substitution index out-of-range");
1467 QualType Result = ArgPack.pack_begin()[Index].getAsType();
1468 Result = getSema().Context.getSubstTemplateTypeParmType(
1469 TL.getTypePtr()->getReplacedParameter(),
1471 SubstTemplateTypeParmTypeLoc NewTL
1472 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
1473 NewTL.setNameLoc(TL.getNameLoc());
1477 /// \brief Perform substitution on the type T with a given set of template
1480 /// This routine substitutes the given template arguments into the
1481 /// type T and produces the instantiated type.
1483 /// \param T the type into which the template arguments will be
1484 /// substituted. If this type is not dependent, it will be returned
1487 /// \param Args the template arguments that will be
1488 /// substituted for the top-level template parameters within T.
1490 /// \param Loc the location in the source code where this substitution
1491 /// is being performed. It will typically be the location of the
1492 /// declarator (if we're instantiating the type of some declaration)
1493 /// or the location of the type in the source code (if, e.g., we're
1494 /// instantiating the type of a cast expression).
1496 /// \param Entity the name of the entity associated with a declaration
1497 /// being instantiated (if any). May be empty to indicate that there
1498 /// is no such entity (if, e.g., this is a type that occurs as part of
1499 /// a cast expression) or that the entity has no name (e.g., an
1500 /// unnamed function parameter).
1502 /// \returns If the instantiation succeeds, the instantiated
1503 /// type. Otherwise, produces diagnostics and returns a NULL type.
1504 TypeSourceInfo *Sema::SubstType(TypeSourceInfo *T,
1505 const MultiLevelTemplateArgumentList &Args,
1507 DeclarationName Entity) {
1508 assert(!ActiveTemplateInstantiations.empty() &&
1509 "Cannot perform an instantiation without some context on the "
1510 "instantiation stack");
1512 if (!T->getType()->isInstantiationDependentType() &&
1513 !T->getType()->isVariablyModifiedType())
1516 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1517 return Instantiator.TransformType(T);
1520 TypeSourceInfo *Sema::SubstType(TypeLoc TL,
1521 const MultiLevelTemplateArgumentList &Args,
1523 DeclarationName Entity) {
1524 assert(!ActiveTemplateInstantiations.empty() &&
1525 "Cannot perform an instantiation without some context on the "
1526 "instantiation stack");
1528 if (TL.getType().isNull())
1531 if (!TL.getType()->isInstantiationDependentType() &&
1532 !TL.getType()->isVariablyModifiedType()) {
1533 // FIXME: Make a copy of the TypeLoc data here, so that we can
1534 // return a new TypeSourceInfo. Inefficient!
1536 TLB.pushFullCopy(TL);
1537 return TLB.getTypeSourceInfo(Context, TL.getType());
1540 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1542 TLB.reserve(TL.getFullDataSize());
1543 QualType Result = Instantiator.TransformType(TLB, TL);
1544 if (Result.isNull())
1547 return TLB.getTypeSourceInfo(Context, Result);
1550 /// Deprecated form of the above.
1551 QualType Sema::SubstType(QualType T,
1552 const MultiLevelTemplateArgumentList &TemplateArgs,
1553 SourceLocation Loc, DeclarationName Entity) {
1554 assert(!ActiveTemplateInstantiations.empty() &&
1555 "Cannot perform an instantiation without some context on the "
1556 "instantiation stack");
1558 // If T is not a dependent type or a variably-modified type, there
1559 // is nothing to do.
1560 if (!T->isInstantiationDependentType() && !T->isVariablyModifiedType())
1563 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity);
1564 return Instantiator.TransformType(T);
1567 static bool NeedsInstantiationAsFunctionType(TypeSourceInfo *T) {
1568 if (T->getType()->isInstantiationDependentType() ||
1569 T->getType()->isVariablyModifiedType())
1572 TypeLoc TL = T->getTypeLoc().IgnoreParens();
1573 if (!TL.getAs<FunctionProtoTypeLoc>())
1576 FunctionProtoTypeLoc FP = TL.castAs<FunctionProtoTypeLoc>();
1577 for (unsigned I = 0, E = FP.getNumArgs(); I != E; ++I) {
1578 ParmVarDecl *P = FP.getArg(I);
1580 // The parameter's type as written might be dependent even if the
1581 // decayed type was not dependent.
1582 if (TypeSourceInfo *TSInfo = P->getTypeSourceInfo())
1583 if (TSInfo->getType()->isInstantiationDependentType())
1586 // TODO: currently we always rebuild expressions. When we
1587 // properly get lazier about this, we should use the same
1588 // logic to avoid rebuilding prototypes here.
1589 if (P->hasDefaultArg())
1596 /// A form of SubstType intended specifically for instantiating the
1597 /// type of a FunctionDecl. Its purpose is solely to force the
1598 /// instantiation of default-argument expressions.
1599 TypeSourceInfo *Sema::SubstFunctionDeclType(TypeSourceInfo *T,
1600 const MultiLevelTemplateArgumentList &Args,
1602 DeclarationName Entity,
1603 CXXRecordDecl *ThisContext,
1604 unsigned ThisTypeQuals) {
1605 assert(!ActiveTemplateInstantiations.empty() &&
1606 "Cannot perform an instantiation without some context on the "
1607 "instantiation stack");
1609 if (!NeedsInstantiationAsFunctionType(T))
1612 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1616 TypeLoc TL = T->getTypeLoc();
1617 TLB.reserve(TL.getFullDataSize());
1621 if (FunctionProtoTypeLoc Proto = TL.getAs<FunctionProtoTypeLoc>()) {
1622 Result = Instantiator.TransformFunctionProtoType(TLB, Proto, ThisContext,
1625 Result = Instantiator.TransformType(TLB, TL);
1627 if (Result.isNull())
1630 return TLB.getTypeSourceInfo(Context, Result);
1633 ParmVarDecl *Sema::SubstParmVarDecl(ParmVarDecl *OldParm,
1634 const MultiLevelTemplateArgumentList &TemplateArgs,
1635 int indexAdjustment,
1636 Optional<unsigned> NumExpansions,
1637 bool ExpectParameterPack) {
1638 TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
1639 TypeSourceInfo *NewDI = 0;
1641 TypeLoc OldTL = OldDI->getTypeLoc();
1642 if (PackExpansionTypeLoc ExpansionTL = OldTL.getAs<PackExpansionTypeLoc>()) {
1644 // We have a function parameter pack. Substitute into the pattern of the
1646 NewDI = SubstType(ExpansionTL.getPatternLoc(), TemplateArgs,
1647 OldParm->getLocation(), OldParm->getDeclName());
1651 if (NewDI->getType()->containsUnexpandedParameterPack()) {
1652 // We still have unexpanded parameter packs, which means that
1653 // our function parameter is still a function parameter pack.
1654 // Therefore, make its type a pack expansion type.
1655 NewDI = CheckPackExpansion(NewDI, ExpansionTL.getEllipsisLoc(),
1657 } else if (ExpectParameterPack) {
1658 // We expected to get a parameter pack but didn't (because the type
1659 // itself is not a pack expansion type), so complain. This can occur when
1660 // the substitution goes through an alias template that "loses" the
1662 Diag(OldParm->getLocation(),
1663 diag::err_function_parameter_pack_without_parameter_packs)
1664 << NewDI->getType();
1668 NewDI = SubstType(OldDI, TemplateArgs, OldParm->getLocation(),
1669 OldParm->getDeclName());
1675 if (NewDI->getType()->isVoidType()) {
1676 Diag(OldParm->getLocation(), diag::err_param_with_void_type);
1680 ParmVarDecl *NewParm = CheckParameter(Context.getTranslationUnitDecl(),
1681 OldParm->getInnerLocStart(),
1682 OldParm->getLocation(),
1683 OldParm->getIdentifier(),
1684 NewDI->getType(), NewDI,
1685 OldParm->getStorageClass());
1689 // Mark the (new) default argument as uninstantiated (if any).
1690 if (OldParm->hasUninstantiatedDefaultArg()) {
1691 Expr *Arg = OldParm->getUninstantiatedDefaultArg();
1692 NewParm->setUninstantiatedDefaultArg(Arg);
1693 } else if (OldParm->hasUnparsedDefaultArg()) {
1694 NewParm->setUnparsedDefaultArg();
1695 UnparsedDefaultArgInstantiations[OldParm].push_back(NewParm);
1696 } else if (Expr *Arg = OldParm->getDefaultArg())
1697 // FIXME: if we non-lazily instantiated non-dependent default args for
1698 // non-dependent parameter types we could remove a bunch of duplicate
1699 // conversion warnings for such arguments.
1700 NewParm->setUninstantiatedDefaultArg(Arg);
1702 NewParm->setHasInheritedDefaultArg(OldParm->hasInheritedDefaultArg());
1704 if (OldParm->isParameterPack() && !NewParm->isParameterPack()) {
1705 // Add the new parameter to the instantiated parameter pack.
1706 CurrentInstantiationScope->InstantiatedLocalPackArg(OldParm, NewParm);
1708 // Introduce an Old -> New mapping
1709 CurrentInstantiationScope->InstantiatedLocal(OldParm, NewParm);
1712 // FIXME: OldParm may come from a FunctionProtoType, in which case CurContext
1713 // can be anything, is this right ?
1714 NewParm->setDeclContext(CurContext);
1716 NewParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
1717 OldParm->getFunctionScopeIndex() + indexAdjustment);
1719 InstantiateAttrs(TemplateArgs, OldParm, NewParm);
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.
1727 bool Sema::SubstParmTypes(SourceLocation Loc,
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");
1736 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
1738 return Instantiator.TransformFunctionTypeParams(Loc, Params, NumParams, 0,
1739 ParamTypes, OutParams);
1742 /// \brief Perform substitution on the base class specifiers of the
1743 /// given class template specialization.
1745 /// Produces a diagnostic and returns true on error, returns false and
1746 /// attaches the instantiated base classes to the class template
1747 /// specialization if successful.
1749 Sema::SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
1750 CXXRecordDecl *Pattern,
1751 const MultiLevelTemplateArgumentList &TemplateArgs) {
1752 bool Invalid = false;
1753 SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases;
1754 for (ClassTemplateSpecializationDecl::base_class_iterator
1755 Base = Pattern->bases_begin(), BaseEnd = Pattern->bases_end();
1756 Base != BaseEnd; ++Base) {
1757 if (!Base->getType()->isDependentType()) {
1758 InstantiatedBases.push_back(new (Context) CXXBaseSpecifier(*Base));
1762 SourceLocation EllipsisLoc;
1763 TypeSourceInfo *BaseTypeLoc;
1764 if (Base->isPackExpansion()) {
1765 // This is a pack expansion. See whether we should expand it now, or
1766 // wait until later.
1767 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
1768 collectUnexpandedParameterPacks(Base->getTypeSourceInfo()->getTypeLoc(),
1770 bool ShouldExpand = false;
1771 bool RetainExpansion = false;
1772 Optional<unsigned> NumExpansions;
1773 if (CheckParameterPacksForExpansion(Base->getEllipsisLoc(),
1774 Base->getSourceRange(),
1776 TemplateArgs, ShouldExpand,
1783 // If we should expand this pack expansion now, do so.
1785 for (unsigned I = 0; I != *NumExpansions; ++I) {
1786 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
1788 TypeSourceInfo *BaseTypeLoc = SubstType(Base->getTypeSourceInfo(),
1790 Base->getSourceRange().getBegin(),
1797 if (CXXBaseSpecifier *InstantiatedBase
1798 = CheckBaseSpecifier(Instantiation,
1799 Base->getSourceRange(),
1801 Base->getAccessSpecifierAsWritten(),
1804 InstantiatedBases.push_back(InstantiatedBase);
1812 // The resulting base specifier will (still) be a pack expansion.
1813 EllipsisLoc = Base->getEllipsisLoc();
1814 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
1815 BaseTypeLoc = SubstType(Base->getTypeSourceInfo(),
1817 Base->getSourceRange().getBegin(),
1820 BaseTypeLoc = SubstType(Base->getTypeSourceInfo(),
1822 Base->getSourceRange().getBegin(),
1831 if (CXXBaseSpecifier *InstantiatedBase
1832 = CheckBaseSpecifier(Instantiation,
1833 Base->getSourceRange(),
1835 Base->getAccessSpecifierAsWritten(),
1838 InstantiatedBases.push_back(InstantiatedBase);
1844 AttachBaseSpecifiers(Instantiation, InstantiatedBases.data(),
1845 InstantiatedBases.size()))
1851 // Defined via #include from SemaTemplateInstantiateDecl.cpp
1854 Attr *instantiateTemplateAttribute(const Attr *At, ASTContext &C, Sema &S,
1855 const MultiLevelTemplateArgumentList &TemplateArgs);
1859 /// Determine whether we would be unable to instantiate this template (because
1860 /// it either has no definition, or is in the process of being instantiated).
1861 static bool DiagnoseUninstantiableTemplate(Sema &S,
1862 SourceLocation PointOfInstantiation,
1863 TagDecl *Instantiation,
1864 bool InstantiatedFromMember,
1866 TagDecl *PatternDef,
1867 TemplateSpecializationKind TSK,
1868 bool Complain = true) {
1869 if (PatternDef && !PatternDef->isBeingDefined())
1872 if (!Complain || (PatternDef && PatternDef->isInvalidDecl())) {
1874 } else if (PatternDef) {
1875 assert(PatternDef->isBeingDefined());
1876 S.Diag(PointOfInstantiation,
1877 diag::err_template_instantiate_within_definition)
1878 << (TSK != TSK_ImplicitInstantiation)
1879 << S.Context.getTypeDeclType(Instantiation);
1880 // Not much point in noting the template declaration here, since
1881 // we're lexically inside it.
1882 Instantiation->setInvalidDecl();
1883 } else if (InstantiatedFromMember) {
1884 S.Diag(PointOfInstantiation,
1885 diag::err_implicit_instantiate_member_undefined)
1886 << S.Context.getTypeDeclType(Instantiation);
1887 S.Diag(Pattern->getLocation(), diag::note_member_of_template_here);
1889 S.Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
1890 << (TSK != TSK_ImplicitInstantiation)
1891 << S.Context.getTypeDeclType(Instantiation);
1892 S.Diag(Pattern->getLocation(), diag::note_template_decl_here);
1895 // In general, Instantiation isn't marked invalid to get more than one
1896 // error for multiple undefined instantiations. But the code that does
1897 // explicit declaration -> explicit definition conversion can't handle
1898 // invalid declarations, so mark as invalid in that case.
1899 if (TSK == TSK_ExplicitInstantiationDeclaration)
1900 Instantiation->setInvalidDecl();
1904 /// \brief Instantiate the definition of a class from a given pattern.
1906 /// \param PointOfInstantiation The point of instantiation within the
1909 /// \param Instantiation is the declaration whose definition is being
1910 /// instantiated. This will be either a class template specialization
1911 /// or a member class of a class template specialization.
1913 /// \param Pattern is the pattern from which the instantiation
1914 /// occurs. This will be either the declaration of a class template or
1915 /// the declaration of a member class of a class template.
1917 /// \param TemplateArgs The template arguments to be substituted into
1920 /// \param TSK the kind of implicit or explicit instantiation to perform.
1922 /// \param Complain whether to complain if the class cannot be instantiated due
1923 /// to the lack of a definition.
1925 /// \returns true if an error occurred, false otherwise.
1927 Sema::InstantiateClass(SourceLocation PointOfInstantiation,
1928 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
1929 const MultiLevelTemplateArgumentList &TemplateArgs,
1930 TemplateSpecializationKind TSK,
1932 CXXRecordDecl *PatternDef
1933 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
1934 if (DiagnoseUninstantiableTemplate(*this, PointOfInstantiation, Instantiation,
1935 Instantiation->getInstantiatedFromMemberClass(),
1936 Pattern, PatternDef, TSK, Complain))
1938 Pattern = PatternDef;
1940 // \brief Record the point of instantiation.
1941 if (MemberSpecializationInfo *MSInfo
1942 = Instantiation->getMemberSpecializationInfo()) {
1943 MSInfo->setTemplateSpecializationKind(TSK);
1944 MSInfo->setPointOfInstantiation(PointOfInstantiation);
1945 } else if (ClassTemplateSpecializationDecl *Spec
1946 = dyn_cast<ClassTemplateSpecializationDecl>(Instantiation)) {
1947 Spec->setTemplateSpecializationKind(TSK);
1948 Spec->setPointOfInstantiation(PointOfInstantiation);
1951 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
1955 // Enter the scope of this instantiation. We don't use
1956 // PushDeclContext because we don't have a scope.
1957 ContextRAII SavedContext(*this, Instantiation);
1958 EnterExpressionEvaluationContext EvalContext(*this,
1959 Sema::PotentiallyEvaluated);
1961 // If this is an instantiation of a local class, merge this local
1962 // instantiation scope with the enclosing scope. Otherwise, every
1963 // instantiation of a class has its own local instantiation scope.
1964 bool MergeWithParentScope = !Instantiation->isDefinedOutsideFunctionOrMethod();
1965 LocalInstantiationScope Scope(*this, MergeWithParentScope);
1967 // Pull attributes from the pattern onto the instantiation.
1968 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
1970 // Start the definition of this instantiation.
1971 Instantiation->startDefinition();
1973 Instantiation->setTagKind(Pattern->getTagKind());
1975 // Do substitution on the base class specifiers.
1976 if (SubstBaseSpecifiers(Instantiation, Pattern, TemplateArgs))
1977 Instantiation->setInvalidDecl();
1979 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
1980 SmallVector<Decl*, 4> Fields;
1981 SmallVector<std::pair<FieldDecl*, FieldDecl*>, 4>
1982 FieldsWithMemberInitializers;
1983 // Delay instantiation of late parsed attributes.
1984 LateInstantiatedAttrVec LateAttrs;
1985 Instantiator.enableLateAttributeInstantiation(&LateAttrs);
1987 for (RecordDecl::decl_iterator Member = Pattern->decls_begin(),
1988 MemberEnd = Pattern->decls_end();
1989 Member != MemberEnd; ++Member) {
1990 // Don't instantiate members not belonging in this semantic context.
1993 // template <int i> class A {
1997 // 'class B' has the template as lexical context but semantically it is
1998 // introduced in namespace scope.
1999 if ((*Member)->getDeclContext() != Pattern)
2002 if ((*Member)->isInvalidDecl()) {
2003 Instantiation->setInvalidDecl();
2007 Decl *NewMember = Instantiator.Visit(*Member);
2009 if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember)) {
2010 Fields.push_back(Field);
2011 FieldDecl *OldField = cast<FieldDecl>(*Member);
2012 if (OldField->getInClassInitializer())
2013 FieldsWithMemberInitializers.push_back(std::make_pair(OldField,
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");
2024 MSInfo->setTemplateSpecializationKind(TSK_ImplicitInstantiation);
2025 MSInfo->setPointOfInstantiation(PointOfInstantiation);
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();
2036 if (NewMember->isInvalidDecl())
2037 Instantiation->setInvalidDecl();
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.
2046 // Finish checking fields.
2047 ActOnFields(0, Instantiation->getLocation(), Instantiation, Fields,
2048 SourceLocation(), SourceLocation(), 0);
2049 CheckCompletedCXXClass(Instantiation);
2051 // Attach any in-class member initializers now the class is complete.
2052 // FIXME: We are supposed to defer instantiating these until they are needed.
2053 if (!FieldsWithMemberInitializers.empty()) {
2054 // C++11 [expr.prim.general]p4:
2055 // Otherwise, if a member-declarator declares a non-static data member
2056 // (9.2) of a class X, the expression this is a prvalue of type "pointer
2057 // to X" within the optional brace-or-equal-initializer. It shall not
2058 // appear elsewhere in the member-declarator.
2059 CXXThisScopeRAII ThisScope(*this, Instantiation, (unsigned)0);
2061 for (unsigned I = 0, N = FieldsWithMemberInitializers.size(); I != N; ++I) {
2062 FieldDecl *OldField = FieldsWithMemberInitializers[I].first;
2063 FieldDecl *NewField = FieldsWithMemberInitializers[I].second;
2064 Expr *OldInit = OldField->getInClassInitializer();
2066 ExprResult NewInit = SubstInitializer(OldInit, TemplateArgs,
2067 /*CXXDirectInit=*/false);
2068 if (NewInit.isInvalid())
2069 NewField->setInvalidDecl();
2071 Expr *Init = NewInit.take();
2072 assert(Init && "no-argument initializer in class");
2073 assert(!isa<ParenListExpr>(Init) && "call-style init in class");
2074 ActOnCXXInClassMemberInitializer(NewField, Init->getLocStart(), Init);
2078 // Instantiate late parsed attributes, and attach them to their decls.
2079 // See Sema::InstantiateAttrs
2080 for (LateInstantiatedAttrVec::iterator I = LateAttrs.begin(),
2081 E = LateAttrs.end(); I != E; ++I) {
2082 assert(CurrentInstantiationScope == Instantiator.getStartingScope());
2083 CurrentInstantiationScope = I->Scope;
2085 instantiateTemplateAttribute(I->TmplAttr, Context, *this, TemplateArgs);
2086 I->NewDecl->addAttr(NewAttr);
2087 LocalInstantiationScope::deleteScopes(I->Scope,
2088 Instantiator.getStartingScope());
2090 Instantiator.disableLateAttributeInstantiation();
2093 ActOnFinishDelayedMemberInitializers(Instantiation);
2095 if (TSK == TSK_ImplicitInstantiation) {
2096 Instantiation->setLocation(Pattern->getLocation());
2097 Instantiation->setLocStart(Pattern->getInnerLocStart());
2098 Instantiation->setRBraceLoc(Pattern->getRBraceLoc());
2101 if (!Instantiation->isInvalidDecl()) {
2102 // Perform any dependent diagnostics from the pattern.
2103 PerformDependentDiagnostics(Pattern, TemplateArgs);
2105 // Instantiate any out-of-line class template partial
2106 // specializations now.
2107 for (TemplateDeclInstantiator::delayed_partial_spec_iterator
2108 P = Instantiator.delayed_partial_spec_begin(),
2109 PEnd = Instantiator.delayed_partial_spec_end();
2111 if (!Instantiator.InstantiateClassTemplatePartialSpecialization(
2114 Instantiation->setInvalidDecl();
2120 // Exit the scope of this instantiation.
2123 if (!Instantiation->isInvalidDecl()) {
2124 Consumer.HandleTagDeclDefinition(Instantiation);
2126 // Always emit the vtable for an explicit instantiation definition
2127 // of a polymorphic class template specialization.
2128 if (TSK == TSK_ExplicitInstantiationDefinition)
2129 MarkVTableUsed(PointOfInstantiation, Instantiation, true);
2132 return Instantiation->isInvalidDecl();
2135 /// \brief Instantiate the definition of an enum from a given pattern.
2137 /// \param PointOfInstantiation The point of instantiation within the
2139 /// \param Instantiation is the declaration whose definition is being
2140 /// instantiated. This will be a member enumeration of a class
2141 /// temploid specialization, or a local enumeration within a
2142 /// function temploid specialization.
2143 /// \param Pattern The templated declaration from which the instantiation
2145 /// \param TemplateArgs The template arguments to be substituted into
2147 /// \param TSK The kind of implicit or explicit instantiation to perform.
2149 /// \return \c true if an error occurred, \c false otherwise.
2150 bool Sema::InstantiateEnum(SourceLocation PointOfInstantiation,
2151 EnumDecl *Instantiation, EnumDecl *Pattern,
2152 const MultiLevelTemplateArgumentList &TemplateArgs,
2153 TemplateSpecializationKind TSK) {
2154 EnumDecl *PatternDef = Pattern->getDefinition();
2155 if (DiagnoseUninstantiableTemplate(*this, PointOfInstantiation, Instantiation,
2156 Instantiation->getInstantiatedFromMemberEnum(),
2157 Pattern, PatternDef, TSK,/*Complain*/true))
2159 Pattern = PatternDef;
2161 // Record the point of instantiation.
2162 if (MemberSpecializationInfo *MSInfo
2163 = Instantiation->getMemberSpecializationInfo()) {
2164 MSInfo->setTemplateSpecializationKind(TSK);
2165 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2168 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
2172 // Enter the scope of this instantiation. We don't use
2173 // PushDeclContext because we don't have a scope.
2174 ContextRAII SavedContext(*this, Instantiation);
2175 EnterExpressionEvaluationContext EvalContext(*this,
2176 Sema::PotentiallyEvaluated);
2178 LocalInstantiationScope Scope(*this, /*MergeWithParentScope*/true);
2180 // Pull attributes from the pattern onto the instantiation.
2181 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
2183 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
2184 Instantiator.InstantiateEnumDefinition(Instantiation, Pattern);
2186 // Exit the scope of this instantiation.
2189 return Instantiation->isInvalidDecl();
2193 /// \brief A partial specialization whose template arguments have matched
2194 /// a given template-id.
2195 struct PartialSpecMatchResult {
2196 ClassTemplatePartialSpecializationDecl *Partial;
2197 TemplateArgumentList *Args;
2202 Sema::InstantiateClassTemplateSpecialization(
2203 SourceLocation PointOfInstantiation,
2204 ClassTemplateSpecializationDecl *ClassTemplateSpec,
2205 TemplateSpecializationKind TSK,
2207 // Perform the actual instantiation on the canonical declaration.
2208 ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>(
2209 ClassTemplateSpec->getCanonicalDecl());
2211 // Check whether we have already instantiated or specialized this class
2212 // template specialization.
2213 if (ClassTemplateSpec->getSpecializationKind() != TSK_Undeclared) {
2214 if (ClassTemplateSpec->getSpecializationKind() ==
2215 TSK_ExplicitInstantiationDeclaration &&
2216 TSK == TSK_ExplicitInstantiationDefinition) {
2217 // An explicit instantiation definition follows an explicit instantiation
2218 // declaration (C++0x [temp.explicit]p10); go ahead and perform the
2219 // explicit instantiation.
2220 ClassTemplateSpec->setSpecializationKind(TSK);
2222 // If this is an explicit instantiation definition, mark the
2224 if (TSK == TSK_ExplicitInstantiationDefinition &&
2225 !ClassTemplateSpec->isInvalidDecl())
2226 MarkVTableUsed(PointOfInstantiation, ClassTemplateSpec, true);
2231 // We can only instantiate something that hasn't already been
2232 // instantiated or specialized. Fail without any diagnostics: our
2233 // caller will provide an error message.
2237 if (ClassTemplateSpec->isInvalidDecl())
2240 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
2241 CXXRecordDecl *Pattern = 0;
2243 // C++ [temp.class.spec.match]p1:
2244 // When a class template is used in a context that requires an
2245 // instantiation of the class, it is necessary to determine
2246 // whether the instantiation is to be generated using the primary
2247 // template or one of the partial specializations. This is done by
2248 // matching the template arguments of the class template
2249 // specialization with the template argument lists of the partial
2251 typedef PartialSpecMatchResult MatchResult;
2252 SmallVector<MatchResult, 4> Matched;
2253 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
2254 Template->getPartialSpecializations(PartialSpecs);
2255 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
2256 ClassTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
2257 TemplateDeductionInfo Info(PointOfInstantiation);
2258 if (TemplateDeductionResult Result
2259 = DeduceTemplateArguments(Partial,
2260 ClassTemplateSpec->getTemplateArgs(),
2262 // FIXME: Store the failed-deduction information for use in
2263 // diagnostics, later.
2266 Matched.push_back(PartialSpecMatchResult());
2267 Matched.back().Partial = Partial;
2268 Matched.back().Args = Info.take();
2272 // If we're dealing with a member template where the template parameters
2273 // have been instantiated, this provides the original template parameters
2274 // from which the member template's parameters were instantiated.
2275 SmallVector<const NamedDecl *, 4> InstantiatedTemplateParameters;
2277 if (Matched.size() >= 1) {
2278 SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
2279 if (Matched.size() == 1) {
2280 // -- If exactly one matching specialization is found, the
2281 // instantiation is generated from that specialization.
2282 // We don't need to do anything for this.
2284 // -- If more than one matching specialization is found, the
2285 // partial order rules (14.5.4.2) are used to determine
2286 // whether one of the specializations is more specialized
2287 // than the others. If none of the specializations is more
2288 // specialized than all of the other matching
2289 // specializations, then the use of the class template is
2290 // ambiguous and the program is ill-formed.
2291 for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
2292 PEnd = Matched.end();
2294 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
2295 PointOfInstantiation)
2300 // Determine if the best partial specialization is more specialized than
2302 bool Ambiguous = false;
2303 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
2304 PEnd = Matched.end();
2307 getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
2308 PointOfInstantiation)
2316 // Partial ordering did not produce a clear winner. Complain.
2317 ClassTemplateSpec->setInvalidDecl();
2318 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
2319 << ClassTemplateSpec;
2321 // Print the matching partial specializations.
2322 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
2323 PEnd = Matched.end();
2325 Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
2326 << getTemplateArgumentBindingsText(
2327 P->Partial->getTemplateParameters(),
2334 // Instantiate using the best class template partial specialization.
2335 ClassTemplatePartialSpecializationDecl *OrigPartialSpec = Best->Partial;
2336 while (OrigPartialSpec->getInstantiatedFromMember()) {
2337 // If we've found an explicit specialization of this class template,
2338 // stop here and use that as the pattern.
2339 if (OrigPartialSpec->isMemberSpecialization())
2342 OrigPartialSpec = OrigPartialSpec->getInstantiatedFromMember();
2345 Pattern = OrigPartialSpec;
2346 ClassTemplateSpec->setInstantiationOf(Best->Partial, Best->Args);
2348 // -- If no matches are found, the instantiation is generated
2349 // from the primary template.
2350 ClassTemplateDecl *OrigTemplate = Template;
2351 while (OrigTemplate->getInstantiatedFromMemberTemplate()) {
2352 // If we've found an explicit specialization of this class template,
2353 // stop here and use that as the pattern.
2354 if (OrigTemplate->isMemberSpecialization())
2357 OrigTemplate = OrigTemplate->getInstantiatedFromMemberTemplate();
2360 Pattern = OrigTemplate->getTemplatedDecl();
2363 bool Result = InstantiateClass(PointOfInstantiation, ClassTemplateSpec,
2365 getTemplateInstantiationArgs(ClassTemplateSpec),
2372 /// \brief Instantiates the definitions of all of the member
2373 /// of the given class, which is an instantiation of a class template
2374 /// or a member class of a template.
2376 Sema::InstantiateClassMembers(SourceLocation PointOfInstantiation,
2377 CXXRecordDecl *Instantiation,
2378 const MultiLevelTemplateArgumentList &TemplateArgs,
2379 TemplateSpecializationKind TSK) {
2380 for (DeclContext::decl_iterator D = Instantiation->decls_begin(),
2381 DEnd = Instantiation->decls_end();
2383 bool SuppressNew = false;
2384 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(*D)) {
2385 if (FunctionDecl *Pattern
2386 = Function->getInstantiatedFromMemberFunction()) {
2387 MemberSpecializationInfo *MSInfo
2388 = Function->getMemberSpecializationInfo();
2389 assert(MSInfo && "No member specialization information?");
2390 if (MSInfo->getTemplateSpecializationKind()
2391 == TSK_ExplicitSpecialization)
2394 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2396 MSInfo->getTemplateSpecializationKind(),
2397 MSInfo->getPointOfInstantiation(),
2402 if (Function->isDefined())
2405 if (TSK == TSK_ExplicitInstantiationDefinition) {
2406 // C++0x [temp.explicit]p8:
2407 // An explicit instantiation definition that names a class template
2408 // specialization explicitly instantiates the class template
2409 // specialization and is only an explicit instantiation definition
2410 // of members whose definition is visible at the point of
2412 if (!Pattern->isDefined())
2415 Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2417 InstantiateFunctionDefinition(PointOfInstantiation, Function);
2419 Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2422 } else if (VarDecl *Var = dyn_cast<VarDecl>(*D)) {
2423 if (Var->isStaticDataMember()) {
2424 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
2425 assert(MSInfo && "No member specialization information?");
2426 if (MSInfo->getTemplateSpecializationKind()
2427 == TSK_ExplicitSpecialization)
2430 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2432 MSInfo->getTemplateSpecializationKind(),
2433 MSInfo->getPointOfInstantiation(),
2438 if (TSK == TSK_ExplicitInstantiationDefinition) {
2439 // C++0x [temp.explicit]p8:
2440 // An explicit instantiation definition that names a class template
2441 // specialization explicitly instantiates the class template
2442 // specialization and is only an explicit instantiation definition
2443 // of members whose definition is visible at the point of
2445 if (!Var->getInstantiatedFromStaticDataMember()
2446 ->getOutOfLineDefinition())
2449 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2450 InstantiateStaticDataMemberDefinition(PointOfInstantiation, Var);
2452 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2455 } else if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(*D)) {
2456 // Always skip the injected-class-name, along with any
2457 // redeclarations of nested classes, since both would cause us
2458 // to try to instantiate the members of a class twice.
2459 if (Record->isInjectedClassName() || Record->getPreviousDecl())
2462 MemberSpecializationInfo *MSInfo = Record->getMemberSpecializationInfo();
2463 assert(MSInfo && "No member specialization information?");
2465 if (MSInfo->getTemplateSpecializationKind()
2466 == TSK_ExplicitSpecialization)
2469 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2471 MSInfo->getTemplateSpecializationKind(),
2472 MSInfo->getPointOfInstantiation(),
2477 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
2478 assert(Pattern && "Missing instantiated-from-template information");
2480 if (!Record->getDefinition()) {
2481 if (!Pattern->getDefinition()) {
2482 // C++0x [temp.explicit]p8:
2483 // An explicit instantiation definition that names a class template
2484 // specialization explicitly instantiates the class template
2485 // specialization and is only an explicit instantiation definition
2486 // of members whose definition is visible at the point of
2488 if (TSK == TSK_ExplicitInstantiationDeclaration) {
2489 MSInfo->setTemplateSpecializationKind(TSK);
2490 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2496 InstantiateClass(PointOfInstantiation, Record, Pattern,
2500 if (TSK == TSK_ExplicitInstantiationDefinition &&
2501 Record->getTemplateSpecializationKind() ==
2502 TSK_ExplicitInstantiationDeclaration) {
2503 Record->setTemplateSpecializationKind(TSK);
2504 MarkVTableUsed(PointOfInstantiation, Record, true);
2508 Pattern = cast_or_null<CXXRecordDecl>(Record->getDefinition());
2510 InstantiateClassMembers(PointOfInstantiation, Pattern, TemplateArgs,
2512 } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(*D)) {
2513 MemberSpecializationInfo *MSInfo = Enum->getMemberSpecializationInfo();
2514 assert(MSInfo && "No member specialization information?");
2516 if (MSInfo->getTemplateSpecializationKind()
2517 == TSK_ExplicitSpecialization)
2520 if (CheckSpecializationInstantiationRedecl(
2521 PointOfInstantiation, TSK, Enum,
2522 MSInfo->getTemplateSpecializationKind(),
2523 MSInfo->getPointOfInstantiation(), SuppressNew) ||
2527 if (Enum->getDefinition())
2530 EnumDecl *Pattern = Enum->getInstantiatedFromMemberEnum();
2531 assert(Pattern && "Missing instantiated-from-template information");
2533 if (TSK == TSK_ExplicitInstantiationDefinition) {
2534 if (!Pattern->getDefinition())
2537 InstantiateEnum(PointOfInstantiation, Enum, Pattern, TemplateArgs, TSK);
2539 MSInfo->setTemplateSpecializationKind(TSK);
2540 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2546 /// \brief Instantiate the definitions of all of the members of the
2547 /// given class template specialization, which was named as part of an
2548 /// explicit instantiation.
2550 Sema::InstantiateClassTemplateSpecializationMembers(
2551 SourceLocation PointOfInstantiation,
2552 ClassTemplateSpecializationDecl *ClassTemplateSpec,
2553 TemplateSpecializationKind TSK) {
2554 // C++0x [temp.explicit]p7:
2555 // An explicit instantiation that names a class template
2556 // specialization is an explicit instantion of the same kind
2557 // (declaration or definition) of each of its members (not
2558 // including members inherited from base classes) that has not
2559 // been previously explicitly specialized in the translation unit
2560 // containing the explicit instantiation, except as described
2562 InstantiateClassMembers(PointOfInstantiation, ClassTemplateSpec,
2563 getTemplateInstantiationArgs(ClassTemplateSpec),
2568 Sema::SubstStmt(Stmt *S, const MultiLevelTemplateArgumentList &TemplateArgs) {
2572 TemplateInstantiator Instantiator(*this, TemplateArgs,
2575 return Instantiator.TransformStmt(S);
2579 Sema::SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs) {
2583 TemplateInstantiator Instantiator(*this, TemplateArgs,
2586 return Instantiator.TransformExpr(E);
2589 ExprResult Sema::SubstInitializer(Expr *Init,
2590 const MultiLevelTemplateArgumentList &TemplateArgs,
2591 bool CXXDirectInit) {
2592 TemplateInstantiator Instantiator(*this, TemplateArgs,
2595 return Instantiator.TransformInitializer(Init, CXXDirectInit);
2598 bool Sema::SubstExprs(Expr **Exprs, unsigned NumExprs, bool IsCall,
2599 const MultiLevelTemplateArgumentList &TemplateArgs,
2600 SmallVectorImpl<Expr *> &Outputs) {
2604 TemplateInstantiator Instantiator(*this, TemplateArgs,
2607 return Instantiator.TransformExprs(Exprs, NumExprs, IsCall, Outputs);
2610 NestedNameSpecifierLoc
2611 Sema::SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
2612 const MultiLevelTemplateArgumentList &TemplateArgs) {
2614 return NestedNameSpecifierLoc();
2616 TemplateInstantiator Instantiator(*this, TemplateArgs, NNS.getBeginLoc(),
2618 return Instantiator.TransformNestedNameSpecifierLoc(NNS);
2621 /// \brief Do template substitution on declaration name info.
2623 Sema::SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
2624 const MultiLevelTemplateArgumentList &TemplateArgs) {
2625 TemplateInstantiator Instantiator(*this, TemplateArgs, NameInfo.getLoc(),
2626 NameInfo.getName());
2627 return Instantiator.TransformDeclarationNameInfo(NameInfo);
2631 Sema::SubstTemplateName(NestedNameSpecifierLoc QualifierLoc,
2632 TemplateName Name, SourceLocation Loc,
2633 const MultiLevelTemplateArgumentList &TemplateArgs) {
2634 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
2637 SS.Adopt(QualifierLoc);
2638 return Instantiator.TransformTemplateName(SS, Name, Loc);
2641 bool Sema::Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
2642 TemplateArgumentListInfo &Result,
2643 const MultiLevelTemplateArgumentList &TemplateArgs) {
2644 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
2647 return Instantiator.TransformTemplateArguments(Args, NumArgs, Result);
2651 static const Decl* getCanonicalParmVarDecl(const Decl *D) {
2652 // When storing ParmVarDecls in the local instantiation scope, we always
2653 // want to use the ParmVarDecl from the canonical function declaration,
2654 // since the map is then valid for any redeclaration or definition of that
2656 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(D)) {
2657 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
2658 unsigned i = PV->getFunctionScopeIndex();
2659 return FD->getCanonicalDecl()->getParamDecl(i);
2666 llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> *
2667 LocalInstantiationScope::findInstantiationOf(const Decl *D) {
2668 D = getCanonicalParmVarDecl(D);
2669 for (LocalInstantiationScope *Current = this; Current;
2670 Current = Current->Outer) {
2672 // Check if we found something within this scope.
2673 const Decl *CheckD = D;
2675 LocalDeclsMap::iterator Found = Current->LocalDecls.find(CheckD);
2676 if (Found != Current->LocalDecls.end())
2677 return &Found->second;
2679 // If this is a tag declaration, it's possible that we need to look for
2680 // a previous declaration.
2681 if (const TagDecl *Tag = dyn_cast<TagDecl>(CheckD))
2682 CheckD = Tag->getPreviousDecl();
2687 // If we aren't combined with our outer scope, we're done.
2688 if (!Current->CombineWithOuterScope)
2692 // If we didn't find the decl, then we either have a sema bug, or we have a
2693 // forward reference to a label declaration. Return null to indicate that
2694 // we have an uninstantiated label.
2695 assert(isa<LabelDecl>(D) && "declaration not instantiated in this scope");
2699 void LocalInstantiationScope::InstantiatedLocal(const Decl *D, Decl *Inst) {
2700 D = getCanonicalParmVarDecl(D);
2701 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
2702 if (Stored.isNull())
2704 else if (DeclArgumentPack *Pack = Stored.dyn_cast<DeclArgumentPack *>())
2705 Pack->push_back(Inst);
2707 assert(Stored.get<Decl *>() == Inst && "Already instantiated this local");
2710 void LocalInstantiationScope::InstantiatedLocalPackArg(const Decl *D,
2712 D = getCanonicalParmVarDecl(D);
2713 DeclArgumentPack *Pack = LocalDecls[D].get<DeclArgumentPack *>();
2714 Pack->push_back(Inst);
2717 void LocalInstantiationScope::MakeInstantiatedLocalArgPack(const Decl *D) {
2718 D = getCanonicalParmVarDecl(D);
2719 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
2720 assert(Stored.isNull() && "Already instantiated this local");
2721 DeclArgumentPack *Pack = new DeclArgumentPack;
2723 ArgumentPacks.push_back(Pack);
2726 void LocalInstantiationScope::SetPartiallySubstitutedPack(NamedDecl *Pack,
2727 const TemplateArgument *ExplicitArgs,
2728 unsigned NumExplicitArgs) {
2729 assert((!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack) &&
2730 "Already have a partially-substituted pack");
2731 assert((!PartiallySubstitutedPack
2732 || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) &&
2733 "Wrong number of arguments in partially-substituted pack");
2734 PartiallySubstitutedPack = Pack;
2735 ArgsInPartiallySubstitutedPack = ExplicitArgs;
2736 NumArgsInPartiallySubstitutedPack = NumExplicitArgs;
2739 NamedDecl *LocalInstantiationScope::getPartiallySubstitutedPack(
2740 const TemplateArgument **ExplicitArgs,
2741 unsigned *NumExplicitArgs) const {
2744 if (NumExplicitArgs)
2745 *NumExplicitArgs = 0;
2747 for (const LocalInstantiationScope *Current = this; Current;
2748 Current = Current->Outer) {
2749 if (Current->PartiallySubstitutedPack) {
2751 *ExplicitArgs = Current->ArgsInPartiallySubstitutedPack;
2752 if (NumExplicitArgs)
2753 *NumExplicitArgs = Current->NumArgsInPartiallySubstitutedPack;
2755 return Current->PartiallySubstitutedPack;
2758 if (!Current->CombineWithOuterScope)