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:
203 llvm_unreachable("Invalid SynthesisKind!");
206 Sema::InstantiatingTemplate::InstantiatingTemplate(
207 Sema &SemaRef, CodeSynthesisContext::SynthesisKind Kind,
208 SourceLocation PointOfInstantiation, SourceRange InstantiationRange,
209 Decl *Entity, NamedDecl *Template, ArrayRef<TemplateArgument> TemplateArgs,
210 sema::TemplateDeductionInfo *DeductionInfo)
212 // Don't allow further instantiation if a fatal error and an uncompilable
213 // error have occurred. Any diagnostics we might have raised will not be
214 // visible, and we do not need to construct a correct AST.
215 if (SemaRef.Diags.hasFatalErrorOccurred() &&
216 SemaRef.Diags.hasUncompilableErrorOccurred()) {
220 Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
222 CodeSynthesisContext Inst;
224 Inst.PointOfInstantiation = PointOfInstantiation;
225 Inst.Entity = Entity;
226 Inst.Template = Template;
227 Inst.TemplateArgs = TemplateArgs.data();
228 Inst.NumTemplateArgs = TemplateArgs.size();
229 Inst.DeductionInfo = DeductionInfo;
230 Inst.InstantiationRange = InstantiationRange;
231 SemaRef.pushCodeSynthesisContext(Inst);
233 AlreadyInstantiating =
234 !SemaRef.InstantiatingSpecializations
235 .insert(std::make_pair(Inst.Entity->getCanonicalDecl(), Inst.Kind))
240 Sema::InstantiatingTemplate::InstantiatingTemplate(
241 Sema &SemaRef, SourceLocation PointOfInstantiation, Decl *Entity,
242 SourceRange InstantiationRange)
243 : InstantiatingTemplate(SemaRef,
244 CodeSynthesisContext::TemplateInstantiation,
245 PointOfInstantiation, InstantiationRange, Entity) {}
247 Sema::InstantiatingTemplate::InstantiatingTemplate(
248 Sema &SemaRef, SourceLocation PointOfInstantiation, FunctionDecl *Entity,
249 ExceptionSpecification, SourceRange InstantiationRange)
250 : InstantiatingTemplate(
251 SemaRef, CodeSynthesisContext::ExceptionSpecInstantiation,
252 PointOfInstantiation, InstantiationRange, Entity) {}
254 Sema::InstantiatingTemplate::InstantiatingTemplate(
255 Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateParameter Param,
256 TemplateDecl *Template, ArrayRef<TemplateArgument> TemplateArgs,
257 SourceRange InstantiationRange)
258 : InstantiatingTemplate(
260 CodeSynthesisContext::DefaultTemplateArgumentInstantiation,
261 PointOfInstantiation, InstantiationRange, getAsNamedDecl(Param),
262 Template, TemplateArgs) {}
264 Sema::InstantiatingTemplate::InstantiatingTemplate(
265 Sema &SemaRef, SourceLocation PointOfInstantiation,
266 FunctionTemplateDecl *FunctionTemplate,
267 ArrayRef<TemplateArgument> TemplateArgs,
268 CodeSynthesisContext::SynthesisKind Kind,
269 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
270 : InstantiatingTemplate(SemaRef, Kind, PointOfInstantiation,
271 InstantiationRange, FunctionTemplate, nullptr,
272 TemplateArgs, &DeductionInfo) {
274 Kind == CodeSynthesisContext::ExplicitTemplateArgumentSubstitution ||
275 Kind == CodeSynthesisContext::DeducedTemplateArgumentSubstitution);
278 Sema::InstantiatingTemplate::InstantiatingTemplate(
279 Sema &SemaRef, SourceLocation PointOfInstantiation,
280 TemplateDecl *Template,
281 ArrayRef<TemplateArgument> TemplateArgs,
282 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
283 : InstantiatingTemplate(
285 CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
286 PointOfInstantiation, InstantiationRange, Template, nullptr,
287 TemplateArgs, &DeductionInfo) {}
289 Sema::InstantiatingTemplate::InstantiatingTemplate(
290 Sema &SemaRef, SourceLocation PointOfInstantiation,
291 ClassTemplatePartialSpecializationDecl *PartialSpec,
292 ArrayRef<TemplateArgument> TemplateArgs,
293 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
294 : InstantiatingTemplate(
296 CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
297 PointOfInstantiation, InstantiationRange, PartialSpec, nullptr,
298 TemplateArgs, &DeductionInfo) {}
300 Sema::InstantiatingTemplate::InstantiatingTemplate(
301 Sema &SemaRef, SourceLocation PointOfInstantiation,
302 VarTemplatePartialSpecializationDecl *PartialSpec,
303 ArrayRef<TemplateArgument> TemplateArgs,
304 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
305 : InstantiatingTemplate(
307 CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
308 PointOfInstantiation, InstantiationRange, PartialSpec, nullptr,
309 TemplateArgs, &DeductionInfo) {}
311 Sema::InstantiatingTemplate::InstantiatingTemplate(
312 Sema &SemaRef, SourceLocation PointOfInstantiation, ParmVarDecl *Param,
313 ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange)
314 : InstantiatingTemplate(
316 CodeSynthesisContext::DefaultFunctionArgumentInstantiation,
317 PointOfInstantiation, InstantiationRange, Param, nullptr,
320 Sema::InstantiatingTemplate::InstantiatingTemplate(
321 Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template,
322 NonTypeTemplateParmDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
323 SourceRange InstantiationRange)
324 : InstantiatingTemplate(
326 CodeSynthesisContext::PriorTemplateArgumentSubstitution,
327 PointOfInstantiation, InstantiationRange, Param, Template,
330 Sema::InstantiatingTemplate::InstantiatingTemplate(
331 Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template,
332 TemplateTemplateParmDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
333 SourceRange InstantiationRange)
334 : InstantiatingTemplate(
336 CodeSynthesisContext::PriorTemplateArgumentSubstitution,
337 PointOfInstantiation, InstantiationRange, Param, Template,
340 Sema::InstantiatingTemplate::InstantiatingTemplate(
341 Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Template,
342 NamedDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
343 SourceRange InstantiationRange)
344 : InstantiatingTemplate(
345 SemaRef, CodeSynthesisContext::DefaultTemplateArgumentChecking,
346 PointOfInstantiation, InstantiationRange, Param, Template,
349 void Sema::pushCodeSynthesisContext(CodeSynthesisContext Ctx) {
350 Ctx.SavedInNonInstantiationSFINAEContext = InNonInstantiationSFINAEContext;
351 InNonInstantiationSFINAEContext = false;
353 CodeSynthesisContexts.push_back(Ctx);
355 if (!Ctx.isInstantiationRecord())
356 ++NonInstantiationEntries;
359 void Sema::popCodeSynthesisContext() {
360 auto &Active = CodeSynthesisContexts.back();
361 if (!Active.isInstantiationRecord()) {
362 assert(NonInstantiationEntries > 0);
363 --NonInstantiationEntries;
366 InNonInstantiationSFINAEContext = Active.SavedInNonInstantiationSFINAEContext;
368 // Name lookup no longer looks in this template's defining module.
369 assert(CodeSynthesisContexts.size() >=
370 CodeSynthesisContextLookupModules.size() &&
371 "forgot to remove a lookup module for a template instantiation");
372 if (CodeSynthesisContexts.size() ==
373 CodeSynthesisContextLookupModules.size()) {
374 if (Module *M = CodeSynthesisContextLookupModules.back())
375 LookupModulesCache.erase(M);
376 CodeSynthesisContextLookupModules.pop_back();
379 // If we've left the code synthesis context for the current context stack,
380 // stop remembering that we've emitted that stack.
381 if (CodeSynthesisContexts.size() ==
382 LastEmittedCodeSynthesisContextDepth)
383 LastEmittedCodeSynthesisContextDepth = 0;
385 CodeSynthesisContexts.pop_back();
388 void Sema::InstantiatingTemplate::Clear() {
390 if (!AlreadyInstantiating) {
391 auto &Active = SemaRef.CodeSynthesisContexts.back();
392 SemaRef.InstantiatingSpecializations.erase(
393 std::make_pair(Active.Entity, Active.Kind));
396 SemaRef.popCodeSynthesisContext();
402 bool Sema::InstantiatingTemplate::CheckInstantiationDepth(
403 SourceLocation PointOfInstantiation,
404 SourceRange InstantiationRange) {
405 assert(SemaRef.NonInstantiationEntries <=
406 SemaRef.CodeSynthesisContexts.size());
407 if ((SemaRef.CodeSynthesisContexts.size() -
408 SemaRef.NonInstantiationEntries)
409 <= SemaRef.getLangOpts().InstantiationDepth)
412 SemaRef.Diag(PointOfInstantiation,
413 diag::err_template_recursion_depth_exceeded)
414 << SemaRef.getLangOpts().InstantiationDepth
415 << InstantiationRange;
416 SemaRef.Diag(PointOfInstantiation, diag::note_template_recursion_depth)
417 << SemaRef.getLangOpts().InstantiationDepth;
421 /// \brief Prints the current instantiation stack through a series of
423 void Sema::PrintInstantiationStack() {
424 // Determine which template instantiations to skip, if any.
425 unsigned SkipStart = CodeSynthesisContexts.size(), SkipEnd = SkipStart;
426 unsigned Limit = Diags.getTemplateBacktraceLimit();
427 if (Limit && Limit < CodeSynthesisContexts.size()) {
428 SkipStart = Limit / 2 + Limit % 2;
429 SkipEnd = CodeSynthesisContexts.size() - Limit / 2;
432 // FIXME: In all of these cases, we need to show the template arguments
433 unsigned InstantiationIdx = 0;
434 for (SmallVectorImpl<CodeSynthesisContext>::reverse_iterator
435 Active = CodeSynthesisContexts.rbegin(),
436 ActiveEnd = CodeSynthesisContexts.rend();
438 ++Active, ++InstantiationIdx) {
439 // Skip this instantiation?
440 if (InstantiationIdx >= SkipStart && InstantiationIdx < SkipEnd) {
441 if (InstantiationIdx == SkipStart) {
442 // Note that we're skipping instantiations.
443 Diags.Report(Active->PointOfInstantiation,
444 diag::note_instantiation_contexts_suppressed)
445 << unsigned(CodeSynthesisContexts.size() - Limit);
450 switch (Active->Kind) {
451 case CodeSynthesisContext::TemplateInstantiation: {
452 Decl *D = Active->Entity;
453 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
454 unsigned DiagID = diag::note_template_member_class_here;
455 if (isa<ClassTemplateSpecializationDecl>(Record))
456 DiagID = diag::note_template_class_instantiation_here;
457 Diags.Report(Active->PointOfInstantiation, DiagID)
458 << Record << Active->InstantiationRange;
459 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
461 if (Function->getPrimaryTemplate())
462 DiagID = diag::note_function_template_spec_here;
464 DiagID = diag::note_template_member_function_here;
465 Diags.Report(Active->PointOfInstantiation, DiagID)
467 << Active->InstantiationRange;
468 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
469 Diags.Report(Active->PointOfInstantiation,
470 VD->isStaticDataMember()?
471 diag::note_template_static_data_member_def_here
472 : diag::note_template_variable_def_here)
474 << Active->InstantiationRange;
475 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
476 Diags.Report(Active->PointOfInstantiation,
477 diag::note_template_enum_def_here)
479 << Active->InstantiationRange;
480 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
481 Diags.Report(Active->PointOfInstantiation,
482 diag::note_template_nsdmi_here)
483 << FD << Active->InstantiationRange;
485 Diags.Report(Active->PointOfInstantiation,
486 diag::note_template_type_alias_instantiation_here)
487 << cast<TypeAliasTemplateDecl>(D)
488 << Active->InstantiationRange;
493 case CodeSynthesisContext::DefaultTemplateArgumentInstantiation: {
494 TemplateDecl *Template = cast<TemplateDecl>(Active->Template);
495 SmallVector<char, 128> TemplateArgsStr;
496 llvm::raw_svector_ostream OS(TemplateArgsStr);
497 Template->printName(OS);
498 TemplateSpecializationType::PrintTemplateArgumentList(
499 OS, Active->template_arguments(), getPrintingPolicy());
500 Diags.Report(Active->PointOfInstantiation,
501 diag::note_default_arg_instantiation_here)
503 << Active->InstantiationRange;
507 case CodeSynthesisContext::ExplicitTemplateArgumentSubstitution: {
508 FunctionTemplateDecl *FnTmpl = cast<FunctionTemplateDecl>(Active->Entity);
509 Diags.Report(Active->PointOfInstantiation,
510 diag::note_explicit_template_arg_substitution_here)
512 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
513 Active->TemplateArgs,
514 Active->NumTemplateArgs)
515 << Active->InstantiationRange;
519 case CodeSynthesisContext::DeducedTemplateArgumentSubstitution: {
520 if (FunctionTemplateDecl *FnTmpl =
521 dyn_cast<FunctionTemplateDecl>(Active->Entity)) {
522 Diags.Report(Active->PointOfInstantiation,
523 diag::note_function_template_deduction_instantiation_here)
525 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
526 Active->TemplateArgs,
527 Active->NumTemplateArgs)
528 << Active->InstantiationRange;
530 bool IsVar = isa<VarTemplateDecl>(Active->Entity) ||
531 isa<VarTemplateSpecializationDecl>(Active->Entity);
532 bool IsTemplate = false;
533 TemplateParameterList *Params;
534 if (auto *D = dyn_cast<TemplateDecl>(Active->Entity)) {
536 Params = D->getTemplateParameters();
537 } else if (auto *D = dyn_cast<ClassTemplatePartialSpecializationDecl>(
539 Params = D->getTemplateParameters();
540 } else if (auto *D = dyn_cast<VarTemplatePartialSpecializationDecl>(
542 Params = D->getTemplateParameters();
544 llvm_unreachable("unexpected template kind");
547 Diags.Report(Active->PointOfInstantiation,
548 diag::note_deduced_template_arg_substitution_here)
549 << IsVar << IsTemplate << cast<NamedDecl>(Active->Entity)
550 << getTemplateArgumentBindingsText(Params, Active->TemplateArgs,
551 Active->NumTemplateArgs)
552 << Active->InstantiationRange;
557 case CodeSynthesisContext::DefaultFunctionArgumentInstantiation: {
558 ParmVarDecl *Param = cast<ParmVarDecl>(Active->Entity);
559 FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());
561 SmallVector<char, 128> TemplateArgsStr;
562 llvm::raw_svector_ostream OS(TemplateArgsStr);
564 TemplateSpecializationType::PrintTemplateArgumentList(
565 OS, Active->template_arguments(), getPrintingPolicy());
566 Diags.Report(Active->PointOfInstantiation,
567 diag::note_default_function_arg_instantiation_here)
569 << Active->InstantiationRange;
573 case CodeSynthesisContext::PriorTemplateArgumentSubstitution: {
574 NamedDecl *Parm = cast<NamedDecl>(Active->Entity);
576 if (!Parm->getName().empty())
577 Name = std::string(" '") + Parm->getName().str() + "'";
579 TemplateParameterList *TemplateParams = nullptr;
580 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
581 TemplateParams = Template->getTemplateParameters();
584 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
585 ->getTemplateParameters();
586 Diags.Report(Active->PointOfInstantiation,
587 diag::note_prior_template_arg_substitution)
588 << isa<TemplateTemplateParmDecl>(Parm)
590 << getTemplateArgumentBindingsText(TemplateParams,
591 Active->TemplateArgs,
592 Active->NumTemplateArgs)
593 << Active->InstantiationRange;
597 case CodeSynthesisContext::DefaultTemplateArgumentChecking: {
598 TemplateParameterList *TemplateParams = nullptr;
599 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
600 TemplateParams = Template->getTemplateParameters();
603 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
604 ->getTemplateParameters();
606 Diags.Report(Active->PointOfInstantiation,
607 diag::note_template_default_arg_checking)
608 << getTemplateArgumentBindingsText(TemplateParams,
609 Active->TemplateArgs,
610 Active->NumTemplateArgs)
611 << Active->InstantiationRange;
615 case CodeSynthesisContext::ExceptionSpecInstantiation:
616 Diags.Report(Active->PointOfInstantiation,
617 diag::note_template_exception_spec_instantiation_here)
618 << cast<FunctionDecl>(Active->Entity)
619 << Active->InstantiationRange;
622 case CodeSynthesisContext::DeclaringSpecialMember:
623 Diags.Report(Active->PointOfInstantiation,
624 diag::note_in_declaration_of_implicit_special_member)
625 << cast<CXXRecordDecl>(Active->Entity) << Active->SpecialMember;
631 Optional<TemplateDeductionInfo *> Sema::isSFINAEContext() const {
632 if (InNonInstantiationSFINAEContext)
633 return Optional<TemplateDeductionInfo *>(nullptr);
635 for (SmallVectorImpl<CodeSynthesisContext>::const_reverse_iterator
636 Active = CodeSynthesisContexts.rbegin(),
637 ActiveEnd = CodeSynthesisContexts.rend();
641 switch (Active->Kind) {
642 case CodeSynthesisContext::TemplateInstantiation:
643 // An instantiation of an alias template may or may not be a SFINAE
644 // context, depending on what else is on the stack.
645 if (isa<TypeAliasTemplateDecl>(Active->Entity))
648 case CodeSynthesisContext::DefaultFunctionArgumentInstantiation:
649 case CodeSynthesisContext::ExceptionSpecInstantiation:
650 // This is a template instantiation, so there is no SFINAE.
653 case CodeSynthesisContext::DefaultTemplateArgumentInstantiation:
654 case CodeSynthesisContext::PriorTemplateArgumentSubstitution:
655 case CodeSynthesisContext::DefaultTemplateArgumentChecking:
656 // A default template argument instantiation and substitution into
657 // template parameters with arguments for prior parameters may or may
658 // not be a SFINAE context; look further up the stack.
661 case CodeSynthesisContext::ExplicitTemplateArgumentSubstitution:
662 case CodeSynthesisContext::DeducedTemplateArgumentSubstitution:
663 // We're either substitution explicitly-specified template arguments
664 // or deduced template arguments, so SFINAE applies.
665 assert(Active->DeductionInfo && "Missing deduction info pointer");
666 return Active->DeductionInfo;
668 case CodeSynthesisContext::DeclaringSpecialMember:
669 // This happens in a context unrelated to template instantiation, so
670 // there is no SFINAE.
674 // The inner context was transparent for SFINAE. If it occurred within a
675 // non-instantiation SFINAE context, then SFINAE applies.
676 if (Active->SavedInNonInstantiationSFINAEContext)
677 return Optional<TemplateDeductionInfo *>(nullptr);
683 /// \brief Retrieve the depth and index of a parameter pack.
684 static std::pair<unsigned, unsigned>
685 getDepthAndIndex(NamedDecl *ND) {
686 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ND))
687 return std::make_pair(TTP->getDepth(), TTP->getIndex());
689 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND))
690 return std::make_pair(NTTP->getDepth(), NTTP->getIndex());
692 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(ND);
693 return std::make_pair(TTP->getDepth(), TTP->getIndex());
696 //===----------------------------------------------------------------------===/
697 // Template Instantiation for Types
698 //===----------------------------------------------------------------------===/
700 class TemplateInstantiator : public TreeTransform<TemplateInstantiator> {
701 const MultiLevelTemplateArgumentList &TemplateArgs;
703 DeclarationName Entity;
706 typedef TreeTransform<TemplateInstantiator> inherited;
708 TemplateInstantiator(Sema &SemaRef,
709 const MultiLevelTemplateArgumentList &TemplateArgs,
711 DeclarationName Entity)
712 : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc),
715 /// \brief Determine whether the given type \p T has already been
718 /// For the purposes of template instantiation, a type has already been
719 /// transformed if it is NULL or if it is not dependent.
720 bool AlreadyTransformed(QualType T);
722 /// \brief Returns the location of the entity being instantiated, if known.
723 SourceLocation getBaseLocation() { return Loc; }
725 /// \brief Returns the name of the entity being instantiated, if any.
726 DeclarationName getBaseEntity() { return Entity; }
728 /// \brief Sets the "base" location and entity when that
729 /// information is known based on another transformation.
730 void setBase(SourceLocation Loc, DeclarationName Entity) {
732 this->Entity = Entity;
735 bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
736 SourceRange PatternRange,
737 ArrayRef<UnexpandedParameterPack> Unexpanded,
738 bool &ShouldExpand, bool &RetainExpansion,
739 Optional<unsigned> &NumExpansions) {
740 return getSema().CheckParameterPacksForExpansion(EllipsisLoc,
741 PatternRange, Unexpanded,
748 void ExpandingFunctionParameterPack(ParmVarDecl *Pack) {
749 SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(Pack);
752 TemplateArgument ForgetPartiallySubstitutedPack() {
753 TemplateArgument Result;
754 if (NamedDecl *PartialPack
755 = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
756 MultiLevelTemplateArgumentList &TemplateArgs
757 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
758 unsigned Depth, Index;
759 std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
760 if (TemplateArgs.hasTemplateArgument(Depth, Index)) {
761 Result = TemplateArgs(Depth, Index);
762 TemplateArgs.setArgument(Depth, Index, TemplateArgument());
769 void RememberPartiallySubstitutedPack(TemplateArgument Arg) {
773 if (NamedDecl *PartialPack
774 = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
775 MultiLevelTemplateArgumentList &TemplateArgs
776 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
777 unsigned Depth, Index;
778 std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
779 TemplateArgs.setArgument(Depth, Index, Arg);
783 /// \brief Transform the given declaration by instantiating a reference to
784 /// this declaration.
785 Decl *TransformDecl(SourceLocation Loc, Decl *D);
787 void transformAttrs(Decl *Old, Decl *New) {
788 SemaRef.InstantiateAttrs(TemplateArgs, Old, New);
791 void transformedLocalDecl(Decl *Old, Decl *New) {
792 // If we've instantiated the call operator of a lambda or the call
793 // operator template of a generic lambda, update the "instantiation of"
795 auto *NewMD = dyn_cast<CXXMethodDecl>(New);
796 if (NewMD && isLambdaCallOperator(NewMD)) {
797 auto *OldMD = dyn_cast<CXXMethodDecl>(Old);
798 if (auto *NewTD = NewMD->getDescribedFunctionTemplate())
799 NewTD->setInstantiatedFromMemberTemplate(
800 OldMD->getDescribedFunctionTemplate());
802 NewMD->setInstantiationOfMemberFunction(OldMD,
803 TSK_ImplicitInstantiation);
806 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Old, New);
808 // We recreated a local declaration, but not by instantiating it. There
809 // may be pending dependent diagnostics to produce.
810 if (auto *DC = dyn_cast<DeclContext>(Old))
811 SemaRef.PerformDependentDiagnostics(DC, TemplateArgs);
814 /// \brief Transform the definition of the given declaration by
815 /// instantiating it.
816 Decl *TransformDefinition(SourceLocation Loc, Decl *D);
818 /// \brief Transform the first qualifier within a scope by instantiating the
820 NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc);
822 /// \brief Rebuild the exception declaration and register the declaration
823 /// as an instantiated local.
824 VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
825 TypeSourceInfo *Declarator,
826 SourceLocation StartLoc,
827 SourceLocation NameLoc,
828 IdentifierInfo *Name);
830 /// \brief Rebuild the Objective-C exception declaration and register the
831 /// declaration as an instantiated local.
832 VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
833 TypeSourceInfo *TSInfo, QualType T);
835 /// \brief Check for tag mismatches when instantiating an
837 QualType RebuildElaboratedType(SourceLocation KeywordLoc,
838 ElaboratedTypeKeyword Keyword,
839 NestedNameSpecifierLoc QualifierLoc,
843 TransformTemplateName(CXXScopeSpec &SS, TemplateName Name,
844 SourceLocation NameLoc,
845 QualType ObjectType = QualType(),
846 NamedDecl *FirstQualifierInScope = nullptr,
847 bool AllowInjectedClassName = false);
849 const LoopHintAttr *TransformLoopHintAttr(const LoopHintAttr *LH);
851 ExprResult TransformPredefinedExpr(PredefinedExpr *E);
852 ExprResult TransformDeclRefExpr(DeclRefExpr *E);
853 ExprResult TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E);
855 ExprResult TransformTemplateParmRefExpr(DeclRefExpr *E,
856 NonTypeTemplateParmDecl *D);
857 ExprResult TransformSubstNonTypeTemplateParmPackExpr(
858 SubstNonTypeTemplateParmPackExpr *E);
860 /// \brief Rebuild a DeclRefExpr for a ParmVarDecl reference.
861 ExprResult RebuildParmVarDeclRefExpr(ParmVarDecl *PD, SourceLocation Loc);
863 /// \brief Transform a reference to a function parameter pack.
864 ExprResult TransformFunctionParmPackRefExpr(DeclRefExpr *E,
867 /// \brief Transform a FunctionParmPackExpr which was built when we couldn't
868 /// expand a function parameter pack reference which refers to an expanded
870 ExprResult TransformFunctionParmPackExpr(FunctionParmPackExpr *E);
872 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
873 FunctionProtoTypeLoc TL) {
874 // Call the base version; it will forward to our overridden version below.
875 return inherited::TransformFunctionProtoType(TLB, TL);
878 template<typename Fn>
879 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
880 FunctionProtoTypeLoc TL,
881 CXXRecordDecl *ThisContext,
882 unsigned ThisTypeQuals,
883 Fn TransformExceptionSpec);
885 ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm,
887 Optional<unsigned> NumExpansions,
888 bool ExpectParameterPack);
890 /// \brief Transforms a template type parameter type by performing
891 /// substitution of the corresponding template type argument.
892 QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
893 TemplateTypeParmTypeLoc TL);
895 /// \brief Transforms an already-substituted template type parameter pack
896 /// into either itself (if we aren't substituting into its pack expansion)
897 /// or the appropriate substituted argument.
898 QualType TransformSubstTemplateTypeParmPackType(TypeLocBuilder &TLB,
899 SubstTemplateTypeParmPackTypeLoc TL);
901 ExprResult TransformLambdaExpr(LambdaExpr *E) {
902 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
903 return TreeTransform<TemplateInstantiator>::TransformLambdaExpr(E);
906 TemplateParameterList *TransformTemplateParameterList(
907 TemplateParameterList *OrigTPL) {
908 if (!OrigTPL || !OrigTPL->size()) return OrigTPL;
910 DeclContext *Owner = OrigTPL->getParam(0)->getDeclContext();
911 TemplateDeclInstantiator DeclInstantiator(getSema(),
912 /* DeclContext *Owner */ Owner, TemplateArgs);
913 return DeclInstantiator.SubstTemplateParams(OrigTPL);
916 ExprResult transformNonTypeTemplateParmRef(NonTypeTemplateParmDecl *parm,
918 TemplateArgument arg);
922 bool TemplateInstantiator::AlreadyTransformed(QualType T) {
926 if (T->isInstantiationDependentType() || T->isVariablyModifiedType())
929 getSema().MarkDeclarationsReferencedInType(Loc, T);
933 static TemplateArgument
934 getPackSubstitutedTemplateArgument(Sema &S, TemplateArgument Arg) {
935 assert(S.ArgumentPackSubstitutionIndex >= 0);
936 assert(S.ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
937 Arg = Arg.pack_begin()[S.ArgumentPackSubstitutionIndex];
938 if (Arg.isPackExpansion())
939 Arg = Arg.getPackExpansionPattern();
943 Decl *TemplateInstantiator::TransformDecl(SourceLocation Loc, Decl *D) {
947 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(D)) {
948 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
949 // If the corresponding template argument is NULL or non-existent, it's
950 // because we are performing instantiation from explicitly-specified
951 // template arguments in a function template, but there were some
952 // arguments left unspecified.
953 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
957 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
959 if (TTP->isParameterPack()) {
960 assert(Arg.getKind() == TemplateArgument::Pack &&
961 "Missing argument pack");
962 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
965 TemplateName Template = Arg.getAsTemplate();
966 assert(!Template.isNull() && Template.getAsTemplateDecl() &&
967 "Wrong kind of template template argument");
968 return Template.getAsTemplateDecl();
971 // Fall through to find the instantiated declaration for this template
972 // template parameter.
975 return SemaRef.FindInstantiatedDecl(Loc, cast<NamedDecl>(D), TemplateArgs);
978 Decl *TemplateInstantiator::TransformDefinition(SourceLocation Loc, Decl *D) {
979 Decl *Inst = getSema().SubstDecl(D, getSema().CurContext, TemplateArgs);
983 getSema().CurrentInstantiationScope->InstantiatedLocal(D, Inst);
988 TemplateInstantiator::TransformFirstQualifierInScope(NamedDecl *D,
989 SourceLocation Loc) {
990 // If the first part of the nested-name-specifier was a template type
991 // parameter, instantiate that type parameter down to a tag type.
992 if (TemplateTypeParmDecl *TTPD = dyn_cast_or_null<TemplateTypeParmDecl>(D)) {
993 const TemplateTypeParmType *TTP
994 = cast<TemplateTypeParmType>(getSema().Context.getTypeDeclType(TTPD));
996 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
997 // FIXME: This needs testing w/ member access expressions.
998 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getIndex());
1000 if (TTP->isParameterPack()) {
1001 assert(Arg.getKind() == TemplateArgument::Pack &&
1002 "Missing argument pack");
1004 if (getSema().ArgumentPackSubstitutionIndex == -1)
1007 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1010 QualType T = Arg.getAsType();
1012 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
1014 if (const TagType *Tag = T->getAs<TagType>())
1015 return Tag->getDecl();
1017 // The resulting type is not a tag; complain.
1018 getSema().Diag(Loc, diag::err_nested_name_spec_non_tag) << T;
1023 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
1027 TemplateInstantiator::RebuildExceptionDecl(VarDecl *ExceptionDecl,
1028 TypeSourceInfo *Declarator,
1029 SourceLocation StartLoc,
1030 SourceLocation NameLoc,
1031 IdentifierInfo *Name) {
1032 VarDecl *Var = inherited::RebuildExceptionDecl(ExceptionDecl, Declarator,
1033 StartLoc, NameLoc, Name);
1035 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
1039 VarDecl *TemplateInstantiator::RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
1040 TypeSourceInfo *TSInfo,
1042 VarDecl *Var = inherited::RebuildObjCExceptionDecl(ExceptionDecl, TSInfo, T);
1044 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
1049 TemplateInstantiator::RebuildElaboratedType(SourceLocation KeywordLoc,
1050 ElaboratedTypeKeyword Keyword,
1051 NestedNameSpecifierLoc QualifierLoc,
1053 if (const TagType *TT = T->getAs<TagType>()) {
1054 TagDecl* TD = TT->getDecl();
1056 SourceLocation TagLocation = KeywordLoc;
1058 IdentifierInfo *Id = TD->getIdentifier();
1060 // TODO: should we even warn on struct/class mismatches for this? Seems
1061 // like it's likely to produce a lot of spurious errors.
1062 if (Id && Keyword != ETK_None && Keyword != ETK_Typename) {
1063 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForKeyword(Keyword);
1064 if (!SemaRef.isAcceptableTagRedeclaration(TD, Kind, /*isDefinition*/false,
1066 SemaRef.Diag(TagLocation, diag::err_use_with_wrong_tag)
1068 << FixItHint::CreateReplacement(SourceRange(TagLocation),
1070 SemaRef.Diag(TD->getLocation(), diag::note_previous_use);
1075 return TreeTransform<TemplateInstantiator>::RebuildElaboratedType(KeywordLoc,
1081 TemplateName TemplateInstantiator::TransformTemplateName(
1082 CXXScopeSpec &SS, TemplateName Name, SourceLocation NameLoc,
1083 QualType ObjectType, NamedDecl *FirstQualifierInScope,
1084 bool AllowInjectedClassName) {
1085 if (TemplateTemplateParmDecl *TTP
1086 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl())) {
1087 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1088 // If the corresponding template argument is NULL or non-existent, it's
1089 // because we are performing instantiation from explicitly-specified
1090 // template arguments in a function template, but there were some
1091 // arguments left unspecified.
1092 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
1093 TTP->getPosition()))
1096 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
1098 if (TTP->isParameterPack()) {
1099 assert(Arg.getKind() == TemplateArgument::Pack &&
1100 "Missing argument pack");
1102 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1103 // We have the template argument pack to substitute, but we're not
1104 // actually expanding the enclosing pack expansion yet. So, just
1105 // keep the entire argument pack.
1106 return getSema().Context.getSubstTemplateTemplateParmPack(TTP, Arg);
1109 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1112 TemplateName Template = Arg.getAsTemplate();
1113 assert(!Template.isNull() && "Null template template argument");
1115 // We don't ever want to substitute for a qualified template name, since
1116 // the qualifier is handled separately. So, look through the qualified
1117 // template name to its underlying declaration.
1118 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
1119 Template = TemplateName(QTN->getTemplateDecl());
1121 Template = getSema().Context.getSubstTemplateTemplateParm(TTP, Template);
1126 if (SubstTemplateTemplateParmPackStorage *SubstPack
1127 = Name.getAsSubstTemplateTemplateParmPack()) {
1128 if (getSema().ArgumentPackSubstitutionIndex == -1)
1131 TemplateArgument Arg = SubstPack->getArgumentPack();
1132 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1133 return Arg.getAsTemplate();
1136 return inherited::TransformTemplateName(SS, Name, NameLoc, ObjectType,
1137 FirstQualifierInScope,
1138 AllowInjectedClassName);
1142 TemplateInstantiator::TransformPredefinedExpr(PredefinedExpr *E) {
1143 if (!E->isTypeDependent())
1146 return getSema().BuildPredefinedExpr(E->getLocation(), E->getIdentType());
1150 TemplateInstantiator::TransformTemplateParmRefExpr(DeclRefExpr *E,
1151 NonTypeTemplateParmDecl *NTTP) {
1152 // If the corresponding template argument is NULL or non-existent, it's
1153 // because we are performing instantiation from explicitly-specified
1154 // template arguments in a function template, but there were some
1155 // arguments left unspecified.
1156 if (!TemplateArgs.hasTemplateArgument(NTTP->getDepth(),
1157 NTTP->getPosition()))
1160 TemplateArgument Arg = TemplateArgs(NTTP->getDepth(), NTTP->getPosition());
1162 if (TemplateArgs.getNumLevels() != TemplateArgs.getNumSubstitutedLevels()) {
1163 // We're performing a partial substitution, so the substituted argument
1164 // could be dependent. As a result we can't create a SubstNonType*Expr
1165 // node now, since that represents a fully-substituted argument.
1166 // FIXME: We should have some AST representation for this.
1167 if (Arg.getKind() == TemplateArgument::Pack) {
1168 // FIXME: This won't work for alias templates.
1169 assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() &&
1170 "unexpected pack arguments in partial substitution");
1171 Arg = Arg.pack_begin()->getPackExpansionPattern();
1173 assert(Arg.getKind() == TemplateArgument::Expression &&
1174 "unexpected nontype template argument kind in partial substitution");
1175 return Arg.getAsExpr();
1178 if (NTTP->isParameterPack()) {
1179 assert(Arg.getKind() == TemplateArgument::Pack &&
1180 "Missing argument pack");
1182 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1183 // We have an argument pack, but we can't select a particular argument
1184 // out of it yet. Therefore, we'll build an expression to hold on to that
1186 QualType TargetType = SemaRef.SubstType(NTTP->getType(), TemplateArgs,
1188 NTTP->getDeclName());
1189 if (TargetType.isNull())
1192 return new (SemaRef.Context) SubstNonTypeTemplateParmPackExpr(TargetType,
1198 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1201 return transformNonTypeTemplateParmRef(NTTP, E->getLocation(), Arg);
1204 const LoopHintAttr *
1205 TemplateInstantiator::TransformLoopHintAttr(const LoopHintAttr *LH) {
1206 Expr *TransformedExpr = getDerived().TransformExpr(LH->getValue()).get();
1208 if (TransformedExpr == LH->getValue())
1211 // Generate error if there is a problem with the value.
1212 if (getSema().CheckLoopHintExpr(TransformedExpr, LH->getLocation()))
1215 // Create new LoopHintValueAttr with integral expression in place of the
1216 // non-type template parameter.
1217 return LoopHintAttr::CreateImplicit(
1218 getSema().Context, LH->getSemanticSpelling(), LH->getOption(),
1219 LH->getState(), TransformedExpr, LH->getRange());
1222 ExprResult TemplateInstantiator::transformNonTypeTemplateParmRef(
1223 NonTypeTemplateParmDecl *parm,
1225 TemplateArgument arg) {
1229 // The template argument itself might be an expression, in which
1230 // case we just return that expression.
1231 if (arg.getKind() == TemplateArgument::Expression) {
1232 Expr *argExpr = arg.getAsExpr();
1234 type = argExpr->getType();
1236 } else if (arg.getKind() == TemplateArgument::Declaration ||
1237 arg.getKind() == TemplateArgument::NullPtr) {
1239 if (arg.getKind() == TemplateArgument::Declaration) {
1240 VD = cast<ValueDecl>(arg.getAsDecl());
1242 // Find the instantiation of the template argument. This is
1243 // required for nested templates.
1244 VD = cast_or_null<ValueDecl>(
1245 getSema().FindInstantiatedDecl(loc, VD, TemplateArgs));
1249 // Propagate NULL template argument.
1253 // Derive the type we want the substituted decl to have. This had
1254 // better be non-dependent, or these checks will have serious problems.
1255 if (parm->isExpandedParameterPack()) {
1256 type = parm->getExpansionType(SemaRef.ArgumentPackSubstitutionIndex);
1257 } else if (parm->isParameterPack() &&
1258 isa<PackExpansionType>(parm->getType())) {
1259 type = SemaRef.SubstType(
1260 cast<PackExpansionType>(parm->getType())->getPattern(),
1261 TemplateArgs, loc, parm->getDeclName());
1263 type = SemaRef.SubstType(VD ? arg.getParamTypeForDecl() : arg.getNullPtrType(),
1264 TemplateArgs, loc, parm->getDeclName());
1266 assert(!type.isNull() && "type substitution failed for param type");
1267 assert(!type->isDependentType() && "param type still dependent");
1268 result = SemaRef.BuildExpressionFromDeclTemplateArgument(arg, type, loc);
1270 if (!result.isInvalid()) type = result.get()->getType();
1272 result = SemaRef.BuildExpressionFromIntegralTemplateArgument(arg, loc);
1274 // Note that this type can be different from the type of 'result',
1275 // e.g. if it's an enum type.
1276 type = arg.getIntegralType();
1278 if (result.isInvalid()) return ExprError();
1280 Expr *resultExpr = result.get();
1281 return new (SemaRef.Context) SubstNonTypeTemplateParmExpr(
1282 type, resultExpr->getValueKind(), loc, parm, resultExpr);
1286 TemplateInstantiator::TransformSubstNonTypeTemplateParmPackExpr(
1287 SubstNonTypeTemplateParmPackExpr *E) {
1288 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1289 // We aren't expanding the parameter pack, so just return ourselves.
1293 TemplateArgument Arg = E->getArgumentPack();
1294 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1295 return transformNonTypeTemplateParmRef(E->getParameterPack(),
1296 E->getParameterPackLocation(),
1301 TemplateInstantiator::RebuildParmVarDeclRefExpr(ParmVarDecl *PD,
1302 SourceLocation Loc) {
1303 DeclarationNameInfo NameInfo(PD->getDeclName(), Loc);
1304 return getSema().BuildDeclarationNameExpr(CXXScopeSpec(), NameInfo, PD);
1308 TemplateInstantiator::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {
1309 if (getSema().ArgumentPackSubstitutionIndex != -1) {
1310 // We can expand this parameter pack now.
1311 ParmVarDecl *D = E->getExpansion(getSema().ArgumentPackSubstitutionIndex);
1312 ValueDecl *VD = cast_or_null<ValueDecl>(TransformDecl(E->getExprLoc(), D));
1315 return RebuildParmVarDeclRefExpr(cast<ParmVarDecl>(VD), E->getExprLoc());
1318 QualType T = TransformType(E->getType());
1322 // Transform each of the parameter expansions into the corresponding
1323 // parameters in the instantiation of the function decl.
1324 SmallVector<ParmVarDecl *, 8> Parms;
1325 Parms.reserve(E->getNumExpansions());
1326 for (FunctionParmPackExpr::iterator I = E->begin(), End = E->end();
1329 cast_or_null<ParmVarDecl>(TransformDecl(E->getExprLoc(), *I));
1335 return FunctionParmPackExpr::Create(getSema().Context, T,
1336 E->getParameterPack(),
1337 E->getParameterPackLocation(), Parms);
1341 TemplateInstantiator::TransformFunctionParmPackRefExpr(DeclRefExpr *E,
1343 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
1344 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
1345 = getSema().CurrentInstantiationScope->findInstantiationOf(PD);
1346 assert(Found && "no instantiation for parameter pack");
1348 Decl *TransformedDecl;
1349 if (DeclArgumentPack *Pack = Found->dyn_cast<DeclArgumentPack *>()) {
1350 // If this is a reference to a function parameter pack which we can
1351 // substitute but can't yet expand, build a FunctionParmPackExpr for it.
1352 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1353 QualType T = TransformType(E->getType());
1356 return FunctionParmPackExpr::Create(getSema().Context, T, PD,
1357 E->getExprLoc(), *Pack);
1360 TransformedDecl = (*Pack)[getSema().ArgumentPackSubstitutionIndex];
1362 TransformedDecl = Found->get<Decl*>();
1365 // We have either an unexpanded pack or a specific expansion.
1366 return RebuildParmVarDeclRefExpr(cast<ParmVarDecl>(TransformedDecl),
1371 TemplateInstantiator::TransformDeclRefExpr(DeclRefExpr *E) {
1372 NamedDecl *D = E->getDecl();
1374 // Handle references to non-type template parameters and non-type template
1376 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) {
1377 if (NTTP->getDepth() < TemplateArgs.getNumLevels())
1378 return TransformTemplateParmRefExpr(E, NTTP);
1380 // We have a non-type template parameter that isn't fully substituted;
1381 // FindInstantiatedDecl will find it in the local instantiation scope.
1384 // Handle references to function parameter packs.
1385 if (ParmVarDecl *PD = dyn_cast<ParmVarDecl>(D))
1386 if (PD->isParameterPack())
1387 return TransformFunctionParmPackRefExpr(E, PD);
1389 return TreeTransform<TemplateInstantiator>::TransformDeclRefExpr(E);
1392 ExprResult TemplateInstantiator::TransformCXXDefaultArgExpr(
1393 CXXDefaultArgExpr *E) {
1394 assert(!cast<FunctionDecl>(E->getParam()->getDeclContext())->
1395 getDescribedFunctionTemplate() &&
1396 "Default arg expressions are never formed in dependent cases.");
1397 return SemaRef.BuildCXXDefaultArgExpr(E->getUsedLocation(),
1398 cast<FunctionDecl>(E->getParam()->getDeclContext()),
1402 template<typename Fn>
1403 QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB,
1404 FunctionProtoTypeLoc TL,
1405 CXXRecordDecl *ThisContext,
1406 unsigned ThisTypeQuals,
1407 Fn TransformExceptionSpec) {
1408 // We need a local instantiation scope for this function prototype.
1409 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
1410 return inherited::TransformFunctionProtoType(
1411 TLB, TL, ThisContext, ThisTypeQuals, TransformExceptionSpec);
1415 TemplateInstantiator::TransformFunctionTypeParam(ParmVarDecl *OldParm,
1416 int indexAdjustment,
1417 Optional<unsigned> NumExpansions,
1418 bool ExpectParameterPack) {
1419 return SemaRef.SubstParmVarDecl(OldParm, TemplateArgs, indexAdjustment,
1420 NumExpansions, ExpectParameterPack);
1424 TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB,
1425 TemplateTypeParmTypeLoc TL) {
1426 const TemplateTypeParmType *T = TL.getTypePtr();
1427 if (T->getDepth() < TemplateArgs.getNumLevels()) {
1428 // Replace the template type parameter with its corresponding
1429 // template argument.
1431 // If the corresponding template argument is NULL or doesn't exist, it's
1432 // because we are performing instantiation from explicitly-specified
1433 // template arguments in a function template class, but there were some
1434 // arguments left unspecified.
1435 if (!TemplateArgs.hasTemplateArgument(T->getDepth(), T->getIndex())) {
1436 TemplateTypeParmTypeLoc NewTL
1437 = TLB.push<TemplateTypeParmTypeLoc>(TL.getType());
1438 NewTL.setNameLoc(TL.getNameLoc());
1439 return TL.getType();
1442 TemplateArgument Arg = TemplateArgs(T->getDepth(), T->getIndex());
1444 if (T->isParameterPack()) {
1445 assert(Arg.getKind() == TemplateArgument::Pack &&
1446 "Missing argument pack");
1448 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1449 // We have the template argument pack, but we're not expanding the
1450 // enclosing pack expansion yet. Just save the template argument
1451 // pack for later substitution.
1453 = getSema().Context.getSubstTemplateTypeParmPackType(T, Arg);
1454 SubstTemplateTypeParmPackTypeLoc NewTL
1455 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(Result);
1456 NewTL.setNameLoc(TL.getNameLoc());
1460 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1463 assert(Arg.getKind() == TemplateArgument::Type &&
1464 "Template argument kind mismatch");
1466 QualType Replacement = Arg.getAsType();
1468 // TODO: only do this uniquing once, at the start of instantiation.
1470 = getSema().Context.getSubstTemplateTypeParmType(T, Replacement);
1471 SubstTemplateTypeParmTypeLoc NewTL
1472 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
1473 NewTL.setNameLoc(TL.getNameLoc());
1477 // The template type parameter comes from an inner template (e.g.,
1478 // the template parameter list of a member template inside the
1479 // template we are instantiating). Create a new template type
1480 // parameter with the template "level" reduced by one.
1481 TemplateTypeParmDecl *NewTTPDecl = nullptr;
1482 if (TemplateTypeParmDecl *OldTTPDecl = T->getDecl())
1483 NewTTPDecl = cast_or_null<TemplateTypeParmDecl>(
1484 TransformDecl(TL.getNameLoc(), OldTTPDecl));
1486 QualType Result = getSema().Context.getTemplateTypeParmType(
1487 T->getDepth() - TemplateArgs.getNumSubstitutedLevels(), T->getIndex(),
1488 T->isParameterPack(), NewTTPDecl);
1489 TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result);
1490 NewTL.setNameLoc(TL.getNameLoc());
1495 TemplateInstantiator::TransformSubstTemplateTypeParmPackType(
1496 TypeLocBuilder &TLB,
1497 SubstTemplateTypeParmPackTypeLoc TL) {
1498 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1499 // We aren't expanding the parameter pack, so just return ourselves.
1500 SubstTemplateTypeParmPackTypeLoc NewTL
1501 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(TL.getType());
1502 NewTL.setNameLoc(TL.getNameLoc());
1503 return TL.getType();
1506 TemplateArgument Arg = TL.getTypePtr()->getArgumentPack();
1507 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1508 QualType Result = Arg.getAsType();
1510 Result = getSema().Context.getSubstTemplateTypeParmType(
1511 TL.getTypePtr()->getReplacedParameter(),
1513 SubstTemplateTypeParmTypeLoc NewTL
1514 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
1515 NewTL.setNameLoc(TL.getNameLoc());
1519 /// \brief Perform substitution on the type T with a given set of template
1522 /// This routine substitutes the given template arguments into the
1523 /// type T and produces the instantiated type.
1525 /// \param T the type into which the template arguments will be
1526 /// substituted. If this type is not dependent, it will be returned
1529 /// \param Args the template arguments that will be
1530 /// substituted for the top-level template parameters within T.
1532 /// \param Loc the location in the source code where this substitution
1533 /// is being performed. It will typically be the location of the
1534 /// declarator (if we're instantiating the type of some declaration)
1535 /// or the location of the type in the source code (if, e.g., we're
1536 /// instantiating the type of a cast expression).
1538 /// \param Entity the name of the entity associated with a declaration
1539 /// being instantiated (if any). May be empty to indicate that there
1540 /// is no such entity (if, e.g., this is a type that occurs as part of
1541 /// a cast expression) or that the entity has no name (e.g., an
1542 /// unnamed function parameter).
1544 /// \param AllowDeducedTST Whether a DeducedTemplateSpecializationType is
1545 /// acceptable as the top level type of the result.
1547 /// \returns If the instantiation succeeds, the instantiated
1548 /// type. Otherwise, produces diagnostics and returns a NULL type.
1549 TypeSourceInfo *Sema::SubstType(TypeSourceInfo *T,
1550 const MultiLevelTemplateArgumentList &Args,
1552 DeclarationName Entity,
1553 bool AllowDeducedTST) {
1554 assert(!CodeSynthesisContexts.empty() &&
1555 "Cannot perform an instantiation without some context on the "
1556 "instantiation stack");
1558 if (!T->getType()->isInstantiationDependentType() &&
1559 !T->getType()->isVariablyModifiedType())
1562 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1563 return AllowDeducedTST ? Instantiator.TransformTypeWithDeducedTST(T)
1564 : Instantiator.TransformType(T);
1567 TypeSourceInfo *Sema::SubstType(TypeLoc TL,
1568 const MultiLevelTemplateArgumentList &Args,
1570 DeclarationName Entity) {
1571 assert(!CodeSynthesisContexts.empty() &&
1572 "Cannot perform an instantiation without some context on the "
1573 "instantiation stack");
1575 if (TL.getType().isNull())
1578 if (!TL.getType()->isInstantiationDependentType() &&
1579 !TL.getType()->isVariablyModifiedType()) {
1580 // FIXME: Make a copy of the TypeLoc data here, so that we can
1581 // return a new TypeSourceInfo. Inefficient!
1583 TLB.pushFullCopy(TL);
1584 return TLB.getTypeSourceInfo(Context, TL.getType());
1587 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1589 TLB.reserve(TL.getFullDataSize());
1590 QualType Result = Instantiator.TransformType(TLB, TL);
1591 if (Result.isNull())
1594 return TLB.getTypeSourceInfo(Context, Result);
1597 /// Deprecated form of the above.
1598 QualType Sema::SubstType(QualType T,
1599 const MultiLevelTemplateArgumentList &TemplateArgs,
1600 SourceLocation Loc, DeclarationName Entity) {
1601 assert(!CodeSynthesisContexts.empty() &&
1602 "Cannot perform an instantiation without some context on the "
1603 "instantiation stack");
1605 // If T is not a dependent type or a variably-modified type, there
1606 // is nothing to do.
1607 if (!T->isInstantiationDependentType() && !T->isVariablyModifiedType())
1610 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity);
1611 return Instantiator.TransformType(T);
1614 static bool NeedsInstantiationAsFunctionType(TypeSourceInfo *T) {
1615 if (T->getType()->isInstantiationDependentType() ||
1616 T->getType()->isVariablyModifiedType())
1619 TypeLoc TL = T->getTypeLoc().IgnoreParens();
1620 if (!TL.getAs<FunctionProtoTypeLoc>())
1623 FunctionProtoTypeLoc FP = TL.castAs<FunctionProtoTypeLoc>();
1624 for (ParmVarDecl *P : FP.getParams()) {
1625 // This must be synthesized from a typedef.
1628 // If there are any parameters, a new TypeSourceInfo that refers to the
1629 // instantiated parameters must be built.
1636 /// A form of SubstType intended specifically for instantiating the
1637 /// type of a FunctionDecl. Its purpose is solely to force the
1638 /// instantiation of default-argument expressions and to avoid
1639 /// instantiating an exception-specification.
1640 TypeSourceInfo *Sema::SubstFunctionDeclType(TypeSourceInfo *T,
1641 const MultiLevelTemplateArgumentList &Args,
1643 DeclarationName Entity,
1644 CXXRecordDecl *ThisContext,
1645 unsigned ThisTypeQuals) {
1646 assert(!CodeSynthesisContexts.empty() &&
1647 "Cannot perform an instantiation without some context on the "
1648 "instantiation stack");
1650 if (!NeedsInstantiationAsFunctionType(T))
1653 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1657 TypeLoc TL = T->getTypeLoc();
1658 TLB.reserve(TL.getFullDataSize());
1662 if (FunctionProtoTypeLoc Proto =
1663 TL.IgnoreParens().getAs<FunctionProtoTypeLoc>()) {
1664 // Instantiate the type, other than its exception specification. The
1665 // exception specification is instantiated in InitFunctionInstantiation
1666 // once we've built the FunctionDecl.
1667 // FIXME: Set the exception specification to EST_Uninstantiated here,
1668 // instead of rebuilding the function type again later.
1669 Result = Instantiator.TransformFunctionProtoType(
1670 TLB, Proto, ThisContext, ThisTypeQuals,
1671 [](FunctionProtoType::ExceptionSpecInfo &ESI,
1672 bool &Changed) { return false; });
1674 Result = Instantiator.TransformType(TLB, TL);
1676 if (Result.isNull())
1679 return TLB.getTypeSourceInfo(Context, Result);
1682 void Sema::SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto,
1683 const MultiLevelTemplateArgumentList &Args) {
1684 FunctionProtoType::ExceptionSpecInfo ESI =
1685 Proto->getExtProtoInfo().ExceptionSpec;
1686 assert(ESI.Type != EST_Uninstantiated);
1688 TemplateInstantiator Instantiator(*this, Args, New->getLocation(),
1689 New->getDeclName());
1691 SmallVector<QualType, 4> ExceptionStorage;
1692 bool Changed = false;
1693 if (Instantiator.TransformExceptionSpec(
1694 New->getTypeSourceInfo()->getTypeLoc().getLocEnd(), ESI,
1695 ExceptionStorage, Changed))
1696 // On error, recover by dropping the exception specification.
1697 ESI.Type = EST_None;
1699 UpdateExceptionSpec(New, ESI);
1702 ParmVarDecl *Sema::SubstParmVarDecl(ParmVarDecl *OldParm,
1703 const MultiLevelTemplateArgumentList &TemplateArgs,
1704 int indexAdjustment,
1705 Optional<unsigned> NumExpansions,
1706 bool ExpectParameterPack) {
1707 TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
1708 TypeSourceInfo *NewDI = nullptr;
1710 TypeLoc OldTL = OldDI->getTypeLoc();
1711 if (PackExpansionTypeLoc ExpansionTL = OldTL.getAs<PackExpansionTypeLoc>()) {
1713 // We have a function parameter pack. Substitute into the pattern of the
1715 NewDI = SubstType(ExpansionTL.getPatternLoc(), TemplateArgs,
1716 OldParm->getLocation(), OldParm->getDeclName());
1720 if (NewDI->getType()->containsUnexpandedParameterPack()) {
1721 // We still have unexpanded parameter packs, which means that
1722 // our function parameter is still a function parameter pack.
1723 // Therefore, make its type a pack expansion type.
1724 NewDI = CheckPackExpansion(NewDI, ExpansionTL.getEllipsisLoc(),
1726 } else if (ExpectParameterPack) {
1727 // We expected to get a parameter pack but didn't (because the type
1728 // itself is not a pack expansion type), so complain. This can occur when
1729 // the substitution goes through an alias template that "loses" the
1731 Diag(OldParm->getLocation(),
1732 diag::err_function_parameter_pack_without_parameter_packs)
1733 << NewDI->getType();
1737 NewDI = SubstType(OldDI, TemplateArgs, OldParm->getLocation(),
1738 OldParm->getDeclName());
1744 if (NewDI->getType()->isVoidType()) {
1745 Diag(OldParm->getLocation(), diag::err_param_with_void_type);
1749 ParmVarDecl *NewParm = CheckParameter(Context.getTranslationUnitDecl(),
1750 OldParm->getInnerLocStart(),
1751 OldParm->getLocation(),
1752 OldParm->getIdentifier(),
1753 NewDI->getType(), NewDI,
1754 OldParm->getStorageClass());
1758 // Mark the (new) default argument as uninstantiated (if any).
1759 if (OldParm->hasUninstantiatedDefaultArg()) {
1760 Expr *Arg = OldParm->getUninstantiatedDefaultArg();
1761 NewParm->setUninstantiatedDefaultArg(Arg);
1762 } else if (OldParm->hasUnparsedDefaultArg()) {
1763 NewParm->setUnparsedDefaultArg();
1764 UnparsedDefaultArgInstantiations[OldParm].push_back(NewParm);
1765 } else if (Expr *Arg = OldParm->getDefaultArg()) {
1766 FunctionDecl *OwningFunc = cast<FunctionDecl>(OldParm->getDeclContext());
1767 if (OwningFunc->isLexicallyWithinFunctionOrMethod()) {
1768 // Instantiate default arguments for methods of local classes (DR1484)
1769 // and non-defining declarations.
1770 Sema::ContextRAII SavedContext(*this, OwningFunc);
1771 LocalInstantiationScope Local(*this, true);
1772 ExprResult NewArg = SubstExpr(Arg, TemplateArgs);
1773 if (NewArg.isUsable()) {
1774 // It would be nice if we still had this.
1775 SourceLocation EqualLoc = NewArg.get()->getLocStart();
1776 SetParamDefaultArgument(NewParm, NewArg.get(), EqualLoc);
1779 // FIXME: if we non-lazily instantiated non-dependent default args for
1780 // non-dependent parameter types we could remove a bunch of duplicate
1781 // conversion warnings for such arguments.
1782 NewParm->setUninstantiatedDefaultArg(Arg);
1786 NewParm->setHasInheritedDefaultArg(OldParm->hasInheritedDefaultArg());
1788 if (OldParm->isParameterPack() && !NewParm->isParameterPack()) {
1789 // Add the new parameter to the instantiated parameter pack.
1790 CurrentInstantiationScope->InstantiatedLocalPackArg(OldParm, NewParm);
1792 // Introduce an Old -> New mapping
1793 CurrentInstantiationScope->InstantiatedLocal(OldParm, NewParm);
1796 // FIXME: OldParm may come from a FunctionProtoType, in which case CurContext
1797 // can be anything, is this right ?
1798 NewParm->setDeclContext(CurContext);
1800 NewParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
1801 OldParm->getFunctionScopeIndex() + indexAdjustment);
1803 InstantiateAttrs(TemplateArgs, OldParm, NewParm);
1808 /// \brief Substitute the given template arguments into the given set of
1809 /// parameters, producing the set of parameter types that would be generated
1810 /// from such a substitution.
1811 bool Sema::SubstParmTypes(
1812 SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
1813 const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
1814 const MultiLevelTemplateArgumentList &TemplateArgs,
1815 SmallVectorImpl<QualType> &ParamTypes,
1816 SmallVectorImpl<ParmVarDecl *> *OutParams,
1817 ExtParameterInfoBuilder &ParamInfos) {
1818 assert(!CodeSynthesisContexts.empty() &&
1819 "Cannot perform an instantiation without some context on the "
1820 "instantiation stack");
1822 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
1824 return Instantiator.TransformFunctionTypeParams(
1825 Loc, Params, nullptr, ExtParamInfos, ParamTypes, OutParams, ParamInfos);
1828 /// \brief Perform substitution on the base class specifiers of the
1829 /// given class template specialization.
1831 /// Produces a diagnostic and returns true on error, returns false and
1832 /// attaches the instantiated base classes to the class template
1833 /// specialization if successful.
1835 Sema::SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
1836 CXXRecordDecl *Pattern,
1837 const MultiLevelTemplateArgumentList &TemplateArgs) {
1838 bool Invalid = false;
1839 SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases;
1840 for (const auto &Base : Pattern->bases()) {
1841 if (!Base.getType()->isDependentType()) {
1842 if (const CXXRecordDecl *RD = Base.getType()->getAsCXXRecordDecl()) {
1843 if (RD->isInvalidDecl())
1844 Instantiation->setInvalidDecl();
1846 InstantiatedBases.push_back(new (Context) CXXBaseSpecifier(Base));
1850 SourceLocation EllipsisLoc;
1851 TypeSourceInfo *BaseTypeLoc;
1852 if (Base.isPackExpansion()) {
1853 // This is a pack expansion. See whether we should expand it now, or
1854 // wait until later.
1855 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
1856 collectUnexpandedParameterPacks(Base.getTypeSourceInfo()->getTypeLoc(),
1858 bool ShouldExpand = false;
1859 bool RetainExpansion = false;
1860 Optional<unsigned> NumExpansions;
1861 if (CheckParameterPacksForExpansion(Base.getEllipsisLoc(),
1862 Base.getSourceRange(),
1864 TemplateArgs, ShouldExpand,
1871 // If we should expand this pack expansion now, do so.
1873 for (unsigned I = 0; I != *NumExpansions; ++I) {
1874 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
1876 TypeSourceInfo *BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
1878 Base.getSourceRange().getBegin(),
1885 if (CXXBaseSpecifier *InstantiatedBase
1886 = CheckBaseSpecifier(Instantiation,
1887 Base.getSourceRange(),
1889 Base.getAccessSpecifierAsWritten(),
1892 InstantiatedBases.push_back(InstantiatedBase);
1900 // The resulting base specifier will (still) be a pack expansion.
1901 EllipsisLoc = Base.getEllipsisLoc();
1902 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
1903 BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
1905 Base.getSourceRange().getBegin(),
1908 BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
1910 Base.getSourceRange().getBegin(),
1919 if (CXXBaseSpecifier *InstantiatedBase
1920 = CheckBaseSpecifier(Instantiation,
1921 Base.getSourceRange(),
1923 Base.getAccessSpecifierAsWritten(),
1926 InstantiatedBases.push_back(InstantiatedBase);
1931 if (!Invalid && AttachBaseSpecifiers(Instantiation, InstantiatedBases))
1937 // Defined via #include from SemaTemplateInstantiateDecl.cpp
1940 Attr *instantiateTemplateAttribute(const Attr *At, ASTContext &C, Sema &S,
1941 const MultiLevelTemplateArgumentList &TemplateArgs);
1942 Attr *instantiateTemplateAttributeForDecl(
1943 const Attr *At, ASTContext &C, Sema &S,
1944 const MultiLevelTemplateArgumentList &TemplateArgs);
1948 /// \brief Instantiate the definition of a class from a given pattern.
1950 /// \param PointOfInstantiation The point of instantiation within the
1953 /// \param Instantiation is the declaration whose definition is being
1954 /// instantiated. This will be either a class template specialization
1955 /// or a member class of a class template specialization.
1957 /// \param Pattern is the pattern from which the instantiation
1958 /// occurs. This will be either the declaration of a class template or
1959 /// the declaration of a member class of a class template.
1961 /// \param TemplateArgs The template arguments to be substituted into
1964 /// \param TSK the kind of implicit or explicit instantiation to perform.
1966 /// \param Complain whether to complain if the class cannot be instantiated due
1967 /// to the lack of a definition.
1969 /// \returns true if an error occurred, false otherwise.
1971 Sema::InstantiateClass(SourceLocation PointOfInstantiation,
1972 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
1973 const MultiLevelTemplateArgumentList &TemplateArgs,
1974 TemplateSpecializationKind TSK,
1976 CXXRecordDecl *PatternDef
1977 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
1978 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
1979 Instantiation->getInstantiatedFromMemberClass(),
1980 Pattern, PatternDef, TSK, Complain))
1982 Pattern = PatternDef;
1984 // \brief Record the point of instantiation.
1985 if (MemberSpecializationInfo *MSInfo
1986 = Instantiation->getMemberSpecializationInfo()) {
1987 MSInfo->setTemplateSpecializationKind(TSK);
1988 MSInfo->setPointOfInstantiation(PointOfInstantiation);
1989 } else if (ClassTemplateSpecializationDecl *Spec
1990 = dyn_cast<ClassTemplateSpecializationDecl>(Instantiation)) {
1991 Spec->setTemplateSpecializationKind(TSK);
1992 Spec->setPointOfInstantiation(PointOfInstantiation);
1995 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
1996 if (Inst.isInvalid())
1998 assert(!Inst.isAlreadyInstantiating() && "should have been caught by caller");
1999 PrettyDeclStackTraceEntry CrashInfo(*this, Instantiation, SourceLocation(),
2000 "instantiating class definition");
2002 // Enter the scope of this instantiation. We don't use
2003 // PushDeclContext because we don't have a scope.
2004 ContextRAII SavedContext(*this, Instantiation);
2005 EnterExpressionEvaluationContext EvalContext(
2006 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
2008 // If this is an instantiation of a local class, merge this local
2009 // instantiation scope with the enclosing scope. Otherwise, every
2010 // instantiation of a class has its own local instantiation scope.
2011 bool MergeWithParentScope = !Instantiation->isDefinedOutsideFunctionOrMethod();
2012 LocalInstantiationScope Scope(*this, MergeWithParentScope);
2014 // All dllexported classes created during instantiation should be fully
2015 // emitted after instantiation completes. We may not be ready to emit any
2016 // delayed classes already on the stack, so save them away and put them back
2018 decltype(DelayedDllExportClasses) ExportedClasses;
2019 std::swap(ExportedClasses, DelayedDllExportClasses);
2021 // Pull attributes from the pattern onto the instantiation.
2022 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
2024 // Start the definition of this instantiation.
2025 Instantiation->startDefinition();
2027 // The instantiation is visible here, even if it was first declared in an
2028 // unimported module.
2029 Instantiation->setHidden(false);
2031 // FIXME: This loses the as-written tag kind for an explicit instantiation.
2032 Instantiation->setTagKind(Pattern->getTagKind());
2034 // Do substitution on the base class specifiers.
2035 if (SubstBaseSpecifiers(Instantiation, Pattern, TemplateArgs))
2036 Instantiation->setInvalidDecl();
2038 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
2039 SmallVector<Decl*, 4> Fields;
2040 // Delay instantiation of late parsed attributes.
2041 LateInstantiatedAttrVec LateAttrs;
2042 Instantiator.enableLateAttributeInstantiation(&LateAttrs);
2044 for (auto *Member : Pattern->decls()) {
2045 // Don't instantiate members not belonging in this semantic context.
2048 // template <int i> class A {
2052 // 'class B' has the template as lexical context but semantically it is
2053 // introduced in namespace scope.
2054 if (Member->getDeclContext() != Pattern)
2057 if (Member->isInvalidDecl()) {
2058 Instantiation->setInvalidDecl();
2062 Decl *NewMember = Instantiator.Visit(Member);
2064 if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember)) {
2065 Fields.push_back(Field);
2066 } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(NewMember)) {
2067 // C++11 [temp.inst]p1: The implicit instantiation of a class template
2068 // specialization causes the implicit instantiation of the definitions
2069 // of unscoped member enumerations.
2070 // Record a point of instantiation for this implicit instantiation.
2071 if (TSK == TSK_ImplicitInstantiation && !Enum->isScoped() &&
2072 Enum->isCompleteDefinition()) {
2073 MemberSpecializationInfo *MSInfo =Enum->getMemberSpecializationInfo();
2074 assert(MSInfo && "no spec info for member enum specialization");
2075 MSInfo->setTemplateSpecializationKind(TSK_ImplicitInstantiation);
2076 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2078 } else if (StaticAssertDecl *SA = dyn_cast<StaticAssertDecl>(NewMember)) {
2079 if (SA->isFailed()) {
2080 // A static_assert failed. Bail out; instantiating this
2081 // class is probably not meaningful.
2082 Instantiation->setInvalidDecl();
2087 if (NewMember->isInvalidDecl())
2088 Instantiation->setInvalidDecl();
2090 // FIXME: Eventually, a NULL return will mean that one of the
2091 // instantiations was a semantic disaster, and we'll want to mark the
2092 // declaration invalid.
2093 // For now, we expect to skip some members that we can't yet handle.
2097 // Finish checking fields.
2098 ActOnFields(nullptr, Instantiation->getLocation(), Instantiation, Fields,
2099 SourceLocation(), SourceLocation(), nullptr);
2100 CheckCompletedCXXClass(Instantiation);
2102 // Default arguments are parsed, if not instantiated. We can go instantiate
2103 // default arg exprs for default constructors if necessary now.
2104 ActOnFinishCXXNonNestedClass(Instantiation);
2106 // Put back the delayed exported classes that we moved out of the way.
2107 std::swap(ExportedClasses, DelayedDllExportClasses);
2109 // Instantiate late parsed attributes, and attach them to their decls.
2110 // See Sema::InstantiateAttrs
2111 for (LateInstantiatedAttrVec::iterator I = LateAttrs.begin(),
2112 E = LateAttrs.end(); I != E; ++I) {
2113 assert(CurrentInstantiationScope == Instantiator.getStartingScope());
2114 CurrentInstantiationScope = I->Scope;
2116 // Allow 'this' within late-parsed attributes.
2117 NamedDecl *ND = dyn_cast<NamedDecl>(I->NewDecl);
2118 CXXRecordDecl *ThisContext =
2119 dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
2120 CXXThisScopeRAII ThisScope(*this, ThisContext, /*TypeQuals*/0,
2121 ND && ND->isCXXInstanceMember());
2124 instantiateTemplateAttribute(I->TmplAttr, Context, *this, TemplateArgs);
2125 I->NewDecl->addAttr(NewAttr);
2126 LocalInstantiationScope::deleteScopes(I->Scope,
2127 Instantiator.getStartingScope());
2129 Instantiator.disableLateAttributeInstantiation();
2132 ActOnFinishDelayedMemberInitializers(Instantiation);
2134 // FIXME: We should do something similar for explicit instantiations so they
2135 // end up in the right module.
2136 if (TSK == TSK_ImplicitInstantiation) {
2137 Instantiation->setLocation(Pattern->getLocation());
2138 Instantiation->setLocStart(Pattern->getInnerLocStart());
2139 Instantiation->setBraceRange(Pattern->getBraceRange());
2142 if (!Instantiation->isInvalidDecl()) {
2143 // Perform any dependent diagnostics from the pattern.
2144 PerformDependentDiagnostics(Pattern, TemplateArgs);
2146 // Instantiate any out-of-line class template partial
2147 // specializations now.
2148 for (TemplateDeclInstantiator::delayed_partial_spec_iterator
2149 P = Instantiator.delayed_partial_spec_begin(),
2150 PEnd = Instantiator.delayed_partial_spec_end();
2152 if (!Instantiator.InstantiateClassTemplatePartialSpecialization(
2153 P->first, P->second)) {
2154 Instantiation->setInvalidDecl();
2159 // Instantiate any out-of-line variable template partial
2160 // specializations now.
2161 for (TemplateDeclInstantiator::delayed_var_partial_spec_iterator
2162 P = Instantiator.delayed_var_partial_spec_begin(),
2163 PEnd = Instantiator.delayed_var_partial_spec_end();
2165 if (!Instantiator.InstantiateVarTemplatePartialSpecialization(
2166 P->first, P->second)) {
2167 Instantiation->setInvalidDecl();
2173 // Exit the scope of this instantiation.
2176 if (!Instantiation->isInvalidDecl()) {
2177 Consumer.HandleTagDeclDefinition(Instantiation);
2179 // Always emit the vtable for an explicit instantiation definition
2180 // of a polymorphic class template specialization.
2181 if (TSK == TSK_ExplicitInstantiationDefinition)
2182 MarkVTableUsed(PointOfInstantiation, Instantiation, true);
2185 return Instantiation->isInvalidDecl();
2188 /// \brief Instantiate the definition of an enum from a given pattern.
2190 /// \param PointOfInstantiation The point of instantiation within the
2192 /// \param Instantiation is the declaration whose definition is being
2193 /// instantiated. This will be a member enumeration of a class
2194 /// temploid specialization, or a local enumeration within a
2195 /// function temploid specialization.
2196 /// \param Pattern The templated declaration from which the instantiation
2198 /// \param TemplateArgs The template arguments to be substituted into
2200 /// \param TSK The kind of implicit or explicit instantiation to perform.
2202 /// \return \c true if an error occurred, \c false otherwise.
2203 bool Sema::InstantiateEnum(SourceLocation PointOfInstantiation,
2204 EnumDecl *Instantiation, EnumDecl *Pattern,
2205 const MultiLevelTemplateArgumentList &TemplateArgs,
2206 TemplateSpecializationKind TSK) {
2207 EnumDecl *PatternDef = Pattern->getDefinition();
2208 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
2209 Instantiation->getInstantiatedFromMemberEnum(),
2210 Pattern, PatternDef, TSK,/*Complain*/true))
2212 Pattern = PatternDef;
2214 // Record the point of instantiation.
2215 if (MemberSpecializationInfo *MSInfo
2216 = Instantiation->getMemberSpecializationInfo()) {
2217 MSInfo->setTemplateSpecializationKind(TSK);
2218 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2221 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
2222 if (Inst.isInvalid())
2224 if (Inst.isAlreadyInstantiating())
2226 PrettyDeclStackTraceEntry CrashInfo(*this, Instantiation, SourceLocation(),
2227 "instantiating enum definition");
2229 // The instantiation is visible here, even if it was first declared in an
2230 // unimported module.
2231 Instantiation->setHidden(false);
2233 // Enter the scope of this instantiation. We don't use
2234 // PushDeclContext because we don't have a scope.
2235 ContextRAII SavedContext(*this, Instantiation);
2236 EnterExpressionEvaluationContext EvalContext(
2237 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
2239 LocalInstantiationScope Scope(*this, /*MergeWithParentScope*/true);
2241 // Pull attributes from the pattern onto the instantiation.
2242 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
2244 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
2245 Instantiator.InstantiateEnumDefinition(Instantiation, Pattern);
2247 // Exit the scope of this instantiation.
2250 return Instantiation->isInvalidDecl();
2254 /// \brief Instantiate the definition of a field from the given pattern.
2256 /// \param PointOfInstantiation The point of instantiation within the
2258 /// \param Instantiation is the declaration whose definition is being
2259 /// instantiated. This will be a class of a class temploid
2260 /// specialization, or a local enumeration within a function temploid
2262 /// \param Pattern The templated declaration from which the instantiation
2264 /// \param TemplateArgs The template arguments to be substituted into
2267 /// \return \c true if an error occurred, \c false otherwise.
2268 bool Sema::InstantiateInClassInitializer(
2269 SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
2270 FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs) {
2271 // If there is no initializer, we don't need to do anything.
2272 if (!Pattern->hasInClassInitializer())
2275 assert(Instantiation->getInClassInitStyle() ==
2276 Pattern->getInClassInitStyle() &&
2277 "pattern and instantiation disagree about init style");
2279 // Error out if we haven't parsed the initializer of the pattern yet because
2280 // we are waiting for the closing brace of the outer class.
2281 Expr *OldInit = Pattern->getInClassInitializer();
2283 RecordDecl *PatternRD = Pattern->getParent();
2284 RecordDecl *OutermostClass = PatternRD->getOuterLexicalRecordContext();
2285 Diag(PointOfInstantiation,
2286 diag::err_in_class_initializer_not_yet_parsed)
2287 << OutermostClass << Pattern;
2288 Diag(Pattern->getLocEnd(), diag::note_in_class_initializer_not_yet_parsed);
2289 Instantiation->setInvalidDecl();
2293 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
2294 if (Inst.isInvalid())
2296 if (Inst.isAlreadyInstantiating()) {
2297 // Error out if we hit an instantiation cycle for this initializer.
2298 Diag(PointOfInstantiation, diag::err_in_class_initializer_cycle)
2302 PrettyDeclStackTraceEntry CrashInfo(*this, Instantiation, SourceLocation(),
2303 "instantiating default member init");
2305 // Enter the scope of this instantiation. We don't use PushDeclContext because
2306 // we don't have a scope.
2307 ContextRAII SavedContext(*this, Instantiation->getParent());
2308 EnterExpressionEvaluationContext EvalContext(
2309 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
2311 LocalInstantiationScope Scope(*this, true);
2313 // Instantiate the initializer.
2314 ActOnStartCXXInClassMemberInitializer();
2315 CXXThisScopeRAII ThisScope(*this, Instantiation->getParent(), /*TypeQuals=*/0);
2317 ExprResult NewInit = SubstInitializer(OldInit, TemplateArgs,
2318 /*CXXDirectInit=*/false);
2319 Expr *Init = NewInit.get();
2320 assert((!Init || !isa<ParenListExpr>(Init)) && "call-style init in class");
2321 ActOnFinishCXXInClassMemberInitializer(
2322 Instantiation, Init ? Init->getLocStart() : SourceLocation(), Init);
2324 if (auto *L = getASTMutationListener())
2325 L->DefaultMemberInitializerInstantiated(Instantiation);
2327 // Return true if the in-class initializer is still missing.
2328 return !Instantiation->getInClassInitializer();
2332 /// \brief A partial specialization whose template arguments have matched
2333 /// a given template-id.
2334 struct PartialSpecMatchResult {
2335 ClassTemplatePartialSpecializationDecl *Partial;
2336 TemplateArgumentList *Args;
2340 /// Get the instantiation pattern to use to instantiate the definition of a
2341 /// given ClassTemplateSpecializationDecl (either the pattern of the primary
2342 /// template or of a partial specialization).
2343 static CXXRecordDecl *
2344 getPatternForClassTemplateSpecialization(
2345 Sema &S, SourceLocation PointOfInstantiation,
2346 ClassTemplateSpecializationDecl *ClassTemplateSpec,
2347 TemplateSpecializationKind TSK, bool Complain) {
2348 Sema::InstantiatingTemplate Inst(S, PointOfInstantiation, ClassTemplateSpec);
2349 if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
2352 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
2353 CXXRecordDecl *Pattern = nullptr;
2355 // C++ [temp.class.spec.match]p1:
2356 // When a class template is used in a context that requires an
2357 // instantiation of the class, it is necessary to determine
2358 // whether the instantiation is to be generated using the primary
2359 // template or one of the partial specializations. This is done by
2360 // matching the template arguments of the class template
2361 // specialization with the template argument lists of the partial
2363 typedef PartialSpecMatchResult MatchResult;
2364 SmallVector<MatchResult, 4> Matched;
2365 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
2366 Template->getPartialSpecializations(PartialSpecs);
2367 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation);
2368 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
2369 ClassTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
2370 TemplateDeductionInfo Info(FailedCandidates.getLocation());
2371 if (Sema::TemplateDeductionResult Result = S.DeduceTemplateArguments(
2372 Partial, ClassTemplateSpec->getTemplateArgs(), Info)) {
2373 // Store the failed-deduction information for use in diagnostics, later.
2374 // TODO: Actually use the failed-deduction info?
2375 FailedCandidates.addCandidate().set(
2376 DeclAccessPair::make(Template, AS_public), Partial,
2377 MakeDeductionFailureInfo(S.Context, Result, Info));
2380 Matched.push_back(PartialSpecMatchResult());
2381 Matched.back().Partial = Partial;
2382 Matched.back().Args = Info.take();
2386 // If we're dealing with a member template where the template parameters
2387 // have been instantiated, this provides the original template parameters
2388 // from which the member template's parameters were instantiated.
2390 if (Matched.size() >= 1) {
2391 SmallVectorImpl<MatchResult>::iterator Best = Matched.begin();
2392 if (Matched.size() == 1) {
2393 // -- If exactly one matching specialization is found, the
2394 // instantiation is generated from that specialization.
2395 // We don't need to do anything for this.
2397 // -- If more than one matching specialization is found, the
2398 // partial order rules (14.5.4.2) are used to determine
2399 // whether one of the specializations is more specialized
2400 // than the others. If none of the specializations is more
2401 // specialized than all of the other matching
2402 // specializations, then the use of the class template is
2403 // ambiguous and the program is ill-formed.
2404 for (SmallVectorImpl<MatchResult>::iterator P = Best + 1,
2405 PEnd = Matched.end();
2407 if (S.getMoreSpecializedPartialSpecialization(
2408 P->Partial, Best->Partial, PointOfInstantiation) == P->Partial)
2412 // Determine if the best partial specialization is more specialized than
2414 bool Ambiguous = false;
2415 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
2416 PEnd = Matched.end();
2419 S.getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
2420 PointOfInstantiation) !=
2428 // Partial ordering did not produce a clear winner. Complain.
2430 ClassTemplateSpec->setInvalidDecl();
2431 S.Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
2432 << ClassTemplateSpec;
2434 // Print the matching partial specializations.
2435 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
2436 PEnd = Matched.end();
2438 S.Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
2439 << S.getTemplateArgumentBindingsText(
2440 P->Partial->getTemplateParameters(), *P->Args);
2446 // Instantiate using the best class template partial specialization.
2447 ClassTemplatePartialSpecializationDecl *OrigPartialSpec = Best->Partial;
2448 while (OrigPartialSpec->getInstantiatedFromMember()) {
2449 // If we've found an explicit specialization of this class template,
2450 // stop here and use that as the pattern.
2451 if (OrigPartialSpec->isMemberSpecialization())
2454 OrigPartialSpec = OrigPartialSpec->getInstantiatedFromMember();
2457 Pattern = OrigPartialSpec;
2458 ClassTemplateSpec->setInstantiationOf(Best->Partial, Best->Args);
2460 // -- If no matches are found, the instantiation is generated
2461 // from the primary template.
2462 ClassTemplateDecl *OrigTemplate = Template;
2463 while (OrigTemplate->getInstantiatedFromMemberTemplate()) {
2464 // If we've found an explicit specialization of this class template,
2465 // stop here and use that as the pattern.
2466 if (OrigTemplate->isMemberSpecialization())
2469 OrigTemplate = OrigTemplate->getInstantiatedFromMemberTemplate();
2472 Pattern = OrigTemplate->getTemplatedDecl();
2478 bool Sema::InstantiateClassTemplateSpecialization(
2479 SourceLocation PointOfInstantiation,
2480 ClassTemplateSpecializationDecl *ClassTemplateSpec,
2481 TemplateSpecializationKind TSK, bool Complain) {
2482 // Perform the actual instantiation on the canonical declaration.
2483 ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>(
2484 ClassTemplateSpec->getCanonicalDecl());
2485 if (ClassTemplateSpec->isInvalidDecl())
2488 CXXRecordDecl *Pattern = getPatternForClassTemplateSpecialization(
2489 *this, PointOfInstantiation, ClassTemplateSpec, TSK, Complain);
2493 return InstantiateClass(PointOfInstantiation, ClassTemplateSpec, Pattern,
2494 getTemplateInstantiationArgs(ClassTemplateSpec), TSK,
2498 /// \brief Instantiates the definitions of all of the member
2499 /// of the given class, which is an instantiation of a class template
2500 /// or a member class of a template.
2502 Sema::InstantiateClassMembers(SourceLocation PointOfInstantiation,
2503 CXXRecordDecl *Instantiation,
2504 const MultiLevelTemplateArgumentList &TemplateArgs,
2505 TemplateSpecializationKind TSK) {
2506 // FIXME: We need to notify the ASTMutationListener that we did all of these
2507 // things, in case we have an explicit instantiation definition in a PCM, a
2508 // module, or preamble, and the declaration is in an imported AST.
2510 (TSK == TSK_ExplicitInstantiationDefinition ||
2511 TSK == TSK_ExplicitInstantiationDeclaration ||
2512 (TSK == TSK_ImplicitInstantiation && Instantiation->isLocalClass())) &&
2513 "Unexpected template specialization kind!");
2514 for (auto *D : Instantiation->decls()) {
2515 bool SuppressNew = false;
2516 if (auto *Function = dyn_cast<FunctionDecl>(D)) {
2517 if (FunctionDecl *Pattern
2518 = Function->getInstantiatedFromMemberFunction()) {
2519 MemberSpecializationInfo *MSInfo
2520 = Function->getMemberSpecializationInfo();
2521 assert(MSInfo && "No member specialization information?");
2522 if (MSInfo->getTemplateSpecializationKind()
2523 == TSK_ExplicitSpecialization)
2526 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2528 MSInfo->getTemplateSpecializationKind(),
2529 MSInfo->getPointOfInstantiation(),
2534 // C++11 [temp.explicit]p8:
2535 // An explicit instantiation definition that names a class template
2536 // specialization explicitly instantiates the class template
2537 // specialization and is only an explicit instantiation definition
2538 // of members whose definition is visible at the point of
2540 if (TSK == TSK_ExplicitInstantiationDefinition && !Pattern->isDefined())
2543 Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2545 if (Function->isDefined()) {
2546 // Let the ASTConsumer know that this function has been explicitly
2547 // instantiated now, and its linkage might have changed.
2548 Consumer.HandleTopLevelDecl(DeclGroupRef(Function));
2549 } else if (TSK == TSK_ExplicitInstantiationDefinition) {
2550 InstantiateFunctionDefinition(PointOfInstantiation, Function);
2551 } else if (TSK == TSK_ImplicitInstantiation) {
2552 PendingLocalImplicitInstantiations.push_back(
2553 std::make_pair(Function, PointOfInstantiation));
2556 } else if (auto *Var = dyn_cast<VarDecl>(D)) {
2557 if (isa<VarTemplateSpecializationDecl>(Var))
2560 if (Var->isStaticDataMember()) {
2561 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
2562 assert(MSInfo && "No member specialization information?");
2563 if (MSInfo->getTemplateSpecializationKind()
2564 == TSK_ExplicitSpecialization)
2567 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2569 MSInfo->getTemplateSpecializationKind(),
2570 MSInfo->getPointOfInstantiation(),
2575 if (TSK == TSK_ExplicitInstantiationDefinition) {
2576 // C++0x [temp.explicit]p8:
2577 // An explicit instantiation definition that names a class template
2578 // specialization explicitly instantiates the class template
2579 // specialization and is only an explicit instantiation definition
2580 // of members whose definition is visible at the point of
2582 if (!Var->getInstantiatedFromStaticDataMember()->getDefinition())
2585 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2586 InstantiateStaticDataMemberDefinition(PointOfInstantiation, Var);
2588 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2591 } else if (auto *Record = dyn_cast<CXXRecordDecl>(D)) {
2592 // Always skip the injected-class-name, along with any
2593 // redeclarations of nested classes, since both would cause us
2594 // to try to instantiate the members of a class twice.
2595 // Skip closure types; they'll get instantiated when we instantiate
2596 // the corresponding lambda-expression.
2597 if (Record->isInjectedClassName() || Record->getPreviousDecl() ||
2601 MemberSpecializationInfo *MSInfo = Record->getMemberSpecializationInfo();
2602 assert(MSInfo && "No member specialization information?");
2604 if (MSInfo->getTemplateSpecializationKind()
2605 == TSK_ExplicitSpecialization)
2608 if ((Context.getTargetInfo().getCXXABI().isMicrosoft() ||
2609 Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment()) &&
2610 TSK == TSK_ExplicitInstantiationDeclaration) {
2611 // In MSVC and Windows Itanium mode, explicit instantiation decl of the
2612 // outer class doesn't affect the inner class.
2616 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2618 MSInfo->getTemplateSpecializationKind(),
2619 MSInfo->getPointOfInstantiation(),
2624 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
2625 assert(Pattern && "Missing instantiated-from-template information");
2627 if (!Record->getDefinition()) {
2628 if (!Pattern->getDefinition()) {
2629 // C++0x [temp.explicit]p8:
2630 // An explicit instantiation definition that names a class template
2631 // specialization explicitly instantiates the class template
2632 // specialization and is only an explicit instantiation definition
2633 // of members whose definition is visible at the point of
2635 if (TSK == TSK_ExplicitInstantiationDeclaration) {
2636 MSInfo->setTemplateSpecializationKind(TSK);
2637 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2643 InstantiateClass(PointOfInstantiation, Record, Pattern,
2647 if (TSK == TSK_ExplicitInstantiationDefinition &&
2648 Record->getTemplateSpecializationKind() ==
2649 TSK_ExplicitInstantiationDeclaration) {
2650 Record->setTemplateSpecializationKind(TSK);
2651 MarkVTableUsed(PointOfInstantiation, Record, true);
2655 Pattern = cast_or_null<CXXRecordDecl>(Record->getDefinition());
2657 InstantiateClassMembers(PointOfInstantiation, Pattern, TemplateArgs,
2659 } else if (auto *Enum = dyn_cast<EnumDecl>(D)) {
2660 MemberSpecializationInfo *MSInfo = Enum->getMemberSpecializationInfo();
2661 assert(MSInfo && "No member specialization information?");
2663 if (MSInfo->getTemplateSpecializationKind()
2664 == TSK_ExplicitSpecialization)
2667 if (CheckSpecializationInstantiationRedecl(
2668 PointOfInstantiation, TSK, Enum,
2669 MSInfo->getTemplateSpecializationKind(),
2670 MSInfo->getPointOfInstantiation(), SuppressNew) ||
2674 if (Enum->getDefinition())
2677 EnumDecl *Pattern = Enum->getTemplateInstantiationPattern();
2678 assert(Pattern && "Missing instantiated-from-template information");
2680 if (TSK == TSK_ExplicitInstantiationDefinition) {
2681 if (!Pattern->getDefinition())
2684 InstantiateEnum(PointOfInstantiation, Enum, Pattern, TemplateArgs, TSK);
2686 MSInfo->setTemplateSpecializationKind(TSK);
2687 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2689 } else if (auto *Field = dyn_cast<FieldDecl>(D)) {
2690 // No need to instantiate in-class initializers during explicit
2692 if (Field->hasInClassInitializer() && TSK == TSK_ImplicitInstantiation) {
2693 CXXRecordDecl *ClassPattern =
2694 Instantiation->getTemplateInstantiationPattern();
2695 DeclContext::lookup_result Lookup =
2696 ClassPattern->lookup(Field->getDeclName());
2697 FieldDecl *Pattern = cast<FieldDecl>(Lookup.front());
2698 InstantiateInClassInitializer(PointOfInstantiation, Field, Pattern,
2705 /// \brief Instantiate the definitions of all of the members of the
2706 /// given class template specialization, which was named as part of an
2707 /// explicit instantiation.
2709 Sema::InstantiateClassTemplateSpecializationMembers(
2710 SourceLocation PointOfInstantiation,
2711 ClassTemplateSpecializationDecl *ClassTemplateSpec,
2712 TemplateSpecializationKind TSK) {
2713 // C++0x [temp.explicit]p7:
2714 // An explicit instantiation that names a class template
2715 // specialization is an explicit instantion of the same kind
2716 // (declaration or definition) of each of its members (not
2717 // including members inherited from base classes) that has not
2718 // been previously explicitly specialized in the translation unit
2719 // containing the explicit instantiation, except as described
2721 InstantiateClassMembers(PointOfInstantiation, ClassTemplateSpec,
2722 getTemplateInstantiationArgs(ClassTemplateSpec),
2727 Sema::SubstStmt(Stmt *S, const MultiLevelTemplateArgumentList &TemplateArgs) {
2731 TemplateInstantiator Instantiator(*this, TemplateArgs,
2734 return Instantiator.TransformStmt(S);
2738 Sema::SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs) {
2742 TemplateInstantiator Instantiator(*this, TemplateArgs,
2745 return Instantiator.TransformExpr(E);
2748 ExprResult Sema::SubstInitializer(Expr *Init,
2749 const MultiLevelTemplateArgumentList &TemplateArgs,
2750 bool CXXDirectInit) {
2751 TemplateInstantiator Instantiator(*this, TemplateArgs,
2754 return Instantiator.TransformInitializer(Init, CXXDirectInit);
2757 bool Sema::SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
2758 const MultiLevelTemplateArgumentList &TemplateArgs,
2759 SmallVectorImpl<Expr *> &Outputs) {
2763 TemplateInstantiator Instantiator(*this, TemplateArgs,
2766 return Instantiator.TransformExprs(Exprs.data(), Exprs.size(),
2770 NestedNameSpecifierLoc
2771 Sema::SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
2772 const MultiLevelTemplateArgumentList &TemplateArgs) {
2774 return NestedNameSpecifierLoc();
2776 TemplateInstantiator Instantiator(*this, TemplateArgs, NNS.getBeginLoc(),
2778 return Instantiator.TransformNestedNameSpecifierLoc(NNS);
2781 /// \brief Do template substitution on declaration name info.
2783 Sema::SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
2784 const MultiLevelTemplateArgumentList &TemplateArgs) {
2785 TemplateInstantiator Instantiator(*this, TemplateArgs, NameInfo.getLoc(),
2786 NameInfo.getName());
2787 return Instantiator.TransformDeclarationNameInfo(NameInfo);
2791 Sema::SubstTemplateName(NestedNameSpecifierLoc QualifierLoc,
2792 TemplateName Name, SourceLocation Loc,
2793 const MultiLevelTemplateArgumentList &TemplateArgs) {
2794 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
2797 SS.Adopt(QualifierLoc);
2798 return Instantiator.TransformTemplateName(SS, Name, Loc);
2801 bool Sema::Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
2802 TemplateArgumentListInfo &Result,
2803 const MultiLevelTemplateArgumentList &TemplateArgs) {
2804 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
2807 return Instantiator.TransformTemplateArguments(Args, NumArgs, Result);
2810 static const Decl *getCanonicalParmVarDecl(const Decl *D) {
2811 // When storing ParmVarDecls in the local instantiation scope, we always
2812 // want to use the ParmVarDecl from the canonical function declaration,
2813 // since the map is then valid for any redeclaration or definition of that
2815 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(D)) {
2816 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
2817 unsigned i = PV->getFunctionScopeIndex();
2818 // This parameter might be from a freestanding function type within the
2819 // function and isn't necessarily referring to one of FD's parameters.
2820 if (FD->getParamDecl(i) == PV)
2821 return FD->getCanonicalDecl()->getParamDecl(i);
2828 llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> *
2829 LocalInstantiationScope::findInstantiationOf(const Decl *D) {
2830 D = getCanonicalParmVarDecl(D);
2831 for (LocalInstantiationScope *Current = this; Current;
2832 Current = Current->Outer) {
2834 // Check if we found something within this scope.
2835 const Decl *CheckD = D;
2837 LocalDeclsMap::iterator Found = Current->LocalDecls.find(CheckD);
2838 if (Found != Current->LocalDecls.end())
2839 return &Found->second;
2841 // If this is a tag declaration, it's possible that we need to look for
2842 // a previous declaration.
2843 if (const TagDecl *Tag = dyn_cast<TagDecl>(CheckD))
2844 CheckD = Tag->getPreviousDecl();
2849 // If we aren't combined with our outer scope, we're done.
2850 if (!Current->CombineWithOuterScope)
2854 // If we're performing a partial substitution during template argument
2855 // deduction, we may not have values for template parameters yet.
2856 if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
2857 isa<TemplateTemplateParmDecl>(D))
2860 // Local types referenced prior to definition may require instantiation.
2861 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
2862 if (RD->isLocalClass())
2865 // Enumeration types referenced prior to definition may appear as a result of
2867 if (isa<EnumDecl>(D))
2870 // If we didn't find the decl, then we either have a sema bug, or we have a
2871 // forward reference to a label declaration. Return null to indicate that
2872 // we have an uninstantiated label.
2873 assert(isa<LabelDecl>(D) && "declaration not instantiated in this scope");
2877 void LocalInstantiationScope::InstantiatedLocal(const Decl *D, Decl *Inst) {
2878 D = getCanonicalParmVarDecl(D);
2879 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
2880 if (Stored.isNull()) {
2882 // It should not be present in any surrounding scope either.
2883 LocalInstantiationScope *Current = this;
2884 while (Current->CombineWithOuterScope && Current->Outer) {
2885 Current = Current->Outer;
2886 assert(Current->LocalDecls.find(D) == Current->LocalDecls.end() &&
2887 "Instantiated local in inner and outer scopes");
2891 } else if (DeclArgumentPack *Pack = Stored.dyn_cast<DeclArgumentPack *>()) {
2892 Pack->push_back(cast<ParmVarDecl>(Inst));
2894 assert(Stored.get<Decl *>() == Inst && "Already instantiated this local");
2898 void LocalInstantiationScope::InstantiatedLocalPackArg(const Decl *D,
2899 ParmVarDecl *Inst) {
2900 D = getCanonicalParmVarDecl(D);
2901 DeclArgumentPack *Pack = LocalDecls[D].get<DeclArgumentPack *>();
2902 Pack->push_back(Inst);
2905 void LocalInstantiationScope::MakeInstantiatedLocalArgPack(const Decl *D) {
2907 // This should be the first time we've been told about this decl.
2908 for (LocalInstantiationScope *Current = this;
2909 Current && Current->CombineWithOuterScope; Current = Current->Outer)
2910 assert(Current->LocalDecls.find(D) == Current->LocalDecls.end() &&
2911 "Creating local pack after instantiation of local");
2914 D = getCanonicalParmVarDecl(D);
2915 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
2916 DeclArgumentPack *Pack = new DeclArgumentPack;
2918 ArgumentPacks.push_back(Pack);
2921 void LocalInstantiationScope::SetPartiallySubstitutedPack(NamedDecl *Pack,
2922 const TemplateArgument *ExplicitArgs,
2923 unsigned NumExplicitArgs) {
2924 assert((!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack) &&
2925 "Already have a partially-substituted pack");
2926 assert((!PartiallySubstitutedPack
2927 || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) &&
2928 "Wrong number of arguments in partially-substituted pack");
2929 PartiallySubstitutedPack = Pack;
2930 ArgsInPartiallySubstitutedPack = ExplicitArgs;
2931 NumArgsInPartiallySubstitutedPack = NumExplicitArgs;
2934 NamedDecl *LocalInstantiationScope::getPartiallySubstitutedPack(
2935 const TemplateArgument **ExplicitArgs,
2936 unsigned *NumExplicitArgs) const {
2938 *ExplicitArgs = nullptr;
2939 if (NumExplicitArgs)
2940 *NumExplicitArgs = 0;
2942 for (const LocalInstantiationScope *Current = this; Current;
2943 Current = Current->Outer) {
2944 if (Current->PartiallySubstitutedPack) {
2946 *ExplicitArgs = Current->ArgsInPartiallySubstitutedPack;
2947 if (NumExplicitArgs)
2948 *NumExplicitArgs = Current->NumArgsInPartiallySubstitutedPack;
2950 return Current->PartiallySubstitutedPack;
2953 if (!Current->CombineWithOuterScope)