1 //===------- SemaTemplateInstantiate.cpp - C++ Template Instantiation ------===/
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //===----------------------------------------------------------------------===/
8 // This file implements C++ template instantiation.
10 //===----------------------------------------------------------------------===/
12 #include "clang/Sema/SemaInternal.h"
13 #include "TreeTransform.h"
14 #include "clang/AST/ASTConsumer.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTLambda.h"
17 #include "clang/AST/ASTMutationListener.h"
18 #include "clang/AST/DeclTemplate.h"
19 #include "clang/AST/Expr.h"
20 #include "clang/AST/PrettyDeclStackTrace.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/Template.h"
26 #include "clang/Sema/TemplateDeduction.h"
27 #include "clang/Sema/TemplateInstCallback.h"
28 #include "llvm/Support/TimeProfiler.h"
30 using namespace clang;
33 //===----------------------------------------------------------------------===/
34 // Template Instantiation Support
35 //===----------------------------------------------------------------------===/
37 /// Retrieve the template argument list(s) that should be used to
38 /// instantiate the definition of the given declaration.
40 /// \param D the declaration for which we are computing template instantiation
43 /// \param Innermost if non-NULL, the innermost template argument list.
45 /// \param RelativeToPrimary true if we should get the template
46 /// arguments relative to the primary template, even when we're
47 /// dealing with a specialization. This is only relevant for function
48 /// template specializations.
50 /// \param Pattern If non-NULL, indicates the pattern from which we will be
51 /// instantiating the definition of the given declaration, \p D. This is
52 /// used to determine the proper set of template instantiation arguments for
53 /// friend function template specializations.
54 MultiLevelTemplateArgumentList
55 Sema::getTemplateInstantiationArgs(NamedDecl *D,
56 const TemplateArgumentList *Innermost,
57 bool RelativeToPrimary,
58 const FunctionDecl *Pattern) {
59 // Accumulate the set of template argument lists in this structure.
60 MultiLevelTemplateArgumentList Result;
63 Result.addOuterTemplateArguments(Innermost);
65 DeclContext *Ctx = dyn_cast<DeclContext>(D);
67 Ctx = D->getDeclContext();
69 // Add template arguments from a variable template instantiation. For a
70 // class-scope explicit specialization, there are no template arguments
71 // at this level, but there may be enclosing template arguments.
72 VarTemplateSpecializationDecl *Spec =
73 dyn_cast<VarTemplateSpecializationDecl>(D);
74 if (Spec && !Spec->isClassScopeExplicitSpecialization()) {
75 // We're done when we hit an explicit specialization.
76 if (Spec->getSpecializationKind() == TSK_ExplicitSpecialization &&
77 !isa<VarTemplatePartialSpecializationDecl>(Spec))
80 Result.addOuterTemplateArguments(&Spec->getTemplateInstantiationArgs());
82 // If this variable template specialization was instantiated from a
83 // specialized member that is a variable template, we're done.
84 assert(Spec->getSpecializedTemplate() && "No variable template?");
85 llvm::PointerUnion<VarTemplateDecl*,
86 VarTemplatePartialSpecializationDecl*> Specialized
87 = Spec->getSpecializedTemplateOrPartial();
88 if (VarTemplatePartialSpecializationDecl *Partial =
89 Specialized.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
90 if (Partial->isMemberSpecialization())
93 VarTemplateDecl *Tmpl = Specialized.get<VarTemplateDecl *>();
94 if (Tmpl->isMemberSpecialization())
99 // If we have a template template parameter with translation unit context,
100 // then we're performing substitution into a default template argument of
101 // this template template parameter before we've constructed the template
102 // that will own this template template parameter. In this case, we
103 // use empty template parameter lists for all of the outer templates
104 // to avoid performing any substitutions.
105 if (Ctx->isTranslationUnit()) {
106 if (TemplateTemplateParmDecl *TTP
107 = dyn_cast<TemplateTemplateParmDecl>(D)) {
108 for (unsigned I = 0, N = TTP->getDepth() + 1; I != N; ++I)
109 Result.addOuterTemplateArguments(None);
115 while (!Ctx->isFileContext()) {
116 // Add template arguments from a class template instantiation.
117 ClassTemplateSpecializationDecl *Spec
118 = dyn_cast<ClassTemplateSpecializationDecl>(Ctx);
119 if (Spec && !Spec->isClassScopeExplicitSpecialization()) {
120 // We're done when we hit an explicit specialization.
121 if (Spec->getSpecializationKind() == TSK_ExplicitSpecialization &&
122 !isa<ClassTemplatePartialSpecializationDecl>(Spec))
125 Result.addOuterTemplateArguments(&Spec->getTemplateInstantiationArgs());
127 // If this class template specialization was instantiated from a
128 // specialized member that is a class template, we're done.
129 assert(Spec->getSpecializedTemplate() && "No class template?");
130 if (Spec->getSpecializedTemplate()->isMemberSpecialization())
133 // Add template arguments from a function template specialization.
134 else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Ctx)) {
135 if (!RelativeToPrimary &&
136 Function->getTemplateSpecializationKindForInstantiation() ==
137 TSK_ExplicitSpecialization)
140 if (const TemplateArgumentList *TemplateArgs
141 = Function->getTemplateSpecializationArgs()) {
142 // Add the template arguments for this specialization.
143 Result.addOuterTemplateArguments(TemplateArgs);
145 // If this function was instantiated from a specialized member that is
146 // a function template, we're done.
147 assert(Function->getPrimaryTemplate() && "No function template?");
148 if (Function->getPrimaryTemplate()->isMemberSpecialization())
151 // If this function is a generic lambda specialization, we are done.
152 if (isGenericLambdaCallOperatorSpecialization(Function))
155 } else if (FunctionTemplateDecl *FunTmpl
156 = Function->getDescribedFunctionTemplate()) {
157 // Add the "injected" template arguments.
158 Result.addOuterTemplateArguments(FunTmpl->getInjectedTemplateArgs());
161 // If this is a friend declaration and it declares an entity at
162 // namespace scope, take arguments from its lexical parent
163 // instead of its semantic parent, unless of course the pattern we're
164 // instantiating actually comes from the file's context!
165 if (Function->getFriendObjectKind() &&
166 Function->getDeclContext()->isFileContext() &&
167 (!Pattern || !Pattern->getLexicalDeclContext()->isFileContext())) {
168 Ctx = Function->getLexicalDeclContext();
169 RelativeToPrimary = false;
172 } else if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Ctx)) {
173 if (ClassTemplateDecl *ClassTemplate = Rec->getDescribedClassTemplate()) {
174 QualType T = ClassTemplate->getInjectedClassNameSpecialization();
175 const TemplateSpecializationType *TST =
176 cast<TemplateSpecializationType>(Context.getCanonicalType(T));
177 Result.addOuterTemplateArguments(
178 llvm::makeArrayRef(TST->getArgs(), TST->getNumArgs()));
179 if (ClassTemplate->isMemberSpecialization())
184 Ctx = Ctx->getParent();
185 RelativeToPrimary = false;
191 bool Sema::CodeSynthesisContext::isInstantiationRecord() const {
193 case TemplateInstantiation:
194 case ExceptionSpecInstantiation:
195 case DefaultTemplateArgumentInstantiation:
196 case DefaultFunctionArgumentInstantiation:
197 case ExplicitTemplateArgumentSubstitution:
198 case DeducedTemplateArgumentSubstitution:
199 case PriorTemplateArgumentSubstitution:
202 case DefaultTemplateArgumentChecking:
203 case DeclaringSpecialMember:
204 case DefiningSynthesizedFunction:
205 case ExceptionSpecEvaluation:
208 // This function should never be called when Kind's value is Memoization.
213 llvm_unreachable("Invalid SynthesisKind!");
216 Sema::InstantiatingTemplate::InstantiatingTemplate(
217 Sema &SemaRef, CodeSynthesisContext::SynthesisKind Kind,
218 SourceLocation PointOfInstantiation, SourceRange InstantiationRange,
219 Decl *Entity, NamedDecl *Template, ArrayRef<TemplateArgument> TemplateArgs,
220 sema::TemplateDeductionInfo *DeductionInfo)
222 // Don't allow further instantiation if a fatal error and an uncompilable
223 // error have occurred. Any diagnostics we might have raised will not be
224 // visible, and we do not need to construct a correct AST.
225 if (SemaRef.Diags.hasFatalErrorOccurred() &&
226 SemaRef.Diags.hasUncompilableErrorOccurred()) {
230 Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
232 CodeSynthesisContext Inst;
234 Inst.PointOfInstantiation = PointOfInstantiation;
235 Inst.Entity = Entity;
236 Inst.Template = Template;
237 Inst.TemplateArgs = TemplateArgs.data();
238 Inst.NumTemplateArgs = TemplateArgs.size();
239 Inst.DeductionInfo = DeductionInfo;
240 Inst.InstantiationRange = InstantiationRange;
241 SemaRef.pushCodeSynthesisContext(Inst);
243 AlreadyInstantiating =
244 !SemaRef.InstantiatingSpecializations
245 .insert(std::make_pair(Inst.Entity->getCanonicalDecl(), Inst.Kind))
247 atTemplateBegin(SemaRef.TemplateInstCallbacks, SemaRef, Inst);
251 Sema::InstantiatingTemplate::InstantiatingTemplate(
252 Sema &SemaRef, SourceLocation PointOfInstantiation, Decl *Entity,
253 SourceRange InstantiationRange)
254 : InstantiatingTemplate(SemaRef,
255 CodeSynthesisContext::TemplateInstantiation,
256 PointOfInstantiation, InstantiationRange, Entity) {}
258 Sema::InstantiatingTemplate::InstantiatingTemplate(
259 Sema &SemaRef, SourceLocation PointOfInstantiation, FunctionDecl *Entity,
260 ExceptionSpecification, SourceRange InstantiationRange)
261 : InstantiatingTemplate(
262 SemaRef, CodeSynthesisContext::ExceptionSpecInstantiation,
263 PointOfInstantiation, InstantiationRange, Entity) {}
265 Sema::InstantiatingTemplate::InstantiatingTemplate(
266 Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateParameter Param,
267 TemplateDecl *Template, ArrayRef<TemplateArgument> TemplateArgs,
268 SourceRange InstantiationRange)
269 : InstantiatingTemplate(
271 CodeSynthesisContext::DefaultTemplateArgumentInstantiation,
272 PointOfInstantiation, InstantiationRange, getAsNamedDecl(Param),
273 Template, TemplateArgs) {}
275 Sema::InstantiatingTemplate::InstantiatingTemplate(
276 Sema &SemaRef, SourceLocation PointOfInstantiation,
277 FunctionTemplateDecl *FunctionTemplate,
278 ArrayRef<TemplateArgument> TemplateArgs,
279 CodeSynthesisContext::SynthesisKind Kind,
280 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
281 : InstantiatingTemplate(SemaRef, Kind, PointOfInstantiation,
282 InstantiationRange, FunctionTemplate, nullptr,
283 TemplateArgs, &DeductionInfo) {
285 Kind == CodeSynthesisContext::ExplicitTemplateArgumentSubstitution ||
286 Kind == CodeSynthesisContext::DeducedTemplateArgumentSubstitution);
289 Sema::InstantiatingTemplate::InstantiatingTemplate(
290 Sema &SemaRef, SourceLocation PointOfInstantiation,
291 TemplateDecl *Template,
292 ArrayRef<TemplateArgument> TemplateArgs,
293 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
294 : InstantiatingTemplate(
296 CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
297 PointOfInstantiation, InstantiationRange, Template, nullptr,
298 TemplateArgs, &DeductionInfo) {}
300 Sema::InstantiatingTemplate::InstantiatingTemplate(
301 Sema &SemaRef, SourceLocation PointOfInstantiation,
302 ClassTemplatePartialSpecializationDecl *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,
313 VarTemplatePartialSpecializationDecl *PartialSpec,
314 ArrayRef<TemplateArgument> TemplateArgs,
315 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
316 : InstantiatingTemplate(
318 CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
319 PointOfInstantiation, InstantiationRange, PartialSpec, nullptr,
320 TemplateArgs, &DeductionInfo) {}
322 Sema::InstantiatingTemplate::InstantiatingTemplate(
323 Sema &SemaRef, SourceLocation PointOfInstantiation, ParmVarDecl *Param,
324 ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange)
325 : InstantiatingTemplate(
327 CodeSynthesisContext::DefaultFunctionArgumentInstantiation,
328 PointOfInstantiation, InstantiationRange, Param, nullptr,
331 Sema::InstantiatingTemplate::InstantiatingTemplate(
332 Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template,
333 NonTypeTemplateParmDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
334 SourceRange InstantiationRange)
335 : InstantiatingTemplate(
337 CodeSynthesisContext::PriorTemplateArgumentSubstitution,
338 PointOfInstantiation, InstantiationRange, Param, Template,
341 Sema::InstantiatingTemplate::InstantiatingTemplate(
342 Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template,
343 TemplateTemplateParmDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
344 SourceRange InstantiationRange)
345 : InstantiatingTemplate(
347 CodeSynthesisContext::PriorTemplateArgumentSubstitution,
348 PointOfInstantiation, InstantiationRange, Param, Template,
351 Sema::InstantiatingTemplate::InstantiatingTemplate(
352 Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Template,
353 NamedDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
354 SourceRange InstantiationRange)
355 : InstantiatingTemplate(
356 SemaRef, CodeSynthesisContext::DefaultTemplateArgumentChecking,
357 PointOfInstantiation, InstantiationRange, Param, Template,
360 void Sema::pushCodeSynthesisContext(CodeSynthesisContext Ctx) {
361 Ctx.SavedInNonInstantiationSFINAEContext = InNonInstantiationSFINAEContext;
362 InNonInstantiationSFINAEContext = false;
364 CodeSynthesisContexts.push_back(Ctx);
366 if (!Ctx.isInstantiationRecord())
367 ++NonInstantiationEntries;
370 void Sema::popCodeSynthesisContext() {
371 auto &Active = CodeSynthesisContexts.back();
372 if (!Active.isInstantiationRecord()) {
373 assert(NonInstantiationEntries > 0);
374 --NonInstantiationEntries;
377 InNonInstantiationSFINAEContext = Active.SavedInNonInstantiationSFINAEContext;
379 // Name lookup no longer looks in this template's defining module.
380 assert(CodeSynthesisContexts.size() >=
381 CodeSynthesisContextLookupModules.size() &&
382 "forgot to remove a lookup module for a template instantiation");
383 if (CodeSynthesisContexts.size() ==
384 CodeSynthesisContextLookupModules.size()) {
385 if (Module *M = CodeSynthesisContextLookupModules.back())
386 LookupModulesCache.erase(M);
387 CodeSynthesisContextLookupModules.pop_back();
390 // If we've left the code synthesis context for the current context stack,
391 // stop remembering that we've emitted that stack.
392 if (CodeSynthesisContexts.size() ==
393 LastEmittedCodeSynthesisContextDepth)
394 LastEmittedCodeSynthesisContextDepth = 0;
396 CodeSynthesisContexts.pop_back();
399 void Sema::InstantiatingTemplate::Clear() {
401 if (!AlreadyInstantiating) {
402 auto &Active = SemaRef.CodeSynthesisContexts.back();
403 SemaRef.InstantiatingSpecializations.erase(
404 std::make_pair(Active.Entity, Active.Kind));
407 atTemplateEnd(SemaRef.TemplateInstCallbacks, SemaRef,
408 SemaRef.CodeSynthesisContexts.back());
410 SemaRef.popCodeSynthesisContext();
415 bool Sema::InstantiatingTemplate::CheckInstantiationDepth(
416 SourceLocation PointOfInstantiation,
417 SourceRange InstantiationRange) {
418 assert(SemaRef.NonInstantiationEntries <=
419 SemaRef.CodeSynthesisContexts.size());
420 if ((SemaRef.CodeSynthesisContexts.size() -
421 SemaRef.NonInstantiationEntries)
422 <= SemaRef.getLangOpts().InstantiationDepth)
425 SemaRef.Diag(PointOfInstantiation,
426 diag::err_template_recursion_depth_exceeded)
427 << SemaRef.getLangOpts().InstantiationDepth
428 << InstantiationRange;
429 SemaRef.Diag(PointOfInstantiation, diag::note_template_recursion_depth)
430 << SemaRef.getLangOpts().InstantiationDepth;
434 /// Prints the current instantiation stack through a series of
436 void Sema::PrintInstantiationStack() {
437 // Determine which template instantiations to skip, if any.
438 unsigned SkipStart = CodeSynthesisContexts.size(), SkipEnd = SkipStart;
439 unsigned Limit = Diags.getTemplateBacktraceLimit();
440 if (Limit && Limit < CodeSynthesisContexts.size()) {
441 SkipStart = Limit / 2 + Limit % 2;
442 SkipEnd = CodeSynthesisContexts.size() - Limit / 2;
445 // FIXME: In all of these cases, we need to show the template arguments
446 unsigned InstantiationIdx = 0;
447 for (SmallVectorImpl<CodeSynthesisContext>::reverse_iterator
448 Active = CodeSynthesisContexts.rbegin(),
449 ActiveEnd = CodeSynthesisContexts.rend();
451 ++Active, ++InstantiationIdx) {
452 // Skip this instantiation?
453 if (InstantiationIdx >= SkipStart && InstantiationIdx < SkipEnd) {
454 if (InstantiationIdx == SkipStart) {
455 // Note that we're skipping instantiations.
456 Diags.Report(Active->PointOfInstantiation,
457 diag::note_instantiation_contexts_suppressed)
458 << unsigned(CodeSynthesisContexts.size() - Limit);
463 switch (Active->Kind) {
464 case CodeSynthesisContext::TemplateInstantiation: {
465 Decl *D = Active->Entity;
466 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
467 unsigned DiagID = diag::note_template_member_class_here;
468 if (isa<ClassTemplateSpecializationDecl>(Record))
469 DiagID = diag::note_template_class_instantiation_here;
470 Diags.Report(Active->PointOfInstantiation, DiagID)
471 << Record << Active->InstantiationRange;
472 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
474 if (Function->getPrimaryTemplate())
475 DiagID = diag::note_function_template_spec_here;
477 DiagID = diag::note_template_member_function_here;
478 Diags.Report(Active->PointOfInstantiation, DiagID)
480 << Active->InstantiationRange;
481 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
482 Diags.Report(Active->PointOfInstantiation,
483 VD->isStaticDataMember()?
484 diag::note_template_static_data_member_def_here
485 : diag::note_template_variable_def_here)
487 << Active->InstantiationRange;
488 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
489 Diags.Report(Active->PointOfInstantiation,
490 diag::note_template_enum_def_here)
492 << Active->InstantiationRange;
493 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
494 Diags.Report(Active->PointOfInstantiation,
495 diag::note_template_nsdmi_here)
496 << FD << Active->InstantiationRange;
498 Diags.Report(Active->PointOfInstantiation,
499 diag::note_template_type_alias_instantiation_here)
500 << cast<TypeAliasTemplateDecl>(D)
501 << Active->InstantiationRange;
506 case CodeSynthesisContext::DefaultTemplateArgumentInstantiation: {
507 TemplateDecl *Template = cast<TemplateDecl>(Active->Template);
508 SmallVector<char, 128> TemplateArgsStr;
509 llvm::raw_svector_ostream OS(TemplateArgsStr);
510 Template->printName(OS);
511 printTemplateArgumentList(OS, Active->template_arguments(),
512 getPrintingPolicy());
513 Diags.Report(Active->PointOfInstantiation,
514 diag::note_default_arg_instantiation_here)
516 << Active->InstantiationRange;
520 case CodeSynthesisContext::ExplicitTemplateArgumentSubstitution: {
521 FunctionTemplateDecl *FnTmpl = cast<FunctionTemplateDecl>(Active->Entity);
522 Diags.Report(Active->PointOfInstantiation,
523 diag::note_explicit_template_arg_substitution_here)
525 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
526 Active->TemplateArgs,
527 Active->NumTemplateArgs)
528 << Active->InstantiationRange;
532 case CodeSynthesisContext::DeducedTemplateArgumentSubstitution: {
533 if (FunctionTemplateDecl *FnTmpl =
534 dyn_cast<FunctionTemplateDecl>(Active->Entity)) {
535 Diags.Report(Active->PointOfInstantiation,
536 diag::note_function_template_deduction_instantiation_here)
538 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
539 Active->TemplateArgs,
540 Active->NumTemplateArgs)
541 << Active->InstantiationRange;
543 bool IsVar = isa<VarTemplateDecl>(Active->Entity) ||
544 isa<VarTemplateSpecializationDecl>(Active->Entity);
545 bool IsTemplate = false;
546 TemplateParameterList *Params;
547 if (auto *D = dyn_cast<TemplateDecl>(Active->Entity)) {
549 Params = D->getTemplateParameters();
550 } else if (auto *D = dyn_cast<ClassTemplatePartialSpecializationDecl>(
552 Params = D->getTemplateParameters();
553 } else if (auto *D = dyn_cast<VarTemplatePartialSpecializationDecl>(
555 Params = D->getTemplateParameters();
557 llvm_unreachable("unexpected template kind");
560 Diags.Report(Active->PointOfInstantiation,
561 diag::note_deduced_template_arg_substitution_here)
562 << IsVar << IsTemplate << cast<NamedDecl>(Active->Entity)
563 << getTemplateArgumentBindingsText(Params, Active->TemplateArgs,
564 Active->NumTemplateArgs)
565 << Active->InstantiationRange;
570 case CodeSynthesisContext::DefaultFunctionArgumentInstantiation: {
571 ParmVarDecl *Param = cast<ParmVarDecl>(Active->Entity);
572 FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());
574 SmallVector<char, 128> TemplateArgsStr;
575 llvm::raw_svector_ostream OS(TemplateArgsStr);
577 printTemplateArgumentList(OS, Active->template_arguments(),
578 getPrintingPolicy());
579 Diags.Report(Active->PointOfInstantiation,
580 diag::note_default_function_arg_instantiation_here)
582 << Active->InstantiationRange;
586 case CodeSynthesisContext::PriorTemplateArgumentSubstitution: {
587 NamedDecl *Parm = cast<NamedDecl>(Active->Entity);
589 if (!Parm->getName().empty())
590 Name = std::string(" '") + Parm->getName().str() + "'";
592 TemplateParameterList *TemplateParams = nullptr;
593 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
594 TemplateParams = Template->getTemplateParameters();
597 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
598 ->getTemplateParameters();
599 Diags.Report(Active->PointOfInstantiation,
600 diag::note_prior_template_arg_substitution)
601 << isa<TemplateTemplateParmDecl>(Parm)
603 << getTemplateArgumentBindingsText(TemplateParams,
604 Active->TemplateArgs,
605 Active->NumTemplateArgs)
606 << Active->InstantiationRange;
610 case CodeSynthesisContext::DefaultTemplateArgumentChecking: {
611 TemplateParameterList *TemplateParams = nullptr;
612 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
613 TemplateParams = Template->getTemplateParameters();
616 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
617 ->getTemplateParameters();
619 Diags.Report(Active->PointOfInstantiation,
620 diag::note_template_default_arg_checking)
621 << getTemplateArgumentBindingsText(TemplateParams,
622 Active->TemplateArgs,
623 Active->NumTemplateArgs)
624 << Active->InstantiationRange;
628 case CodeSynthesisContext::ExceptionSpecEvaluation:
629 Diags.Report(Active->PointOfInstantiation,
630 diag::note_evaluating_exception_spec_here)
631 << cast<FunctionDecl>(Active->Entity);
634 case CodeSynthesisContext::ExceptionSpecInstantiation:
635 Diags.Report(Active->PointOfInstantiation,
636 diag::note_template_exception_spec_instantiation_here)
637 << cast<FunctionDecl>(Active->Entity)
638 << Active->InstantiationRange;
641 case CodeSynthesisContext::DeclaringSpecialMember:
642 Diags.Report(Active->PointOfInstantiation,
643 diag::note_in_declaration_of_implicit_special_member)
644 << cast<CXXRecordDecl>(Active->Entity) << Active->SpecialMember;
647 case CodeSynthesisContext::DefiningSynthesizedFunction: {
648 // FIXME: For synthesized members other than special members, produce a note.
649 auto *MD = dyn_cast<CXXMethodDecl>(Active->Entity);
650 auto CSM = MD ? getSpecialMember(MD) : CXXInvalid;
651 if (CSM != CXXInvalid) {
652 Diags.Report(Active->PointOfInstantiation,
653 diag::note_member_synthesized_at)
654 << CSM << Context.getTagDeclType(MD->getParent());
659 case CodeSynthesisContext::Memoization:
665 Optional<TemplateDeductionInfo *> Sema::isSFINAEContext() const {
666 if (InNonInstantiationSFINAEContext)
667 return Optional<TemplateDeductionInfo *>(nullptr);
669 for (SmallVectorImpl<CodeSynthesisContext>::const_reverse_iterator
670 Active = CodeSynthesisContexts.rbegin(),
671 ActiveEnd = CodeSynthesisContexts.rend();
675 switch (Active->Kind) {
676 case CodeSynthesisContext::TemplateInstantiation:
677 // An instantiation of an alias template may or may not be a SFINAE
678 // context, depending on what else is on the stack.
679 if (isa<TypeAliasTemplateDecl>(Active->Entity))
682 case CodeSynthesisContext::DefaultFunctionArgumentInstantiation:
683 case CodeSynthesisContext::ExceptionSpecInstantiation:
684 // This is a template instantiation, so there is no SFINAE.
687 case CodeSynthesisContext::DefaultTemplateArgumentInstantiation:
688 case CodeSynthesisContext::PriorTemplateArgumentSubstitution:
689 case CodeSynthesisContext::DefaultTemplateArgumentChecking:
690 // A default template argument instantiation and substitution into
691 // template parameters with arguments for prior parameters may or may
692 // not be a SFINAE context; look further up the stack.
695 case CodeSynthesisContext::ExplicitTemplateArgumentSubstitution:
696 case CodeSynthesisContext::DeducedTemplateArgumentSubstitution:
697 // We're either substitution explicitly-specified template arguments
698 // or deduced template arguments, so SFINAE applies.
699 assert(Active->DeductionInfo && "Missing deduction info pointer");
700 return Active->DeductionInfo;
702 case CodeSynthesisContext::DeclaringSpecialMember:
703 case CodeSynthesisContext::DefiningSynthesizedFunction:
704 // This happens in a context unrelated to template instantiation, so
705 // there is no SFINAE.
708 case CodeSynthesisContext::ExceptionSpecEvaluation:
709 // FIXME: This should not be treated as a SFINAE context, because
710 // we will cache an incorrect exception specification. However, clang
711 // bootstrap relies this! See PR31692.
714 case CodeSynthesisContext::Memoization:
718 // The inner context was transparent for SFINAE. If it occurred within a
719 // non-instantiation SFINAE context, then SFINAE applies.
720 if (Active->SavedInNonInstantiationSFINAEContext)
721 return Optional<TemplateDeductionInfo *>(nullptr);
727 //===----------------------------------------------------------------------===/
728 // Template Instantiation for Types
729 //===----------------------------------------------------------------------===/
731 class TemplateInstantiator : public TreeTransform<TemplateInstantiator> {
732 const MultiLevelTemplateArgumentList &TemplateArgs;
734 DeclarationName Entity;
737 typedef TreeTransform<TemplateInstantiator> inherited;
739 TemplateInstantiator(Sema &SemaRef,
740 const MultiLevelTemplateArgumentList &TemplateArgs,
742 DeclarationName Entity)
743 : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc),
746 /// Determine whether the given type \p T has already been
749 /// For the purposes of template instantiation, a type has already been
750 /// transformed if it is NULL or if it is not dependent.
751 bool AlreadyTransformed(QualType T);
753 /// Returns the location of the entity being instantiated, if known.
754 SourceLocation getBaseLocation() { return Loc; }
756 /// Returns the name of the entity being instantiated, if any.
757 DeclarationName getBaseEntity() { return Entity; }
759 /// Sets the "base" location and entity when that
760 /// information is known based on another transformation.
761 void setBase(SourceLocation Loc, DeclarationName Entity) {
763 this->Entity = Entity;
766 bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
767 SourceRange PatternRange,
768 ArrayRef<UnexpandedParameterPack> Unexpanded,
769 bool &ShouldExpand, bool &RetainExpansion,
770 Optional<unsigned> &NumExpansions) {
771 return getSema().CheckParameterPacksForExpansion(EllipsisLoc,
772 PatternRange, Unexpanded,
779 void ExpandingFunctionParameterPack(ParmVarDecl *Pack) {
780 SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(Pack);
783 TemplateArgument ForgetPartiallySubstitutedPack() {
784 TemplateArgument Result;
785 if (NamedDecl *PartialPack
786 = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
787 MultiLevelTemplateArgumentList &TemplateArgs
788 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
789 unsigned Depth, Index;
790 std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
791 if (TemplateArgs.hasTemplateArgument(Depth, Index)) {
792 Result = TemplateArgs(Depth, Index);
793 TemplateArgs.setArgument(Depth, Index, TemplateArgument());
800 void RememberPartiallySubstitutedPack(TemplateArgument Arg) {
804 if (NamedDecl *PartialPack
805 = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
806 MultiLevelTemplateArgumentList &TemplateArgs
807 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
808 unsigned Depth, Index;
809 std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
810 TemplateArgs.setArgument(Depth, Index, Arg);
814 /// Transform the given declaration by instantiating a reference to
815 /// this declaration.
816 Decl *TransformDecl(SourceLocation Loc, Decl *D);
818 void transformAttrs(Decl *Old, Decl *New) {
819 SemaRef.InstantiateAttrs(TemplateArgs, Old, New);
822 void transformedLocalDecl(Decl *Old, ArrayRef<Decl *> NewDecls) {
823 if (Old->isParameterPack()) {
824 SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(Old);
825 for (auto *New : NewDecls)
826 SemaRef.CurrentInstantiationScope->InstantiatedLocalPackArg(
827 Old, cast<VarDecl>(New));
831 assert(NewDecls.size() == 1 &&
832 "should only have multiple expansions for a pack");
833 Decl *New = NewDecls.front();
835 // If we've instantiated the call operator of a lambda or the call
836 // operator template of a generic lambda, update the "instantiation of"
838 auto *NewMD = dyn_cast<CXXMethodDecl>(New);
839 if (NewMD && isLambdaCallOperator(NewMD)) {
840 auto *OldMD = dyn_cast<CXXMethodDecl>(Old);
841 if (auto *NewTD = NewMD->getDescribedFunctionTemplate())
842 NewTD->setInstantiatedFromMemberTemplate(
843 OldMD->getDescribedFunctionTemplate());
845 NewMD->setInstantiationOfMemberFunction(OldMD,
846 TSK_ImplicitInstantiation);
849 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Old, New);
851 // We recreated a local declaration, but not by instantiating it. There
852 // may be pending dependent diagnostics to produce.
853 if (auto *DC = dyn_cast<DeclContext>(Old))
854 SemaRef.PerformDependentDiagnostics(DC, TemplateArgs);
857 /// Transform the definition of the given declaration by
858 /// instantiating it.
859 Decl *TransformDefinition(SourceLocation Loc, Decl *D);
861 /// Transform the first qualifier within a scope by instantiating the
863 NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc);
865 /// Rebuild the exception declaration and register the declaration
866 /// as an instantiated local.
867 VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
868 TypeSourceInfo *Declarator,
869 SourceLocation StartLoc,
870 SourceLocation NameLoc,
871 IdentifierInfo *Name);
873 /// Rebuild the Objective-C exception declaration and register the
874 /// declaration as an instantiated local.
875 VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
876 TypeSourceInfo *TSInfo, QualType T);
878 /// Check for tag mismatches when instantiating an
880 QualType RebuildElaboratedType(SourceLocation KeywordLoc,
881 ElaboratedTypeKeyword Keyword,
882 NestedNameSpecifierLoc QualifierLoc,
886 TransformTemplateName(CXXScopeSpec &SS, TemplateName Name,
887 SourceLocation NameLoc,
888 QualType ObjectType = QualType(),
889 NamedDecl *FirstQualifierInScope = nullptr,
890 bool AllowInjectedClassName = false);
892 const LoopHintAttr *TransformLoopHintAttr(const LoopHintAttr *LH);
894 ExprResult TransformPredefinedExpr(PredefinedExpr *E);
895 ExprResult TransformDeclRefExpr(DeclRefExpr *E);
896 ExprResult TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E);
898 ExprResult TransformTemplateParmRefExpr(DeclRefExpr *E,
899 NonTypeTemplateParmDecl *D);
900 ExprResult TransformSubstNonTypeTemplateParmPackExpr(
901 SubstNonTypeTemplateParmPackExpr *E);
903 /// Rebuild a DeclRefExpr for a VarDecl reference.
904 ExprResult RebuildVarDeclRefExpr(VarDecl *PD, SourceLocation Loc);
906 /// Transform a reference to a function or init-capture parameter pack.
907 ExprResult TransformFunctionParmPackRefExpr(DeclRefExpr *E, VarDecl *PD);
909 /// Transform a FunctionParmPackExpr which was built when we couldn't
910 /// expand a function parameter pack reference which refers to an expanded
912 ExprResult TransformFunctionParmPackExpr(FunctionParmPackExpr *E);
914 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
915 FunctionProtoTypeLoc TL) {
916 // Call the base version; it will forward to our overridden version below.
917 return inherited::TransformFunctionProtoType(TLB, TL);
920 template<typename Fn>
921 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
922 FunctionProtoTypeLoc TL,
923 CXXRecordDecl *ThisContext,
924 Qualifiers ThisTypeQuals,
925 Fn TransformExceptionSpec);
927 ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm,
929 Optional<unsigned> NumExpansions,
930 bool ExpectParameterPack);
932 /// Transforms a template type parameter type by performing
933 /// substitution of the corresponding template type argument.
934 QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
935 TemplateTypeParmTypeLoc TL);
937 /// Transforms an already-substituted template type parameter pack
938 /// into either itself (if we aren't substituting into its pack expansion)
939 /// or the appropriate substituted argument.
940 QualType TransformSubstTemplateTypeParmPackType(TypeLocBuilder &TLB,
941 SubstTemplateTypeParmPackTypeLoc TL);
943 ExprResult TransformLambdaExpr(LambdaExpr *E) {
944 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
945 return TreeTransform<TemplateInstantiator>::TransformLambdaExpr(E);
948 TemplateParameterList *TransformTemplateParameterList(
949 TemplateParameterList *OrigTPL) {
950 if (!OrigTPL || !OrigTPL->size()) return OrigTPL;
952 DeclContext *Owner = OrigTPL->getParam(0)->getDeclContext();
953 TemplateDeclInstantiator DeclInstantiator(getSema(),
954 /* DeclContext *Owner */ Owner, TemplateArgs);
955 return DeclInstantiator.SubstTemplateParams(OrigTPL);
958 ExprResult transformNonTypeTemplateParmRef(NonTypeTemplateParmDecl *parm,
960 TemplateArgument arg);
964 bool TemplateInstantiator::AlreadyTransformed(QualType T) {
968 if (T->isInstantiationDependentType() || T->isVariablyModifiedType())
971 getSema().MarkDeclarationsReferencedInType(Loc, T);
975 static TemplateArgument
976 getPackSubstitutedTemplateArgument(Sema &S, TemplateArgument Arg) {
977 assert(S.ArgumentPackSubstitutionIndex >= 0);
978 assert(S.ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
979 Arg = Arg.pack_begin()[S.ArgumentPackSubstitutionIndex];
980 if (Arg.isPackExpansion())
981 Arg = Arg.getPackExpansionPattern();
985 Decl *TemplateInstantiator::TransformDecl(SourceLocation Loc, Decl *D) {
989 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(D)) {
990 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
991 // If the corresponding template argument is NULL or non-existent, it's
992 // because we are performing instantiation from explicitly-specified
993 // template arguments in a function template, but there were some
994 // arguments left unspecified.
995 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
999 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
1001 if (TTP->isParameterPack()) {
1002 assert(Arg.getKind() == TemplateArgument::Pack &&
1003 "Missing argument pack");
1004 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1007 TemplateName Template = Arg.getAsTemplate().getNameToSubstitute();
1008 assert(!Template.isNull() && Template.getAsTemplateDecl() &&
1009 "Wrong kind of template template argument");
1010 return Template.getAsTemplateDecl();
1013 // Fall through to find the instantiated declaration for this template
1014 // template parameter.
1017 return SemaRef.FindInstantiatedDecl(Loc, cast<NamedDecl>(D), TemplateArgs);
1020 Decl *TemplateInstantiator::TransformDefinition(SourceLocation Loc, Decl *D) {
1021 Decl *Inst = getSema().SubstDecl(D, getSema().CurContext, TemplateArgs);
1025 getSema().CurrentInstantiationScope->InstantiatedLocal(D, Inst);
1030 TemplateInstantiator::TransformFirstQualifierInScope(NamedDecl *D,
1031 SourceLocation Loc) {
1032 // If the first part of the nested-name-specifier was a template type
1033 // parameter, instantiate that type parameter down to a tag type.
1034 if (TemplateTypeParmDecl *TTPD = dyn_cast_or_null<TemplateTypeParmDecl>(D)) {
1035 const TemplateTypeParmType *TTP
1036 = cast<TemplateTypeParmType>(getSema().Context.getTypeDeclType(TTPD));
1038 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1039 // FIXME: This needs testing w/ member access expressions.
1040 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getIndex());
1042 if (TTP->isParameterPack()) {
1043 assert(Arg.getKind() == TemplateArgument::Pack &&
1044 "Missing argument pack");
1046 if (getSema().ArgumentPackSubstitutionIndex == -1)
1049 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1052 QualType T = Arg.getAsType();
1054 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
1056 if (const TagType *Tag = T->getAs<TagType>())
1057 return Tag->getDecl();
1059 // The resulting type is not a tag; complain.
1060 getSema().Diag(Loc, diag::err_nested_name_spec_non_tag) << T;
1065 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
1069 TemplateInstantiator::RebuildExceptionDecl(VarDecl *ExceptionDecl,
1070 TypeSourceInfo *Declarator,
1071 SourceLocation StartLoc,
1072 SourceLocation NameLoc,
1073 IdentifierInfo *Name) {
1074 VarDecl *Var = inherited::RebuildExceptionDecl(ExceptionDecl, Declarator,
1075 StartLoc, NameLoc, Name);
1077 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
1081 VarDecl *TemplateInstantiator::RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
1082 TypeSourceInfo *TSInfo,
1084 VarDecl *Var = inherited::RebuildObjCExceptionDecl(ExceptionDecl, TSInfo, T);
1086 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
1091 TemplateInstantiator::RebuildElaboratedType(SourceLocation KeywordLoc,
1092 ElaboratedTypeKeyword Keyword,
1093 NestedNameSpecifierLoc QualifierLoc,
1095 if (const TagType *TT = T->getAs<TagType>()) {
1096 TagDecl* TD = TT->getDecl();
1098 SourceLocation TagLocation = KeywordLoc;
1100 IdentifierInfo *Id = TD->getIdentifier();
1102 // TODO: should we even warn on struct/class mismatches for this? Seems
1103 // like it's likely to produce a lot of spurious errors.
1104 if (Id && Keyword != ETK_None && Keyword != ETK_Typename) {
1105 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForKeyword(Keyword);
1106 if (!SemaRef.isAcceptableTagRedeclaration(TD, Kind, /*isDefinition*/false,
1108 SemaRef.Diag(TagLocation, diag::err_use_with_wrong_tag)
1110 << FixItHint::CreateReplacement(SourceRange(TagLocation),
1112 SemaRef.Diag(TD->getLocation(), diag::note_previous_use);
1117 return TreeTransform<TemplateInstantiator>::RebuildElaboratedType(KeywordLoc,
1123 TemplateName TemplateInstantiator::TransformTemplateName(
1124 CXXScopeSpec &SS, TemplateName Name, SourceLocation NameLoc,
1125 QualType ObjectType, NamedDecl *FirstQualifierInScope,
1126 bool AllowInjectedClassName) {
1127 if (TemplateTemplateParmDecl *TTP
1128 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl())) {
1129 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1130 // If the corresponding template argument is NULL or non-existent, it's
1131 // because we are performing instantiation from explicitly-specified
1132 // template arguments in a function template, but there were some
1133 // arguments left unspecified.
1134 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
1135 TTP->getPosition()))
1138 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
1140 if (TTP->isParameterPack()) {
1141 assert(Arg.getKind() == TemplateArgument::Pack &&
1142 "Missing argument pack");
1144 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1145 // We have the template argument pack to substitute, but we're not
1146 // actually expanding the enclosing pack expansion yet. So, just
1147 // keep the entire argument pack.
1148 return getSema().Context.getSubstTemplateTemplateParmPack(TTP, Arg);
1151 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1154 TemplateName Template = Arg.getAsTemplate().getNameToSubstitute();
1155 assert(!Template.isNull() && "Null template template argument");
1156 assert(!Template.getAsQualifiedTemplateName() &&
1157 "template decl to substitute is qualified?");
1159 Template = getSema().Context.getSubstTemplateTemplateParm(TTP, Template);
1164 if (SubstTemplateTemplateParmPackStorage *SubstPack
1165 = Name.getAsSubstTemplateTemplateParmPack()) {
1166 if (getSema().ArgumentPackSubstitutionIndex == -1)
1169 TemplateArgument Arg = SubstPack->getArgumentPack();
1170 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1171 return Arg.getAsTemplate().getNameToSubstitute();
1174 return inherited::TransformTemplateName(SS, Name, NameLoc, ObjectType,
1175 FirstQualifierInScope,
1176 AllowInjectedClassName);
1180 TemplateInstantiator::TransformPredefinedExpr(PredefinedExpr *E) {
1181 if (!E->isTypeDependent())
1184 return getSema().BuildPredefinedExpr(E->getLocation(), E->getIdentKind());
1188 TemplateInstantiator::TransformTemplateParmRefExpr(DeclRefExpr *E,
1189 NonTypeTemplateParmDecl *NTTP) {
1190 // If the corresponding template argument is NULL or non-existent, it's
1191 // because we are performing instantiation from explicitly-specified
1192 // template arguments in a function template, but there were some
1193 // arguments left unspecified.
1194 if (!TemplateArgs.hasTemplateArgument(NTTP->getDepth(),
1195 NTTP->getPosition()))
1198 TemplateArgument Arg = TemplateArgs(NTTP->getDepth(), NTTP->getPosition());
1200 if (TemplateArgs.getNumLevels() != TemplateArgs.getNumSubstitutedLevels()) {
1201 // We're performing a partial substitution, so the substituted argument
1202 // could be dependent. As a result we can't create a SubstNonType*Expr
1203 // node now, since that represents a fully-substituted argument.
1204 // FIXME: We should have some AST representation for this.
1205 if (Arg.getKind() == TemplateArgument::Pack) {
1206 // FIXME: This won't work for alias templates.
1207 assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() &&
1208 "unexpected pack arguments in partial substitution");
1209 Arg = Arg.pack_begin()->getPackExpansionPattern();
1211 assert(Arg.getKind() == TemplateArgument::Expression &&
1212 "unexpected nontype template argument kind in partial substitution");
1213 return Arg.getAsExpr();
1216 if (NTTP->isParameterPack()) {
1217 assert(Arg.getKind() == TemplateArgument::Pack &&
1218 "Missing argument pack");
1220 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1221 // We have an argument pack, but we can't select a particular argument
1222 // out of it yet. Therefore, we'll build an expression to hold on to that
1224 QualType TargetType = SemaRef.SubstType(NTTP->getType(), TemplateArgs,
1226 NTTP->getDeclName());
1227 if (TargetType.isNull())
1230 return new (SemaRef.Context) SubstNonTypeTemplateParmPackExpr(
1231 TargetType.getNonLValueExprType(SemaRef.Context),
1232 TargetType->isReferenceType() ? VK_LValue : VK_RValue, NTTP,
1233 E->getLocation(), Arg);
1236 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1239 return transformNonTypeTemplateParmRef(NTTP, E->getLocation(), Arg);
1242 const LoopHintAttr *
1243 TemplateInstantiator::TransformLoopHintAttr(const LoopHintAttr *LH) {
1244 Expr *TransformedExpr = getDerived().TransformExpr(LH->getValue()).get();
1246 if (TransformedExpr == LH->getValue())
1249 // Generate error if there is a problem with the value.
1250 if (getSema().CheckLoopHintExpr(TransformedExpr, LH->getLocation()))
1253 // Create new LoopHintValueAttr with integral expression in place of the
1254 // non-type template parameter.
1255 return LoopHintAttr::CreateImplicit(
1256 getSema().Context, LH->getSemanticSpelling(), LH->getOption(),
1257 LH->getState(), TransformedExpr, LH->getRange());
1260 ExprResult TemplateInstantiator::transformNonTypeTemplateParmRef(
1261 NonTypeTemplateParmDecl *parm,
1263 TemplateArgument arg) {
1267 // The template argument itself might be an expression, in which
1268 // case we just return that expression.
1269 if (arg.getKind() == TemplateArgument::Expression) {
1270 Expr *argExpr = arg.getAsExpr();
1272 type = argExpr->getType();
1274 } else if (arg.getKind() == TemplateArgument::Declaration ||
1275 arg.getKind() == TemplateArgument::NullPtr) {
1277 if (arg.getKind() == TemplateArgument::Declaration) {
1278 VD = arg.getAsDecl();
1280 // Find the instantiation of the template argument. This is
1281 // required for nested templates.
1282 VD = cast_or_null<ValueDecl>(
1283 getSema().FindInstantiatedDecl(loc, VD, TemplateArgs));
1287 // Propagate NULL template argument.
1291 // Derive the type we want the substituted decl to have. This had
1292 // better be non-dependent, or these checks will have serious problems.
1293 if (parm->isExpandedParameterPack()) {
1294 type = parm->getExpansionType(SemaRef.ArgumentPackSubstitutionIndex);
1295 } else if (parm->isParameterPack() &&
1296 isa<PackExpansionType>(parm->getType())) {
1297 type = SemaRef.SubstType(
1298 cast<PackExpansionType>(parm->getType())->getPattern(),
1299 TemplateArgs, loc, parm->getDeclName());
1301 type = SemaRef.SubstType(VD ? arg.getParamTypeForDecl() : arg.getNullPtrType(),
1302 TemplateArgs, loc, parm->getDeclName());
1304 assert(!type.isNull() && "type substitution failed for param type");
1305 assert(!type->isDependentType() && "param type still dependent");
1306 result = SemaRef.BuildExpressionFromDeclTemplateArgument(arg, type, loc);
1308 if (!result.isInvalid()) type = result.get()->getType();
1310 result = SemaRef.BuildExpressionFromIntegralTemplateArgument(arg, loc);
1312 // Note that this type can be different from the type of 'result',
1313 // e.g. if it's an enum type.
1314 type = arg.getIntegralType();
1316 if (result.isInvalid()) return ExprError();
1318 Expr *resultExpr = result.get();
1319 return new (SemaRef.Context) SubstNonTypeTemplateParmExpr(
1320 type, resultExpr->getValueKind(), loc, parm, resultExpr);
1324 TemplateInstantiator::TransformSubstNonTypeTemplateParmPackExpr(
1325 SubstNonTypeTemplateParmPackExpr *E) {
1326 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1327 // We aren't expanding the parameter pack, so just return ourselves.
1331 TemplateArgument Arg = E->getArgumentPack();
1332 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1333 return transformNonTypeTemplateParmRef(E->getParameterPack(),
1334 E->getParameterPackLocation(),
1338 ExprResult TemplateInstantiator::RebuildVarDeclRefExpr(VarDecl *PD,
1339 SourceLocation Loc) {
1340 DeclarationNameInfo NameInfo(PD->getDeclName(), Loc);
1341 return getSema().BuildDeclarationNameExpr(CXXScopeSpec(), NameInfo, PD);
1345 TemplateInstantiator::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {
1346 if (getSema().ArgumentPackSubstitutionIndex != -1) {
1347 // We can expand this parameter pack now.
1348 VarDecl *D = E->getExpansion(getSema().ArgumentPackSubstitutionIndex);
1349 VarDecl *VD = cast_or_null<VarDecl>(TransformDecl(E->getExprLoc(), D));
1352 return RebuildVarDeclRefExpr(VD, E->getExprLoc());
1355 QualType T = TransformType(E->getType());
1359 // Transform each of the parameter expansions into the corresponding
1360 // parameters in the instantiation of the function decl.
1361 SmallVector<VarDecl *, 8> Vars;
1362 Vars.reserve(E->getNumExpansions());
1363 for (FunctionParmPackExpr::iterator I = E->begin(), End = E->end();
1365 VarDecl *D = cast_or_null<VarDecl>(TransformDecl(E->getExprLoc(), *I));
1372 FunctionParmPackExpr::Create(getSema().Context, T, E->getParameterPack(),
1373 E->getParameterPackLocation(), Vars);
1374 getSema().MarkFunctionParmPackReferenced(PackExpr);
1379 TemplateInstantiator::TransformFunctionParmPackRefExpr(DeclRefExpr *E,
1381 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
1382 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
1383 = getSema().CurrentInstantiationScope->findInstantiationOf(PD);
1384 assert(Found && "no instantiation for parameter pack");
1386 Decl *TransformedDecl;
1387 if (DeclArgumentPack *Pack = Found->dyn_cast<DeclArgumentPack *>()) {
1388 // If this is a reference to a function parameter pack which we can
1389 // substitute but can't yet expand, build a FunctionParmPackExpr for it.
1390 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1391 QualType T = TransformType(E->getType());
1394 auto *PackExpr = FunctionParmPackExpr::Create(getSema().Context, T, PD,
1395 E->getExprLoc(), *Pack);
1396 getSema().MarkFunctionParmPackReferenced(PackExpr);
1400 TransformedDecl = (*Pack)[getSema().ArgumentPackSubstitutionIndex];
1402 TransformedDecl = Found->get<Decl*>();
1405 // We have either an unexpanded pack or a specific expansion.
1406 return RebuildVarDeclRefExpr(cast<VarDecl>(TransformedDecl), E->getExprLoc());
1410 TemplateInstantiator::TransformDeclRefExpr(DeclRefExpr *E) {
1411 NamedDecl *D = E->getDecl();
1413 // Handle references to non-type template parameters and non-type template
1415 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) {
1416 if (NTTP->getDepth() < TemplateArgs.getNumLevels())
1417 return TransformTemplateParmRefExpr(E, NTTP);
1419 // We have a non-type template parameter that isn't fully substituted;
1420 // FindInstantiatedDecl will find it in the local instantiation scope.
1423 // Handle references to function parameter packs.
1424 if (VarDecl *PD = dyn_cast<VarDecl>(D))
1425 if (PD->isParameterPack())
1426 return TransformFunctionParmPackRefExpr(E, PD);
1428 return TreeTransform<TemplateInstantiator>::TransformDeclRefExpr(E);
1431 ExprResult TemplateInstantiator::TransformCXXDefaultArgExpr(
1432 CXXDefaultArgExpr *E) {
1433 assert(!cast<FunctionDecl>(E->getParam()->getDeclContext())->
1434 getDescribedFunctionTemplate() &&
1435 "Default arg expressions are never formed in dependent cases.");
1436 return SemaRef.BuildCXXDefaultArgExpr(E->getUsedLocation(),
1437 cast<FunctionDecl>(E->getParam()->getDeclContext()),
1441 template<typename Fn>
1442 QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB,
1443 FunctionProtoTypeLoc TL,
1444 CXXRecordDecl *ThisContext,
1445 Qualifiers ThisTypeQuals,
1446 Fn TransformExceptionSpec) {
1447 // We need a local instantiation scope for this function prototype.
1448 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
1449 return inherited::TransformFunctionProtoType(
1450 TLB, TL, ThisContext, ThisTypeQuals, TransformExceptionSpec);
1454 TemplateInstantiator::TransformFunctionTypeParam(ParmVarDecl *OldParm,
1455 int indexAdjustment,
1456 Optional<unsigned> NumExpansions,
1457 bool ExpectParameterPack) {
1458 return SemaRef.SubstParmVarDecl(OldParm, TemplateArgs, indexAdjustment,
1459 NumExpansions, ExpectParameterPack);
1463 TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB,
1464 TemplateTypeParmTypeLoc TL) {
1465 const TemplateTypeParmType *T = TL.getTypePtr();
1466 if (T->getDepth() < TemplateArgs.getNumLevels()) {
1467 // Replace the template type parameter with its corresponding
1468 // template argument.
1470 // If the corresponding template argument is NULL or doesn't exist, it's
1471 // because we are performing instantiation from explicitly-specified
1472 // template arguments in a function template class, but there were some
1473 // arguments left unspecified.
1474 if (!TemplateArgs.hasTemplateArgument(T->getDepth(), T->getIndex())) {
1475 TemplateTypeParmTypeLoc NewTL
1476 = TLB.push<TemplateTypeParmTypeLoc>(TL.getType());
1477 NewTL.setNameLoc(TL.getNameLoc());
1478 return TL.getType();
1481 TemplateArgument Arg = TemplateArgs(T->getDepth(), T->getIndex());
1483 if (T->isParameterPack()) {
1484 assert(Arg.getKind() == TemplateArgument::Pack &&
1485 "Missing argument pack");
1487 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1488 // We have the template argument pack, but we're not expanding the
1489 // enclosing pack expansion yet. Just save the template argument
1490 // pack for later substitution.
1492 = getSema().Context.getSubstTemplateTypeParmPackType(T, Arg);
1493 SubstTemplateTypeParmPackTypeLoc NewTL
1494 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(Result);
1495 NewTL.setNameLoc(TL.getNameLoc());
1499 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1502 assert(Arg.getKind() == TemplateArgument::Type &&
1503 "Template argument kind mismatch");
1505 QualType Replacement = Arg.getAsType();
1507 // TODO: only do this uniquing once, at the start of instantiation.
1509 = getSema().Context.getSubstTemplateTypeParmType(T, Replacement);
1510 SubstTemplateTypeParmTypeLoc NewTL
1511 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
1512 NewTL.setNameLoc(TL.getNameLoc());
1516 // The template type parameter comes from an inner template (e.g.,
1517 // the template parameter list of a member template inside the
1518 // template we are instantiating). Create a new template type
1519 // parameter with the template "level" reduced by one.
1520 TemplateTypeParmDecl *NewTTPDecl = nullptr;
1521 if (TemplateTypeParmDecl *OldTTPDecl = T->getDecl())
1522 NewTTPDecl = cast_or_null<TemplateTypeParmDecl>(
1523 TransformDecl(TL.getNameLoc(), OldTTPDecl));
1525 QualType Result = getSema().Context.getTemplateTypeParmType(
1526 T->getDepth() - TemplateArgs.getNumSubstitutedLevels(), T->getIndex(),
1527 T->isParameterPack(), NewTTPDecl);
1528 TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result);
1529 NewTL.setNameLoc(TL.getNameLoc());
1534 TemplateInstantiator::TransformSubstTemplateTypeParmPackType(
1535 TypeLocBuilder &TLB,
1536 SubstTemplateTypeParmPackTypeLoc TL) {
1537 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1538 // We aren't expanding the parameter pack, so just return ourselves.
1539 SubstTemplateTypeParmPackTypeLoc NewTL
1540 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(TL.getType());
1541 NewTL.setNameLoc(TL.getNameLoc());
1542 return TL.getType();
1545 TemplateArgument Arg = TL.getTypePtr()->getArgumentPack();
1546 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1547 QualType Result = Arg.getAsType();
1549 Result = getSema().Context.getSubstTemplateTypeParmType(
1550 TL.getTypePtr()->getReplacedParameter(),
1552 SubstTemplateTypeParmTypeLoc NewTL
1553 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
1554 NewTL.setNameLoc(TL.getNameLoc());
1558 /// Perform substitution on the type T with a given set of template
1561 /// This routine substitutes the given template arguments into the
1562 /// type T and produces the instantiated type.
1564 /// \param T the type into which the template arguments will be
1565 /// substituted. If this type is not dependent, it will be returned
1568 /// \param Args the template arguments that will be
1569 /// substituted for the top-level template parameters within T.
1571 /// \param Loc the location in the source code where this substitution
1572 /// is being performed. It will typically be the location of the
1573 /// declarator (if we're instantiating the type of some declaration)
1574 /// or the location of the type in the source code (if, e.g., we're
1575 /// instantiating the type of a cast expression).
1577 /// \param Entity the name of the entity associated with a declaration
1578 /// being instantiated (if any). May be empty to indicate that there
1579 /// is no such entity (if, e.g., this is a type that occurs as part of
1580 /// a cast expression) or that the entity has no name (e.g., an
1581 /// unnamed function parameter).
1583 /// \param AllowDeducedTST Whether a DeducedTemplateSpecializationType is
1584 /// acceptable as the top level type of the result.
1586 /// \returns If the instantiation succeeds, the instantiated
1587 /// type. Otherwise, produces diagnostics and returns a NULL type.
1588 TypeSourceInfo *Sema::SubstType(TypeSourceInfo *T,
1589 const MultiLevelTemplateArgumentList &Args,
1591 DeclarationName Entity,
1592 bool AllowDeducedTST) {
1593 assert(!CodeSynthesisContexts.empty() &&
1594 "Cannot perform an instantiation without some context on the "
1595 "instantiation stack");
1597 if (!T->getType()->isInstantiationDependentType() &&
1598 !T->getType()->isVariablyModifiedType())
1601 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1602 return AllowDeducedTST ? Instantiator.TransformTypeWithDeducedTST(T)
1603 : Instantiator.TransformType(T);
1606 TypeSourceInfo *Sema::SubstType(TypeLoc TL,
1607 const MultiLevelTemplateArgumentList &Args,
1609 DeclarationName Entity) {
1610 assert(!CodeSynthesisContexts.empty() &&
1611 "Cannot perform an instantiation without some context on the "
1612 "instantiation stack");
1614 if (TL.getType().isNull())
1617 if (!TL.getType()->isInstantiationDependentType() &&
1618 !TL.getType()->isVariablyModifiedType()) {
1619 // FIXME: Make a copy of the TypeLoc data here, so that we can
1620 // return a new TypeSourceInfo. Inefficient!
1622 TLB.pushFullCopy(TL);
1623 return TLB.getTypeSourceInfo(Context, TL.getType());
1626 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1628 TLB.reserve(TL.getFullDataSize());
1629 QualType Result = Instantiator.TransformType(TLB, TL);
1630 if (Result.isNull())
1633 return TLB.getTypeSourceInfo(Context, Result);
1636 /// Deprecated form of the above.
1637 QualType Sema::SubstType(QualType T,
1638 const MultiLevelTemplateArgumentList &TemplateArgs,
1639 SourceLocation Loc, DeclarationName Entity) {
1640 assert(!CodeSynthesisContexts.empty() &&
1641 "Cannot perform an instantiation without some context on the "
1642 "instantiation stack");
1644 // If T is not a dependent type or a variably-modified type, there
1645 // is nothing to do.
1646 if (!T->isInstantiationDependentType() && !T->isVariablyModifiedType())
1649 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity);
1650 return Instantiator.TransformType(T);
1653 static bool NeedsInstantiationAsFunctionType(TypeSourceInfo *T) {
1654 if (T->getType()->isInstantiationDependentType() ||
1655 T->getType()->isVariablyModifiedType())
1658 TypeLoc TL = T->getTypeLoc().IgnoreParens();
1659 if (!TL.getAs<FunctionProtoTypeLoc>())
1662 FunctionProtoTypeLoc FP = TL.castAs<FunctionProtoTypeLoc>();
1663 for (ParmVarDecl *P : FP.getParams()) {
1664 // This must be synthesized from a typedef.
1667 // If there are any parameters, a new TypeSourceInfo that refers to the
1668 // instantiated parameters must be built.
1675 /// A form of SubstType intended specifically for instantiating the
1676 /// type of a FunctionDecl. Its purpose is solely to force the
1677 /// instantiation of default-argument expressions and to avoid
1678 /// instantiating an exception-specification.
1679 TypeSourceInfo *Sema::SubstFunctionDeclType(TypeSourceInfo *T,
1680 const MultiLevelTemplateArgumentList &Args,
1682 DeclarationName Entity,
1683 CXXRecordDecl *ThisContext,
1684 Qualifiers ThisTypeQuals) {
1685 assert(!CodeSynthesisContexts.empty() &&
1686 "Cannot perform an instantiation without some context on the "
1687 "instantiation stack");
1689 if (!NeedsInstantiationAsFunctionType(T))
1692 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1696 TypeLoc TL = T->getTypeLoc();
1697 TLB.reserve(TL.getFullDataSize());
1701 if (FunctionProtoTypeLoc Proto =
1702 TL.IgnoreParens().getAs<FunctionProtoTypeLoc>()) {
1703 // Instantiate the type, other than its exception specification. The
1704 // exception specification is instantiated in InitFunctionInstantiation
1705 // once we've built the FunctionDecl.
1706 // FIXME: Set the exception specification to EST_Uninstantiated here,
1707 // instead of rebuilding the function type again later.
1708 Result = Instantiator.TransformFunctionProtoType(
1709 TLB, Proto, ThisContext, ThisTypeQuals,
1710 [](FunctionProtoType::ExceptionSpecInfo &ESI,
1711 bool &Changed) { return false; });
1713 Result = Instantiator.TransformType(TLB, TL);
1715 if (Result.isNull())
1718 return TLB.getTypeSourceInfo(Context, Result);
1721 bool Sema::SubstExceptionSpec(SourceLocation Loc,
1722 FunctionProtoType::ExceptionSpecInfo &ESI,
1723 SmallVectorImpl<QualType> &ExceptionStorage,
1724 const MultiLevelTemplateArgumentList &Args) {
1725 assert(ESI.Type != EST_Uninstantiated);
1727 bool Changed = false;
1728 TemplateInstantiator Instantiator(*this, Args, Loc, DeclarationName());
1729 return Instantiator.TransformExceptionSpec(Loc, ESI, ExceptionStorage,
1733 void Sema::SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto,
1734 const MultiLevelTemplateArgumentList &Args) {
1735 FunctionProtoType::ExceptionSpecInfo ESI =
1736 Proto->getExtProtoInfo().ExceptionSpec;
1738 SmallVector<QualType, 4> ExceptionStorage;
1739 if (SubstExceptionSpec(New->getTypeSourceInfo()->getTypeLoc().getEndLoc(),
1740 ESI, ExceptionStorage, Args))
1741 // On error, recover by dropping the exception specification.
1742 ESI.Type = EST_None;
1744 UpdateExceptionSpec(New, ESI);
1747 ParmVarDecl *Sema::SubstParmVarDecl(ParmVarDecl *OldParm,
1748 const MultiLevelTemplateArgumentList &TemplateArgs,
1749 int indexAdjustment,
1750 Optional<unsigned> NumExpansions,
1751 bool ExpectParameterPack) {
1752 TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
1753 TypeSourceInfo *NewDI = nullptr;
1755 TypeLoc OldTL = OldDI->getTypeLoc();
1756 if (PackExpansionTypeLoc ExpansionTL = OldTL.getAs<PackExpansionTypeLoc>()) {
1758 // We have a function parameter pack. Substitute into the pattern of the
1760 NewDI = SubstType(ExpansionTL.getPatternLoc(), TemplateArgs,
1761 OldParm->getLocation(), OldParm->getDeclName());
1765 if (NewDI->getType()->containsUnexpandedParameterPack()) {
1766 // We still have unexpanded parameter packs, which means that
1767 // our function parameter is still a function parameter pack.
1768 // Therefore, make its type a pack expansion type.
1769 NewDI = CheckPackExpansion(NewDI, ExpansionTL.getEllipsisLoc(),
1771 } else if (ExpectParameterPack) {
1772 // We expected to get a parameter pack but didn't (because the type
1773 // itself is not a pack expansion type), so complain. This can occur when
1774 // the substitution goes through an alias template that "loses" the
1776 Diag(OldParm->getLocation(),
1777 diag::err_function_parameter_pack_without_parameter_packs)
1778 << NewDI->getType();
1782 NewDI = SubstType(OldDI, TemplateArgs, OldParm->getLocation(),
1783 OldParm->getDeclName());
1789 if (NewDI->getType()->isVoidType()) {
1790 Diag(OldParm->getLocation(), diag::err_param_with_void_type);
1794 ParmVarDecl *NewParm = CheckParameter(Context.getTranslationUnitDecl(),
1795 OldParm->getInnerLocStart(),
1796 OldParm->getLocation(),
1797 OldParm->getIdentifier(),
1798 NewDI->getType(), NewDI,
1799 OldParm->getStorageClass());
1803 // Mark the (new) default argument as uninstantiated (if any).
1804 if (OldParm->hasUninstantiatedDefaultArg()) {
1805 Expr *Arg = OldParm->getUninstantiatedDefaultArg();
1806 NewParm->setUninstantiatedDefaultArg(Arg);
1807 } else if (OldParm->hasUnparsedDefaultArg()) {
1808 NewParm->setUnparsedDefaultArg();
1809 UnparsedDefaultArgInstantiations[OldParm].push_back(NewParm);
1810 } else if (Expr *Arg = OldParm->getDefaultArg()) {
1811 FunctionDecl *OwningFunc = cast<FunctionDecl>(OldParm->getDeclContext());
1812 if (OwningFunc->isLexicallyWithinFunctionOrMethod()) {
1813 // Instantiate default arguments for methods of local classes (DR1484)
1814 // and non-defining declarations.
1815 Sema::ContextRAII SavedContext(*this, OwningFunc);
1816 LocalInstantiationScope Local(*this, true);
1817 ExprResult NewArg = SubstExpr(Arg, TemplateArgs);
1818 if (NewArg.isUsable()) {
1819 // It would be nice if we still had this.
1820 SourceLocation EqualLoc = NewArg.get()->getBeginLoc();
1821 SetParamDefaultArgument(NewParm, NewArg.get(), EqualLoc);
1824 // FIXME: if we non-lazily instantiated non-dependent default args for
1825 // non-dependent parameter types we could remove a bunch of duplicate
1826 // conversion warnings for such arguments.
1827 NewParm->setUninstantiatedDefaultArg(Arg);
1831 NewParm->setHasInheritedDefaultArg(OldParm->hasInheritedDefaultArg());
1833 if (OldParm->isParameterPack() && !NewParm->isParameterPack()) {
1834 // Add the new parameter to the instantiated parameter pack.
1835 CurrentInstantiationScope->InstantiatedLocalPackArg(OldParm, NewParm);
1837 // Introduce an Old -> New mapping
1838 CurrentInstantiationScope->InstantiatedLocal(OldParm, NewParm);
1841 // FIXME: OldParm may come from a FunctionProtoType, in which case CurContext
1842 // can be anything, is this right ?
1843 NewParm->setDeclContext(CurContext);
1845 NewParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
1846 OldParm->getFunctionScopeIndex() + indexAdjustment);
1848 InstantiateAttrs(TemplateArgs, OldParm, NewParm);
1853 /// Substitute the given template arguments into the given set of
1854 /// parameters, producing the set of parameter types that would be generated
1855 /// from such a substitution.
1856 bool Sema::SubstParmTypes(
1857 SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
1858 const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
1859 const MultiLevelTemplateArgumentList &TemplateArgs,
1860 SmallVectorImpl<QualType> &ParamTypes,
1861 SmallVectorImpl<ParmVarDecl *> *OutParams,
1862 ExtParameterInfoBuilder &ParamInfos) {
1863 assert(!CodeSynthesisContexts.empty() &&
1864 "Cannot perform an instantiation without some context on the "
1865 "instantiation stack");
1867 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
1869 return Instantiator.TransformFunctionTypeParams(
1870 Loc, Params, nullptr, ExtParamInfos, ParamTypes, OutParams, ParamInfos);
1873 /// Perform substitution on the base class specifiers of the
1874 /// given class template specialization.
1876 /// Produces a diagnostic and returns true on error, returns false and
1877 /// attaches the instantiated base classes to the class template
1878 /// specialization if successful.
1880 Sema::SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
1881 CXXRecordDecl *Pattern,
1882 const MultiLevelTemplateArgumentList &TemplateArgs) {
1883 bool Invalid = false;
1884 SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases;
1885 for (const auto &Base : Pattern->bases()) {
1886 if (!Base.getType()->isDependentType()) {
1887 if (const CXXRecordDecl *RD = Base.getType()->getAsCXXRecordDecl()) {
1888 if (RD->isInvalidDecl())
1889 Instantiation->setInvalidDecl();
1891 InstantiatedBases.push_back(new (Context) CXXBaseSpecifier(Base));
1895 SourceLocation EllipsisLoc;
1896 TypeSourceInfo *BaseTypeLoc;
1897 if (Base.isPackExpansion()) {
1898 // This is a pack expansion. See whether we should expand it now, or
1899 // wait until later.
1900 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
1901 collectUnexpandedParameterPacks(Base.getTypeSourceInfo()->getTypeLoc(),
1903 bool ShouldExpand = false;
1904 bool RetainExpansion = false;
1905 Optional<unsigned> NumExpansions;
1906 if (CheckParameterPacksForExpansion(Base.getEllipsisLoc(),
1907 Base.getSourceRange(),
1909 TemplateArgs, ShouldExpand,
1916 // If we should expand this pack expansion now, do so.
1918 for (unsigned I = 0; I != *NumExpansions; ++I) {
1919 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
1921 TypeSourceInfo *BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
1923 Base.getSourceRange().getBegin(),
1930 if (CXXBaseSpecifier *InstantiatedBase
1931 = CheckBaseSpecifier(Instantiation,
1932 Base.getSourceRange(),
1934 Base.getAccessSpecifierAsWritten(),
1937 InstantiatedBases.push_back(InstantiatedBase);
1945 // The resulting base specifier will (still) be a pack expansion.
1946 EllipsisLoc = Base.getEllipsisLoc();
1947 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
1948 BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
1950 Base.getSourceRange().getBegin(),
1953 BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
1955 Base.getSourceRange().getBegin(),
1964 if (CXXBaseSpecifier *InstantiatedBase
1965 = CheckBaseSpecifier(Instantiation,
1966 Base.getSourceRange(),
1968 Base.getAccessSpecifierAsWritten(),
1971 InstantiatedBases.push_back(InstantiatedBase);
1976 if (!Invalid && AttachBaseSpecifiers(Instantiation, InstantiatedBases))
1982 // Defined via #include from SemaTemplateInstantiateDecl.cpp
1985 Attr *instantiateTemplateAttribute(const Attr *At, ASTContext &C, Sema &S,
1986 const MultiLevelTemplateArgumentList &TemplateArgs);
1987 Attr *instantiateTemplateAttributeForDecl(
1988 const Attr *At, ASTContext &C, Sema &S,
1989 const MultiLevelTemplateArgumentList &TemplateArgs);
1993 /// Instantiate the definition of a class from a given pattern.
1995 /// \param PointOfInstantiation The point of instantiation within the
1998 /// \param Instantiation is the declaration whose definition is being
1999 /// instantiated. This will be either a class template specialization
2000 /// or a member class of a class template specialization.
2002 /// \param Pattern is the pattern from which the instantiation
2003 /// occurs. This will be either the declaration of a class template or
2004 /// the declaration of a member class of a class template.
2006 /// \param TemplateArgs The template arguments to be substituted into
2009 /// \param TSK the kind of implicit or explicit instantiation to perform.
2011 /// \param Complain whether to complain if the class cannot be instantiated due
2012 /// to the lack of a definition.
2014 /// \returns true if an error occurred, false otherwise.
2016 Sema::InstantiateClass(SourceLocation PointOfInstantiation,
2017 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
2018 const MultiLevelTemplateArgumentList &TemplateArgs,
2019 TemplateSpecializationKind TSK,
2021 CXXRecordDecl *PatternDef
2022 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
2023 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
2024 Instantiation->getInstantiatedFromMemberClass(),
2025 Pattern, PatternDef, TSK, Complain))
2028 llvm::TimeTraceScope TimeScope("InstantiateClass", [&]() {
2030 llvm::raw_string_ostream OS(Name);
2031 Instantiation->getNameForDiagnostic(OS, getPrintingPolicy(),
2032 /*Qualified=*/true);
2036 Pattern = PatternDef;
2038 // Record the point of instantiation.
2039 if (MemberSpecializationInfo *MSInfo
2040 = Instantiation->getMemberSpecializationInfo()) {
2041 MSInfo->setTemplateSpecializationKind(TSK);
2042 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2043 } else if (ClassTemplateSpecializationDecl *Spec
2044 = dyn_cast<ClassTemplateSpecializationDecl>(Instantiation)) {
2045 Spec->setTemplateSpecializationKind(TSK);
2046 Spec->setPointOfInstantiation(PointOfInstantiation);
2049 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
2050 if (Inst.isInvalid())
2052 assert(!Inst.isAlreadyInstantiating() && "should have been caught by caller");
2053 PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
2054 "instantiating class definition");
2056 // Enter the scope of this instantiation. We don't use
2057 // PushDeclContext because we don't have a scope.
2058 ContextRAII SavedContext(*this, Instantiation);
2059 EnterExpressionEvaluationContext EvalContext(
2060 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
2062 // If this is an instantiation of a local class, merge this local
2063 // instantiation scope with the enclosing scope. Otherwise, every
2064 // instantiation of a class has its own local instantiation scope.
2065 bool MergeWithParentScope = !Instantiation->isDefinedOutsideFunctionOrMethod();
2066 LocalInstantiationScope Scope(*this, MergeWithParentScope);
2068 // Some class state isn't processed immediately but delayed till class
2069 // instantiation completes. We may not be ready to handle any delayed state
2070 // already on the stack as it might correspond to a different class, so save
2071 // it now and put it back later.
2072 SavePendingParsedClassStateRAII SavedPendingParsedClassState(*this);
2074 // Pull attributes from the pattern onto the instantiation.
2075 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
2077 // Start the definition of this instantiation.
2078 Instantiation->startDefinition();
2080 // The instantiation is visible here, even if it was first declared in an
2081 // unimported module.
2082 Instantiation->setVisibleDespiteOwningModule();
2084 // FIXME: This loses the as-written tag kind for an explicit instantiation.
2085 Instantiation->setTagKind(Pattern->getTagKind());
2087 // Do substitution on the base class specifiers.
2088 if (SubstBaseSpecifiers(Instantiation, Pattern, TemplateArgs))
2089 Instantiation->setInvalidDecl();
2091 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
2092 SmallVector<Decl*, 4> Fields;
2093 // Delay instantiation of late parsed attributes.
2094 LateInstantiatedAttrVec LateAttrs;
2095 Instantiator.enableLateAttributeInstantiation(&LateAttrs);
2097 bool MightHaveConstexprVirtualFunctions = false;
2098 for (auto *Member : Pattern->decls()) {
2099 // Don't instantiate members not belonging in this semantic context.
2102 // template <int i> class A {
2106 // 'class B' has the template as lexical context but semantically it is
2107 // introduced in namespace scope.
2108 if (Member->getDeclContext() != Pattern)
2111 // BlockDecls can appear in a default-member-initializer. They must be the
2112 // child of a BlockExpr, so we only know how to instantiate them from there.
2113 if (isa<BlockDecl>(Member))
2116 if (Member->isInvalidDecl()) {
2117 Instantiation->setInvalidDecl();
2121 Decl *NewMember = Instantiator.Visit(Member);
2123 if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember)) {
2124 Fields.push_back(Field);
2125 } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(NewMember)) {
2126 // C++11 [temp.inst]p1: The implicit instantiation of a class template
2127 // specialization causes the implicit instantiation of the definitions
2128 // of unscoped member enumerations.
2129 // Record a point of instantiation for this implicit instantiation.
2130 if (TSK == TSK_ImplicitInstantiation && !Enum->isScoped() &&
2131 Enum->isCompleteDefinition()) {
2132 MemberSpecializationInfo *MSInfo =Enum->getMemberSpecializationInfo();
2133 assert(MSInfo && "no spec info for member enum specialization");
2134 MSInfo->setTemplateSpecializationKind(TSK_ImplicitInstantiation);
2135 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2137 } else if (StaticAssertDecl *SA = dyn_cast<StaticAssertDecl>(NewMember)) {
2138 if (SA->isFailed()) {
2139 // A static_assert failed. Bail out; instantiating this
2140 // class is probably not meaningful.
2141 Instantiation->setInvalidDecl();
2144 } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewMember)) {
2145 if (MD->isConstexpr() && !MD->getFriendObjectKind() &&
2146 (MD->isVirtualAsWritten() || Instantiation->getNumBases()))
2147 MightHaveConstexprVirtualFunctions = true;
2150 if (NewMember->isInvalidDecl())
2151 Instantiation->setInvalidDecl();
2153 // FIXME: Eventually, a NULL return will mean that one of the
2154 // instantiations was a semantic disaster, and we'll want to mark the
2155 // declaration invalid.
2156 // For now, we expect to skip some members that we can't yet handle.
2160 // Finish checking fields.
2161 ActOnFields(nullptr, Instantiation->getLocation(), Instantiation, Fields,
2162 SourceLocation(), SourceLocation(), ParsedAttributesView());
2163 CheckCompletedCXXClass(Instantiation);
2165 // Default arguments are parsed, if not instantiated. We can go instantiate
2166 // default arg exprs for default constructors if necessary now.
2167 ActOnFinishCXXNonNestedClass(Instantiation);
2169 // Instantiate late parsed attributes, and attach them to their decls.
2170 // See Sema::InstantiateAttrs
2171 for (LateInstantiatedAttrVec::iterator I = LateAttrs.begin(),
2172 E = LateAttrs.end(); I != E; ++I) {
2173 assert(CurrentInstantiationScope == Instantiator.getStartingScope());
2174 CurrentInstantiationScope = I->Scope;
2176 // Allow 'this' within late-parsed attributes.
2177 NamedDecl *ND = dyn_cast<NamedDecl>(I->NewDecl);
2178 CXXRecordDecl *ThisContext =
2179 dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
2180 CXXThisScopeRAII ThisScope(*this, ThisContext, Qualifiers(),
2181 ND && ND->isCXXInstanceMember());
2184 instantiateTemplateAttribute(I->TmplAttr, Context, *this, TemplateArgs);
2185 I->NewDecl->addAttr(NewAttr);
2186 LocalInstantiationScope::deleteScopes(I->Scope,
2187 Instantiator.getStartingScope());
2189 Instantiator.disableLateAttributeInstantiation();
2192 ActOnFinishDelayedMemberInitializers(Instantiation);
2194 // FIXME: We should do something similar for explicit instantiations so they
2195 // end up in the right module.
2196 if (TSK == TSK_ImplicitInstantiation) {
2197 Instantiation->setLocation(Pattern->getLocation());
2198 Instantiation->setLocStart(Pattern->getInnerLocStart());
2199 Instantiation->setBraceRange(Pattern->getBraceRange());
2202 if (!Instantiation->isInvalidDecl()) {
2203 // Perform any dependent diagnostics from the pattern.
2204 PerformDependentDiagnostics(Pattern, TemplateArgs);
2206 // Instantiate any out-of-line class template partial
2207 // specializations now.
2208 for (TemplateDeclInstantiator::delayed_partial_spec_iterator
2209 P = Instantiator.delayed_partial_spec_begin(),
2210 PEnd = Instantiator.delayed_partial_spec_end();
2212 if (!Instantiator.InstantiateClassTemplatePartialSpecialization(
2213 P->first, P->second)) {
2214 Instantiation->setInvalidDecl();
2219 // Instantiate any out-of-line variable template partial
2220 // specializations now.
2221 for (TemplateDeclInstantiator::delayed_var_partial_spec_iterator
2222 P = Instantiator.delayed_var_partial_spec_begin(),
2223 PEnd = Instantiator.delayed_var_partial_spec_end();
2225 if (!Instantiator.InstantiateVarTemplatePartialSpecialization(
2226 P->first, P->second)) {
2227 Instantiation->setInvalidDecl();
2233 // Exit the scope of this instantiation.
2236 if (!Instantiation->isInvalidDecl()) {
2237 Consumer.HandleTagDeclDefinition(Instantiation);
2239 // Always emit the vtable for an explicit instantiation definition
2240 // of a polymorphic class template specialization. Otherwise, eagerly
2241 // instantiate only constexpr virtual functions in preparation for their use
2242 // in constant evaluation.
2243 if (TSK == TSK_ExplicitInstantiationDefinition)
2244 MarkVTableUsed(PointOfInstantiation, Instantiation, true);
2245 else if (MightHaveConstexprVirtualFunctions)
2246 MarkVirtualMembersReferenced(PointOfInstantiation, Instantiation,
2247 /*ConstexprOnly*/ true);
2250 return Instantiation->isInvalidDecl();
2253 /// Instantiate the definition of an enum from a given pattern.
2255 /// \param PointOfInstantiation The point of instantiation within the
2257 /// \param Instantiation is the declaration whose definition is being
2258 /// instantiated. This will be a member enumeration of a class
2259 /// temploid specialization, or a local enumeration within a
2260 /// function temploid specialization.
2261 /// \param Pattern The templated declaration from which the instantiation
2263 /// \param TemplateArgs The template arguments to be substituted into
2265 /// \param TSK The kind of implicit or explicit instantiation to perform.
2267 /// \return \c true if an error occurred, \c false otherwise.
2268 bool Sema::InstantiateEnum(SourceLocation PointOfInstantiation,
2269 EnumDecl *Instantiation, EnumDecl *Pattern,
2270 const MultiLevelTemplateArgumentList &TemplateArgs,
2271 TemplateSpecializationKind TSK) {
2272 EnumDecl *PatternDef = Pattern->getDefinition();
2273 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
2274 Instantiation->getInstantiatedFromMemberEnum(),
2275 Pattern, PatternDef, TSK,/*Complain*/true))
2277 Pattern = PatternDef;
2279 // Record the point of instantiation.
2280 if (MemberSpecializationInfo *MSInfo
2281 = Instantiation->getMemberSpecializationInfo()) {
2282 MSInfo->setTemplateSpecializationKind(TSK);
2283 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2286 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
2287 if (Inst.isInvalid())
2289 if (Inst.isAlreadyInstantiating())
2291 PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
2292 "instantiating enum definition");
2294 // The instantiation is visible here, even if it was first declared in an
2295 // unimported module.
2296 Instantiation->setVisibleDespiteOwningModule();
2298 // Enter the scope of this instantiation. We don't use
2299 // PushDeclContext because we don't have a scope.
2300 ContextRAII SavedContext(*this, Instantiation);
2301 EnterExpressionEvaluationContext EvalContext(
2302 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
2304 LocalInstantiationScope Scope(*this, /*MergeWithParentScope*/true);
2306 // Pull attributes from the pattern onto the instantiation.
2307 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
2309 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
2310 Instantiator.InstantiateEnumDefinition(Instantiation, Pattern);
2312 // Exit the scope of this instantiation.
2315 return Instantiation->isInvalidDecl();
2319 /// Instantiate the definition of a field from the given pattern.
2321 /// \param PointOfInstantiation The point of instantiation within the
2323 /// \param Instantiation is the declaration whose definition is being
2324 /// instantiated. This will be a class of a class temploid
2325 /// specialization, or a local enumeration within a function temploid
2327 /// \param Pattern The templated declaration from which the instantiation
2329 /// \param TemplateArgs The template arguments to be substituted into
2332 /// \return \c true if an error occurred, \c false otherwise.
2333 bool Sema::InstantiateInClassInitializer(
2334 SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
2335 FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs) {
2336 // If there is no initializer, we don't need to do anything.
2337 if (!Pattern->hasInClassInitializer())
2340 assert(Instantiation->getInClassInitStyle() ==
2341 Pattern->getInClassInitStyle() &&
2342 "pattern and instantiation disagree about init style");
2344 // Error out if we haven't parsed the initializer of the pattern yet because
2345 // we are waiting for the closing brace of the outer class.
2346 Expr *OldInit = Pattern->getInClassInitializer();
2348 RecordDecl *PatternRD = Pattern->getParent();
2349 RecordDecl *OutermostClass = PatternRD->getOuterLexicalRecordContext();
2350 Diag(PointOfInstantiation,
2351 diag::err_in_class_initializer_not_yet_parsed)
2352 << OutermostClass << Pattern;
2353 Diag(Pattern->getEndLoc(), diag::note_in_class_initializer_not_yet_parsed);
2354 Instantiation->setInvalidDecl();
2358 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
2359 if (Inst.isInvalid())
2361 if (Inst.isAlreadyInstantiating()) {
2362 // Error out if we hit an instantiation cycle for this initializer.
2363 Diag(PointOfInstantiation, diag::err_in_class_initializer_cycle)
2367 PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
2368 "instantiating default member init");
2370 // Enter the scope of this instantiation. We don't use PushDeclContext because
2371 // we don't have a scope.
2372 ContextRAII SavedContext(*this, Instantiation->getParent());
2373 EnterExpressionEvaluationContext EvalContext(
2374 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
2376 LocalInstantiationScope Scope(*this, true);
2378 // Instantiate the initializer.
2379 ActOnStartCXXInClassMemberInitializer();
2380 CXXThisScopeRAII ThisScope(*this, Instantiation->getParent(), Qualifiers());
2382 ExprResult NewInit = SubstInitializer(OldInit, TemplateArgs,
2383 /*CXXDirectInit=*/false);
2384 Expr *Init = NewInit.get();
2385 assert((!Init || !isa<ParenListExpr>(Init)) && "call-style init in class");
2386 ActOnFinishCXXInClassMemberInitializer(
2387 Instantiation, Init ? Init->getBeginLoc() : SourceLocation(), Init);
2389 if (auto *L = getASTMutationListener())
2390 L->DefaultMemberInitializerInstantiated(Instantiation);
2392 // Return true if the in-class initializer is still missing.
2393 return !Instantiation->getInClassInitializer();
2397 /// A partial specialization whose template arguments have matched
2398 /// a given template-id.
2399 struct PartialSpecMatchResult {
2400 ClassTemplatePartialSpecializationDecl *Partial;
2401 TemplateArgumentList *Args;
2405 bool Sema::usesPartialOrExplicitSpecialization(
2406 SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec) {
2407 if (ClassTemplateSpec->getTemplateSpecializationKind() ==
2408 TSK_ExplicitSpecialization)
2411 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
2412 ClassTemplateSpec->getSpecializedTemplate()
2413 ->getPartialSpecializations(PartialSpecs);
2414 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
2415 TemplateDeductionInfo Info(Loc);
2416 if (!DeduceTemplateArguments(PartialSpecs[I],
2417 ClassTemplateSpec->getTemplateArgs(), Info))
2424 /// Get the instantiation pattern to use to instantiate the definition of a
2425 /// given ClassTemplateSpecializationDecl (either the pattern of the primary
2426 /// template or of a partial specialization).
2427 static CXXRecordDecl *
2428 getPatternForClassTemplateSpecialization(
2429 Sema &S, SourceLocation PointOfInstantiation,
2430 ClassTemplateSpecializationDecl *ClassTemplateSpec,
2431 TemplateSpecializationKind TSK, bool Complain) {
2432 Sema::InstantiatingTemplate Inst(S, PointOfInstantiation, ClassTemplateSpec);
2433 if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
2436 llvm::PointerUnion<ClassTemplateDecl *,
2437 ClassTemplatePartialSpecializationDecl *>
2438 Specialized = ClassTemplateSpec->getSpecializedTemplateOrPartial();
2439 if (!Specialized.is<ClassTemplatePartialSpecializationDecl *>()) {
2440 // Find best matching specialization.
2441 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
2443 // C++ [temp.class.spec.match]p1:
2444 // When a class template is used in a context that requires an
2445 // instantiation of the class, it is necessary to determine
2446 // whether the instantiation is to be generated using the primary
2447 // template or one of the partial specializations. This is done by
2448 // matching the template arguments of the class template
2449 // specialization with the template argument lists of the partial
2451 typedef PartialSpecMatchResult MatchResult;
2452 SmallVector<MatchResult, 4> Matched;
2453 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
2454 Template->getPartialSpecializations(PartialSpecs);
2455 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation);
2456 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
2457 ClassTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
2458 TemplateDeductionInfo Info(FailedCandidates.getLocation());
2459 if (Sema::TemplateDeductionResult Result = S.DeduceTemplateArguments(
2460 Partial, ClassTemplateSpec->getTemplateArgs(), Info)) {
2461 // Store the failed-deduction information for use in diagnostics, later.
2462 // TODO: Actually use the failed-deduction info?
2463 FailedCandidates.addCandidate().set(
2464 DeclAccessPair::make(Template, AS_public), Partial,
2465 MakeDeductionFailureInfo(S.Context, Result, Info));
2468 Matched.push_back(PartialSpecMatchResult());
2469 Matched.back().Partial = Partial;
2470 Matched.back().Args = Info.take();
2474 // If we're dealing with a member template where the template parameters
2475 // have been instantiated, this provides the original template parameters
2476 // from which the member template's parameters were instantiated.
2478 if (Matched.size() >= 1) {
2479 SmallVectorImpl<MatchResult>::iterator Best = Matched.begin();
2480 if (Matched.size() == 1) {
2481 // -- If exactly one matching specialization is found, the
2482 // instantiation is generated from that specialization.
2483 // We don't need to do anything for this.
2485 // -- If more than one matching specialization is found, the
2486 // partial order rules (14.5.4.2) are used to determine
2487 // whether one of the specializations is more specialized
2488 // than the others. If none of the specializations is more
2489 // specialized than all of the other matching
2490 // specializations, then the use of the class template is
2491 // ambiguous and the program is ill-formed.
2492 for (SmallVectorImpl<MatchResult>::iterator P = Best + 1,
2493 PEnd = Matched.end();
2495 if (S.getMoreSpecializedPartialSpecialization(
2496 P->Partial, Best->Partial, PointOfInstantiation) ==
2501 // Determine if the best partial specialization is more specialized than
2503 bool Ambiguous = false;
2504 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
2505 PEnd = Matched.end();
2507 if (P != Best && S.getMoreSpecializedPartialSpecialization(
2508 P->Partial, Best->Partial,
2509 PointOfInstantiation) != Best->Partial) {
2516 // Partial ordering did not produce a clear winner. Complain.
2518 ClassTemplateSpec->setInvalidDecl();
2519 S.Diag(PointOfInstantiation,
2520 diag::err_partial_spec_ordering_ambiguous)
2521 << ClassTemplateSpec;
2523 // Print the matching partial specializations.
2524 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
2525 PEnd = Matched.end();
2527 S.Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
2528 << S.getTemplateArgumentBindingsText(
2529 P->Partial->getTemplateParameters(), *P->Args);
2535 ClassTemplateSpec->setInstantiationOf(Best->Partial, Best->Args);
2537 // -- If no matches are found, the instantiation is generated
2538 // from the primary template.
2542 CXXRecordDecl *Pattern = nullptr;
2543 Specialized = ClassTemplateSpec->getSpecializedTemplateOrPartial();
2544 if (auto *PartialSpec =
2545 Specialized.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
2546 // Instantiate using the best class template partial specialization.
2547 while (PartialSpec->getInstantiatedFromMember()) {
2548 // If we've found an explicit specialization of this class template,
2549 // stop here and use that as the pattern.
2550 if (PartialSpec->isMemberSpecialization())
2553 PartialSpec = PartialSpec->getInstantiatedFromMember();
2555 Pattern = PartialSpec;
2557 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
2558 while (Template->getInstantiatedFromMemberTemplate()) {
2559 // If we've found an explicit specialization of this class template,
2560 // stop here and use that as the pattern.
2561 if (Template->isMemberSpecialization())
2564 Template = Template->getInstantiatedFromMemberTemplate();
2566 Pattern = Template->getTemplatedDecl();
2572 bool Sema::InstantiateClassTemplateSpecialization(
2573 SourceLocation PointOfInstantiation,
2574 ClassTemplateSpecializationDecl *ClassTemplateSpec,
2575 TemplateSpecializationKind TSK, bool Complain) {
2576 // Perform the actual instantiation on the canonical declaration.
2577 ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>(
2578 ClassTemplateSpec->getCanonicalDecl());
2579 if (ClassTemplateSpec->isInvalidDecl())
2582 CXXRecordDecl *Pattern = getPatternForClassTemplateSpecialization(
2583 *this, PointOfInstantiation, ClassTemplateSpec, TSK, Complain);
2587 return InstantiateClass(PointOfInstantiation, ClassTemplateSpec, Pattern,
2588 getTemplateInstantiationArgs(ClassTemplateSpec), TSK,
2592 /// Instantiates the definitions of all of the member
2593 /// of the given class, which is an instantiation of a class template
2594 /// or a member class of a template.
2596 Sema::InstantiateClassMembers(SourceLocation PointOfInstantiation,
2597 CXXRecordDecl *Instantiation,
2598 const MultiLevelTemplateArgumentList &TemplateArgs,
2599 TemplateSpecializationKind TSK) {
2600 // FIXME: We need to notify the ASTMutationListener that we did all of these
2601 // things, in case we have an explicit instantiation definition in a PCM, a
2602 // module, or preamble, and the declaration is in an imported AST.
2604 (TSK == TSK_ExplicitInstantiationDefinition ||
2605 TSK == TSK_ExplicitInstantiationDeclaration ||
2606 (TSK == TSK_ImplicitInstantiation && Instantiation->isLocalClass())) &&
2607 "Unexpected template specialization kind!");
2608 for (auto *D : Instantiation->decls()) {
2609 bool SuppressNew = false;
2610 if (auto *Function = dyn_cast<FunctionDecl>(D)) {
2611 if (FunctionDecl *Pattern =
2612 Function->getInstantiatedFromMemberFunction()) {
2614 if (Function->hasAttr<ExcludeFromExplicitInstantiationAttr>())
2617 MemberSpecializationInfo *MSInfo =
2618 Function->getMemberSpecializationInfo();
2619 assert(MSInfo && "No member specialization information?");
2620 if (MSInfo->getTemplateSpecializationKind()
2621 == TSK_ExplicitSpecialization)
2624 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2626 MSInfo->getTemplateSpecializationKind(),
2627 MSInfo->getPointOfInstantiation(),
2632 // C++11 [temp.explicit]p8:
2633 // An explicit instantiation definition that names a class template
2634 // specialization explicitly instantiates the class template
2635 // specialization and is only an explicit instantiation definition
2636 // of members whose definition is visible at the point of
2638 if (TSK == TSK_ExplicitInstantiationDefinition && !Pattern->isDefined())
2641 Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2643 if (Function->isDefined()) {
2644 // Let the ASTConsumer know that this function has been explicitly
2645 // instantiated now, and its linkage might have changed.
2646 Consumer.HandleTopLevelDecl(DeclGroupRef(Function));
2647 } else if (TSK == TSK_ExplicitInstantiationDefinition) {
2648 InstantiateFunctionDefinition(PointOfInstantiation, Function);
2649 } else if (TSK == TSK_ImplicitInstantiation) {
2650 PendingLocalImplicitInstantiations.push_back(
2651 std::make_pair(Function, PointOfInstantiation));
2654 } else if (auto *Var = dyn_cast<VarDecl>(D)) {
2655 if (isa<VarTemplateSpecializationDecl>(Var))
2658 if (Var->isStaticDataMember()) {
2659 if (Var->hasAttr<ExcludeFromExplicitInstantiationAttr>())
2662 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
2663 assert(MSInfo && "No member specialization information?");
2664 if (MSInfo->getTemplateSpecializationKind()
2665 == TSK_ExplicitSpecialization)
2668 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2670 MSInfo->getTemplateSpecializationKind(),
2671 MSInfo->getPointOfInstantiation(),
2676 if (TSK == TSK_ExplicitInstantiationDefinition) {
2677 // C++0x [temp.explicit]p8:
2678 // An explicit instantiation definition that names a class template
2679 // specialization explicitly instantiates the class template
2680 // specialization and is only an explicit instantiation definition
2681 // of members whose definition is visible at the point of
2683 if (!Var->getInstantiatedFromStaticDataMember()->getDefinition())
2686 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2687 InstantiateVariableDefinition(PointOfInstantiation, Var);
2689 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2692 } else if (auto *Record = dyn_cast<CXXRecordDecl>(D)) {
2693 if (Record->hasAttr<ExcludeFromExplicitInstantiationAttr>())
2696 // Always skip the injected-class-name, along with any
2697 // redeclarations of nested classes, since both would cause us
2698 // to try to instantiate the members of a class twice.
2699 // Skip closure types; they'll get instantiated when we instantiate
2700 // the corresponding lambda-expression.
2701 if (Record->isInjectedClassName() || Record->getPreviousDecl() ||
2705 MemberSpecializationInfo *MSInfo = Record->getMemberSpecializationInfo();
2706 assert(MSInfo && "No member specialization information?");
2708 if (MSInfo->getTemplateSpecializationKind()
2709 == TSK_ExplicitSpecialization)
2712 if (Context.getTargetInfo().getTriple().isOSWindows() &&
2713 TSK == TSK_ExplicitInstantiationDeclaration) {
2714 // On Windows, explicit instantiation decl of the outer class doesn't
2715 // affect the inner class. Typically extern template declarations are
2716 // used in combination with dll import/export annotations, but those
2717 // are not propagated from the outer class templates to inner classes.
2718 // Therefore, do not instantiate inner classes on this platform, so
2719 // that users don't end up with undefined symbols during linking.
2723 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2725 MSInfo->getTemplateSpecializationKind(),
2726 MSInfo->getPointOfInstantiation(),
2731 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
2732 assert(Pattern && "Missing instantiated-from-template information");
2734 if (!Record->getDefinition()) {
2735 if (!Pattern->getDefinition()) {
2736 // C++0x [temp.explicit]p8:
2737 // An explicit instantiation definition that names a class template
2738 // specialization explicitly instantiates the class template
2739 // specialization and is only an explicit instantiation definition
2740 // of members whose definition is visible at the point of
2742 if (TSK == TSK_ExplicitInstantiationDeclaration) {
2743 MSInfo->setTemplateSpecializationKind(TSK);
2744 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2750 InstantiateClass(PointOfInstantiation, Record, Pattern,
2754 if (TSK == TSK_ExplicitInstantiationDefinition &&
2755 Record->getTemplateSpecializationKind() ==
2756 TSK_ExplicitInstantiationDeclaration) {
2757 Record->setTemplateSpecializationKind(TSK);
2758 MarkVTableUsed(PointOfInstantiation, Record, true);
2762 Pattern = cast_or_null<CXXRecordDecl>(Record->getDefinition());
2764 InstantiateClassMembers(PointOfInstantiation, Pattern, TemplateArgs,
2766 } else if (auto *Enum = dyn_cast<EnumDecl>(D)) {
2767 MemberSpecializationInfo *MSInfo = Enum->getMemberSpecializationInfo();
2768 assert(MSInfo && "No member specialization information?");
2770 if (MSInfo->getTemplateSpecializationKind()
2771 == TSK_ExplicitSpecialization)
2774 if (CheckSpecializationInstantiationRedecl(
2775 PointOfInstantiation, TSK, Enum,
2776 MSInfo->getTemplateSpecializationKind(),
2777 MSInfo->getPointOfInstantiation(), SuppressNew) ||
2781 if (Enum->getDefinition())
2784 EnumDecl *Pattern = Enum->getTemplateInstantiationPattern();
2785 assert(Pattern && "Missing instantiated-from-template information");
2787 if (TSK == TSK_ExplicitInstantiationDefinition) {
2788 if (!Pattern->getDefinition())
2791 InstantiateEnum(PointOfInstantiation, Enum, Pattern, TemplateArgs, TSK);
2793 MSInfo->setTemplateSpecializationKind(TSK);
2794 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2796 } else if (auto *Field = dyn_cast<FieldDecl>(D)) {
2797 // No need to instantiate in-class initializers during explicit
2799 if (Field->hasInClassInitializer() && TSK == TSK_ImplicitInstantiation) {
2800 CXXRecordDecl *ClassPattern =
2801 Instantiation->getTemplateInstantiationPattern();
2802 DeclContext::lookup_result Lookup =
2803 ClassPattern->lookup(Field->getDeclName());
2804 FieldDecl *Pattern = cast<FieldDecl>(Lookup.front());
2805 InstantiateInClassInitializer(PointOfInstantiation, Field, Pattern,
2812 /// Instantiate the definitions of all of the members of the
2813 /// given class template specialization, which was named as part of an
2814 /// explicit instantiation.
2816 Sema::InstantiateClassTemplateSpecializationMembers(
2817 SourceLocation PointOfInstantiation,
2818 ClassTemplateSpecializationDecl *ClassTemplateSpec,
2819 TemplateSpecializationKind TSK) {
2820 // C++0x [temp.explicit]p7:
2821 // An explicit instantiation that names a class template
2822 // specialization is an explicit instantion of the same kind
2823 // (declaration or definition) of each of its members (not
2824 // including members inherited from base classes) that has not
2825 // been previously explicitly specialized in the translation unit
2826 // containing the explicit instantiation, except as described
2828 InstantiateClassMembers(PointOfInstantiation, ClassTemplateSpec,
2829 getTemplateInstantiationArgs(ClassTemplateSpec),
2834 Sema::SubstStmt(Stmt *S, const MultiLevelTemplateArgumentList &TemplateArgs) {
2838 TemplateInstantiator Instantiator(*this, TemplateArgs,
2841 return Instantiator.TransformStmt(S);
2845 Sema::SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs) {
2849 TemplateInstantiator Instantiator(*this, TemplateArgs,
2852 return Instantiator.TransformExpr(E);
2855 ExprResult Sema::SubstInitializer(Expr *Init,
2856 const MultiLevelTemplateArgumentList &TemplateArgs,
2857 bool CXXDirectInit) {
2858 TemplateInstantiator Instantiator(*this, TemplateArgs,
2861 return Instantiator.TransformInitializer(Init, CXXDirectInit);
2864 bool Sema::SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
2865 const MultiLevelTemplateArgumentList &TemplateArgs,
2866 SmallVectorImpl<Expr *> &Outputs) {
2870 TemplateInstantiator Instantiator(*this, TemplateArgs,
2873 return Instantiator.TransformExprs(Exprs.data(), Exprs.size(),
2877 NestedNameSpecifierLoc
2878 Sema::SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
2879 const MultiLevelTemplateArgumentList &TemplateArgs) {
2881 return NestedNameSpecifierLoc();
2883 TemplateInstantiator Instantiator(*this, TemplateArgs, NNS.getBeginLoc(),
2885 return Instantiator.TransformNestedNameSpecifierLoc(NNS);
2888 /// Do template substitution on declaration name info.
2890 Sema::SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
2891 const MultiLevelTemplateArgumentList &TemplateArgs) {
2892 TemplateInstantiator Instantiator(*this, TemplateArgs, NameInfo.getLoc(),
2893 NameInfo.getName());
2894 return Instantiator.TransformDeclarationNameInfo(NameInfo);
2898 Sema::SubstTemplateName(NestedNameSpecifierLoc QualifierLoc,
2899 TemplateName Name, SourceLocation Loc,
2900 const MultiLevelTemplateArgumentList &TemplateArgs) {
2901 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
2904 SS.Adopt(QualifierLoc);
2905 return Instantiator.TransformTemplateName(SS, Name, Loc);
2908 bool Sema::Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
2909 TemplateArgumentListInfo &Result,
2910 const MultiLevelTemplateArgumentList &TemplateArgs) {
2911 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
2914 return Instantiator.TransformTemplateArguments(Args, NumArgs, Result);
2917 static const Decl *getCanonicalParmVarDecl(const Decl *D) {
2918 // When storing ParmVarDecls in the local instantiation scope, we always
2919 // want to use the ParmVarDecl from the canonical function declaration,
2920 // since the map is then valid for any redeclaration or definition of that
2922 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(D)) {
2923 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
2924 unsigned i = PV->getFunctionScopeIndex();
2925 // This parameter might be from a freestanding function type within the
2926 // function and isn't necessarily referring to one of FD's parameters.
2927 if (i < FD->getNumParams() && FD->getParamDecl(i) == PV)
2928 return FD->getCanonicalDecl()->getParamDecl(i);
2935 llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> *
2936 LocalInstantiationScope::findInstantiationOf(const Decl *D) {
2937 D = getCanonicalParmVarDecl(D);
2938 for (LocalInstantiationScope *Current = this; Current;
2939 Current = Current->Outer) {
2941 // Check if we found something within this scope.
2942 const Decl *CheckD = D;
2944 LocalDeclsMap::iterator Found = Current->LocalDecls.find(CheckD);
2945 if (Found != Current->LocalDecls.end())
2946 return &Found->second;
2948 // If this is a tag declaration, it's possible that we need to look for
2949 // a previous declaration.
2950 if (const TagDecl *Tag = dyn_cast<TagDecl>(CheckD))
2951 CheckD = Tag->getPreviousDecl();
2956 // If we aren't combined with our outer scope, we're done.
2957 if (!Current->CombineWithOuterScope)
2961 // If we're performing a partial substitution during template argument
2962 // deduction, we may not have values for template parameters yet.
2963 if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
2964 isa<TemplateTemplateParmDecl>(D))
2967 // Local types referenced prior to definition may require instantiation.
2968 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
2969 if (RD->isLocalClass())
2972 // Enumeration types referenced prior to definition may appear as a result of
2974 if (isa<EnumDecl>(D))
2977 // If we didn't find the decl, then we either have a sema bug, or we have a
2978 // forward reference to a label declaration. Return null to indicate that
2979 // we have an uninstantiated label.
2980 assert(isa<LabelDecl>(D) && "declaration not instantiated in this scope");
2984 void LocalInstantiationScope::InstantiatedLocal(const Decl *D, Decl *Inst) {
2985 D = getCanonicalParmVarDecl(D);
2986 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
2987 if (Stored.isNull()) {
2989 // It should not be present in any surrounding scope either.
2990 LocalInstantiationScope *Current = this;
2991 while (Current->CombineWithOuterScope && Current->Outer) {
2992 Current = Current->Outer;
2993 assert(Current->LocalDecls.find(D) == Current->LocalDecls.end() &&
2994 "Instantiated local in inner and outer scopes");
2998 } else if (DeclArgumentPack *Pack = Stored.dyn_cast<DeclArgumentPack *>()) {
2999 Pack->push_back(cast<VarDecl>(Inst));
3001 assert(Stored.get<Decl *>() == Inst && "Already instantiated this local");
3005 void LocalInstantiationScope::InstantiatedLocalPackArg(const Decl *D,
3007 D = getCanonicalParmVarDecl(D);
3008 DeclArgumentPack *Pack = LocalDecls[D].get<DeclArgumentPack *>();
3009 Pack->push_back(Inst);
3012 void LocalInstantiationScope::MakeInstantiatedLocalArgPack(const Decl *D) {
3014 // This should be the first time we've been told about this decl.
3015 for (LocalInstantiationScope *Current = this;
3016 Current && Current->CombineWithOuterScope; Current = Current->Outer)
3017 assert(Current->LocalDecls.find(D) == Current->LocalDecls.end() &&
3018 "Creating local pack after instantiation of local");
3021 D = getCanonicalParmVarDecl(D);
3022 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
3023 DeclArgumentPack *Pack = new DeclArgumentPack;
3025 ArgumentPacks.push_back(Pack);
3028 void LocalInstantiationScope::SetPartiallySubstitutedPack(NamedDecl *Pack,
3029 const TemplateArgument *ExplicitArgs,
3030 unsigned NumExplicitArgs) {
3031 assert((!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack) &&
3032 "Already have a partially-substituted pack");
3033 assert((!PartiallySubstitutedPack
3034 || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) &&
3035 "Wrong number of arguments in partially-substituted pack");
3036 PartiallySubstitutedPack = Pack;
3037 ArgsInPartiallySubstitutedPack = ExplicitArgs;
3038 NumArgsInPartiallySubstitutedPack = NumExplicitArgs;
3041 NamedDecl *LocalInstantiationScope::getPartiallySubstitutedPack(
3042 const TemplateArgument **ExplicitArgs,
3043 unsigned *NumExplicitArgs) const {
3045 *ExplicitArgs = nullptr;
3046 if (NumExplicitArgs)
3047 *NumExplicitArgs = 0;
3049 for (const LocalInstantiationScope *Current = this; Current;
3050 Current = Current->Outer) {
3051 if (Current->PartiallySubstitutedPack) {
3053 *ExplicitArgs = Current->ArgsInPartiallySubstitutedPack;
3054 if (NumExplicitArgs)
3055 *NumExplicitArgs = Current->NumArgsInPartiallySubstitutedPack;
3057 return Current->PartiallySubstitutedPack;
3060 if (!Current->CombineWithOuterScope)