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 bool Sema::SubstExceptionSpec(SourceLocation Loc,
1696 FunctionProtoType::ExceptionSpecInfo &ESI,
1697 SmallVectorImpl<QualType> &ExceptionStorage,
1698 const MultiLevelTemplateArgumentList &Args) {
1699 assert(ESI.Type != EST_Uninstantiated);
1701 bool Changed = false;
1702 TemplateInstantiator Instantiator(*this, Args, Loc, DeclarationName());
1703 return Instantiator.TransformExceptionSpec(Loc, ESI, ExceptionStorage,
1707 void Sema::SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto,
1708 const MultiLevelTemplateArgumentList &Args) {
1709 FunctionProtoType::ExceptionSpecInfo ESI =
1710 Proto->getExtProtoInfo().ExceptionSpec;
1712 SmallVector<QualType, 4> ExceptionStorage;
1713 if (SubstExceptionSpec(New->getTypeSourceInfo()->getTypeLoc().getLocEnd(),
1714 ESI, ExceptionStorage, Args))
1715 // On error, recover by dropping the exception specification.
1716 ESI.Type = EST_None;
1718 UpdateExceptionSpec(New, ESI);
1721 ParmVarDecl *Sema::SubstParmVarDecl(ParmVarDecl *OldParm,
1722 const MultiLevelTemplateArgumentList &TemplateArgs,
1723 int indexAdjustment,
1724 Optional<unsigned> NumExpansions,
1725 bool ExpectParameterPack) {
1726 TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
1727 TypeSourceInfo *NewDI = nullptr;
1729 TypeLoc OldTL = OldDI->getTypeLoc();
1730 if (PackExpansionTypeLoc ExpansionTL = OldTL.getAs<PackExpansionTypeLoc>()) {
1732 // We have a function parameter pack. Substitute into the pattern of the
1734 NewDI = SubstType(ExpansionTL.getPatternLoc(), TemplateArgs,
1735 OldParm->getLocation(), OldParm->getDeclName());
1739 if (NewDI->getType()->containsUnexpandedParameterPack()) {
1740 // We still have unexpanded parameter packs, which means that
1741 // our function parameter is still a function parameter pack.
1742 // Therefore, make its type a pack expansion type.
1743 NewDI = CheckPackExpansion(NewDI, ExpansionTL.getEllipsisLoc(),
1745 } else if (ExpectParameterPack) {
1746 // We expected to get a parameter pack but didn't (because the type
1747 // itself is not a pack expansion type), so complain. This can occur when
1748 // the substitution goes through an alias template that "loses" the
1750 Diag(OldParm->getLocation(),
1751 diag::err_function_parameter_pack_without_parameter_packs)
1752 << NewDI->getType();
1756 NewDI = SubstType(OldDI, TemplateArgs, OldParm->getLocation(),
1757 OldParm->getDeclName());
1763 if (NewDI->getType()->isVoidType()) {
1764 Diag(OldParm->getLocation(), diag::err_param_with_void_type);
1768 ParmVarDecl *NewParm = CheckParameter(Context.getTranslationUnitDecl(),
1769 OldParm->getInnerLocStart(),
1770 OldParm->getLocation(),
1771 OldParm->getIdentifier(),
1772 NewDI->getType(), NewDI,
1773 OldParm->getStorageClass());
1777 // Mark the (new) default argument as uninstantiated (if any).
1778 if (OldParm->hasUninstantiatedDefaultArg()) {
1779 Expr *Arg = OldParm->getUninstantiatedDefaultArg();
1780 NewParm->setUninstantiatedDefaultArg(Arg);
1781 } else if (OldParm->hasUnparsedDefaultArg()) {
1782 NewParm->setUnparsedDefaultArg();
1783 UnparsedDefaultArgInstantiations[OldParm].push_back(NewParm);
1784 } else if (Expr *Arg = OldParm->getDefaultArg()) {
1785 FunctionDecl *OwningFunc = cast<FunctionDecl>(OldParm->getDeclContext());
1786 if (OwningFunc->isLexicallyWithinFunctionOrMethod()) {
1787 // Instantiate default arguments for methods of local classes (DR1484)
1788 // and non-defining declarations.
1789 Sema::ContextRAII SavedContext(*this, OwningFunc);
1790 LocalInstantiationScope Local(*this, true);
1791 ExprResult NewArg = SubstExpr(Arg, TemplateArgs);
1792 if (NewArg.isUsable()) {
1793 // It would be nice if we still had this.
1794 SourceLocation EqualLoc = NewArg.get()->getLocStart();
1795 SetParamDefaultArgument(NewParm, NewArg.get(), EqualLoc);
1798 // FIXME: if we non-lazily instantiated non-dependent default args for
1799 // non-dependent parameter types we could remove a bunch of duplicate
1800 // conversion warnings for such arguments.
1801 NewParm->setUninstantiatedDefaultArg(Arg);
1805 NewParm->setHasInheritedDefaultArg(OldParm->hasInheritedDefaultArg());
1807 if (OldParm->isParameterPack() && !NewParm->isParameterPack()) {
1808 // Add the new parameter to the instantiated parameter pack.
1809 CurrentInstantiationScope->InstantiatedLocalPackArg(OldParm, NewParm);
1811 // Introduce an Old -> New mapping
1812 CurrentInstantiationScope->InstantiatedLocal(OldParm, NewParm);
1815 // FIXME: OldParm may come from a FunctionProtoType, in which case CurContext
1816 // can be anything, is this right ?
1817 NewParm->setDeclContext(CurContext);
1819 NewParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
1820 OldParm->getFunctionScopeIndex() + indexAdjustment);
1822 InstantiateAttrs(TemplateArgs, OldParm, NewParm);
1827 /// \brief Substitute the given template arguments into the given set of
1828 /// parameters, producing the set of parameter types that would be generated
1829 /// from such a substitution.
1830 bool Sema::SubstParmTypes(
1831 SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
1832 const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
1833 const MultiLevelTemplateArgumentList &TemplateArgs,
1834 SmallVectorImpl<QualType> &ParamTypes,
1835 SmallVectorImpl<ParmVarDecl *> *OutParams,
1836 ExtParameterInfoBuilder &ParamInfos) {
1837 assert(!CodeSynthesisContexts.empty() &&
1838 "Cannot perform an instantiation without some context on the "
1839 "instantiation stack");
1841 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
1843 return Instantiator.TransformFunctionTypeParams(
1844 Loc, Params, nullptr, ExtParamInfos, ParamTypes, OutParams, ParamInfos);
1847 /// \brief Perform substitution on the base class specifiers of the
1848 /// given class template specialization.
1850 /// Produces a diagnostic and returns true on error, returns false and
1851 /// attaches the instantiated base classes to the class template
1852 /// specialization if successful.
1854 Sema::SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
1855 CXXRecordDecl *Pattern,
1856 const MultiLevelTemplateArgumentList &TemplateArgs) {
1857 bool Invalid = false;
1858 SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases;
1859 for (const auto &Base : Pattern->bases()) {
1860 if (!Base.getType()->isDependentType()) {
1861 if (const CXXRecordDecl *RD = Base.getType()->getAsCXXRecordDecl()) {
1862 if (RD->isInvalidDecl())
1863 Instantiation->setInvalidDecl();
1865 InstantiatedBases.push_back(new (Context) CXXBaseSpecifier(Base));
1869 SourceLocation EllipsisLoc;
1870 TypeSourceInfo *BaseTypeLoc;
1871 if (Base.isPackExpansion()) {
1872 // This is a pack expansion. See whether we should expand it now, or
1873 // wait until later.
1874 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
1875 collectUnexpandedParameterPacks(Base.getTypeSourceInfo()->getTypeLoc(),
1877 bool ShouldExpand = false;
1878 bool RetainExpansion = false;
1879 Optional<unsigned> NumExpansions;
1880 if (CheckParameterPacksForExpansion(Base.getEllipsisLoc(),
1881 Base.getSourceRange(),
1883 TemplateArgs, ShouldExpand,
1890 // If we should expand this pack expansion now, do so.
1892 for (unsigned I = 0; I != *NumExpansions; ++I) {
1893 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
1895 TypeSourceInfo *BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
1897 Base.getSourceRange().getBegin(),
1904 if (CXXBaseSpecifier *InstantiatedBase
1905 = CheckBaseSpecifier(Instantiation,
1906 Base.getSourceRange(),
1908 Base.getAccessSpecifierAsWritten(),
1911 InstantiatedBases.push_back(InstantiatedBase);
1919 // The resulting base specifier will (still) be a pack expansion.
1920 EllipsisLoc = Base.getEllipsisLoc();
1921 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
1922 BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
1924 Base.getSourceRange().getBegin(),
1927 BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
1929 Base.getSourceRange().getBegin(),
1938 if (CXXBaseSpecifier *InstantiatedBase
1939 = CheckBaseSpecifier(Instantiation,
1940 Base.getSourceRange(),
1942 Base.getAccessSpecifierAsWritten(),
1945 InstantiatedBases.push_back(InstantiatedBase);
1950 if (!Invalid && AttachBaseSpecifiers(Instantiation, InstantiatedBases))
1956 // Defined via #include from SemaTemplateInstantiateDecl.cpp
1959 Attr *instantiateTemplateAttribute(const Attr *At, ASTContext &C, Sema &S,
1960 const MultiLevelTemplateArgumentList &TemplateArgs);
1961 Attr *instantiateTemplateAttributeForDecl(
1962 const Attr *At, ASTContext &C, Sema &S,
1963 const MultiLevelTemplateArgumentList &TemplateArgs);
1967 /// \brief Instantiate the definition of a class from a given pattern.
1969 /// \param PointOfInstantiation The point of instantiation within the
1972 /// \param Instantiation is the declaration whose definition is being
1973 /// instantiated. This will be either a class template specialization
1974 /// or a member class of a class template specialization.
1976 /// \param Pattern is the pattern from which the instantiation
1977 /// occurs. This will be either the declaration of a class template or
1978 /// the declaration of a member class of a class template.
1980 /// \param TemplateArgs The template arguments to be substituted into
1983 /// \param TSK the kind of implicit or explicit instantiation to perform.
1985 /// \param Complain whether to complain if the class cannot be instantiated due
1986 /// to the lack of a definition.
1988 /// \returns true if an error occurred, false otherwise.
1990 Sema::InstantiateClass(SourceLocation PointOfInstantiation,
1991 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
1992 const MultiLevelTemplateArgumentList &TemplateArgs,
1993 TemplateSpecializationKind TSK,
1995 CXXRecordDecl *PatternDef
1996 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
1997 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
1998 Instantiation->getInstantiatedFromMemberClass(),
1999 Pattern, PatternDef, TSK, Complain))
2001 Pattern = PatternDef;
2003 // \brief Record the point of instantiation.
2004 if (MemberSpecializationInfo *MSInfo
2005 = Instantiation->getMemberSpecializationInfo()) {
2006 MSInfo->setTemplateSpecializationKind(TSK);
2007 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2008 } else if (ClassTemplateSpecializationDecl *Spec
2009 = dyn_cast<ClassTemplateSpecializationDecl>(Instantiation)) {
2010 Spec->setTemplateSpecializationKind(TSK);
2011 Spec->setPointOfInstantiation(PointOfInstantiation);
2014 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
2015 if (Inst.isInvalid())
2017 assert(!Inst.isAlreadyInstantiating() && "should have been caught by caller");
2018 PrettyDeclStackTraceEntry CrashInfo(*this, Instantiation, SourceLocation(),
2019 "instantiating class definition");
2021 // Enter the scope of this instantiation. We don't use
2022 // PushDeclContext because we don't have a scope.
2023 ContextRAII SavedContext(*this, Instantiation);
2024 EnterExpressionEvaluationContext EvalContext(
2025 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
2027 // If this is an instantiation of a local class, merge this local
2028 // instantiation scope with the enclosing scope. Otherwise, every
2029 // instantiation of a class has its own local instantiation scope.
2030 bool MergeWithParentScope = !Instantiation->isDefinedOutsideFunctionOrMethod();
2031 LocalInstantiationScope Scope(*this, MergeWithParentScope);
2033 // All dllexported classes created during instantiation should be fully
2034 // emitted after instantiation completes. We may not be ready to emit any
2035 // delayed classes already on the stack, so save them away and put them back
2037 decltype(DelayedDllExportClasses) ExportedClasses;
2038 std::swap(ExportedClasses, DelayedDllExportClasses);
2040 // Pull attributes from the pattern onto the instantiation.
2041 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
2043 // Start the definition of this instantiation.
2044 Instantiation->startDefinition();
2046 // The instantiation is visible here, even if it was first declared in an
2047 // unimported module.
2048 Instantiation->setVisibleDespiteOwningModule();
2050 // FIXME: This loses the as-written tag kind for an explicit instantiation.
2051 Instantiation->setTagKind(Pattern->getTagKind());
2053 // Do substitution on the base class specifiers.
2054 if (SubstBaseSpecifiers(Instantiation, Pattern, TemplateArgs))
2055 Instantiation->setInvalidDecl();
2057 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
2058 SmallVector<Decl*, 4> Fields;
2059 // Delay instantiation of late parsed attributes.
2060 LateInstantiatedAttrVec LateAttrs;
2061 Instantiator.enableLateAttributeInstantiation(&LateAttrs);
2063 for (auto *Member : Pattern->decls()) {
2064 // Don't instantiate members not belonging in this semantic context.
2067 // template <int i> class A {
2071 // 'class B' has the template as lexical context but semantically it is
2072 // introduced in namespace scope.
2073 if (Member->getDeclContext() != Pattern)
2076 if (Member->isInvalidDecl()) {
2077 Instantiation->setInvalidDecl();
2081 Decl *NewMember = Instantiator.Visit(Member);
2083 if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember)) {
2084 Fields.push_back(Field);
2085 } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(NewMember)) {
2086 // C++11 [temp.inst]p1: The implicit instantiation of a class template
2087 // specialization causes the implicit instantiation of the definitions
2088 // of unscoped member enumerations.
2089 // Record a point of instantiation for this implicit instantiation.
2090 if (TSK == TSK_ImplicitInstantiation && !Enum->isScoped() &&
2091 Enum->isCompleteDefinition()) {
2092 MemberSpecializationInfo *MSInfo =Enum->getMemberSpecializationInfo();
2093 assert(MSInfo && "no spec info for member enum specialization");
2094 MSInfo->setTemplateSpecializationKind(TSK_ImplicitInstantiation);
2095 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2097 } else if (StaticAssertDecl *SA = dyn_cast<StaticAssertDecl>(NewMember)) {
2098 if (SA->isFailed()) {
2099 // A static_assert failed. Bail out; instantiating this
2100 // class is probably not meaningful.
2101 Instantiation->setInvalidDecl();
2106 if (NewMember->isInvalidDecl())
2107 Instantiation->setInvalidDecl();
2109 // FIXME: Eventually, a NULL return will mean that one of the
2110 // instantiations was a semantic disaster, and we'll want to mark the
2111 // declaration invalid.
2112 // For now, we expect to skip some members that we can't yet handle.
2116 // Finish checking fields.
2117 ActOnFields(nullptr, Instantiation->getLocation(), Instantiation, Fields,
2118 SourceLocation(), SourceLocation(), nullptr);
2119 CheckCompletedCXXClass(Instantiation);
2121 // Default arguments are parsed, if not instantiated. We can go instantiate
2122 // default arg exprs for default constructors if necessary now.
2123 ActOnFinishCXXNonNestedClass(Instantiation);
2125 // Put back the delayed exported classes that we moved out of the way.
2126 std::swap(ExportedClasses, DelayedDllExportClasses);
2128 // Instantiate late parsed attributes, and attach them to their decls.
2129 // See Sema::InstantiateAttrs
2130 for (LateInstantiatedAttrVec::iterator I = LateAttrs.begin(),
2131 E = LateAttrs.end(); I != E; ++I) {
2132 assert(CurrentInstantiationScope == Instantiator.getStartingScope());
2133 CurrentInstantiationScope = I->Scope;
2135 // Allow 'this' within late-parsed attributes.
2136 NamedDecl *ND = dyn_cast<NamedDecl>(I->NewDecl);
2137 CXXRecordDecl *ThisContext =
2138 dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
2139 CXXThisScopeRAII ThisScope(*this, ThisContext, /*TypeQuals*/0,
2140 ND && ND->isCXXInstanceMember());
2143 instantiateTemplateAttribute(I->TmplAttr, Context, *this, TemplateArgs);
2144 I->NewDecl->addAttr(NewAttr);
2145 LocalInstantiationScope::deleteScopes(I->Scope,
2146 Instantiator.getStartingScope());
2148 Instantiator.disableLateAttributeInstantiation();
2151 ActOnFinishDelayedMemberInitializers(Instantiation);
2153 // FIXME: We should do something similar for explicit instantiations so they
2154 // end up in the right module.
2155 if (TSK == TSK_ImplicitInstantiation) {
2156 Instantiation->setLocation(Pattern->getLocation());
2157 Instantiation->setLocStart(Pattern->getInnerLocStart());
2158 Instantiation->setBraceRange(Pattern->getBraceRange());
2161 if (!Instantiation->isInvalidDecl()) {
2162 // Perform any dependent diagnostics from the pattern.
2163 PerformDependentDiagnostics(Pattern, TemplateArgs);
2165 // Instantiate any out-of-line class template partial
2166 // specializations now.
2167 for (TemplateDeclInstantiator::delayed_partial_spec_iterator
2168 P = Instantiator.delayed_partial_spec_begin(),
2169 PEnd = Instantiator.delayed_partial_spec_end();
2171 if (!Instantiator.InstantiateClassTemplatePartialSpecialization(
2172 P->first, P->second)) {
2173 Instantiation->setInvalidDecl();
2178 // Instantiate any out-of-line variable template partial
2179 // specializations now.
2180 for (TemplateDeclInstantiator::delayed_var_partial_spec_iterator
2181 P = Instantiator.delayed_var_partial_spec_begin(),
2182 PEnd = Instantiator.delayed_var_partial_spec_end();
2184 if (!Instantiator.InstantiateVarTemplatePartialSpecialization(
2185 P->first, P->second)) {
2186 Instantiation->setInvalidDecl();
2192 // Exit the scope of this instantiation.
2195 if (!Instantiation->isInvalidDecl()) {
2196 Consumer.HandleTagDeclDefinition(Instantiation);
2198 // Always emit the vtable for an explicit instantiation definition
2199 // of a polymorphic class template specialization.
2200 if (TSK == TSK_ExplicitInstantiationDefinition)
2201 MarkVTableUsed(PointOfInstantiation, Instantiation, true);
2204 return Instantiation->isInvalidDecl();
2207 /// \brief Instantiate the definition of an enum from a given pattern.
2209 /// \param PointOfInstantiation The point of instantiation within the
2211 /// \param Instantiation is the declaration whose definition is being
2212 /// instantiated. This will be a member enumeration of a class
2213 /// temploid specialization, or a local enumeration within a
2214 /// function temploid specialization.
2215 /// \param Pattern The templated declaration from which the instantiation
2217 /// \param TemplateArgs The template arguments to be substituted into
2219 /// \param TSK The kind of implicit or explicit instantiation to perform.
2221 /// \return \c true if an error occurred, \c false otherwise.
2222 bool Sema::InstantiateEnum(SourceLocation PointOfInstantiation,
2223 EnumDecl *Instantiation, EnumDecl *Pattern,
2224 const MultiLevelTemplateArgumentList &TemplateArgs,
2225 TemplateSpecializationKind TSK) {
2226 EnumDecl *PatternDef = Pattern->getDefinition();
2227 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
2228 Instantiation->getInstantiatedFromMemberEnum(),
2229 Pattern, PatternDef, TSK,/*Complain*/true))
2231 Pattern = PatternDef;
2233 // Record the point of instantiation.
2234 if (MemberSpecializationInfo *MSInfo
2235 = Instantiation->getMemberSpecializationInfo()) {
2236 MSInfo->setTemplateSpecializationKind(TSK);
2237 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2240 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
2241 if (Inst.isInvalid())
2243 if (Inst.isAlreadyInstantiating())
2245 PrettyDeclStackTraceEntry CrashInfo(*this, Instantiation, SourceLocation(),
2246 "instantiating enum definition");
2248 // The instantiation is visible here, even if it was first declared in an
2249 // unimported module.
2250 Instantiation->setVisibleDespiteOwningModule();
2252 // Enter the scope of this instantiation. We don't use
2253 // PushDeclContext because we don't have a scope.
2254 ContextRAII SavedContext(*this, Instantiation);
2255 EnterExpressionEvaluationContext EvalContext(
2256 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
2258 LocalInstantiationScope Scope(*this, /*MergeWithParentScope*/true);
2260 // Pull attributes from the pattern onto the instantiation.
2261 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
2263 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
2264 Instantiator.InstantiateEnumDefinition(Instantiation, Pattern);
2266 // Exit the scope of this instantiation.
2269 return Instantiation->isInvalidDecl();
2273 /// \brief Instantiate the definition of a field from the given pattern.
2275 /// \param PointOfInstantiation The point of instantiation within the
2277 /// \param Instantiation is the declaration whose definition is being
2278 /// instantiated. This will be a class of a class temploid
2279 /// specialization, or a local enumeration within a function temploid
2281 /// \param Pattern The templated declaration from which the instantiation
2283 /// \param TemplateArgs The template arguments to be substituted into
2286 /// \return \c true if an error occurred, \c false otherwise.
2287 bool Sema::InstantiateInClassInitializer(
2288 SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
2289 FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs) {
2290 // If there is no initializer, we don't need to do anything.
2291 if (!Pattern->hasInClassInitializer())
2294 assert(Instantiation->getInClassInitStyle() ==
2295 Pattern->getInClassInitStyle() &&
2296 "pattern and instantiation disagree about init style");
2298 // Error out if we haven't parsed the initializer of the pattern yet because
2299 // we are waiting for the closing brace of the outer class.
2300 Expr *OldInit = Pattern->getInClassInitializer();
2302 RecordDecl *PatternRD = Pattern->getParent();
2303 RecordDecl *OutermostClass = PatternRD->getOuterLexicalRecordContext();
2304 Diag(PointOfInstantiation,
2305 diag::err_in_class_initializer_not_yet_parsed)
2306 << OutermostClass << Pattern;
2307 Diag(Pattern->getLocEnd(), diag::note_in_class_initializer_not_yet_parsed);
2308 Instantiation->setInvalidDecl();
2312 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
2313 if (Inst.isInvalid())
2315 if (Inst.isAlreadyInstantiating()) {
2316 // Error out if we hit an instantiation cycle for this initializer.
2317 Diag(PointOfInstantiation, diag::err_in_class_initializer_cycle)
2321 PrettyDeclStackTraceEntry CrashInfo(*this, Instantiation, SourceLocation(),
2322 "instantiating default member init");
2324 // Enter the scope of this instantiation. We don't use PushDeclContext because
2325 // we don't have a scope.
2326 ContextRAII SavedContext(*this, Instantiation->getParent());
2327 EnterExpressionEvaluationContext EvalContext(
2328 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
2330 LocalInstantiationScope Scope(*this, true);
2332 // Instantiate the initializer.
2333 ActOnStartCXXInClassMemberInitializer();
2334 CXXThisScopeRAII ThisScope(*this, Instantiation->getParent(), /*TypeQuals=*/0);
2336 ExprResult NewInit = SubstInitializer(OldInit, TemplateArgs,
2337 /*CXXDirectInit=*/false);
2338 Expr *Init = NewInit.get();
2339 assert((!Init || !isa<ParenListExpr>(Init)) && "call-style init in class");
2340 ActOnFinishCXXInClassMemberInitializer(
2341 Instantiation, Init ? Init->getLocStart() : SourceLocation(), Init);
2343 if (auto *L = getASTMutationListener())
2344 L->DefaultMemberInitializerInstantiated(Instantiation);
2346 // Return true if the in-class initializer is still missing.
2347 return !Instantiation->getInClassInitializer();
2351 /// \brief A partial specialization whose template arguments have matched
2352 /// a given template-id.
2353 struct PartialSpecMatchResult {
2354 ClassTemplatePartialSpecializationDecl *Partial;
2355 TemplateArgumentList *Args;
2359 bool Sema::usesPartialOrExplicitSpecialization(
2360 SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec) {
2361 if (ClassTemplateSpec->getTemplateSpecializationKind() ==
2362 TSK_ExplicitSpecialization)
2365 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
2366 ClassTemplateSpec->getSpecializedTemplate()
2367 ->getPartialSpecializations(PartialSpecs);
2368 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
2369 TemplateDeductionInfo Info(Loc);
2370 if (!DeduceTemplateArguments(PartialSpecs[I],
2371 ClassTemplateSpec->getTemplateArgs(), Info))
2378 /// Get the instantiation pattern to use to instantiate the definition of a
2379 /// given ClassTemplateSpecializationDecl (either the pattern of the primary
2380 /// template or of a partial specialization).
2381 static CXXRecordDecl *
2382 getPatternForClassTemplateSpecialization(
2383 Sema &S, SourceLocation PointOfInstantiation,
2384 ClassTemplateSpecializationDecl *ClassTemplateSpec,
2385 TemplateSpecializationKind TSK, bool Complain) {
2386 Sema::InstantiatingTemplate Inst(S, PointOfInstantiation, ClassTemplateSpec);
2387 if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
2390 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
2391 CXXRecordDecl *Pattern = nullptr;
2393 // C++ [temp.class.spec.match]p1:
2394 // When a class template is used in a context that requires an
2395 // instantiation of the class, it is necessary to determine
2396 // whether the instantiation is to be generated using the primary
2397 // template or one of the partial specializations. This is done by
2398 // matching the template arguments of the class template
2399 // specialization with the template argument lists of the partial
2401 typedef PartialSpecMatchResult MatchResult;
2402 SmallVector<MatchResult, 4> Matched;
2403 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
2404 Template->getPartialSpecializations(PartialSpecs);
2405 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation);
2406 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
2407 ClassTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
2408 TemplateDeductionInfo Info(FailedCandidates.getLocation());
2409 if (Sema::TemplateDeductionResult Result = S.DeduceTemplateArguments(
2410 Partial, ClassTemplateSpec->getTemplateArgs(), Info)) {
2411 // Store the failed-deduction information for use in diagnostics, later.
2412 // TODO: Actually use the failed-deduction info?
2413 FailedCandidates.addCandidate().set(
2414 DeclAccessPair::make(Template, AS_public), Partial,
2415 MakeDeductionFailureInfo(S.Context, Result, Info));
2418 Matched.push_back(PartialSpecMatchResult());
2419 Matched.back().Partial = Partial;
2420 Matched.back().Args = Info.take();
2424 // If we're dealing with a member template where the template parameters
2425 // have been instantiated, this provides the original template parameters
2426 // from which the member template's parameters were instantiated.
2428 if (Matched.size() >= 1) {
2429 SmallVectorImpl<MatchResult>::iterator Best = Matched.begin();
2430 if (Matched.size() == 1) {
2431 // -- If exactly one matching specialization is found, the
2432 // instantiation is generated from that specialization.
2433 // We don't need to do anything for this.
2435 // -- If more than one matching specialization is found, the
2436 // partial order rules (14.5.4.2) are used to determine
2437 // whether one of the specializations is more specialized
2438 // than the others. If none of the specializations is more
2439 // specialized than all of the other matching
2440 // specializations, then the use of the class template is
2441 // ambiguous and the program is ill-formed.
2442 for (SmallVectorImpl<MatchResult>::iterator P = Best + 1,
2443 PEnd = Matched.end();
2445 if (S.getMoreSpecializedPartialSpecialization(
2446 P->Partial, Best->Partial, PointOfInstantiation) == P->Partial)
2450 // Determine if the best partial specialization is more specialized than
2452 bool Ambiguous = false;
2453 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
2454 PEnd = Matched.end();
2457 S.getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
2458 PointOfInstantiation) !=
2466 // Partial ordering did not produce a clear winner. Complain.
2468 ClassTemplateSpec->setInvalidDecl();
2469 S.Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
2470 << ClassTemplateSpec;
2472 // Print the matching partial specializations.
2473 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
2474 PEnd = Matched.end();
2476 S.Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
2477 << S.getTemplateArgumentBindingsText(
2478 P->Partial->getTemplateParameters(), *P->Args);
2484 // Instantiate using the best class template partial specialization.
2485 ClassTemplatePartialSpecializationDecl *OrigPartialSpec = Best->Partial;
2486 while (OrigPartialSpec->getInstantiatedFromMember()) {
2487 // If we've found an explicit specialization of this class template,
2488 // stop here and use that as the pattern.
2489 if (OrigPartialSpec->isMemberSpecialization())
2492 OrigPartialSpec = OrigPartialSpec->getInstantiatedFromMember();
2495 Pattern = OrigPartialSpec;
2496 ClassTemplateSpec->setInstantiationOf(Best->Partial, Best->Args);
2498 // -- If no matches are found, the instantiation is generated
2499 // from the primary template.
2500 ClassTemplateDecl *OrigTemplate = Template;
2501 while (OrigTemplate->getInstantiatedFromMemberTemplate()) {
2502 // If we've found an explicit specialization of this class template,
2503 // stop here and use that as the pattern.
2504 if (OrigTemplate->isMemberSpecialization())
2507 OrigTemplate = OrigTemplate->getInstantiatedFromMemberTemplate();
2510 Pattern = OrigTemplate->getTemplatedDecl();
2516 bool Sema::InstantiateClassTemplateSpecialization(
2517 SourceLocation PointOfInstantiation,
2518 ClassTemplateSpecializationDecl *ClassTemplateSpec,
2519 TemplateSpecializationKind TSK, bool Complain) {
2520 // Perform the actual instantiation on the canonical declaration.
2521 ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>(
2522 ClassTemplateSpec->getCanonicalDecl());
2523 if (ClassTemplateSpec->isInvalidDecl())
2526 CXXRecordDecl *Pattern = getPatternForClassTemplateSpecialization(
2527 *this, PointOfInstantiation, ClassTemplateSpec, TSK, Complain);
2531 return InstantiateClass(PointOfInstantiation, ClassTemplateSpec, Pattern,
2532 getTemplateInstantiationArgs(ClassTemplateSpec), TSK,
2536 /// \brief Instantiates the definitions of all of the member
2537 /// of the given class, which is an instantiation of a class template
2538 /// or a member class of a template.
2540 Sema::InstantiateClassMembers(SourceLocation PointOfInstantiation,
2541 CXXRecordDecl *Instantiation,
2542 const MultiLevelTemplateArgumentList &TemplateArgs,
2543 TemplateSpecializationKind TSK) {
2544 // FIXME: We need to notify the ASTMutationListener that we did all of these
2545 // things, in case we have an explicit instantiation definition in a PCM, a
2546 // module, or preamble, and the declaration is in an imported AST.
2548 (TSK == TSK_ExplicitInstantiationDefinition ||
2549 TSK == TSK_ExplicitInstantiationDeclaration ||
2550 (TSK == TSK_ImplicitInstantiation && Instantiation->isLocalClass())) &&
2551 "Unexpected template specialization kind!");
2552 for (auto *D : Instantiation->decls()) {
2553 bool SuppressNew = false;
2554 if (auto *Function = dyn_cast<FunctionDecl>(D)) {
2555 if (FunctionDecl *Pattern
2556 = Function->getInstantiatedFromMemberFunction()) {
2557 MemberSpecializationInfo *MSInfo
2558 = Function->getMemberSpecializationInfo();
2559 assert(MSInfo && "No member specialization information?");
2560 if (MSInfo->getTemplateSpecializationKind()
2561 == TSK_ExplicitSpecialization)
2564 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2566 MSInfo->getTemplateSpecializationKind(),
2567 MSInfo->getPointOfInstantiation(),
2572 // C++11 [temp.explicit]p8:
2573 // An explicit instantiation definition that names a class template
2574 // specialization explicitly instantiates the class template
2575 // specialization and is only an explicit instantiation definition
2576 // of members whose definition is visible at the point of
2578 if (TSK == TSK_ExplicitInstantiationDefinition && !Pattern->isDefined())
2581 Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2583 if (Function->isDefined()) {
2584 // Let the ASTConsumer know that this function has been explicitly
2585 // instantiated now, and its linkage might have changed.
2586 Consumer.HandleTopLevelDecl(DeclGroupRef(Function));
2587 } else if (TSK == TSK_ExplicitInstantiationDefinition) {
2588 InstantiateFunctionDefinition(PointOfInstantiation, Function);
2589 } else if (TSK == TSK_ImplicitInstantiation) {
2590 PendingLocalImplicitInstantiations.push_back(
2591 std::make_pair(Function, PointOfInstantiation));
2594 } else if (auto *Var = dyn_cast<VarDecl>(D)) {
2595 if (isa<VarTemplateSpecializationDecl>(Var))
2598 if (Var->isStaticDataMember()) {
2599 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
2600 assert(MSInfo && "No member specialization information?");
2601 if (MSInfo->getTemplateSpecializationKind()
2602 == TSK_ExplicitSpecialization)
2605 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2607 MSInfo->getTemplateSpecializationKind(),
2608 MSInfo->getPointOfInstantiation(),
2613 if (TSK == TSK_ExplicitInstantiationDefinition) {
2614 // C++0x [temp.explicit]p8:
2615 // An explicit instantiation definition that names a class template
2616 // specialization explicitly instantiates the class template
2617 // specialization and is only an explicit instantiation definition
2618 // of members whose definition is visible at the point of
2620 if (!Var->getInstantiatedFromStaticDataMember()->getDefinition())
2623 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2624 InstantiateStaticDataMemberDefinition(PointOfInstantiation, Var);
2626 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2629 } else if (auto *Record = dyn_cast<CXXRecordDecl>(D)) {
2630 // Always skip the injected-class-name, along with any
2631 // redeclarations of nested classes, since both would cause us
2632 // to try to instantiate the members of a class twice.
2633 // Skip closure types; they'll get instantiated when we instantiate
2634 // the corresponding lambda-expression.
2635 if (Record->isInjectedClassName() || Record->getPreviousDecl() ||
2639 MemberSpecializationInfo *MSInfo = Record->getMemberSpecializationInfo();
2640 assert(MSInfo && "No member specialization information?");
2642 if (MSInfo->getTemplateSpecializationKind()
2643 == TSK_ExplicitSpecialization)
2646 if ((Context.getTargetInfo().getCXXABI().isMicrosoft() ||
2647 Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment()) &&
2648 TSK == TSK_ExplicitInstantiationDeclaration) {
2649 // In MSVC and Windows Itanium mode, explicit instantiation decl of the
2650 // outer class doesn't affect the inner class.
2654 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2656 MSInfo->getTemplateSpecializationKind(),
2657 MSInfo->getPointOfInstantiation(),
2662 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
2663 assert(Pattern && "Missing instantiated-from-template information");
2665 if (!Record->getDefinition()) {
2666 if (!Pattern->getDefinition()) {
2667 // C++0x [temp.explicit]p8:
2668 // An explicit instantiation definition that names a class template
2669 // specialization explicitly instantiates the class template
2670 // specialization and is only an explicit instantiation definition
2671 // of members whose definition is visible at the point of
2673 if (TSK == TSK_ExplicitInstantiationDeclaration) {
2674 MSInfo->setTemplateSpecializationKind(TSK);
2675 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2681 InstantiateClass(PointOfInstantiation, Record, Pattern,
2685 if (TSK == TSK_ExplicitInstantiationDefinition &&
2686 Record->getTemplateSpecializationKind() ==
2687 TSK_ExplicitInstantiationDeclaration) {
2688 Record->setTemplateSpecializationKind(TSK);
2689 MarkVTableUsed(PointOfInstantiation, Record, true);
2693 Pattern = cast_or_null<CXXRecordDecl>(Record->getDefinition());
2695 InstantiateClassMembers(PointOfInstantiation, Pattern, TemplateArgs,
2697 } else if (auto *Enum = dyn_cast<EnumDecl>(D)) {
2698 MemberSpecializationInfo *MSInfo = Enum->getMemberSpecializationInfo();
2699 assert(MSInfo && "No member specialization information?");
2701 if (MSInfo->getTemplateSpecializationKind()
2702 == TSK_ExplicitSpecialization)
2705 if (CheckSpecializationInstantiationRedecl(
2706 PointOfInstantiation, TSK, Enum,
2707 MSInfo->getTemplateSpecializationKind(),
2708 MSInfo->getPointOfInstantiation(), SuppressNew) ||
2712 if (Enum->getDefinition())
2715 EnumDecl *Pattern = Enum->getTemplateInstantiationPattern();
2716 assert(Pattern && "Missing instantiated-from-template information");
2718 if (TSK == TSK_ExplicitInstantiationDefinition) {
2719 if (!Pattern->getDefinition())
2722 InstantiateEnum(PointOfInstantiation, Enum, Pattern, TemplateArgs, TSK);
2724 MSInfo->setTemplateSpecializationKind(TSK);
2725 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2727 } else if (auto *Field = dyn_cast<FieldDecl>(D)) {
2728 // No need to instantiate in-class initializers during explicit
2730 if (Field->hasInClassInitializer() && TSK == TSK_ImplicitInstantiation) {
2731 CXXRecordDecl *ClassPattern =
2732 Instantiation->getTemplateInstantiationPattern();
2733 DeclContext::lookup_result Lookup =
2734 ClassPattern->lookup(Field->getDeclName());
2735 FieldDecl *Pattern = cast<FieldDecl>(Lookup.front());
2736 InstantiateInClassInitializer(PointOfInstantiation, Field, Pattern,
2743 /// \brief Instantiate the definitions of all of the members of the
2744 /// given class template specialization, which was named as part of an
2745 /// explicit instantiation.
2747 Sema::InstantiateClassTemplateSpecializationMembers(
2748 SourceLocation PointOfInstantiation,
2749 ClassTemplateSpecializationDecl *ClassTemplateSpec,
2750 TemplateSpecializationKind TSK) {
2751 // C++0x [temp.explicit]p7:
2752 // An explicit instantiation that names a class template
2753 // specialization is an explicit instantion of the same kind
2754 // (declaration or definition) of each of its members (not
2755 // including members inherited from base classes) that has not
2756 // been previously explicitly specialized in the translation unit
2757 // containing the explicit instantiation, except as described
2759 InstantiateClassMembers(PointOfInstantiation, ClassTemplateSpec,
2760 getTemplateInstantiationArgs(ClassTemplateSpec),
2765 Sema::SubstStmt(Stmt *S, const MultiLevelTemplateArgumentList &TemplateArgs) {
2769 TemplateInstantiator Instantiator(*this, TemplateArgs,
2772 return Instantiator.TransformStmt(S);
2776 Sema::SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs) {
2780 TemplateInstantiator Instantiator(*this, TemplateArgs,
2783 return Instantiator.TransformExpr(E);
2786 ExprResult Sema::SubstInitializer(Expr *Init,
2787 const MultiLevelTemplateArgumentList &TemplateArgs,
2788 bool CXXDirectInit) {
2789 TemplateInstantiator Instantiator(*this, TemplateArgs,
2792 return Instantiator.TransformInitializer(Init, CXXDirectInit);
2795 bool Sema::SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
2796 const MultiLevelTemplateArgumentList &TemplateArgs,
2797 SmallVectorImpl<Expr *> &Outputs) {
2801 TemplateInstantiator Instantiator(*this, TemplateArgs,
2804 return Instantiator.TransformExprs(Exprs.data(), Exprs.size(),
2808 NestedNameSpecifierLoc
2809 Sema::SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
2810 const MultiLevelTemplateArgumentList &TemplateArgs) {
2812 return NestedNameSpecifierLoc();
2814 TemplateInstantiator Instantiator(*this, TemplateArgs, NNS.getBeginLoc(),
2816 return Instantiator.TransformNestedNameSpecifierLoc(NNS);
2819 /// \brief Do template substitution on declaration name info.
2821 Sema::SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
2822 const MultiLevelTemplateArgumentList &TemplateArgs) {
2823 TemplateInstantiator Instantiator(*this, TemplateArgs, NameInfo.getLoc(),
2824 NameInfo.getName());
2825 return Instantiator.TransformDeclarationNameInfo(NameInfo);
2829 Sema::SubstTemplateName(NestedNameSpecifierLoc QualifierLoc,
2830 TemplateName Name, SourceLocation Loc,
2831 const MultiLevelTemplateArgumentList &TemplateArgs) {
2832 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
2835 SS.Adopt(QualifierLoc);
2836 return Instantiator.TransformTemplateName(SS, Name, Loc);
2839 bool Sema::Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
2840 TemplateArgumentListInfo &Result,
2841 const MultiLevelTemplateArgumentList &TemplateArgs) {
2842 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
2845 return Instantiator.TransformTemplateArguments(Args, NumArgs, Result);
2848 static const Decl *getCanonicalParmVarDecl(const Decl *D) {
2849 // When storing ParmVarDecls in the local instantiation scope, we always
2850 // want to use the ParmVarDecl from the canonical function declaration,
2851 // since the map is then valid for any redeclaration or definition of that
2853 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(D)) {
2854 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
2855 unsigned i = PV->getFunctionScopeIndex();
2856 // This parameter might be from a freestanding function type within the
2857 // function and isn't necessarily referring to one of FD's parameters.
2858 if (FD->getParamDecl(i) == PV)
2859 return FD->getCanonicalDecl()->getParamDecl(i);
2866 llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> *
2867 LocalInstantiationScope::findInstantiationOf(const Decl *D) {
2868 D = getCanonicalParmVarDecl(D);
2869 for (LocalInstantiationScope *Current = this; Current;
2870 Current = Current->Outer) {
2872 // Check if we found something within this scope.
2873 const Decl *CheckD = D;
2875 LocalDeclsMap::iterator Found = Current->LocalDecls.find(CheckD);
2876 if (Found != Current->LocalDecls.end())
2877 return &Found->second;
2879 // If this is a tag declaration, it's possible that we need to look for
2880 // a previous declaration.
2881 if (const TagDecl *Tag = dyn_cast<TagDecl>(CheckD))
2882 CheckD = Tag->getPreviousDecl();
2887 // If we aren't combined with our outer scope, we're done.
2888 if (!Current->CombineWithOuterScope)
2892 // If we're performing a partial substitution during template argument
2893 // deduction, we may not have values for template parameters yet.
2894 if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
2895 isa<TemplateTemplateParmDecl>(D))
2898 // Local types referenced prior to definition may require instantiation.
2899 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
2900 if (RD->isLocalClass())
2903 // Enumeration types referenced prior to definition may appear as a result of
2905 if (isa<EnumDecl>(D))
2908 // If we didn't find the decl, then we either have a sema bug, or we have a
2909 // forward reference to a label declaration. Return null to indicate that
2910 // we have an uninstantiated label.
2911 assert(isa<LabelDecl>(D) && "declaration not instantiated in this scope");
2915 void LocalInstantiationScope::InstantiatedLocal(const Decl *D, Decl *Inst) {
2916 D = getCanonicalParmVarDecl(D);
2917 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
2918 if (Stored.isNull()) {
2920 // It should not be present in any surrounding scope either.
2921 LocalInstantiationScope *Current = this;
2922 while (Current->CombineWithOuterScope && Current->Outer) {
2923 Current = Current->Outer;
2924 assert(Current->LocalDecls.find(D) == Current->LocalDecls.end() &&
2925 "Instantiated local in inner and outer scopes");
2929 } else if (DeclArgumentPack *Pack = Stored.dyn_cast<DeclArgumentPack *>()) {
2930 Pack->push_back(cast<ParmVarDecl>(Inst));
2932 assert(Stored.get<Decl *>() == Inst && "Already instantiated this local");
2936 void LocalInstantiationScope::InstantiatedLocalPackArg(const Decl *D,
2937 ParmVarDecl *Inst) {
2938 D = getCanonicalParmVarDecl(D);
2939 DeclArgumentPack *Pack = LocalDecls[D].get<DeclArgumentPack *>();
2940 Pack->push_back(Inst);
2943 void LocalInstantiationScope::MakeInstantiatedLocalArgPack(const Decl *D) {
2945 // This should be the first time we've been told about this decl.
2946 for (LocalInstantiationScope *Current = this;
2947 Current && Current->CombineWithOuterScope; Current = Current->Outer)
2948 assert(Current->LocalDecls.find(D) == Current->LocalDecls.end() &&
2949 "Creating local pack after instantiation of local");
2952 D = getCanonicalParmVarDecl(D);
2953 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
2954 DeclArgumentPack *Pack = new DeclArgumentPack;
2956 ArgumentPacks.push_back(Pack);
2959 void LocalInstantiationScope::SetPartiallySubstitutedPack(NamedDecl *Pack,
2960 const TemplateArgument *ExplicitArgs,
2961 unsigned NumExplicitArgs) {
2962 assert((!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack) &&
2963 "Already have a partially-substituted pack");
2964 assert((!PartiallySubstitutedPack
2965 || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) &&
2966 "Wrong number of arguments in partially-substituted pack");
2967 PartiallySubstitutedPack = Pack;
2968 ArgsInPartiallySubstitutedPack = ExplicitArgs;
2969 NumArgsInPartiallySubstitutedPack = NumExplicitArgs;
2972 NamedDecl *LocalInstantiationScope::getPartiallySubstitutedPack(
2973 const TemplateArgument **ExplicitArgs,
2974 unsigned *NumExplicitArgs) const {
2976 *ExplicitArgs = nullptr;
2977 if (NumExplicitArgs)
2978 *NumExplicitArgs = 0;
2980 for (const LocalInstantiationScope *Current = this; Current;
2981 Current = Current->Outer) {
2982 if (Current->PartiallySubstitutedPack) {
2984 *ExplicitArgs = Current->ArgsInPartiallySubstitutedPack;
2985 if (NumExplicitArgs)
2986 *NumExplicitArgs = Current->NumArgsInPartiallySubstitutedPack;
2988 return Current->PartiallySubstitutedPack;
2991 if (!Current->CombineWithOuterScope)