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/ASTLambda.h"
18 #include "clang/AST/ASTMutationListener.h"
19 #include "clang/AST/DeclTemplate.h"
20 #include "clang/AST/Expr.h"
21 #include "clang/Basic/LangOptions.h"
22 #include "clang/Sema/DeclSpec.h"
23 #include "clang/Sema/Initialization.h"
24 #include "clang/Sema/Lookup.h"
25 #include "clang/Sema/PrettyDeclStackTrace.h"
26 #include "clang/Sema/Template.h"
27 #include "clang/Sema/TemplateDeduction.h"
29 using namespace clang;
32 //===----------------------------------------------------------------------===/
33 // Template Instantiation Support
34 //===----------------------------------------------------------------------===/
36 /// \brief Retrieve the template argument list(s) that should be used to
37 /// instantiate the definition of the given declaration.
39 /// \param D the declaration for which we are computing template instantiation
42 /// \param Innermost if non-NULL, the innermost template argument list.
44 /// \param RelativeToPrimary true if we should get the template
45 /// arguments relative to the primary template, even when we're
46 /// dealing with a specialization. This is only relevant for function
47 /// template specializations.
49 /// \param Pattern If non-NULL, indicates the pattern from which we will be
50 /// instantiating the definition of the given declaration, \p D. This is
51 /// used to determine the proper set of template instantiation arguments for
52 /// friend function template specializations.
53 MultiLevelTemplateArgumentList
54 Sema::getTemplateInstantiationArgs(NamedDecl *D,
55 const TemplateArgumentList *Innermost,
56 bool RelativeToPrimary,
57 const FunctionDecl *Pattern) {
58 // Accumulate the set of template argument lists in this structure.
59 MultiLevelTemplateArgumentList Result;
62 Result.addOuterTemplateArguments(Innermost);
64 DeclContext *Ctx = dyn_cast<DeclContext>(D);
66 Ctx = D->getDeclContext();
68 // Add template arguments from a variable template instantiation.
69 if (VarTemplateSpecializationDecl *Spec =
70 dyn_cast<VarTemplateSpecializationDecl>(D)) {
71 // We're done when we hit an explicit specialization.
72 if (Spec->getSpecializationKind() == TSK_ExplicitSpecialization &&
73 !isa<VarTemplatePartialSpecializationDecl>(Spec))
76 Result.addOuterTemplateArguments(&Spec->getTemplateInstantiationArgs());
78 // If this variable template specialization was instantiated from a
79 // specialized member that is a variable template, we're done.
80 assert(Spec->getSpecializedTemplate() && "No variable template?");
81 llvm::PointerUnion<VarTemplateDecl*,
82 VarTemplatePartialSpecializationDecl*> Specialized
83 = Spec->getSpecializedTemplateOrPartial();
84 if (VarTemplatePartialSpecializationDecl *Partial =
85 Specialized.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
86 if (Partial->isMemberSpecialization())
89 VarTemplateDecl *Tmpl = Specialized.get<VarTemplateDecl *>();
90 if (Tmpl->isMemberSpecialization())
95 // If we have a template template parameter with translation unit context,
96 // then we're performing substitution into a default template argument of
97 // this template template parameter before we've constructed the template
98 // that will own this template template parameter. In this case, we
99 // use empty template parameter lists for all of the outer templates
100 // to avoid performing any substitutions.
101 if (Ctx->isTranslationUnit()) {
102 if (TemplateTemplateParmDecl *TTP
103 = dyn_cast<TemplateTemplateParmDecl>(D)) {
104 for (unsigned I = 0, N = TTP->getDepth() + 1; I != N; ++I)
105 Result.addOuterTemplateArguments(None);
111 while (!Ctx->isFileContext()) {
112 // Add template arguments from a class template instantiation.
113 if (ClassTemplateSpecializationDecl *Spec
114 = dyn_cast<ClassTemplateSpecializationDecl>(Ctx)) {
115 // We're done when we hit an explicit specialization.
116 if (Spec->getSpecializationKind() == TSK_ExplicitSpecialization &&
117 !isa<ClassTemplatePartialSpecializationDecl>(Spec))
120 Result.addOuterTemplateArguments(&Spec->getTemplateInstantiationArgs());
122 // If this class template specialization was instantiated from a
123 // specialized member that is a class template, we're done.
124 assert(Spec->getSpecializedTemplate() && "No class template?");
125 if (Spec->getSpecializedTemplate()->isMemberSpecialization())
128 // Add template arguments from a function template specialization.
129 else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Ctx)) {
130 if (!RelativeToPrimary &&
131 (Function->getTemplateSpecializationKind() ==
132 TSK_ExplicitSpecialization &&
133 !Function->getClassScopeSpecializationPattern()))
136 if (const TemplateArgumentList *TemplateArgs
137 = Function->getTemplateSpecializationArgs()) {
138 // Add the template arguments for this specialization.
139 Result.addOuterTemplateArguments(TemplateArgs);
141 // If this function was instantiated from a specialized member that is
142 // a function template, we're done.
143 assert(Function->getPrimaryTemplate() && "No function template?");
144 if (Function->getPrimaryTemplate()->isMemberSpecialization())
147 // If this function is a generic lambda specialization, we are done.
148 if (isGenericLambdaCallOperatorSpecialization(Function))
151 } else if (FunctionTemplateDecl *FunTmpl
152 = Function->getDescribedFunctionTemplate()) {
153 // Add the "injected" template arguments.
154 Result.addOuterTemplateArguments(FunTmpl->getInjectedTemplateArgs());
157 // If this is a friend declaration and it declares an entity at
158 // namespace scope, take arguments from its lexical parent
159 // instead of its semantic parent, unless of course the pattern we're
160 // instantiating actually comes from the file's context!
161 if (Function->getFriendObjectKind() &&
162 Function->getDeclContext()->isFileContext() &&
163 (!Pattern || !Pattern->getLexicalDeclContext()->isFileContext())) {
164 Ctx = Function->getLexicalDeclContext();
165 RelativeToPrimary = false;
168 } else if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Ctx)) {
169 if (ClassTemplateDecl *ClassTemplate = Rec->getDescribedClassTemplate()) {
170 QualType T = ClassTemplate->getInjectedClassNameSpecialization();
171 const TemplateSpecializationType *TST =
172 cast<TemplateSpecializationType>(Context.getCanonicalType(T));
173 Result.addOuterTemplateArguments(
174 llvm::makeArrayRef(TST->getArgs(), TST->getNumArgs()));
175 if (ClassTemplate->isMemberSpecialization())
180 Ctx = Ctx->getParent();
181 RelativeToPrimary = false;
187 bool Sema::CodeSynthesisContext::isInstantiationRecord() const {
189 case TemplateInstantiation:
190 case ExceptionSpecInstantiation:
191 case DefaultTemplateArgumentInstantiation:
192 case DefaultFunctionArgumentInstantiation:
193 case ExplicitTemplateArgumentSubstitution:
194 case DeducedTemplateArgumentSubstitution:
195 case PriorTemplateArgumentSubstitution:
198 case DefaultTemplateArgumentChecking:
199 case DeclaringSpecialMember:
200 case DefiningSynthesizedFunction:
204 llvm_unreachable("Invalid SynthesisKind!");
207 Sema::InstantiatingTemplate::InstantiatingTemplate(
208 Sema &SemaRef, CodeSynthesisContext::SynthesisKind Kind,
209 SourceLocation PointOfInstantiation, SourceRange InstantiationRange,
210 Decl *Entity, NamedDecl *Template, ArrayRef<TemplateArgument> TemplateArgs,
211 sema::TemplateDeductionInfo *DeductionInfo)
213 // Don't allow further instantiation if a fatal error and an uncompilable
214 // error have occurred. Any diagnostics we might have raised will not be
215 // visible, and we do not need to construct a correct AST.
216 if (SemaRef.Diags.hasFatalErrorOccurred() &&
217 SemaRef.Diags.hasUncompilableErrorOccurred()) {
221 Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
223 CodeSynthesisContext Inst;
225 Inst.PointOfInstantiation = PointOfInstantiation;
226 Inst.Entity = Entity;
227 Inst.Template = Template;
228 Inst.TemplateArgs = TemplateArgs.data();
229 Inst.NumTemplateArgs = TemplateArgs.size();
230 Inst.DeductionInfo = DeductionInfo;
231 Inst.InstantiationRange = InstantiationRange;
232 SemaRef.pushCodeSynthesisContext(Inst);
234 AlreadyInstantiating =
235 !SemaRef.InstantiatingSpecializations
236 .insert(std::make_pair(Inst.Entity->getCanonicalDecl(), Inst.Kind))
241 Sema::InstantiatingTemplate::InstantiatingTemplate(
242 Sema &SemaRef, SourceLocation PointOfInstantiation, Decl *Entity,
243 SourceRange InstantiationRange)
244 : InstantiatingTemplate(SemaRef,
245 CodeSynthesisContext::TemplateInstantiation,
246 PointOfInstantiation, InstantiationRange, Entity) {}
248 Sema::InstantiatingTemplate::InstantiatingTemplate(
249 Sema &SemaRef, SourceLocation PointOfInstantiation, FunctionDecl *Entity,
250 ExceptionSpecification, SourceRange InstantiationRange)
251 : InstantiatingTemplate(
252 SemaRef, CodeSynthesisContext::ExceptionSpecInstantiation,
253 PointOfInstantiation, InstantiationRange, Entity) {}
255 Sema::InstantiatingTemplate::InstantiatingTemplate(
256 Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateParameter Param,
257 TemplateDecl *Template, ArrayRef<TemplateArgument> TemplateArgs,
258 SourceRange InstantiationRange)
259 : InstantiatingTemplate(
261 CodeSynthesisContext::DefaultTemplateArgumentInstantiation,
262 PointOfInstantiation, InstantiationRange, getAsNamedDecl(Param),
263 Template, TemplateArgs) {}
265 Sema::InstantiatingTemplate::InstantiatingTemplate(
266 Sema &SemaRef, SourceLocation PointOfInstantiation,
267 FunctionTemplateDecl *FunctionTemplate,
268 ArrayRef<TemplateArgument> TemplateArgs,
269 CodeSynthesisContext::SynthesisKind Kind,
270 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
271 : InstantiatingTemplate(SemaRef, Kind, PointOfInstantiation,
272 InstantiationRange, FunctionTemplate, nullptr,
273 TemplateArgs, &DeductionInfo) {
275 Kind == CodeSynthesisContext::ExplicitTemplateArgumentSubstitution ||
276 Kind == CodeSynthesisContext::DeducedTemplateArgumentSubstitution);
279 Sema::InstantiatingTemplate::InstantiatingTemplate(
280 Sema &SemaRef, SourceLocation PointOfInstantiation,
281 TemplateDecl *Template,
282 ArrayRef<TemplateArgument> TemplateArgs,
283 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
284 : InstantiatingTemplate(
286 CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
287 PointOfInstantiation, InstantiationRange, Template, nullptr,
288 TemplateArgs, &DeductionInfo) {}
290 Sema::InstantiatingTemplate::InstantiatingTemplate(
291 Sema &SemaRef, SourceLocation PointOfInstantiation,
292 ClassTemplatePartialSpecializationDecl *PartialSpec,
293 ArrayRef<TemplateArgument> TemplateArgs,
294 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
295 : InstantiatingTemplate(
297 CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
298 PointOfInstantiation, InstantiationRange, PartialSpec, nullptr,
299 TemplateArgs, &DeductionInfo) {}
301 Sema::InstantiatingTemplate::InstantiatingTemplate(
302 Sema &SemaRef, SourceLocation PointOfInstantiation,
303 VarTemplatePartialSpecializationDecl *PartialSpec,
304 ArrayRef<TemplateArgument> TemplateArgs,
305 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
306 : InstantiatingTemplate(
308 CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
309 PointOfInstantiation, InstantiationRange, PartialSpec, nullptr,
310 TemplateArgs, &DeductionInfo) {}
312 Sema::InstantiatingTemplate::InstantiatingTemplate(
313 Sema &SemaRef, SourceLocation PointOfInstantiation, ParmVarDecl *Param,
314 ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange)
315 : InstantiatingTemplate(
317 CodeSynthesisContext::DefaultFunctionArgumentInstantiation,
318 PointOfInstantiation, InstantiationRange, Param, nullptr,
321 Sema::InstantiatingTemplate::InstantiatingTemplate(
322 Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template,
323 NonTypeTemplateParmDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
324 SourceRange InstantiationRange)
325 : InstantiatingTemplate(
327 CodeSynthesisContext::PriorTemplateArgumentSubstitution,
328 PointOfInstantiation, InstantiationRange, Param, Template,
331 Sema::InstantiatingTemplate::InstantiatingTemplate(
332 Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template,
333 TemplateTemplateParmDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
334 SourceRange InstantiationRange)
335 : InstantiatingTemplate(
337 CodeSynthesisContext::PriorTemplateArgumentSubstitution,
338 PointOfInstantiation, InstantiationRange, Param, Template,
341 Sema::InstantiatingTemplate::InstantiatingTemplate(
342 Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Template,
343 NamedDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
344 SourceRange InstantiationRange)
345 : InstantiatingTemplate(
346 SemaRef, CodeSynthesisContext::DefaultTemplateArgumentChecking,
347 PointOfInstantiation, InstantiationRange, Param, Template,
350 void Sema::pushCodeSynthesisContext(CodeSynthesisContext Ctx) {
351 Ctx.SavedInNonInstantiationSFINAEContext = InNonInstantiationSFINAEContext;
352 InNonInstantiationSFINAEContext = false;
354 CodeSynthesisContexts.push_back(Ctx);
356 if (!Ctx.isInstantiationRecord())
357 ++NonInstantiationEntries;
360 void Sema::popCodeSynthesisContext() {
361 auto &Active = CodeSynthesisContexts.back();
362 if (!Active.isInstantiationRecord()) {
363 assert(NonInstantiationEntries > 0);
364 --NonInstantiationEntries;
367 InNonInstantiationSFINAEContext = Active.SavedInNonInstantiationSFINAEContext;
369 // Name lookup no longer looks in this template's defining module.
370 assert(CodeSynthesisContexts.size() >=
371 CodeSynthesisContextLookupModules.size() &&
372 "forgot to remove a lookup module for a template instantiation");
373 if (CodeSynthesisContexts.size() ==
374 CodeSynthesisContextLookupModules.size()) {
375 if (Module *M = CodeSynthesisContextLookupModules.back())
376 LookupModulesCache.erase(M);
377 CodeSynthesisContextLookupModules.pop_back();
380 // If we've left the code synthesis context for the current context stack,
381 // stop remembering that we've emitted that stack.
382 if (CodeSynthesisContexts.size() ==
383 LastEmittedCodeSynthesisContextDepth)
384 LastEmittedCodeSynthesisContextDepth = 0;
386 CodeSynthesisContexts.pop_back();
389 void Sema::InstantiatingTemplate::Clear() {
391 if (!AlreadyInstantiating) {
392 auto &Active = SemaRef.CodeSynthesisContexts.back();
393 SemaRef.InstantiatingSpecializations.erase(
394 std::make_pair(Active.Entity, Active.Kind));
397 SemaRef.popCodeSynthesisContext();
403 bool Sema::InstantiatingTemplate::CheckInstantiationDepth(
404 SourceLocation PointOfInstantiation,
405 SourceRange InstantiationRange) {
406 assert(SemaRef.NonInstantiationEntries <=
407 SemaRef.CodeSynthesisContexts.size());
408 if ((SemaRef.CodeSynthesisContexts.size() -
409 SemaRef.NonInstantiationEntries)
410 <= SemaRef.getLangOpts().InstantiationDepth)
413 SemaRef.Diag(PointOfInstantiation,
414 diag::err_template_recursion_depth_exceeded)
415 << SemaRef.getLangOpts().InstantiationDepth
416 << InstantiationRange;
417 SemaRef.Diag(PointOfInstantiation, diag::note_template_recursion_depth)
418 << SemaRef.getLangOpts().InstantiationDepth;
422 /// \brief Prints the current instantiation stack through a series of
424 void Sema::PrintInstantiationStack() {
425 // Determine which template instantiations to skip, if any.
426 unsigned SkipStart = CodeSynthesisContexts.size(), SkipEnd = SkipStart;
427 unsigned Limit = Diags.getTemplateBacktraceLimit();
428 if (Limit && Limit < CodeSynthesisContexts.size()) {
429 SkipStart = Limit / 2 + Limit % 2;
430 SkipEnd = CodeSynthesisContexts.size() - Limit / 2;
433 // FIXME: In all of these cases, we need to show the template arguments
434 unsigned InstantiationIdx = 0;
435 for (SmallVectorImpl<CodeSynthesisContext>::reverse_iterator
436 Active = CodeSynthesisContexts.rbegin(),
437 ActiveEnd = CodeSynthesisContexts.rend();
439 ++Active, ++InstantiationIdx) {
440 // Skip this instantiation?
441 if (InstantiationIdx >= SkipStart && InstantiationIdx < SkipEnd) {
442 if (InstantiationIdx == SkipStart) {
443 // Note that we're skipping instantiations.
444 Diags.Report(Active->PointOfInstantiation,
445 diag::note_instantiation_contexts_suppressed)
446 << unsigned(CodeSynthesisContexts.size() - Limit);
451 switch (Active->Kind) {
452 case CodeSynthesisContext::TemplateInstantiation: {
453 Decl *D = Active->Entity;
454 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
455 unsigned DiagID = diag::note_template_member_class_here;
456 if (isa<ClassTemplateSpecializationDecl>(Record))
457 DiagID = diag::note_template_class_instantiation_here;
458 Diags.Report(Active->PointOfInstantiation, DiagID)
459 << Record << Active->InstantiationRange;
460 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
462 if (Function->getPrimaryTemplate())
463 DiagID = diag::note_function_template_spec_here;
465 DiagID = diag::note_template_member_function_here;
466 Diags.Report(Active->PointOfInstantiation, DiagID)
468 << Active->InstantiationRange;
469 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
470 Diags.Report(Active->PointOfInstantiation,
471 VD->isStaticDataMember()?
472 diag::note_template_static_data_member_def_here
473 : diag::note_template_variable_def_here)
475 << Active->InstantiationRange;
476 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
477 Diags.Report(Active->PointOfInstantiation,
478 diag::note_template_enum_def_here)
480 << Active->InstantiationRange;
481 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
482 Diags.Report(Active->PointOfInstantiation,
483 diag::note_template_nsdmi_here)
484 << FD << Active->InstantiationRange;
486 Diags.Report(Active->PointOfInstantiation,
487 diag::note_template_type_alias_instantiation_here)
488 << cast<TypeAliasTemplateDecl>(D)
489 << Active->InstantiationRange;
494 case CodeSynthesisContext::DefaultTemplateArgumentInstantiation: {
495 TemplateDecl *Template = cast<TemplateDecl>(Active->Template);
496 SmallVector<char, 128> TemplateArgsStr;
497 llvm::raw_svector_ostream OS(TemplateArgsStr);
498 Template->printName(OS);
499 TemplateSpecializationType::PrintTemplateArgumentList(
500 OS, Active->template_arguments(), getPrintingPolicy());
501 Diags.Report(Active->PointOfInstantiation,
502 diag::note_default_arg_instantiation_here)
504 << Active->InstantiationRange;
508 case CodeSynthesisContext::ExplicitTemplateArgumentSubstitution: {
509 FunctionTemplateDecl *FnTmpl = cast<FunctionTemplateDecl>(Active->Entity);
510 Diags.Report(Active->PointOfInstantiation,
511 diag::note_explicit_template_arg_substitution_here)
513 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
514 Active->TemplateArgs,
515 Active->NumTemplateArgs)
516 << Active->InstantiationRange;
520 case CodeSynthesisContext::DeducedTemplateArgumentSubstitution: {
521 if (FunctionTemplateDecl *FnTmpl =
522 dyn_cast<FunctionTemplateDecl>(Active->Entity)) {
523 Diags.Report(Active->PointOfInstantiation,
524 diag::note_function_template_deduction_instantiation_here)
526 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
527 Active->TemplateArgs,
528 Active->NumTemplateArgs)
529 << Active->InstantiationRange;
531 bool IsVar = isa<VarTemplateDecl>(Active->Entity) ||
532 isa<VarTemplateSpecializationDecl>(Active->Entity);
533 bool IsTemplate = false;
534 TemplateParameterList *Params;
535 if (auto *D = dyn_cast<TemplateDecl>(Active->Entity)) {
537 Params = D->getTemplateParameters();
538 } else if (auto *D = dyn_cast<ClassTemplatePartialSpecializationDecl>(
540 Params = D->getTemplateParameters();
541 } else if (auto *D = dyn_cast<VarTemplatePartialSpecializationDecl>(
543 Params = D->getTemplateParameters();
545 llvm_unreachable("unexpected template kind");
548 Diags.Report(Active->PointOfInstantiation,
549 diag::note_deduced_template_arg_substitution_here)
550 << IsVar << IsTemplate << cast<NamedDecl>(Active->Entity)
551 << getTemplateArgumentBindingsText(Params, Active->TemplateArgs,
552 Active->NumTemplateArgs)
553 << Active->InstantiationRange;
558 case CodeSynthesisContext::DefaultFunctionArgumentInstantiation: {
559 ParmVarDecl *Param = cast<ParmVarDecl>(Active->Entity);
560 FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());
562 SmallVector<char, 128> TemplateArgsStr;
563 llvm::raw_svector_ostream OS(TemplateArgsStr);
565 TemplateSpecializationType::PrintTemplateArgumentList(
566 OS, Active->template_arguments(), getPrintingPolicy());
567 Diags.Report(Active->PointOfInstantiation,
568 diag::note_default_function_arg_instantiation_here)
570 << Active->InstantiationRange;
574 case CodeSynthesisContext::PriorTemplateArgumentSubstitution: {
575 NamedDecl *Parm = cast<NamedDecl>(Active->Entity);
577 if (!Parm->getName().empty())
578 Name = std::string(" '") + Parm->getName().str() + "'";
580 TemplateParameterList *TemplateParams = nullptr;
581 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
582 TemplateParams = Template->getTemplateParameters();
585 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
586 ->getTemplateParameters();
587 Diags.Report(Active->PointOfInstantiation,
588 diag::note_prior_template_arg_substitution)
589 << isa<TemplateTemplateParmDecl>(Parm)
591 << getTemplateArgumentBindingsText(TemplateParams,
592 Active->TemplateArgs,
593 Active->NumTemplateArgs)
594 << Active->InstantiationRange;
598 case CodeSynthesisContext::DefaultTemplateArgumentChecking: {
599 TemplateParameterList *TemplateParams = nullptr;
600 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
601 TemplateParams = Template->getTemplateParameters();
604 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
605 ->getTemplateParameters();
607 Diags.Report(Active->PointOfInstantiation,
608 diag::note_template_default_arg_checking)
609 << getTemplateArgumentBindingsText(TemplateParams,
610 Active->TemplateArgs,
611 Active->NumTemplateArgs)
612 << Active->InstantiationRange;
616 case CodeSynthesisContext::ExceptionSpecInstantiation:
617 Diags.Report(Active->PointOfInstantiation,
618 diag::note_template_exception_spec_instantiation_here)
619 << cast<FunctionDecl>(Active->Entity)
620 << Active->InstantiationRange;
623 case CodeSynthesisContext::DeclaringSpecialMember:
624 Diags.Report(Active->PointOfInstantiation,
625 diag::note_in_declaration_of_implicit_special_member)
626 << cast<CXXRecordDecl>(Active->Entity) << Active->SpecialMember;
629 case CodeSynthesisContext::DefiningSynthesizedFunction:
630 // FIXME: For synthesized members other than special members, produce a note.
631 auto *MD = dyn_cast<CXXMethodDecl>(Active->Entity);
632 auto CSM = MD ? getSpecialMember(MD) : CXXInvalid;
633 if (CSM != CXXInvalid) {
634 Diags.Report(Active->PointOfInstantiation,
635 diag::note_member_synthesized_at)
636 << CSM << Context.getTagDeclType(MD->getParent());
643 Optional<TemplateDeductionInfo *> Sema::isSFINAEContext() const {
644 if (InNonInstantiationSFINAEContext)
645 return Optional<TemplateDeductionInfo *>(nullptr);
647 for (SmallVectorImpl<CodeSynthesisContext>::const_reverse_iterator
648 Active = CodeSynthesisContexts.rbegin(),
649 ActiveEnd = CodeSynthesisContexts.rend();
653 switch (Active->Kind) {
654 case CodeSynthesisContext::TemplateInstantiation:
655 // An instantiation of an alias template may or may not be a SFINAE
656 // context, depending on what else is on the stack.
657 if (isa<TypeAliasTemplateDecl>(Active->Entity))
660 case CodeSynthesisContext::DefaultFunctionArgumentInstantiation:
661 case CodeSynthesisContext::ExceptionSpecInstantiation:
662 // This is a template instantiation, so there is no SFINAE.
665 case CodeSynthesisContext::DefaultTemplateArgumentInstantiation:
666 case CodeSynthesisContext::PriorTemplateArgumentSubstitution:
667 case CodeSynthesisContext::DefaultTemplateArgumentChecking:
668 // A default template argument instantiation and substitution into
669 // template parameters with arguments for prior parameters may or may
670 // not be a SFINAE context; look further up the stack.
673 case CodeSynthesisContext::ExplicitTemplateArgumentSubstitution:
674 case CodeSynthesisContext::DeducedTemplateArgumentSubstitution:
675 // We're either substitution explicitly-specified template arguments
676 // or deduced template arguments, so SFINAE applies.
677 assert(Active->DeductionInfo && "Missing deduction info pointer");
678 return Active->DeductionInfo;
680 case CodeSynthesisContext::DeclaringSpecialMember:
681 case CodeSynthesisContext::DefiningSynthesizedFunction:
682 // This happens in a context unrelated to template instantiation, so
683 // there is no SFINAE.
687 // The inner context was transparent for SFINAE. If it occurred within a
688 // non-instantiation SFINAE context, then SFINAE applies.
689 if (Active->SavedInNonInstantiationSFINAEContext)
690 return Optional<TemplateDeductionInfo *>(nullptr);
696 /// \brief Retrieve the depth and index of a parameter pack.
697 static std::pair<unsigned, unsigned>
698 getDepthAndIndex(NamedDecl *ND) {
699 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ND))
700 return std::make_pair(TTP->getDepth(), TTP->getIndex());
702 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND))
703 return std::make_pair(NTTP->getDepth(), NTTP->getIndex());
705 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(ND);
706 return std::make_pair(TTP->getDepth(), TTP->getIndex());
709 //===----------------------------------------------------------------------===/
710 // Template Instantiation for Types
711 //===----------------------------------------------------------------------===/
713 class TemplateInstantiator : public TreeTransform<TemplateInstantiator> {
714 const MultiLevelTemplateArgumentList &TemplateArgs;
716 DeclarationName Entity;
719 typedef TreeTransform<TemplateInstantiator> inherited;
721 TemplateInstantiator(Sema &SemaRef,
722 const MultiLevelTemplateArgumentList &TemplateArgs,
724 DeclarationName Entity)
725 : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc),
728 /// \brief Determine whether the given type \p T has already been
731 /// For the purposes of template instantiation, a type has already been
732 /// transformed if it is NULL or if it is not dependent.
733 bool AlreadyTransformed(QualType T);
735 /// \brief Returns the location of the entity being instantiated, if known.
736 SourceLocation getBaseLocation() { return Loc; }
738 /// \brief Returns the name of the entity being instantiated, if any.
739 DeclarationName getBaseEntity() { return Entity; }
741 /// \brief Sets the "base" location and entity when that
742 /// information is known based on another transformation.
743 void setBase(SourceLocation Loc, DeclarationName Entity) {
745 this->Entity = Entity;
748 bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
749 SourceRange PatternRange,
750 ArrayRef<UnexpandedParameterPack> Unexpanded,
751 bool &ShouldExpand, bool &RetainExpansion,
752 Optional<unsigned> &NumExpansions) {
753 return getSema().CheckParameterPacksForExpansion(EllipsisLoc,
754 PatternRange, Unexpanded,
761 void ExpandingFunctionParameterPack(ParmVarDecl *Pack) {
762 SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(Pack);
765 TemplateArgument ForgetPartiallySubstitutedPack() {
766 TemplateArgument Result;
767 if (NamedDecl *PartialPack
768 = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
769 MultiLevelTemplateArgumentList &TemplateArgs
770 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
771 unsigned Depth, Index;
772 std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
773 if (TemplateArgs.hasTemplateArgument(Depth, Index)) {
774 Result = TemplateArgs(Depth, Index);
775 TemplateArgs.setArgument(Depth, Index, TemplateArgument());
782 void RememberPartiallySubstitutedPack(TemplateArgument Arg) {
786 if (NamedDecl *PartialPack
787 = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
788 MultiLevelTemplateArgumentList &TemplateArgs
789 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
790 unsigned Depth, Index;
791 std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
792 TemplateArgs.setArgument(Depth, Index, Arg);
796 /// \brief Transform the given declaration by instantiating a reference to
797 /// this declaration.
798 Decl *TransformDecl(SourceLocation Loc, Decl *D);
800 void transformAttrs(Decl *Old, Decl *New) {
801 SemaRef.InstantiateAttrs(TemplateArgs, Old, New);
804 void transformedLocalDecl(Decl *Old, Decl *New) {
805 // If we've instantiated the call operator of a lambda or the call
806 // operator template of a generic lambda, update the "instantiation of"
808 auto *NewMD = dyn_cast<CXXMethodDecl>(New);
809 if (NewMD && isLambdaCallOperator(NewMD)) {
810 auto *OldMD = dyn_cast<CXXMethodDecl>(Old);
811 if (auto *NewTD = NewMD->getDescribedFunctionTemplate())
812 NewTD->setInstantiatedFromMemberTemplate(
813 OldMD->getDescribedFunctionTemplate());
815 NewMD->setInstantiationOfMemberFunction(OldMD,
816 TSK_ImplicitInstantiation);
819 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Old, New);
821 // We recreated a local declaration, but not by instantiating it. There
822 // may be pending dependent diagnostics to produce.
823 if (auto *DC = dyn_cast<DeclContext>(Old))
824 SemaRef.PerformDependentDiagnostics(DC, TemplateArgs);
827 /// \brief Transform the definition of the given declaration by
828 /// instantiating it.
829 Decl *TransformDefinition(SourceLocation Loc, Decl *D);
831 /// \brief Transform the first qualifier within a scope by instantiating the
833 NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc);
835 /// \brief Rebuild the exception declaration and register the declaration
836 /// as an instantiated local.
837 VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
838 TypeSourceInfo *Declarator,
839 SourceLocation StartLoc,
840 SourceLocation NameLoc,
841 IdentifierInfo *Name);
843 /// \brief Rebuild the Objective-C exception declaration and register the
844 /// declaration as an instantiated local.
845 VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
846 TypeSourceInfo *TSInfo, QualType T);
848 /// \brief Check for tag mismatches when instantiating an
850 QualType RebuildElaboratedType(SourceLocation KeywordLoc,
851 ElaboratedTypeKeyword Keyword,
852 NestedNameSpecifierLoc QualifierLoc,
856 TransformTemplateName(CXXScopeSpec &SS, TemplateName Name,
857 SourceLocation NameLoc,
858 QualType ObjectType = QualType(),
859 NamedDecl *FirstQualifierInScope = nullptr,
860 bool AllowInjectedClassName = false);
862 const LoopHintAttr *TransformLoopHintAttr(const LoopHintAttr *LH);
864 ExprResult TransformPredefinedExpr(PredefinedExpr *E);
865 ExprResult TransformDeclRefExpr(DeclRefExpr *E);
866 ExprResult TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E);
868 ExprResult TransformTemplateParmRefExpr(DeclRefExpr *E,
869 NonTypeTemplateParmDecl *D);
870 ExprResult TransformSubstNonTypeTemplateParmPackExpr(
871 SubstNonTypeTemplateParmPackExpr *E);
873 /// \brief Rebuild a DeclRefExpr for a ParmVarDecl reference.
874 ExprResult RebuildParmVarDeclRefExpr(ParmVarDecl *PD, SourceLocation Loc);
876 /// \brief Transform a reference to a function parameter pack.
877 ExprResult TransformFunctionParmPackRefExpr(DeclRefExpr *E,
880 /// \brief Transform a FunctionParmPackExpr which was built when we couldn't
881 /// expand a function parameter pack reference which refers to an expanded
883 ExprResult TransformFunctionParmPackExpr(FunctionParmPackExpr *E);
885 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
886 FunctionProtoTypeLoc TL) {
887 // Call the base version; it will forward to our overridden version below.
888 return inherited::TransformFunctionProtoType(TLB, TL);
891 template<typename Fn>
892 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
893 FunctionProtoTypeLoc TL,
894 CXXRecordDecl *ThisContext,
895 unsigned ThisTypeQuals,
896 Fn TransformExceptionSpec);
898 ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm,
900 Optional<unsigned> NumExpansions,
901 bool ExpectParameterPack);
903 /// \brief Transforms a template type parameter type by performing
904 /// substitution of the corresponding template type argument.
905 QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
906 TemplateTypeParmTypeLoc TL);
908 /// \brief Transforms an already-substituted template type parameter pack
909 /// into either itself (if we aren't substituting into its pack expansion)
910 /// or the appropriate substituted argument.
911 QualType TransformSubstTemplateTypeParmPackType(TypeLocBuilder &TLB,
912 SubstTemplateTypeParmPackTypeLoc TL);
914 ExprResult TransformLambdaExpr(LambdaExpr *E) {
915 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
916 return TreeTransform<TemplateInstantiator>::TransformLambdaExpr(E);
919 TemplateParameterList *TransformTemplateParameterList(
920 TemplateParameterList *OrigTPL) {
921 if (!OrigTPL || !OrigTPL->size()) return OrigTPL;
923 DeclContext *Owner = OrigTPL->getParam(0)->getDeclContext();
924 TemplateDeclInstantiator DeclInstantiator(getSema(),
925 /* DeclContext *Owner */ Owner, TemplateArgs);
926 return DeclInstantiator.SubstTemplateParams(OrigTPL);
929 ExprResult transformNonTypeTemplateParmRef(NonTypeTemplateParmDecl *parm,
931 TemplateArgument arg);
935 bool TemplateInstantiator::AlreadyTransformed(QualType T) {
939 if (T->isInstantiationDependentType() || T->isVariablyModifiedType())
942 getSema().MarkDeclarationsReferencedInType(Loc, T);
946 static TemplateArgument
947 getPackSubstitutedTemplateArgument(Sema &S, TemplateArgument Arg) {
948 assert(S.ArgumentPackSubstitutionIndex >= 0);
949 assert(S.ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
950 Arg = Arg.pack_begin()[S.ArgumentPackSubstitutionIndex];
951 if (Arg.isPackExpansion())
952 Arg = Arg.getPackExpansionPattern();
956 Decl *TemplateInstantiator::TransformDecl(SourceLocation Loc, Decl *D) {
960 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(D)) {
961 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
962 // If the corresponding template argument is NULL or non-existent, it's
963 // because we are performing instantiation from explicitly-specified
964 // template arguments in a function template, but there were some
965 // arguments left unspecified.
966 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
970 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
972 if (TTP->isParameterPack()) {
973 assert(Arg.getKind() == TemplateArgument::Pack &&
974 "Missing argument pack");
975 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
978 TemplateName Template = Arg.getAsTemplate();
979 assert(!Template.isNull() && Template.getAsTemplateDecl() &&
980 "Wrong kind of template template argument");
981 return Template.getAsTemplateDecl();
984 // Fall through to find the instantiated declaration for this template
985 // template parameter.
988 return SemaRef.FindInstantiatedDecl(Loc, cast<NamedDecl>(D), TemplateArgs);
991 Decl *TemplateInstantiator::TransformDefinition(SourceLocation Loc, Decl *D) {
992 Decl *Inst = getSema().SubstDecl(D, getSema().CurContext, TemplateArgs);
996 getSema().CurrentInstantiationScope->InstantiatedLocal(D, Inst);
1001 TemplateInstantiator::TransformFirstQualifierInScope(NamedDecl *D,
1002 SourceLocation Loc) {
1003 // If the first part of the nested-name-specifier was a template type
1004 // parameter, instantiate that type parameter down to a tag type.
1005 if (TemplateTypeParmDecl *TTPD = dyn_cast_or_null<TemplateTypeParmDecl>(D)) {
1006 const TemplateTypeParmType *TTP
1007 = cast<TemplateTypeParmType>(getSema().Context.getTypeDeclType(TTPD));
1009 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1010 // FIXME: This needs testing w/ member access expressions.
1011 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getIndex());
1013 if (TTP->isParameterPack()) {
1014 assert(Arg.getKind() == TemplateArgument::Pack &&
1015 "Missing argument pack");
1017 if (getSema().ArgumentPackSubstitutionIndex == -1)
1020 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1023 QualType T = Arg.getAsType();
1025 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
1027 if (const TagType *Tag = T->getAs<TagType>())
1028 return Tag->getDecl();
1030 // The resulting type is not a tag; complain.
1031 getSema().Diag(Loc, diag::err_nested_name_spec_non_tag) << T;
1036 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
1040 TemplateInstantiator::RebuildExceptionDecl(VarDecl *ExceptionDecl,
1041 TypeSourceInfo *Declarator,
1042 SourceLocation StartLoc,
1043 SourceLocation NameLoc,
1044 IdentifierInfo *Name) {
1045 VarDecl *Var = inherited::RebuildExceptionDecl(ExceptionDecl, Declarator,
1046 StartLoc, NameLoc, Name);
1048 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
1052 VarDecl *TemplateInstantiator::RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
1053 TypeSourceInfo *TSInfo,
1055 VarDecl *Var = inherited::RebuildObjCExceptionDecl(ExceptionDecl, TSInfo, T);
1057 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
1062 TemplateInstantiator::RebuildElaboratedType(SourceLocation KeywordLoc,
1063 ElaboratedTypeKeyword Keyword,
1064 NestedNameSpecifierLoc QualifierLoc,
1066 if (const TagType *TT = T->getAs<TagType>()) {
1067 TagDecl* TD = TT->getDecl();
1069 SourceLocation TagLocation = KeywordLoc;
1071 IdentifierInfo *Id = TD->getIdentifier();
1073 // TODO: should we even warn on struct/class mismatches for this? Seems
1074 // like it's likely to produce a lot of spurious errors.
1075 if (Id && Keyword != ETK_None && Keyword != ETK_Typename) {
1076 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForKeyword(Keyword);
1077 if (!SemaRef.isAcceptableTagRedeclaration(TD, Kind, /*isDefinition*/false,
1079 SemaRef.Diag(TagLocation, diag::err_use_with_wrong_tag)
1081 << FixItHint::CreateReplacement(SourceRange(TagLocation),
1083 SemaRef.Diag(TD->getLocation(), diag::note_previous_use);
1088 return TreeTransform<TemplateInstantiator>::RebuildElaboratedType(KeywordLoc,
1094 TemplateName TemplateInstantiator::TransformTemplateName(
1095 CXXScopeSpec &SS, TemplateName Name, SourceLocation NameLoc,
1096 QualType ObjectType, NamedDecl *FirstQualifierInScope,
1097 bool AllowInjectedClassName) {
1098 if (TemplateTemplateParmDecl *TTP
1099 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl())) {
1100 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1101 // If the corresponding template argument is NULL or non-existent, it's
1102 // because we are performing instantiation from explicitly-specified
1103 // template arguments in a function template, but there were some
1104 // arguments left unspecified.
1105 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
1106 TTP->getPosition()))
1109 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
1111 if (TTP->isParameterPack()) {
1112 assert(Arg.getKind() == TemplateArgument::Pack &&
1113 "Missing argument pack");
1115 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1116 // We have the template argument pack to substitute, but we're not
1117 // actually expanding the enclosing pack expansion yet. So, just
1118 // keep the entire argument pack.
1119 return getSema().Context.getSubstTemplateTemplateParmPack(TTP, Arg);
1122 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1125 TemplateName Template = Arg.getAsTemplate();
1126 assert(!Template.isNull() && "Null template template argument");
1128 // We don't ever want to substitute for a qualified template name, since
1129 // the qualifier is handled separately. So, look through the qualified
1130 // template name to its underlying declaration.
1131 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
1132 Template = TemplateName(QTN->getTemplateDecl());
1134 Template = getSema().Context.getSubstTemplateTemplateParm(TTP, Template);
1139 if (SubstTemplateTemplateParmPackStorage *SubstPack
1140 = Name.getAsSubstTemplateTemplateParmPack()) {
1141 if (getSema().ArgumentPackSubstitutionIndex == -1)
1144 TemplateArgument Arg = SubstPack->getArgumentPack();
1145 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1146 return Arg.getAsTemplate();
1149 return inherited::TransformTemplateName(SS, Name, NameLoc, ObjectType,
1150 FirstQualifierInScope,
1151 AllowInjectedClassName);
1155 TemplateInstantiator::TransformPredefinedExpr(PredefinedExpr *E) {
1156 if (!E->isTypeDependent())
1159 return getSema().BuildPredefinedExpr(E->getLocation(), E->getIdentType());
1163 TemplateInstantiator::TransformTemplateParmRefExpr(DeclRefExpr *E,
1164 NonTypeTemplateParmDecl *NTTP) {
1165 // If the corresponding template argument is NULL or non-existent, it's
1166 // because we are performing instantiation from explicitly-specified
1167 // template arguments in a function template, but there were some
1168 // arguments left unspecified.
1169 if (!TemplateArgs.hasTemplateArgument(NTTP->getDepth(),
1170 NTTP->getPosition()))
1173 TemplateArgument Arg = TemplateArgs(NTTP->getDepth(), NTTP->getPosition());
1175 if (TemplateArgs.getNumLevels() != TemplateArgs.getNumSubstitutedLevels()) {
1176 // We're performing a partial substitution, so the substituted argument
1177 // could be dependent. As a result we can't create a SubstNonType*Expr
1178 // node now, since that represents a fully-substituted argument.
1179 // FIXME: We should have some AST representation for this.
1180 if (Arg.getKind() == TemplateArgument::Pack) {
1181 // FIXME: This won't work for alias templates.
1182 assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() &&
1183 "unexpected pack arguments in partial substitution");
1184 Arg = Arg.pack_begin()->getPackExpansionPattern();
1186 assert(Arg.getKind() == TemplateArgument::Expression &&
1187 "unexpected nontype template argument kind in partial substitution");
1188 return Arg.getAsExpr();
1191 if (NTTP->isParameterPack()) {
1192 assert(Arg.getKind() == TemplateArgument::Pack &&
1193 "Missing argument pack");
1195 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1196 // We have an argument pack, but we can't select a particular argument
1197 // out of it yet. Therefore, we'll build an expression to hold on to that
1199 QualType TargetType = SemaRef.SubstType(NTTP->getType(), TemplateArgs,
1201 NTTP->getDeclName());
1202 if (TargetType.isNull())
1205 return new (SemaRef.Context) SubstNonTypeTemplateParmPackExpr(TargetType,
1211 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1214 return transformNonTypeTemplateParmRef(NTTP, E->getLocation(), Arg);
1217 const LoopHintAttr *
1218 TemplateInstantiator::TransformLoopHintAttr(const LoopHintAttr *LH) {
1219 Expr *TransformedExpr = getDerived().TransformExpr(LH->getValue()).get();
1221 if (TransformedExpr == LH->getValue())
1224 // Generate error if there is a problem with the value.
1225 if (getSema().CheckLoopHintExpr(TransformedExpr, LH->getLocation()))
1228 // Create new LoopHintValueAttr with integral expression in place of the
1229 // non-type template parameter.
1230 return LoopHintAttr::CreateImplicit(
1231 getSema().Context, LH->getSemanticSpelling(), LH->getOption(),
1232 LH->getState(), TransformedExpr, LH->getRange());
1235 ExprResult TemplateInstantiator::transformNonTypeTemplateParmRef(
1236 NonTypeTemplateParmDecl *parm,
1238 TemplateArgument arg) {
1242 // The template argument itself might be an expression, in which
1243 // case we just return that expression.
1244 if (arg.getKind() == TemplateArgument::Expression) {
1245 Expr *argExpr = arg.getAsExpr();
1247 type = argExpr->getType();
1249 } else if (arg.getKind() == TemplateArgument::Declaration ||
1250 arg.getKind() == TemplateArgument::NullPtr) {
1252 if (arg.getKind() == TemplateArgument::Declaration) {
1253 VD = cast<ValueDecl>(arg.getAsDecl());
1255 // Find the instantiation of the template argument. This is
1256 // required for nested templates.
1257 VD = cast_or_null<ValueDecl>(
1258 getSema().FindInstantiatedDecl(loc, VD, TemplateArgs));
1262 // Propagate NULL template argument.
1266 // Derive the type we want the substituted decl to have. This had
1267 // better be non-dependent, or these checks will have serious problems.
1268 if (parm->isExpandedParameterPack()) {
1269 type = parm->getExpansionType(SemaRef.ArgumentPackSubstitutionIndex);
1270 } else if (parm->isParameterPack() &&
1271 isa<PackExpansionType>(parm->getType())) {
1272 type = SemaRef.SubstType(
1273 cast<PackExpansionType>(parm->getType())->getPattern(),
1274 TemplateArgs, loc, parm->getDeclName());
1276 type = SemaRef.SubstType(VD ? arg.getParamTypeForDecl() : arg.getNullPtrType(),
1277 TemplateArgs, loc, parm->getDeclName());
1279 assert(!type.isNull() && "type substitution failed for param type");
1280 assert(!type->isDependentType() && "param type still dependent");
1281 result = SemaRef.BuildExpressionFromDeclTemplateArgument(arg, type, loc);
1283 if (!result.isInvalid()) type = result.get()->getType();
1285 result = SemaRef.BuildExpressionFromIntegralTemplateArgument(arg, loc);
1287 // Note that this type can be different from the type of 'result',
1288 // e.g. if it's an enum type.
1289 type = arg.getIntegralType();
1291 if (result.isInvalid()) return ExprError();
1293 Expr *resultExpr = result.get();
1294 return new (SemaRef.Context) SubstNonTypeTemplateParmExpr(
1295 type, resultExpr->getValueKind(), loc, parm, resultExpr);
1299 TemplateInstantiator::TransformSubstNonTypeTemplateParmPackExpr(
1300 SubstNonTypeTemplateParmPackExpr *E) {
1301 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1302 // We aren't expanding the parameter pack, so just return ourselves.
1306 TemplateArgument Arg = E->getArgumentPack();
1307 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1308 return transformNonTypeTemplateParmRef(E->getParameterPack(),
1309 E->getParameterPackLocation(),
1314 TemplateInstantiator::RebuildParmVarDeclRefExpr(ParmVarDecl *PD,
1315 SourceLocation Loc) {
1316 DeclarationNameInfo NameInfo(PD->getDeclName(), Loc);
1317 return getSema().BuildDeclarationNameExpr(CXXScopeSpec(), NameInfo, PD);
1321 TemplateInstantiator::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {
1322 if (getSema().ArgumentPackSubstitutionIndex != -1) {
1323 // We can expand this parameter pack now.
1324 ParmVarDecl *D = E->getExpansion(getSema().ArgumentPackSubstitutionIndex);
1325 ValueDecl *VD = cast_or_null<ValueDecl>(TransformDecl(E->getExprLoc(), D));
1328 return RebuildParmVarDeclRefExpr(cast<ParmVarDecl>(VD), E->getExprLoc());
1331 QualType T = TransformType(E->getType());
1335 // Transform each of the parameter expansions into the corresponding
1336 // parameters in the instantiation of the function decl.
1337 SmallVector<ParmVarDecl *, 8> Parms;
1338 Parms.reserve(E->getNumExpansions());
1339 for (FunctionParmPackExpr::iterator I = E->begin(), End = E->end();
1342 cast_or_null<ParmVarDecl>(TransformDecl(E->getExprLoc(), *I));
1348 return FunctionParmPackExpr::Create(getSema().Context, T,
1349 E->getParameterPack(),
1350 E->getParameterPackLocation(), Parms);
1354 TemplateInstantiator::TransformFunctionParmPackRefExpr(DeclRefExpr *E,
1356 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
1357 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
1358 = getSema().CurrentInstantiationScope->findInstantiationOf(PD);
1359 assert(Found && "no instantiation for parameter pack");
1361 Decl *TransformedDecl;
1362 if (DeclArgumentPack *Pack = Found->dyn_cast<DeclArgumentPack *>()) {
1363 // If this is a reference to a function parameter pack which we can
1364 // substitute but can't yet expand, build a FunctionParmPackExpr for it.
1365 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1366 QualType T = TransformType(E->getType());
1369 return FunctionParmPackExpr::Create(getSema().Context, T, PD,
1370 E->getExprLoc(), *Pack);
1373 TransformedDecl = (*Pack)[getSema().ArgumentPackSubstitutionIndex];
1375 TransformedDecl = Found->get<Decl*>();
1378 // We have either an unexpanded pack or a specific expansion.
1379 return RebuildParmVarDeclRefExpr(cast<ParmVarDecl>(TransformedDecl),
1384 TemplateInstantiator::TransformDeclRefExpr(DeclRefExpr *E) {
1385 NamedDecl *D = E->getDecl();
1387 // Handle references to non-type template parameters and non-type template
1389 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) {
1390 if (NTTP->getDepth() < TemplateArgs.getNumLevels())
1391 return TransformTemplateParmRefExpr(E, NTTP);
1393 // We have a non-type template parameter that isn't fully substituted;
1394 // FindInstantiatedDecl will find it in the local instantiation scope.
1397 // Handle references to function parameter packs.
1398 if (ParmVarDecl *PD = dyn_cast<ParmVarDecl>(D))
1399 if (PD->isParameterPack())
1400 return TransformFunctionParmPackRefExpr(E, PD);
1402 return TreeTransform<TemplateInstantiator>::TransformDeclRefExpr(E);
1405 ExprResult TemplateInstantiator::TransformCXXDefaultArgExpr(
1406 CXXDefaultArgExpr *E) {
1407 assert(!cast<FunctionDecl>(E->getParam()->getDeclContext())->
1408 getDescribedFunctionTemplate() &&
1409 "Default arg expressions are never formed in dependent cases.");
1410 return SemaRef.BuildCXXDefaultArgExpr(E->getUsedLocation(),
1411 cast<FunctionDecl>(E->getParam()->getDeclContext()),
1415 template<typename Fn>
1416 QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB,
1417 FunctionProtoTypeLoc TL,
1418 CXXRecordDecl *ThisContext,
1419 unsigned ThisTypeQuals,
1420 Fn TransformExceptionSpec) {
1421 // We need a local instantiation scope for this function prototype.
1422 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
1423 return inherited::TransformFunctionProtoType(
1424 TLB, TL, ThisContext, ThisTypeQuals, TransformExceptionSpec);
1428 TemplateInstantiator::TransformFunctionTypeParam(ParmVarDecl *OldParm,
1429 int indexAdjustment,
1430 Optional<unsigned> NumExpansions,
1431 bool ExpectParameterPack) {
1432 return SemaRef.SubstParmVarDecl(OldParm, TemplateArgs, indexAdjustment,
1433 NumExpansions, ExpectParameterPack);
1437 TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB,
1438 TemplateTypeParmTypeLoc TL) {
1439 const TemplateTypeParmType *T = TL.getTypePtr();
1440 if (T->getDepth() < TemplateArgs.getNumLevels()) {
1441 // Replace the template type parameter with its corresponding
1442 // template argument.
1444 // If the corresponding template argument is NULL or doesn't exist, it's
1445 // because we are performing instantiation from explicitly-specified
1446 // template arguments in a function template class, but there were some
1447 // arguments left unspecified.
1448 if (!TemplateArgs.hasTemplateArgument(T->getDepth(), T->getIndex())) {
1449 TemplateTypeParmTypeLoc NewTL
1450 = TLB.push<TemplateTypeParmTypeLoc>(TL.getType());
1451 NewTL.setNameLoc(TL.getNameLoc());
1452 return TL.getType();
1455 TemplateArgument Arg = TemplateArgs(T->getDepth(), T->getIndex());
1457 if (T->isParameterPack()) {
1458 assert(Arg.getKind() == TemplateArgument::Pack &&
1459 "Missing argument pack");
1461 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1462 // We have the template argument pack, but we're not expanding the
1463 // enclosing pack expansion yet. Just save the template argument
1464 // pack for later substitution.
1466 = getSema().Context.getSubstTemplateTypeParmPackType(T, Arg);
1467 SubstTemplateTypeParmPackTypeLoc NewTL
1468 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(Result);
1469 NewTL.setNameLoc(TL.getNameLoc());
1473 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1476 assert(Arg.getKind() == TemplateArgument::Type &&
1477 "Template argument kind mismatch");
1479 QualType Replacement = Arg.getAsType();
1481 // TODO: only do this uniquing once, at the start of instantiation.
1483 = getSema().Context.getSubstTemplateTypeParmType(T, Replacement);
1484 SubstTemplateTypeParmTypeLoc NewTL
1485 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
1486 NewTL.setNameLoc(TL.getNameLoc());
1490 // The template type parameter comes from an inner template (e.g.,
1491 // the template parameter list of a member template inside the
1492 // template we are instantiating). Create a new template type
1493 // parameter with the template "level" reduced by one.
1494 TemplateTypeParmDecl *NewTTPDecl = nullptr;
1495 if (TemplateTypeParmDecl *OldTTPDecl = T->getDecl())
1496 NewTTPDecl = cast_or_null<TemplateTypeParmDecl>(
1497 TransformDecl(TL.getNameLoc(), OldTTPDecl));
1499 QualType Result = getSema().Context.getTemplateTypeParmType(
1500 T->getDepth() - TemplateArgs.getNumSubstitutedLevels(), T->getIndex(),
1501 T->isParameterPack(), NewTTPDecl);
1502 TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result);
1503 NewTL.setNameLoc(TL.getNameLoc());
1508 TemplateInstantiator::TransformSubstTemplateTypeParmPackType(
1509 TypeLocBuilder &TLB,
1510 SubstTemplateTypeParmPackTypeLoc TL) {
1511 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1512 // We aren't expanding the parameter pack, so just return ourselves.
1513 SubstTemplateTypeParmPackTypeLoc NewTL
1514 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(TL.getType());
1515 NewTL.setNameLoc(TL.getNameLoc());
1516 return TL.getType();
1519 TemplateArgument Arg = TL.getTypePtr()->getArgumentPack();
1520 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1521 QualType Result = Arg.getAsType();
1523 Result = getSema().Context.getSubstTemplateTypeParmType(
1524 TL.getTypePtr()->getReplacedParameter(),
1526 SubstTemplateTypeParmTypeLoc NewTL
1527 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
1528 NewTL.setNameLoc(TL.getNameLoc());
1532 /// \brief Perform substitution on the type T with a given set of template
1535 /// This routine substitutes the given template arguments into the
1536 /// type T and produces the instantiated type.
1538 /// \param T the type into which the template arguments will be
1539 /// substituted. If this type is not dependent, it will be returned
1542 /// \param Args the template arguments that will be
1543 /// substituted for the top-level template parameters within T.
1545 /// \param Loc the location in the source code where this substitution
1546 /// is being performed. It will typically be the location of the
1547 /// declarator (if we're instantiating the type of some declaration)
1548 /// or the location of the type in the source code (if, e.g., we're
1549 /// instantiating the type of a cast expression).
1551 /// \param Entity the name of the entity associated with a declaration
1552 /// being instantiated (if any). May be empty to indicate that there
1553 /// is no such entity (if, e.g., this is a type that occurs as part of
1554 /// a cast expression) or that the entity has no name (e.g., an
1555 /// unnamed function parameter).
1557 /// \param AllowDeducedTST Whether a DeducedTemplateSpecializationType is
1558 /// acceptable as the top level type of the result.
1560 /// \returns If the instantiation succeeds, the instantiated
1561 /// type. Otherwise, produces diagnostics and returns a NULL type.
1562 TypeSourceInfo *Sema::SubstType(TypeSourceInfo *T,
1563 const MultiLevelTemplateArgumentList &Args,
1565 DeclarationName Entity,
1566 bool AllowDeducedTST) {
1567 assert(!CodeSynthesisContexts.empty() &&
1568 "Cannot perform an instantiation without some context on the "
1569 "instantiation stack");
1571 if (!T->getType()->isInstantiationDependentType() &&
1572 !T->getType()->isVariablyModifiedType())
1575 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1576 return AllowDeducedTST ? Instantiator.TransformTypeWithDeducedTST(T)
1577 : Instantiator.TransformType(T);
1580 TypeSourceInfo *Sema::SubstType(TypeLoc TL,
1581 const MultiLevelTemplateArgumentList &Args,
1583 DeclarationName Entity) {
1584 assert(!CodeSynthesisContexts.empty() &&
1585 "Cannot perform an instantiation without some context on the "
1586 "instantiation stack");
1588 if (TL.getType().isNull())
1591 if (!TL.getType()->isInstantiationDependentType() &&
1592 !TL.getType()->isVariablyModifiedType()) {
1593 // FIXME: Make a copy of the TypeLoc data here, so that we can
1594 // return a new TypeSourceInfo. Inefficient!
1596 TLB.pushFullCopy(TL);
1597 return TLB.getTypeSourceInfo(Context, TL.getType());
1600 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1602 TLB.reserve(TL.getFullDataSize());
1603 QualType Result = Instantiator.TransformType(TLB, TL);
1604 if (Result.isNull())
1607 return TLB.getTypeSourceInfo(Context, Result);
1610 /// Deprecated form of the above.
1611 QualType Sema::SubstType(QualType T,
1612 const MultiLevelTemplateArgumentList &TemplateArgs,
1613 SourceLocation Loc, DeclarationName Entity) {
1614 assert(!CodeSynthesisContexts.empty() &&
1615 "Cannot perform an instantiation without some context on the "
1616 "instantiation stack");
1618 // If T is not a dependent type or a variably-modified type, there
1619 // is nothing to do.
1620 if (!T->isInstantiationDependentType() && !T->isVariablyModifiedType())
1623 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity);
1624 return Instantiator.TransformType(T);
1627 static bool NeedsInstantiationAsFunctionType(TypeSourceInfo *T) {
1628 if (T->getType()->isInstantiationDependentType() ||
1629 T->getType()->isVariablyModifiedType())
1632 TypeLoc TL = T->getTypeLoc().IgnoreParens();
1633 if (!TL.getAs<FunctionProtoTypeLoc>())
1636 FunctionProtoTypeLoc FP = TL.castAs<FunctionProtoTypeLoc>();
1637 for (ParmVarDecl *P : FP.getParams()) {
1638 // This must be synthesized from a typedef.
1641 // If there are any parameters, a new TypeSourceInfo that refers to the
1642 // instantiated parameters must be built.
1649 /// A form of SubstType intended specifically for instantiating the
1650 /// type of a FunctionDecl. Its purpose is solely to force the
1651 /// instantiation of default-argument expressions and to avoid
1652 /// instantiating an exception-specification.
1653 TypeSourceInfo *Sema::SubstFunctionDeclType(TypeSourceInfo *T,
1654 const MultiLevelTemplateArgumentList &Args,
1656 DeclarationName Entity,
1657 CXXRecordDecl *ThisContext,
1658 unsigned ThisTypeQuals) {
1659 assert(!CodeSynthesisContexts.empty() &&
1660 "Cannot perform an instantiation without some context on the "
1661 "instantiation stack");
1663 if (!NeedsInstantiationAsFunctionType(T))
1666 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1670 TypeLoc TL = T->getTypeLoc();
1671 TLB.reserve(TL.getFullDataSize());
1675 if (FunctionProtoTypeLoc Proto =
1676 TL.IgnoreParens().getAs<FunctionProtoTypeLoc>()) {
1677 // Instantiate the type, other than its exception specification. The
1678 // exception specification is instantiated in InitFunctionInstantiation
1679 // once we've built the FunctionDecl.
1680 // FIXME: Set the exception specification to EST_Uninstantiated here,
1681 // instead of rebuilding the function type again later.
1682 Result = Instantiator.TransformFunctionProtoType(
1683 TLB, Proto, ThisContext, ThisTypeQuals,
1684 [](FunctionProtoType::ExceptionSpecInfo &ESI,
1685 bool &Changed) { return false; });
1687 Result = Instantiator.TransformType(TLB, TL);
1689 if (Result.isNull())
1692 return TLB.getTypeSourceInfo(Context, Result);
1695 void Sema::SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto,
1696 const MultiLevelTemplateArgumentList &Args) {
1697 FunctionProtoType::ExceptionSpecInfo ESI =
1698 Proto->getExtProtoInfo().ExceptionSpec;
1699 assert(ESI.Type != EST_Uninstantiated);
1701 TemplateInstantiator Instantiator(*this, Args, New->getLocation(),
1702 New->getDeclName());
1704 SmallVector<QualType, 4> ExceptionStorage;
1705 bool Changed = false;
1706 if (Instantiator.TransformExceptionSpec(
1707 New->getTypeSourceInfo()->getTypeLoc().getLocEnd(), ESI,
1708 ExceptionStorage, Changed))
1709 // On error, recover by dropping the exception specification.
1710 ESI.Type = EST_None;
1712 UpdateExceptionSpec(New, ESI);
1715 ParmVarDecl *Sema::SubstParmVarDecl(ParmVarDecl *OldParm,
1716 const MultiLevelTemplateArgumentList &TemplateArgs,
1717 int indexAdjustment,
1718 Optional<unsigned> NumExpansions,
1719 bool ExpectParameterPack) {
1720 TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
1721 TypeSourceInfo *NewDI = nullptr;
1723 TypeLoc OldTL = OldDI->getTypeLoc();
1724 if (PackExpansionTypeLoc ExpansionTL = OldTL.getAs<PackExpansionTypeLoc>()) {
1726 // We have a function parameter pack. Substitute into the pattern of the
1728 NewDI = SubstType(ExpansionTL.getPatternLoc(), TemplateArgs,
1729 OldParm->getLocation(), OldParm->getDeclName());
1733 if (NewDI->getType()->containsUnexpandedParameterPack()) {
1734 // We still have unexpanded parameter packs, which means that
1735 // our function parameter is still a function parameter pack.
1736 // Therefore, make its type a pack expansion type.
1737 NewDI = CheckPackExpansion(NewDI, ExpansionTL.getEllipsisLoc(),
1739 } else if (ExpectParameterPack) {
1740 // We expected to get a parameter pack but didn't (because the type
1741 // itself is not a pack expansion type), so complain. This can occur when
1742 // the substitution goes through an alias template that "loses" the
1744 Diag(OldParm->getLocation(),
1745 diag::err_function_parameter_pack_without_parameter_packs)
1746 << NewDI->getType();
1750 NewDI = SubstType(OldDI, TemplateArgs, OldParm->getLocation(),
1751 OldParm->getDeclName());
1757 if (NewDI->getType()->isVoidType()) {
1758 Diag(OldParm->getLocation(), diag::err_param_with_void_type);
1762 ParmVarDecl *NewParm = CheckParameter(Context.getTranslationUnitDecl(),
1763 OldParm->getInnerLocStart(),
1764 OldParm->getLocation(),
1765 OldParm->getIdentifier(),
1766 NewDI->getType(), NewDI,
1767 OldParm->getStorageClass());
1771 // Mark the (new) default argument as uninstantiated (if any).
1772 if (OldParm->hasUninstantiatedDefaultArg()) {
1773 Expr *Arg = OldParm->getUninstantiatedDefaultArg();
1774 NewParm->setUninstantiatedDefaultArg(Arg);
1775 } else if (OldParm->hasUnparsedDefaultArg()) {
1776 NewParm->setUnparsedDefaultArg();
1777 UnparsedDefaultArgInstantiations[OldParm].push_back(NewParm);
1778 } else if (Expr *Arg = OldParm->getDefaultArg()) {
1779 FunctionDecl *OwningFunc = cast<FunctionDecl>(OldParm->getDeclContext());
1780 if (OwningFunc->isLexicallyWithinFunctionOrMethod()) {
1781 // Instantiate default arguments for methods of local classes (DR1484)
1782 // and non-defining declarations.
1783 Sema::ContextRAII SavedContext(*this, OwningFunc);
1784 LocalInstantiationScope Local(*this, true);
1785 ExprResult NewArg = SubstExpr(Arg, TemplateArgs);
1786 if (NewArg.isUsable()) {
1787 // It would be nice if we still had this.
1788 SourceLocation EqualLoc = NewArg.get()->getLocStart();
1789 SetParamDefaultArgument(NewParm, NewArg.get(), EqualLoc);
1792 // FIXME: if we non-lazily instantiated non-dependent default args for
1793 // non-dependent parameter types we could remove a bunch of duplicate
1794 // conversion warnings for such arguments.
1795 NewParm->setUninstantiatedDefaultArg(Arg);
1799 NewParm->setHasInheritedDefaultArg(OldParm->hasInheritedDefaultArg());
1801 if (OldParm->isParameterPack() && !NewParm->isParameterPack()) {
1802 // Add the new parameter to the instantiated parameter pack.
1803 CurrentInstantiationScope->InstantiatedLocalPackArg(OldParm, NewParm);
1805 // Introduce an Old -> New mapping
1806 CurrentInstantiationScope->InstantiatedLocal(OldParm, NewParm);
1809 // FIXME: OldParm may come from a FunctionProtoType, in which case CurContext
1810 // can be anything, is this right ?
1811 NewParm->setDeclContext(CurContext);
1813 NewParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
1814 OldParm->getFunctionScopeIndex() + indexAdjustment);
1816 InstantiateAttrs(TemplateArgs, OldParm, NewParm);
1821 /// \brief Substitute the given template arguments into the given set of
1822 /// parameters, producing the set of parameter types that would be generated
1823 /// from such a substitution.
1824 bool Sema::SubstParmTypes(
1825 SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
1826 const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
1827 const MultiLevelTemplateArgumentList &TemplateArgs,
1828 SmallVectorImpl<QualType> &ParamTypes,
1829 SmallVectorImpl<ParmVarDecl *> *OutParams,
1830 ExtParameterInfoBuilder &ParamInfos) {
1831 assert(!CodeSynthesisContexts.empty() &&
1832 "Cannot perform an instantiation without some context on the "
1833 "instantiation stack");
1835 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
1837 return Instantiator.TransformFunctionTypeParams(
1838 Loc, Params, nullptr, ExtParamInfos, ParamTypes, OutParams, ParamInfos);
1841 /// \brief Perform substitution on the base class specifiers of the
1842 /// given class template specialization.
1844 /// Produces a diagnostic and returns true on error, returns false and
1845 /// attaches the instantiated base classes to the class template
1846 /// specialization if successful.
1848 Sema::SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
1849 CXXRecordDecl *Pattern,
1850 const MultiLevelTemplateArgumentList &TemplateArgs) {
1851 bool Invalid = false;
1852 SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases;
1853 for (const auto &Base : Pattern->bases()) {
1854 if (!Base.getType()->isDependentType()) {
1855 if (const CXXRecordDecl *RD = Base.getType()->getAsCXXRecordDecl()) {
1856 if (RD->isInvalidDecl())
1857 Instantiation->setInvalidDecl();
1859 InstantiatedBases.push_back(new (Context) CXXBaseSpecifier(Base));
1863 SourceLocation EllipsisLoc;
1864 TypeSourceInfo *BaseTypeLoc;
1865 if (Base.isPackExpansion()) {
1866 // This is a pack expansion. See whether we should expand it now, or
1867 // wait until later.
1868 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
1869 collectUnexpandedParameterPacks(Base.getTypeSourceInfo()->getTypeLoc(),
1871 bool ShouldExpand = false;
1872 bool RetainExpansion = false;
1873 Optional<unsigned> NumExpansions;
1874 if (CheckParameterPacksForExpansion(Base.getEllipsisLoc(),
1875 Base.getSourceRange(),
1877 TemplateArgs, ShouldExpand,
1884 // If we should expand this pack expansion now, do so.
1886 for (unsigned I = 0; I != *NumExpansions; ++I) {
1887 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
1889 TypeSourceInfo *BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
1891 Base.getSourceRange().getBegin(),
1898 if (CXXBaseSpecifier *InstantiatedBase
1899 = CheckBaseSpecifier(Instantiation,
1900 Base.getSourceRange(),
1902 Base.getAccessSpecifierAsWritten(),
1905 InstantiatedBases.push_back(InstantiatedBase);
1913 // The resulting base specifier will (still) be a pack expansion.
1914 EllipsisLoc = Base.getEllipsisLoc();
1915 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
1916 BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
1918 Base.getSourceRange().getBegin(),
1921 BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
1923 Base.getSourceRange().getBegin(),
1932 if (CXXBaseSpecifier *InstantiatedBase
1933 = CheckBaseSpecifier(Instantiation,
1934 Base.getSourceRange(),
1936 Base.getAccessSpecifierAsWritten(),
1939 InstantiatedBases.push_back(InstantiatedBase);
1944 if (!Invalid && AttachBaseSpecifiers(Instantiation, InstantiatedBases))
1950 // Defined via #include from SemaTemplateInstantiateDecl.cpp
1953 Attr *instantiateTemplateAttribute(const Attr *At, ASTContext &C, Sema &S,
1954 const MultiLevelTemplateArgumentList &TemplateArgs);
1955 Attr *instantiateTemplateAttributeForDecl(
1956 const Attr *At, ASTContext &C, Sema &S,
1957 const MultiLevelTemplateArgumentList &TemplateArgs);
1961 /// \brief Instantiate the definition of a class from a given pattern.
1963 /// \param PointOfInstantiation The point of instantiation within the
1966 /// \param Instantiation is the declaration whose definition is being
1967 /// instantiated. This will be either a class template specialization
1968 /// or a member class of a class template specialization.
1970 /// \param Pattern is the pattern from which the instantiation
1971 /// occurs. This will be either the declaration of a class template or
1972 /// the declaration of a member class of a class template.
1974 /// \param TemplateArgs The template arguments to be substituted into
1977 /// \param TSK the kind of implicit or explicit instantiation to perform.
1979 /// \param Complain whether to complain if the class cannot be instantiated due
1980 /// to the lack of a definition.
1982 /// \returns true if an error occurred, false otherwise.
1984 Sema::InstantiateClass(SourceLocation PointOfInstantiation,
1985 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
1986 const MultiLevelTemplateArgumentList &TemplateArgs,
1987 TemplateSpecializationKind TSK,
1989 CXXRecordDecl *PatternDef
1990 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
1991 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
1992 Instantiation->getInstantiatedFromMemberClass(),
1993 Pattern, PatternDef, TSK, Complain))
1995 Pattern = PatternDef;
1997 // \brief Record the point of instantiation.
1998 if (MemberSpecializationInfo *MSInfo
1999 = Instantiation->getMemberSpecializationInfo()) {
2000 MSInfo->setTemplateSpecializationKind(TSK);
2001 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2002 } else if (ClassTemplateSpecializationDecl *Spec
2003 = dyn_cast<ClassTemplateSpecializationDecl>(Instantiation)) {
2004 Spec->setTemplateSpecializationKind(TSK);
2005 Spec->setPointOfInstantiation(PointOfInstantiation);
2008 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
2009 if (Inst.isInvalid())
2011 assert(!Inst.isAlreadyInstantiating() && "should have been caught by caller");
2012 PrettyDeclStackTraceEntry CrashInfo(*this, Instantiation, SourceLocation(),
2013 "instantiating class definition");
2015 // Enter the scope of this instantiation. We don't use
2016 // PushDeclContext because we don't have a scope.
2017 ContextRAII SavedContext(*this, Instantiation);
2018 EnterExpressionEvaluationContext EvalContext(
2019 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
2021 // If this is an instantiation of a local class, merge this local
2022 // instantiation scope with the enclosing scope. Otherwise, every
2023 // instantiation of a class has its own local instantiation scope.
2024 bool MergeWithParentScope = !Instantiation->isDefinedOutsideFunctionOrMethod();
2025 LocalInstantiationScope Scope(*this, MergeWithParentScope);
2027 // All dllexported classes created during instantiation should be fully
2028 // emitted after instantiation completes. We may not be ready to emit any
2029 // delayed classes already on the stack, so save them away and put them back
2031 decltype(DelayedDllExportClasses) ExportedClasses;
2032 std::swap(ExportedClasses, DelayedDllExportClasses);
2034 // Pull attributes from the pattern onto the instantiation.
2035 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
2037 // Start the definition of this instantiation.
2038 Instantiation->startDefinition();
2040 // The instantiation is visible here, even if it was first declared in an
2041 // unimported module.
2042 Instantiation->setHidden(false);
2044 // FIXME: This loses the as-written tag kind for an explicit instantiation.
2045 Instantiation->setTagKind(Pattern->getTagKind());
2047 // Do substitution on the base class specifiers.
2048 if (SubstBaseSpecifiers(Instantiation, Pattern, TemplateArgs))
2049 Instantiation->setInvalidDecl();
2051 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
2052 SmallVector<Decl*, 4> Fields;
2053 // Delay instantiation of late parsed attributes.
2054 LateInstantiatedAttrVec LateAttrs;
2055 Instantiator.enableLateAttributeInstantiation(&LateAttrs);
2057 for (auto *Member : Pattern->decls()) {
2058 // Don't instantiate members not belonging in this semantic context.
2061 // template <int i> class A {
2065 // 'class B' has the template as lexical context but semantically it is
2066 // introduced in namespace scope.
2067 if (Member->getDeclContext() != Pattern)
2070 if (Member->isInvalidDecl()) {
2071 Instantiation->setInvalidDecl();
2075 Decl *NewMember = Instantiator.Visit(Member);
2077 if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember)) {
2078 Fields.push_back(Field);
2079 } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(NewMember)) {
2080 // C++11 [temp.inst]p1: The implicit instantiation of a class template
2081 // specialization causes the implicit instantiation of the definitions
2082 // of unscoped member enumerations.
2083 // Record a point of instantiation for this implicit instantiation.
2084 if (TSK == TSK_ImplicitInstantiation && !Enum->isScoped() &&
2085 Enum->isCompleteDefinition()) {
2086 MemberSpecializationInfo *MSInfo =Enum->getMemberSpecializationInfo();
2087 assert(MSInfo && "no spec info for member enum specialization");
2088 MSInfo->setTemplateSpecializationKind(TSK_ImplicitInstantiation);
2089 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2091 } else if (StaticAssertDecl *SA = dyn_cast<StaticAssertDecl>(NewMember)) {
2092 if (SA->isFailed()) {
2093 // A static_assert failed. Bail out; instantiating this
2094 // class is probably not meaningful.
2095 Instantiation->setInvalidDecl();
2100 if (NewMember->isInvalidDecl())
2101 Instantiation->setInvalidDecl();
2103 // FIXME: Eventually, a NULL return will mean that one of the
2104 // instantiations was a semantic disaster, and we'll want to mark the
2105 // declaration invalid.
2106 // For now, we expect to skip some members that we can't yet handle.
2110 // Finish checking fields.
2111 ActOnFields(nullptr, Instantiation->getLocation(), Instantiation, Fields,
2112 SourceLocation(), SourceLocation(), nullptr);
2113 CheckCompletedCXXClass(Instantiation);
2115 // Default arguments are parsed, if not instantiated. We can go instantiate
2116 // default arg exprs for default constructors if necessary now.
2117 ActOnFinishCXXNonNestedClass(Instantiation);
2119 // Put back the delayed exported classes that we moved out of the way.
2120 std::swap(ExportedClasses, DelayedDllExportClasses);
2122 // Instantiate late parsed attributes, and attach them to their decls.
2123 // See Sema::InstantiateAttrs
2124 for (LateInstantiatedAttrVec::iterator I = LateAttrs.begin(),
2125 E = LateAttrs.end(); I != E; ++I) {
2126 assert(CurrentInstantiationScope == Instantiator.getStartingScope());
2127 CurrentInstantiationScope = I->Scope;
2129 // Allow 'this' within late-parsed attributes.
2130 NamedDecl *ND = dyn_cast<NamedDecl>(I->NewDecl);
2131 CXXRecordDecl *ThisContext =
2132 dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
2133 CXXThisScopeRAII ThisScope(*this, ThisContext, /*TypeQuals*/0,
2134 ND && ND->isCXXInstanceMember());
2137 instantiateTemplateAttribute(I->TmplAttr, Context, *this, TemplateArgs);
2138 I->NewDecl->addAttr(NewAttr);
2139 LocalInstantiationScope::deleteScopes(I->Scope,
2140 Instantiator.getStartingScope());
2142 Instantiator.disableLateAttributeInstantiation();
2145 ActOnFinishDelayedMemberInitializers(Instantiation);
2147 // FIXME: We should do something similar for explicit instantiations so they
2148 // end up in the right module.
2149 if (TSK == TSK_ImplicitInstantiation) {
2150 Instantiation->setLocation(Pattern->getLocation());
2151 Instantiation->setLocStart(Pattern->getInnerLocStart());
2152 Instantiation->setBraceRange(Pattern->getBraceRange());
2155 if (!Instantiation->isInvalidDecl()) {
2156 // Perform any dependent diagnostics from the pattern.
2157 PerformDependentDiagnostics(Pattern, TemplateArgs);
2159 // Instantiate any out-of-line class template partial
2160 // specializations now.
2161 for (TemplateDeclInstantiator::delayed_partial_spec_iterator
2162 P = Instantiator.delayed_partial_spec_begin(),
2163 PEnd = Instantiator.delayed_partial_spec_end();
2165 if (!Instantiator.InstantiateClassTemplatePartialSpecialization(
2166 P->first, P->second)) {
2167 Instantiation->setInvalidDecl();
2172 // Instantiate any out-of-line variable template partial
2173 // specializations now.
2174 for (TemplateDeclInstantiator::delayed_var_partial_spec_iterator
2175 P = Instantiator.delayed_var_partial_spec_begin(),
2176 PEnd = Instantiator.delayed_var_partial_spec_end();
2178 if (!Instantiator.InstantiateVarTemplatePartialSpecialization(
2179 P->first, P->second)) {
2180 Instantiation->setInvalidDecl();
2186 // Exit the scope of this instantiation.
2189 if (!Instantiation->isInvalidDecl()) {
2190 Consumer.HandleTagDeclDefinition(Instantiation);
2192 // Always emit the vtable for an explicit instantiation definition
2193 // of a polymorphic class template specialization.
2194 if (TSK == TSK_ExplicitInstantiationDefinition)
2195 MarkVTableUsed(PointOfInstantiation, Instantiation, true);
2198 return Instantiation->isInvalidDecl();
2201 /// \brief Instantiate the definition of an enum from a given pattern.
2203 /// \param PointOfInstantiation The point of instantiation within the
2205 /// \param Instantiation is the declaration whose definition is being
2206 /// instantiated. This will be a member enumeration of a class
2207 /// temploid specialization, or a local enumeration within a
2208 /// function temploid specialization.
2209 /// \param Pattern The templated declaration from which the instantiation
2211 /// \param TemplateArgs The template arguments to be substituted into
2213 /// \param TSK The kind of implicit or explicit instantiation to perform.
2215 /// \return \c true if an error occurred, \c false otherwise.
2216 bool Sema::InstantiateEnum(SourceLocation PointOfInstantiation,
2217 EnumDecl *Instantiation, EnumDecl *Pattern,
2218 const MultiLevelTemplateArgumentList &TemplateArgs,
2219 TemplateSpecializationKind TSK) {
2220 EnumDecl *PatternDef = Pattern->getDefinition();
2221 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
2222 Instantiation->getInstantiatedFromMemberEnum(),
2223 Pattern, PatternDef, TSK,/*Complain*/true))
2225 Pattern = PatternDef;
2227 // Record the point of instantiation.
2228 if (MemberSpecializationInfo *MSInfo
2229 = Instantiation->getMemberSpecializationInfo()) {
2230 MSInfo->setTemplateSpecializationKind(TSK);
2231 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2234 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
2235 if (Inst.isInvalid())
2237 if (Inst.isAlreadyInstantiating())
2239 PrettyDeclStackTraceEntry CrashInfo(*this, Instantiation, SourceLocation(),
2240 "instantiating enum definition");
2242 // The instantiation is visible here, even if it was first declared in an
2243 // unimported module.
2244 Instantiation->setHidden(false);
2246 // Enter the scope of this instantiation. We don't use
2247 // PushDeclContext because we don't have a scope.
2248 ContextRAII SavedContext(*this, Instantiation);
2249 EnterExpressionEvaluationContext EvalContext(
2250 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
2252 LocalInstantiationScope Scope(*this, /*MergeWithParentScope*/true);
2254 // Pull attributes from the pattern onto the instantiation.
2255 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
2257 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
2258 Instantiator.InstantiateEnumDefinition(Instantiation, Pattern);
2260 // Exit the scope of this instantiation.
2263 return Instantiation->isInvalidDecl();
2267 /// \brief Instantiate the definition of a field from the given pattern.
2269 /// \param PointOfInstantiation The point of instantiation within the
2271 /// \param Instantiation is the declaration whose definition is being
2272 /// instantiated. This will be a class of a class temploid
2273 /// specialization, or a local enumeration within a function temploid
2275 /// \param Pattern The templated declaration from which the instantiation
2277 /// \param TemplateArgs The template arguments to be substituted into
2280 /// \return \c true if an error occurred, \c false otherwise.
2281 bool Sema::InstantiateInClassInitializer(
2282 SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
2283 FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs) {
2284 // If there is no initializer, we don't need to do anything.
2285 if (!Pattern->hasInClassInitializer())
2288 assert(Instantiation->getInClassInitStyle() ==
2289 Pattern->getInClassInitStyle() &&
2290 "pattern and instantiation disagree about init style");
2292 // Error out if we haven't parsed the initializer of the pattern yet because
2293 // we are waiting for the closing brace of the outer class.
2294 Expr *OldInit = Pattern->getInClassInitializer();
2296 RecordDecl *PatternRD = Pattern->getParent();
2297 RecordDecl *OutermostClass = PatternRD->getOuterLexicalRecordContext();
2298 Diag(PointOfInstantiation,
2299 diag::err_in_class_initializer_not_yet_parsed)
2300 << OutermostClass << Pattern;
2301 Diag(Pattern->getLocEnd(), diag::note_in_class_initializer_not_yet_parsed);
2302 Instantiation->setInvalidDecl();
2306 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
2307 if (Inst.isInvalid())
2309 if (Inst.isAlreadyInstantiating()) {
2310 // Error out if we hit an instantiation cycle for this initializer.
2311 Diag(PointOfInstantiation, diag::err_in_class_initializer_cycle)
2315 PrettyDeclStackTraceEntry CrashInfo(*this, Instantiation, SourceLocation(),
2316 "instantiating default member init");
2318 // Enter the scope of this instantiation. We don't use PushDeclContext because
2319 // we don't have a scope.
2320 ContextRAII SavedContext(*this, Instantiation->getParent());
2321 EnterExpressionEvaluationContext EvalContext(
2322 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
2324 LocalInstantiationScope Scope(*this, true);
2326 // Instantiate the initializer.
2327 ActOnStartCXXInClassMemberInitializer();
2328 CXXThisScopeRAII ThisScope(*this, Instantiation->getParent(), /*TypeQuals=*/0);
2330 ExprResult NewInit = SubstInitializer(OldInit, TemplateArgs,
2331 /*CXXDirectInit=*/false);
2332 Expr *Init = NewInit.get();
2333 assert((!Init || !isa<ParenListExpr>(Init)) && "call-style init in class");
2334 ActOnFinishCXXInClassMemberInitializer(
2335 Instantiation, Init ? Init->getLocStart() : SourceLocation(), Init);
2337 if (auto *L = getASTMutationListener())
2338 L->DefaultMemberInitializerInstantiated(Instantiation);
2340 // Return true if the in-class initializer is still missing.
2341 return !Instantiation->getInClassInitializer();
2345 /// \brief A partial specialization whose template arguments have matched
2346 /// a given template-id.
2347 struct PartialSpecMatchResult {
2348 ClassTemplatePartialSpecializationDecl *Partial;
2349 TemplateArgumentList *Args;
2353 /// Get the instantiation pattern to use to instantiate the definition of a
2354 /// given ClassTemplateSpecializationDecl (either the pattern of the primary
2355 /// template or of a partial specialization).
2356 static CXXRecordDecl *
2357 getPatternForClassTemplateSpecialization(
2358 Sema &S, SourceLocation PointOfInstantiation,
2359 ClassTemplateSpecializationDecl *ClassTemplateSpec,
2360 TemplateSpecializationKind TSK, bool Complain) {
2361 Sema::InstantiatingTemplate Inst(S, PointOfInstantiation, ClassTemplateSpec);
2362 if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
2365 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
2366 CXXRecordDecl *Pattern = nullptr;
2368 // C++ [temp.class.spec.match]p1:
2369 // When a class template is used in a context that requires an
2370 // instantiation of the class, it is necessary to determine
2371 // whether the instantiation is to be generated using the primary
2372 // template or one of the partial specializations. This is done by
2373 // matching the template arguments of the class template
2374 // specialization with the template argument lists of the partial
2376 typedef PartialSpecMatchResult MatchResult;
2377 SmallVector<MatchResult, 4> Matched;
2378 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
2379 Template->getPartialSpecializations(PartialSpecs);
2380 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation);
2381 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
2382 ClassTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
2383 TemplateDeductionInfo Info(FailedCandidates.getLocation());
2384 if (Sema::TemplateDeductionResult Result = S.DeduceTemplateArguments(
2385 Partial, ClassTemplateSpec->getTemplateArgs(), Info)) {
2386 // Store the failed-deduction information for use in diagnostics, later.
2387 // TODO: Actually use the failed-deduction info?
2388 FailedCandidates.addCandidate().set(
2389 DeclAccessPair::make(Template, AS_public), Partial,
2390 MakeDeductionFailureInfo(S.Context, Result, Info));
2393 Matched.push_back(PartialSpecMatchResult());
2394 Matched.back().Partial = Partial;
2395 Matched.back().Args = Info.take();
2399 // If we're dealing with a member template where the template parameters
2400 // have been instantiated, this provides the original template parameters
2401 // from which the member template's parameters were instantiated.
2403 if (Matched.size() >= 1) {
2404 SmallVectorImpl<MatchResult>::iterator Best = Matched.begin();
2405 if (Matched.size() == 1) {
2406 // -- If exactly one matching specialization is found, the
2407 // instantiation is generated from that specialization.
2408 // We don't need to do anything for this.
2410 // -- If more than one matching specialization is found, the
2411 // partial order rules (14.5.4.2) are used to determine
2412 // whether one of the specializations is more specialized
2413 // than the others. If none of the specializations is more
2414 // specialized than all of the other matching
2415 // specializations, then the use of the class template is
2416 // ambiguous and the program is ill-formed.
2417 for (SmallVectorImpl<MatchResult>::iterator P = Best + 1,
2418 PEnd = Matched.end();
2420 if (S.getMoreSpecializedPartialSpecialization(
2421 P->Partial, Best->Partial, PointOfInstantiation) == P->Partial)
2425 // Determine if the best partial specialization is more specialized than
2427 bool Ambiguous = false;
2428 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
2429 PEnd = Matched.end();
2432 S.getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
2433 PointOfInstantiation) !=
2441 // Partial ordering did not produce a clear winner. Complain.
2443 ClassTemplateSpec->setInvalidDecl();
2444 S.Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
2445 << ClassTemplateSpec;
2447 // Print the matching partial specializations.
2448 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
2449 PEnd = Matched.end();
2451 S.Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
2452 << S.getTemplateArgumentBindingsText(
2453 P->Partial->getTemplateParameters(), *P->Args);
2459 // Instantiate using the best class template partial specialization.
2460 ClassTemplatePartialSpecializationDecl *OrigPartialSpec = Best->Partial;
2461 while (OrigPartialSpec->getInstantiatedFromMember()) {
2462 // If we've found an explicit specialization of this class template,
2463 // stop here and use that as the pattern.
2464 if (OrigPartialSpec->isMemberSpecialization())
2467 OrigPartialSpec = OrigPartialSpec->getInstantiatedFromMember();
2470 Pattern = OrigPartialSpec;
2471 ClassTemplateSpec->setInstantiationOf(Best->Partial, Best->Args);
2473 // -- If no matches are found, the instantiation is generated
2474 // from the primary template.
2475 ClassTemplateDecl *OrigTemplate = Template;
2476 while (OrigTemplate->getInstantiatedFromMemberTemplate()) {
2477 // If we've found an explicit specialization of this class template,
2478 // stop here and use that as the pattern.
2479 if (OrigTemplate->isMemberSpecialization())
2482 OrigTemplate = OrigTemplate->getInstantiatedFromMemberTemplate();
2485 Pattern = OrigTemplate->getTemplatedDecl();
2491 bool Sema::InstantiateClassTemplateSpecialization(
2492 SourceLocation PointOfInstantiation,
2493 ClassTemplateSpecializationDecl *ClassTemplateSpec,
2494 TemplateSpecializationKind TSK, bool Complain) {
2495 // Perform the actual instantiation on the canonical declaration.
2496 ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>(
2497 ClassTemplateSpec->getCanonicalDecl());
2498 if (ClassTemplateSpec->isInvalidDecl())
2501 CXXRecordDecl *Pattern = getPatternForClassTemplateSpecialization(
2502 *this, PointOfInstantiation, ClassTemplateSpec, TSK, Complain);
2506 return InstantiateClass(PointOfInstantiation, ClassTemplateSpec, Pattern,
2507 getTemplateInstantiationArgs(ClassTemplateSpec), TSK,
2511 /// \brief Instantiates the definitions of all of the member
2512 /// of the given class, which is an instantiation of a class template
2513 /// or a member class of a template.
2515 Sema::InstantiateClassMembers(SourceLocation PointOfInstantiation,
2516 CXXRecordDecl *Instantiation,
2517 const MultiLevelTemplateArgumentList &TemplateArgs,
2518 TemplateSpecializationKind TSK) {
2519 // FIXME: We need to notify the ASTMutationListener that we did all of these
2520 // things, in case we have an explicit instantiation definition in a PCM, a
2521 // module, or preamble, and the declaration is in an imported AST.
2523 (TSK == TSK_ExplicitInstantiationDefinition ||
2524 TSK == TSK_ExplicitInstantiationDeclaration ||
2525 (TSK == TSK_ImplicitInstantiation && Instantiation->isLocalClass())) &&
2526 "Unexpected template specialization kind!");
2527 for (auto *D : Instantiation->decls()) {
2528 bool SuppressNew = false;
2529 if (auto *Function = dyn_cast<FunctionDecl>(D)) {
2530 if (FunctionDecl *Pattern
2531 = Function->getInstantiatedFromMemberFunction()) {
2532 MemberSpecializationInfo *MSInfo
2533 = Function->getMemberSpecializationInfo();
2534 assert(MSInfo && "No member specialization information?");
2535 if (MSInfo->getTemplateSpecializationKind()
2536 == TSK_ExplicitSpecialization)
2539 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2541 MSInfo->getTemplateSpecializationKind(),
2542 MSInfo->getPointOfInstantiation(),
2547 // C++11 [temp.explicit]p8:
2548 // An explicit instantiation definition that names a class template
2549 // specialization explicitly instantiates the class template
2550 // specialization and is only an explicit instantiation definition
2551 // of members whose definition is visible at the point of
2553 if (TSK == TSK_ExplicitInstantiationDefinition && !Pattern->isDefined())
2556 Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2558 if (Function->isDefined()) {
2559 // Let the ASTConsumer know that this function has been explicitly
2560 // instantiated now, and its linkage might have changed.
2561 Consumer.HandleTopLevelDecl(DeclGroupRef(Function));
2562 } else if (TSK == TSK_ExplicitInstantiationDefinition) {
2563 InstantiateFunctionDefinition(PointOfInstantiation, Function);
2564 } else if (TSK == TSK_ImplicitInstantiation) {
2565 PendingLocalImplicitInstantiations.push_back(
2566 std::make_pair(Function, PointOfInstantiation));
2569 } else if (auto *Var = dyn_cast<VarDecl>(D)) {
2570 if (isa<VarTemplateSpecializationDecl>(Var))
2573 if (Var->isStaticDataMember()) {
2574 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
2575 assert(MSInfo && "No member specialization information?");
2576 if (MSInfo->getTemplateSpecializationKind()
2577 == TSK_ExplicitSpecialization)
2580 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2582 MSInfo->getTemplateSpecializationKind(),
2583 MSInfo->getPointOfInstantiation(),
2588 if (TSK == TSK_ExplicitInstantiationDefinition) {
2589 // C++0x [temp.explicit]p8:
2590 // An explicit instantiation definition that names a class template
2591 // specialization explicitly instantiates the class template
2592 // specialization and is only an explicit instantiation definition
2593 // of members whose definition is visible at the point of
2595 if (!Var->getInstantiatedFromStaticDataMember()->getDefinition())
2598 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2599 InstantiateStaticDataMemberDefinition(PointOfInstantiation, Var);
2601 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2604 } else if (auto *Record = dyn_cast<CXXRecordDecl>(D)) {
2605 // Always skip the injected-class-name, along with any
2606 // redeclarations of nested classes, since both would cause us
2607 // to try to instantiate the members of a class twice.
2608 // Skip closure types; they'll get instantiated when we instantiate
2609 // the corresponding lambda-expression.
2610 if (Record->isInjectedClassName() || Record->getPreviousDecl() ||
2614 MemberSpecializationInfo *MSInfo = Record->getMemberSpecializationInfo();
2615 assert(MSInfo && "No member specialization information?");
2617 if (MSInfo->getTemplateSpecializationKind()
2618 == TSK_ExplicitSpecialization)
2621 if ((Context.getTargetInfo().getCXXABI().isMicrosoft() ||
2622 Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment()) &&
2623 TSK == TSK_ExplicitInstantiationDeclaration) {
2624 // In MSVC and Windows Itanium mode, explicit instantiation decl of the
2625 // outer class doesn't affect the inner class.
2629 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2631 MSInfo->getTemplateSpecializationKind(),
2632 MSInfo->getPointOfInstantiation(),
2637 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
2638 assert(Pattern && "Missing instantiated-from-template information");
2640 if (!Record->getDefinition()) {
2641 if (!Pattern->getDefinition()) {
2642 // C++0x [temp.explicit]p8:
2643 // An explicit instantiation definition that names a class template
2644 // specialization explicitly instantiates the class template
2645 // specialization and is only an explicit instantiation definition
2646 // of members whose definition is visible at the point of
2648 if (TSK == TSK_ExplicitInstantiationDeclaration) {
2649 MSInfo->setTemplateSpecializationKind(TSK);
2650 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2656 InstantiateClass(PointOfInstantiation, Record, Pattern,
2660 if (TSK == TSK_ExplicitInstantiationDefinition &&
2661 Record->getTemplateSpecializationKind() ==
2662 TSK_ExplicitInstantiationDeclaration) {
2663 Record->setTemplateSpecializationKind(TSK);
2664 MarkVTableUsed(PointOfInstantiation, Record, true);
2668 Pattern = cast_or_null<CXXRecordDecl>(Record->getDefinition());
2670 InstantiateClassMembers(PointOfInstantiation, Pattern, TemplateArgs,
2672 } else if (auto *Enum = dyn_cast<EnumDecl>(D)) {
2673 MemberSpecializationInfo *MSInfo = Enum->getMemberSpecializationInfo();
2674 assert(MSInfo && "No member specialization information?");
2676 if (MSInfo->getTemplateSpecializationKind()
2677 == TSK_ExplicitSpecialization)
2680 if (CheckSpecializationInstantiationRedecl(
2681 PointOfInstantiation, TSK, Enum,
2682 MSInfo->getTemplateSpecializationKind(),
2683 MSInfo->getPointOfInstantiation(), SuppressNew) ||
2687 if (Enum->getDefinition())
2690 EnumDecl *Pattern = Enum->getTemplateInstantiationPattern();
2691 assert(Pattern && "Missing instantiated-from-template information");
2693 if (TSK == TSK_ExplicitInstantiationDefinition) {
2694 if (!Pattern->getDefinition())
2697 InstantiateEnum(PointOfInstantiation, Enum, Pattern, TemplateArgs, TSK);
2699 MSInfo->setTemplateSpecializationKind(TSK);
2700 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2702 } else if (auto *Field = dyn_cast<FieldDecl>(D)) {
2703 // No need to instantiate in-class initializers during explicit
2705 if (Field->hasInClassInitializer() && TSK == TSK_ImplicitInstantiation) {
2706 CXXRecordDecl *ClassPattern =
2707 Instantiation->getTemplateInstantiationPattern();
2708 DeclContext::lookup_result Lookup =
2709 ClassPattern->lookup(Field->getDeclName());
2710 FieldDecl *Pattern = cast<FieldDecl>(Lookup.front());
2711 InstantiateInClassInitializer(PointOfInstantiation, Field, Pattern,
2718 /// \brief Instantiate the definitions of all of the members of the
2719 /// given class template specialization, which was named as part of an
2720 /// explicit instantiation.
2722 Sema::InstantiateClassTemplateSpecializationMembers(
2723 SourceLocation PointOfInstantiation,
2724 ClassTemplateSpecializationDecl *ClassTemplateSpec,
2725 TemplateSpecializationKind TSK) {
2726 // C++0x [temp.explicit]p7:
2727 // An explicit instantiation that names a class template
2728 // specialization is an explicit instantion of the same kind
2729 // (declaration or definition) of each of its members (not
2730 // including members inherited from base classes) that has not
2731 // been previously explicitly specialized in the translation unit
2732 // containing the explicit instantiation, except as described
2734 InstantiateClassMembers(PointOfInstantiation, ClassTemplateSpec,
2735 getTemplateInstantiationArgs(ClassTemplateSpec),
2740 Sema::SubstStmt(Stmt *S, const MultiLevelTemplateArgumentList &TemplateArgs) {
2744 TemplateInstantiator Instantiator(*this, TemplateArgs,
2747 return Instantiator.TransformStmt(S);
2751 Sema::SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs) {
2755 TemplateInstantiator Instantiator(*this, TemplateArgs,
2758 return Instantiator.TransformExpr(E);
2761 ExprResult Sema::SubstInitializer(Expr *Init,
2762 const MultiLevelTemplateArgumentList &TemplateArgs,
2763 bool CXXDirectInit) {
2764 TemplateInstantiator Instantiator(*this, TemplateArgs,
2767 return Instantiator.TransformInitializer(Init, CXXDirectInit);
2770 bool Sema::SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
2771 const MultiLevelTemplateArgumentList &TemplateArgs,
2772 SmallVectorImpl<Expr *> &Outputs) {
2776 TemplateInstantiator Instantiator(*this, TemplateArgs,
2779 return Instantiator.TransformExprs(Exprs.data(), Exprs.size(),
2783 NestedNameSpecifierLoc
2784 Sema::SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
2785 const MultiLevelTemplateArgumentList &TemplateArgs) {
2787 return NestedNameSpecifierLoc();
2789 TemplateInstantiator Instantiator(*this, TemplateArgs, NNS.getBeginLoc(),
2791 return Instantiator.TransformNestedNameSpecifierLoc(NNS);
2794 /// \brief Do template substitution on declaration name info.
2796 Sema::SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
2797 const MultiLevelTemplateArgumentList &TemplateArgs) {
2798 TemplateInstantiator Instantiator(*this, TemplateArgs, NameInfo.getLoc(),
2799 NameInfo.getName());
2800 return Instantiator.TransformDeclarationNameInfo(NameInfo);
2804 Sema::SubstTemplateName(NestedNameSpecifierLoc QualifierLoc,
2805 TemplateName Name, SourceLocation Loc,
2806 const MultiLevelTemplateArgumentList &TemplateArgs) {
2807 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
2810 SS.Adopt(QualifierLoc);
2811 return Instantiator.TransformTemplateName(SS, Name, Loc);
2814 bool Sema::Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
2815 TemplateArgumentListInfo &Result,
2816 const MultiLevelTemplateArgumentList &TemplateArgs) {
2817 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
2820 return Instantiator.TransformTemplateArguments(Args, NumArgs, Result);
2823 static const Decl *getCanonicalParmVarDecl(const Decl *D) {
2824 // When storing ParmVarDecls in the local instantiation scope, we always
2825 // want to use the ParmVarDecl from the canonical function declaration,
2826 // since the map is then valid for any redeclaration or definition of that
2828 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(D)) {
2829 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
2830 unsigned i = PV->getFunctionScopeIndex();
2831 // This parameter might be from a freestanding function type within the
2832 // function and isn't necessarily referring to one of FD's parameters.
2833 if (FD->getParamDecl(i) == PV)
2834 return FD->getCanonicalDecl()->getParamDecl(i);
2841 llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> *
2842 LocalInstantiationScope::findInstantiationOf(const Decl *D) {
2843 D = getCanonicalParmVarDecl(D);
2844 for (LocalInstantiationScope *Current = this; Current;
2845 Current = Current->Outer) {
2847 // Check if we found something within this scope.
2848 const Decl *CheckD = D;
2850 LocalDeclsMap::iterator Found = Current->LocalDecls.find(CheckD);
2851 if (Found != Current->LocalDecls.end())
2852 return &Found->second;
2854 // If this is a tag declaration, it's possible that we need to look for
2855 // a previous declaration.
2856 if (const TagDecl *Tag = dyn_cast<TagDecl>(CheckD))
2857 CheckD = Tag->getPreviousDecl();
2862 // If we aren't combined with our outer scope, we're done.
2863 if (!Current->CombineWithOuterScope)
2867 // If we're performing a partial substitution during template argument
2868 // deduction, we may not have values for template parameters yet.
2869 if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
2870 isa<TemplateTemplateParmDecl>(D))
2873 // Local types referenced prior to definition may require instantiation.
2874 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
2875 if (RD->isLocalClass())
2878 // Enumeration types referenced prior to definition may appear as a result of
2880 if (isa<EnumDecl>(D))
2883 // If we didn't find the decl, then we either have a sema bug, or we have a
2884 // forward reference to a label declaration. Return null to indicate that
2885 // we have an uninstantiated label.
2886 assert(isa<LabelDecl>(D) && "declaration not instantiated in this scope");
2890 void LocalInstantiationScope::InstantiatedLocal(const Decl *D, Decl *Inst) {
2891 D = getCanonicalParmVarDecl(D);
2892 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
2893 if (Stored.isNull()) {
2895 // It should not be present in any surrounding scope either.
2896 LocalInstantiationScope *Current = this;
2897 while (Current->CombineWithOuterScope && Current->Outer) {
2898 Current = Current->Outer;
2899 assert(Current->LocalDecls.find(D) == Current->LocalDecls.end() &&
2900 "Instantiated local in inner and outer scopes");
2904 } else if (DeclArgumentPack *Pack = Stored.dyn_cast<DeclArgumentPack *>()) {
2905 Pack->push_back(cast<ParmVarDecl>(Inst));
2907 assert(Stored.get<Decl *>() == Inst && "Already instantiated this local");
2911 void LocalInstantiationScope::InstantiatedLocalPackArg(const Decl *D,
2912 ParmVarDecl *Inst) {
2913 D = getCanonicalParmVarDecl(D);
2914 DeclArgumentPack *Pack = LocalDecls[D].get<DeclArgumentPack *>();
2915 Pack->push_back(Inst);
2918 void LocalInstantiationScope::MakeInstantiatedLocalArgPack(const Decl *D) {
2920 // This should be the first time we've been told about this decl.
2921 for (LocalInstantiationScope *Current = this;
2922 Current && Current->CombineWithOuterScope; Current = Current->Outer)
2923 assert(Current->LocalDecls.find(D) == Current->LocalDecls.end() &&
2924 "Creating local pack after instantiation of local");
2927 D = getCanonicalParmVarDecl(D);
2928 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
2929 DeclArgumentPack *Pack = new DeclArgumentPack;
2931 ArgumentPacks.push_back(Pack);
2934 void LocalInstantiationScope::SetPartiallySubstitutedPack(NamedDecl *Pack,
2935 const TemplateArgument *ExplicitArgs,
2936 unsigned NumExplicitArgs) {
2937 assert((!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack) &&
2938 "Already have a partially-substituted pack");
2939 assert((!PartiallySubstitutedPack
2940 || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) &&
2941 "Wrong number of arguments in partially-substituted pack");
2942 PartiallySubstitutedPack = Pack;
2943 ArgsInPartiallySubstitutedPack = ExplicitArgs;
2944 NumArgsInPartiallySubstitutedPack = NumExplicitArgs;
2947 NamedDecl *LocalInstantiationScope::getPartiallySubstitutedPack(
2948 const TemplateArgument **ExplicitArgs,
2949 unsigned *NumExplicitArgs) const {
2951 *ExplicitArgs = nullptr;
2952 if (NumExplicitArgs)
2953 *NumExplicitArgs = 0;
2955 for (const LocalInstantiationScope *Current = this; Current;
2956 Current = Current->Outer) {
2957 if (Current->PartiallySubstitutedPack) {
2959 *ExplicitArgs = Current->ArgsInPartiallySubstitutedPack;
2960 if (NumExplicitArgs)
2961 *NumExplicitArgs = Current->NumArgsInPartiallySubstitutedPack;
2963 return Current->PartiallySubstitutedPack;
2966 if (!Current->CombineWithOuterScope)