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 "TreeTransform.h"
13 #include "clang/AST/ASTConcept.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/DeclBase.h"
19 #include "clang/AST/DeclTemplate.h"
20 #include "clang/AST/Expr.h"
21 #include "clang/AST/ExprConcepts.h"
22 #include "clang/AST/PrettyDeclStackTrace.h"
23 #include "clang/AST/Type.h"
24 #include "clang/AST/TypeVisitor.h"
25 #include "clang/Basic/LangOptions.h"
26 #include "clang/Basic/Stack.h"
27 #include "clang/Basic/TargetInfo.h"
28 #include "clang/Sema/DeclSpec.h"
29 #include "clang/Sema/EnterExpressionEvaluationContext.h"
30 #include "clang/Sema/Initialization.h"
31 #include "clang/Sema/Lookup.h"
32 #include "clang/Sema/Sema.h"
33 #include "clang/Sema/SemaConcept.h"
34 #include "clang/Sema/SemaInternal.h"
35 #include "clang/Sema/Template.h"
36 #include "clang/Sema/TemplateDeduction.h"
37 #include "clang/Sema/TemplateInstCallback.h"
38 #include "llvm/ADT/ScopeExit.h"
39 #include "llvm/ADT/StringExtras.h"
40 #include "llvm/Support/ErrorHandling.h"
41 #include "llvm/Support/TimeProfiler.h"
44 using namespace clang
;
47 //===----------------------------------------------------------------------===/
48 // Template Instantiation Support
49 //===----------------------------------------------------------------------===/
52 namespace TemplateInstArgsHelpers
{
54 const Decl
*NextDecl
= nullptr;
56 bool ClearRelativeToPrimary
= true;
57 static Response
Done() {
62 static Response
ChangeDecl(const Decl
*ND
) {
67 static Response
ChangeDecl(const DeclContext
*Ctx
) {
69 R
.NextDecl
= Decl::castFromDeclContext(Ctx
);
73 static Response
UseNextDecl(const Decl
*CurDecl
) {
74 return ChangeDecl(CurDecl
->getDeclContext());
77 static Response
DontClearRelativeToPrimaryNextDecl(const Decl
*CurDecl
) {
78 Response R
= Response::UseNextDecl(CurDecl
);
79 R
.ClearRelativeToPrimary
= false;
83 // Add template arguments from a variable template instantiation.
85 HandleVarTemplateSpec(const VarTemplateSpecializationDecl
*VarTemplSpec
,
86 MultiLevelTemplateArgumentList
&Result
,
87 bool SkipForSpecialization
) {
88 // For a class-scope explicit specialization, there are no template arguments
89 // at this level, but there may be enclosing template arguments.
90 if (VarTemplSpec
->isClassScopeExplicitSpecialization())
91 return Response::DontClearRelativeToPrimaryNextDecl(VarTemplSpec
);
93 // We're done when we hit an explicit specialization.
94 if (VarTemplSpec
->getSpecializationKind() == TSK_ExplicitSpecialization
&&
95 !isa
<VarTemplatePartialSpecializationDecl
>(VarTemplSpec
))
96 return Response::Done();
98 // If this variable template specialization was instantiated from a
99 // specialized member that is a variable template, we're done.
100 assert(VarTemplSpec
->getSpecializedTemplate() && "No variable template?");
101 llvm::PointerUnion
<VarTemplateDecl
*, VarTemplatePartialSpecializationDecl
*>
102 Specialized
= VarTemplSpec
->getSpecializedTemplateOrPartial();
103 if (VarTemplatePartialSpecializationDecl
*Partial
=
104 Specialized
.dyn_cast
<VarTemplatePartialSpecializationDecl
*>()) {
105 if (!SkipForSpecialization
)
106 Result
.addOuterTemplateArguments(
107 Partial
, VarTemplSpec
->getTemplateInstantiationArgs().asArray(),
109 if (Partial
->isMemberSpecialization())
110 return Response::Done();
112 VarTemplateDecl
*Tmpl
= Specialized
.get
<VarTemplateDecl
*>();
113 if (!SkipForSpecialization
)
114 Result
.addOuterTemplateArguments(
115 Tmpl
, VarTemplSpec
->getTemplateInstantiationArgs().asArray(),
117 if (Tmpl
->isMemberSpecialization())
118 return Response::Done();
120 return Response::DontClearRelativeToPrimaryNextDecl(VarTemplSpec
);
123 // If we have a template template parameter with translation unit context,
124 // then we're performing substitution into a default template argument of
125 // this template template parameter before we've constructed the template
126 // that will own this template template parameter. In this case, we
127 // use empty template parameter lists for all of the outer templates
128 // to avoid performing any substitutions.
130 HandleDefaultTempArgIntoTempTempParam(const TemplateTemplateParmDecl
*TTP
,
131 MultiLevelTemplateArgumentList
&Result
) {
132 for (unsigned I
= 0, N
= TTP
->getDepth() + 1; I
!= N
; ++I
)
133 Result
.addOuterTemplateArguments(std::nullopt
);
134 return Response::Done();
137 Response
HandlePartialClassTemplateSpec(
138 const ClassTemplatePartialSpecializationDecl
*PartialClassTemplSpec
,
139 MultiLevelTemplateArgumentList
&Result
, bool SkipForSpecialization
) {
140 if (!SkipForSpecialization
)
141 Result
.addOuterRetainedLevels(PartialClassTemplSpec
->getTemplateDepth());
142 return Response::Done();
145 // Add template arguments from a class template instantiation.
147 HandleClassTemplateSpec(const ClassTemplateSpecializationDecl
*ClassTemplSpec
,
148 MultiLevelTemplateArgumentList
&Result
,
149 bool SkipForSpecialization
) {
150 if (!ClassTemplSpec
->isClassScopeExplicitSpecialization()) {
151 // We're done when we hit an explicit specialization.
152 if (ClassTemplSpec
->getSpecializationKind() == TSK_ExplicitSpecialization
&&
153 !isa
<ClassTemplatePartialSpecializationDecl
>(ClassTemplSpec
))
154 return Response::Done();
156 if (!SkipForSpecialization
)
157 Result
.addOuterTemplateArguments(
158 const_cast<ClassTemplateSpecializationDecl
*>(ClassTemplSpec
),
159 ClassTemplSpec
->getTemplateInstantiationArgs().asArray(),
162 // If this class template specialization was instantiated from a
163 // specialized member that is a class template, we're done.
164 assert(ClassTemplSpec
->getSpecializedTemplate() && "No class template?");
165 if (ClassTemplSpec
->getSpecializedTemplate()->isMemberSpecialization())
166 return Response::Done();
168 // If this was instantiated from a partial template specialization, we need
169 // to get the next level of declaration context from the partial
170 // specialization, as the ClassTemplateSpecializationDecl's
171 // DeclContext/LexicalDeclContext will be for the primary template.
172 if (auto *InstFromPartialTempl
= ClassTemplSpec
->getSpecializedTemplateOrPartial()
173 .dyn_cast
<ClassTemplatePartialSpecializationDecl
*>())
174 return Response::ChangeDecl(InstFromPartialTempl
->getLexicalDeclContext());
176 return Response::UseNextDecl(ClassTemplSpec
);
179 Response
HandleFunction(const FunctionDecl
*Function
,
180 MultiLevelTemplateArgumentList
&Result
,
181 const FunctionDecl
*Pattern
, bool RelativeToPrimary
,
182 bool ForConstraintInstantiation
) {
183 // Add template arguments from a function template specialization.
184 if (!RelativeToPrimary
&&
185 Function
->getTemplateSpecializationKindForInstantiation() ==
186 TSK_ExplicitSpecialization
)
187 return Response::Done();
189 if (!RelativeToPrimary
&&
190 Function
->getTemplateSpecializationKind() == TSK_ExplicitSpecialization
) {
191 // This is an implicit instantiation of an explicit specialization. We
192 // don't get any template arguments from this function but might get
193 // some from an enclosing template.
194 return Response::UseNextDecl(Function
);
195 } else if (const TemplateArgumentList
*TemplateArgs
=
196 Function
->getTemplateSpecializationArgs()) {
197 // Add the template arguments for this specialization.
198 Result
.addOuterTemplateArguments(const_cast<FunctionDecl
*>(Function
),
199 TemplateArgs
->asArray(),
202 // If this function was instantiated from a specialized member that is
203 // a function template, we're done.
204 assert(Function
->getPrimaryTemplate() && "No function template?");
205 if (Function
->getPrimaryTemplate()->isMemberSpecialization())
206 return Response::Done();
208 // If this function is a generic lambda specialization, we are done.
209 if (!ForConstraintInstantiation
&&
210 isGenericLambdaCallOperatorOrStaticInvokerSpecialization(Function
))
211 return Response::Done();
213 } else if (Function
->getDescribedFunctionTemplate()) {
215 (ForConstraintInstantiation
|| Result
.getNumSubstitutedLevels() == 0) &&
216 "Outer template not instantiated?");
218 // If this is a friend or local declaration and it declares an entity at
219 // namespace scope, take arguments from its lexical parent
220 // instead of its semantic parent, unless of course the pattern we're
221 // instantiating actually comes from the file's context!
222 if ((Function
->getFriendObjectKind() || Function
->isLocalExternDecl()) &&
223 Function
->getNonTransparentDeclContext()->isFileContext() &&
224 (!Pattern
|| !Pattern
->getLexicalDeclContext()->isFileContext())) {
225 return Response::ChangeDecl(Function
->getLexicalDeclContext());
227 return Response::UseNextDecl(Function
);
230 Response
HandleFunctionTemplateDecl(const FunctionTemplateDecl
*FTD
,
231 MultiLevelTemplateArgumentList
&Result
) {
232 if (!isa
<ClassTemplateSpecializationDecl
>(FTD
->getDeclContext())) {
233 Result
.addOuterTemplateArguments(
234 const_cast<FunctionTemplateDecl
*>(FTD
),
235 const_cast<FunctionTemplateDecl
*>(FTD
)->getInjectedTemplateArgs(),
238 NestedNameSpecifier
*NNS
= FTD
->getTemplatedDecl()->getQualifier();
240 while (const Type
*Ty
= NNS
? NNS
->getAsType() : nullptr) {
241 if (NNS
->isInstantiationDependent()) {
242 if (const auto *TSTy
= Ty
->getAs
<TemplateSpecializationType
>())
243 Result
.addOuterTemplateArguments(
244 const_cast<FunctionTemplateDecl
*>(FTD
), TSTy
->template_arguments(),
248 NNS
= NNS
->getPrefix();
252 return Response::ChangeDecl(FTD
->getLexicalDeclContext());
255 Response
HandleRecordDecl(const CXXRecordDecl
*Rec
,
256 MultiLevelTemplateArgumentList
&Result
,
258 bool ForConstraintInstantiation
) {
259 if (ClassTemplateDecl
*ClassTemplate
= Rec
->getDescribedClassTemplate()) {
261 (ForConstraintInstantiation
|| Result
.getNumSubstitutedLevels() == 0) &&
262 "Outer template not instantiated?");
263 if (ClassTemplate
->isMemberSpecialization())
264 return Response::Done();
265 if (ForConstraintInstantiation
)
266 Result
.addOuterTemplateArguments(const_cast<CXXRecordDecl
*>(Rec
),
267 ClassTemplate
->getInjectedTemplateArgs(),
271 if (const MemberSpecializationInfo
*MSInfo
=
272 Rec
->getMemberSpecializationInfo())
273 if (MSInfo
->getTemplateSpecializationKind() == TSK_ExplicitSpecialization
)
274 return Response::Done();
276 bool IsFriend
= Rec
->getFriendObjectKind() ||
277 (Rec
->getDescribedClassTemplate() &&
278 Rec
->getDescribedClassTemplate()->getFriendObjectKind());
279 if (ForConstraintInstantiation
&& IsFriend
&&
280 Rec
->getNonTransparentDeclContext()->isFileContext()) {
281 return Response::ChangeDecl(Rec
->getLexicalDeclContext());
284 // This is to make sure we pick up the VarTemplateSpecializationDecl that this
285 // lambda is defined inside of.
287 if (const Decl
*LCD
= Rec
->getLambdaContextDecl())
288 return Response::ChangeDecl(LCD
);
290 return Response::UseNextDecl(Rec
);
293 Response
HandleImplicitConceptSpecializationDecl(
294 const ImplicitConceptSpecializationDecl
*CSD
,
295 MultiLevelTemplateArgumentList
&Result
) {
296 Result
.addOuterTemplateArguments(
297 const_cast<ImplicitConceptSpecializationDecl
*>(CSD
),
298 CSD
->getTemplateArguments(),
300 return Response::UseNextDecl(CSD
);
303 Response
HandleGenericDeclContext(const Decl
*CurDecl
) {
304 return Response::UseNextDecl(CurDecl
);
306 } // namespace TemplateInstArgsHelpers
309 /// Retrieve the template argument list(s) that should be used to
310 /// instantiate the definition of the given declaration.
312 /// \param ND the declaration for which we are computing template instantiation
315 /// \param DC In the event we don't HAVE a declaration yet, we instead provide
316 /// the decl context where it will be created. In this case, the `Innermost`
317 /// should likely be provided. If ND is non-null, this is ignored.
319 /// \param Innermost if non-NULL, specifies a template argument list for the
320 /// template declaration passed as ND.
322 /// \param RelativeToPrimary true if we should get the template
323 /// arguments relative to the primary template, even when we're
324 /// dealing with a specialization. This is only relevant for function
325 /// template specializations.
327 /// \param Pattern If non-NULL, indicates the pattern from which we will be
328 /// instantiating the definition of the given declaration, \p ND. This is
329 /// used to determine the proper set of template instantiation arguments for
330 /// friend function template specializations.
332 /// \param ForConstraintInstantiation when collecting arguments,
333 /// ForConstraintInstantiation indicates we should continue looking when
334 /// encountering a lambda generic call operator, and continue looking for
335 /// arguments on an enclosing class template.
337 MultiLevelTemplateArgumentList
Sema::getTemplateInstantiationArgs(
338 const NamedDecl
*ND
, const DeclContext
*DC
, bool Final
,
339 const TemplateArgumentList
*Innermost
, bool RelativeToPrimary
,
340 const FunctionDecl
*Pattern
, bool ForConstraintInstantiation
,
341 bool SkipForSpecialization
) {
342 assert((ND
|| DC
) && "Can't find arguments for a decl if one isn't provided");
343 // Accumulate the set of template argument lists in this structure.
344 MultiLevelTemplateArgumentList Result
;
346 using namespace TemplateInstArgsHelpers
;
347 const Decl
*CurDecl
= ND
;
349 Result
.addOuterTemplateArguments(const_cast<NamedDecl
*>(ND
),
350 Innermost
->asArray(), Final
);
351 CurDecl
= Response::UseNextDecl(ND
).NextDecl
;
355 CurDecl
= Decl::castFromDeclContext(DC
);
357 while (!CurDecl
->isFileContextDecl()) {
359 if (const auto *VarTemplSpec
=
360 dyn_cast
<VarTemplateSpecializationDecl
>(CurDecl
)) {
361 R
= HandleVarTemplateSpec(VarTemplSpec
, Result
, SkipForSpecialization
);
362 } else if (const auto *PartialClassTemplSpec
=
363 dyn_cast
<ClassTemplatePartialSpecializationDecl
>(CurDecl
)) {
364 R
= HandlePartialClassTemplateSpec(PartialClassTemplSpec
, Result
,
365 SkipForSpecialization
);
366 } else if (const auto *ClassTemplSpec
=
367 dyn_cast
<ClassTemplateSpecializationDecl
>(CurDecl
)) {
368 R
= HandleClassTemplateSpec(ClassTemplSpec
, Result
,
369 SkipForSpecialization
);
370 } else if (const auto *Function
= dyn_cast
<FunctionDecl
>(CurDecl
)) {
371 R
= HandleFunction(Function
, Result
, Pattern
, RelativeToPrimary
,
372 ForConstraintInstantiation
);
373 } else if (const auto *Rec
= dyn_cast
<CXXRecordDecl
>(CurDecl
)) {
374 R
= HandleRecordDecl(Rec
, Result
, Context
, ForConstraintInstantiation
);
375 } else if (const auto *CSD
=
376 dyn_cast
<ImplicitConceptSpecializationDecl
>(CurDecl
)) {
377 R
= HandleImplicitConceptSpecializationDecl(CSD
, Result
);
378 } else if (const auto *FTD
= dyn_cast
<FunctionTemplateDecl
>(CurDecl
)) {
379 R
= HandleFunctionTemplateDecl(FTD
, Result
);
380 } else if (const auto *CTD
= dyn_cast
<ClassTemplateDecl
>(CurDecl
)) {
381 R
= Response::ChangeDecl(CTD
->getLexicalDeclContext());
382 } else if (!isa
<DeclContext
>(CurDecl
)) {
383 R
= Response::DontClearRelativeToPrimaryNextDecl(CurDecl
);
384 if (CurDecl
->getDeclContext()->isTranslationUnit()) {
385 if (const auto *TTP
= dyn_cast
<TemplateTemplateParmDecl
>(CurDecl
)) {
386 R
= HandleDefaultTempArgIntoTempTempParam(TTP
, Result
);
390 R
= HandleGenericDeclContext(CurDecl
);
395 if (R
.ClearRelativeToPrimary
)
396 RelativeToPrimary
= false;
398 CurDecl
= R
.NextDecl
;
404 bool Sema::CodeSynthesisContext::isInstantiationRecord() const {
406 case TemplateInstantiation
:
407 case ExceptionSpecInstantiation
:
408 case DefaultTemplateArgumentInstantiation
:
409 case DefaultFunctionArgumentInstantiation
:
410 case ExplicitTemplateArgumentSubstitution
:
411 case DeducedTemplateArgumentSubstitution
:
412 case PriorTemplateArgumentSubstitution
:
413 case ConstraintsCheck
:
414 case NestedRequirementConstraintsCheck
:
417 case RequirementInstantiation
:
418 case RequirementParameterInstantiation
:
419 case DefaultTemplateArgumentChecking
:
420 case DeclaringSpecialMember
:
421 case DeclaringImplicitEqualityComparison
:
422 case DefiningSynthesizedFunction
:
423 case ExceptionSpecEvaluation
:
424 case ConstraintSubstitution
:
425 case ParameterMappingSubstitution
:
426 case ConstraintNormalization
:
427 case RewritingOperatorAsSpaceship
:
428 case InitializingStructuredBinding
:
429 case MarkingClassDllexported
:
430 case BuildingBuiltinDumpStructCall
:
431 case LambdaExpressionSubstitution
:
432 case BuildingDeductionGuides
:
435 // This function should never be called when Kind's value is Memoization.
440 llvm_unreachable("Invalid SynthesisKind!");
443 Sema::InstantiatingTemplate::InstantiatingTemplate(
444 Sema
&SemaRef
, CodeSynthesisContext::SynthesisKind Kind
,
445 SourceLocation PointOfInstantiation
, SourceRange InstantiationRange
,
446 Decl
*Entity
, NamedDecl
*Template
, ArrayRef
<TemplateArgument
> TemplateArgs
,
447 sema::TemplateDeductionInfo
*DeductionInfo
)
449 // Don't allow further instantiation if a fatal error and an uncompilable
450 // error have occurred. Any diagnostics we might have raised will not be
451 // visible, and we do not need to construct a correct AST.
452 if (SemaRef
.Diags
.hasFatalErrorOccurred() &&
453 SemaRef
.hasUncompilableErrorOccurred()) {
457 Invalid
= CheckInstantiationDepth(PointOfInstantiation
, InstantiationRange
);
459 CodeSynthesisContext Inst
;
461 Inst
.PointOfInstantiation
= PointOfInstantiation
;
462 Inst
.Entity
= Entity
;
463 Inst
.Template
= Template
;
464 Inst
.TemplateArgs
= TemplateArgs
.data();
465 Inst
.NumTemplateArgs
= TemplateArgs
.size();
466 Inst
.DeductionInfo
= DeductionInfo
;
467 Inst
.InstantiationRange
= InstantiationRange
;
468 SemaRef
.pushCodeSynthesisContext(Inst
);
470 AlreadyInstantiating
= !Inst
.Entity
? false :
471 !SemaRef
.InstantiatingSpecializations
472 .insert({Inst
.Entity
->getCanonicalDecl(), Inst
.Kind
})
474 atTemplateBegin(SemaRef
.TemplateInstCallbacks
, SemaRef
, Inst
);
478 Sema::InstantiatingTemplate::InstantiatingTemplate(
479 Sema
&SemaRef
, SourceLocation PointOfInstantiation
, Decl
*Entity
,
480 SourceRange InstantiationRange
)
481 : InstantiatingTemplate(SemaRef
,
482 CodeSynthesisContext::TemplateInstantiation
,
483 PointOfInstantiation
, InstantiationRange
, Entity
) {}
485 Sema::InstantiatingTemplate::InstantiatingTemplate(
486 Sema
&SemaRef
, SourceLocation PointOfInstantiation
, FunctionDecl
*Entity
,
487 ExceptionSpecification
, SourceRange InstantiationRange
)
488 : InstantiatingTemplate(
489 SemaRef
, CodeSynthesisContext::ExceptionSpecInstantiation
,
490 PointOfInstantiation
, InstantiationRange
, Entity
) {}
492 Sema::InstantiatingTemplate::InstantiatingTemplate(
493 Sema
&SemaRef
, SourceLocation PointOfInstantiation
, TemplateParameter Param
,
494 TemplateDecl
*Template
, ArrayRef
<TemplateArgument
> TemplateArgs
,
495 SourceRange InstantiationRange
)
496 : InstantiatingTemplate(
498 CodeSynthesisContext::DefaultTemplateArgumentInstantiation
,
499 PointOfInstantiation
, InstantiationRange
, getAsNamedDecl(Param
),
500 Template
, TemplateArgs
) {}
502 Sema::InstantiatingTemplate::InstantiatingTemplate(
503 Sema
&SemaRef
, SourceLocation PointOfInstantiation
,
504 FunctionTemplateDecl
*FunctionTemplate
,
505 ArrayRef
<TemplateArgument
> TemplateArgs
,
506 CodeSynthesisContext::SynthesisKind Kind
,
507 sema::TemplateDeductionInfo
&DeductionInfo
, SourceRange InstantiationRange
)
508 : InstantiatingTemplate(SemaRef
, Kind
, PointOfInstantiation
,
509 InstantiationRange
, FunctionTemplate
, nullptr,
510 TemplateArgs
, &DeductionInfo
) {
512 Kind
== CodeSynthesisContext::ExplicitTemplateArgumentSubstitution
||
513 Kind
== CodeSynthesisContext::DeducedTemplateArgumentSubstitution
);
516 Sema::InstantiatingTemplate::InstantiatingTemplate(
517 Sema
&SemaRef
, SourceLocation PointOfInstantiation
,
518 TemplateDecl
*Template
,
519 ArrayRef
<TemplateArgument
> TemplateArgs
,
520 sema::TemplateDeductionInfo
&DeductionInfo
, SourceRange InstantiationRange
)
521 : InstantiatingTemplate(
523 CodeSynthesisContext::DeducedTemplateArgumentSubstitution
,
524 PointOfInstantiation
, InstantiationRange
, Template
, nullptr,
525 TemplateArgs
, &DeductionInfo
) {}
527 Sema::InstantiatingTemplate::InstantiatingTemplate(
528 Sema
&SemaRef
, SourceLocation PointOfInstantiation
,
529 ClassTemplatePartialSpecializationDecl
*PartialSpec
,
530 ArrayRef
<TemplateArgument
> TemplateArgs
,
531 sema::TemplateDeductionInfo
&DeductionInfo
, SourceRange InstantiationRange
)
532 : InstantiatingTemplate(
534 CodeSynthesisContext::DeducedTemplateArgumentSubstitution
,
535 PointOfInstantiation
, InstantiationRange
, PartialSpec
, nullptr,
536 TemplateArgs
, &DeductionInfo
) {}
538 Sema::InstantiatingTemplate::InstantiatingTemplate(
539 Sema
&SemaRef
, SourceLocation PointOfInstantiation
,
540 VarTemplatePartialSpecializationDecl
*PartialSpec
,
541 ArrayRef
<TemplateArgument
> TemplateArgs
,
542 sema::TemplateDeductionInfo
&DeductionInfo
, SourceRange InstantiationRange
)
543 : InstantiatingTemplate(
545 CodeSynthesisContext::DeducedTemplateArgumentSubstitution
,
546 PointOfInstantiation
, InstantiationRange
, PartialSpec
, nullptr,
547 TemplateArgs
, &DeductionInfo
) {}
549 Sema::InstantiatingTemplate::InstantiatingTemplate(
550 Sema
&SemaRef
, SourceLocation PointOfInstantiation
, ParmVarDecl
*Param
,
551 ArrayRef
<TemplateArgument
> TemplateArgs
, SourceRange InstantiationRange
)
552 : InstantiatingTemplate(
554 CodeSynthesisContext::DefaultFunctionArgumentInstantiation
,
555 PointOfInstantiation
, InstantiationRange
, Param
, nullptr,
558 Sema::InstantiatingTemplate::InstantiatingTemplate(
559 Sema
&SemaRef
, SourceLocation PointOfInstantiation
, NamedDecl
*Template
,
560 NonTypeTemplateParmDecl
*Param
, ArrayRef
<TemplateArgument
> TemplateArgs
,
561 SourceRange InstantiationRange
)
562 : InstantiatingTemplate(
564 CodeSynthesisContext::PriorTemplateArgumentSubstitution
,
565 PointOfInstantiation
, InstantiationRange
, Param
, Template
,
568 Sema::InstantiatingTemplate::InstantiatingTemplate(
569 Sema
&SemaRef
, SourceLocation PointOfInstantiation
, NamedDecl
*Template
,
570 TemplateTemplateParmDecl
*Param
, ArrayRef
<TemplateArgument
> TemplateArgs
,
571 SourceRange InstantiationRange
)
572 : InstantiatingTemplate(
574 CodeSynthesisContext::PriorTemplateArgumentSubstitution
,
575 PointOfInstantiation
, InstantiationRange
, Param
, Template
,
578 Sema::InstantiatingTemplate::InstantiatingTemplate(
579 Sema
&SemaRef
, SourceLocation PointOfInstantiation
, TemplateDecl
*Template
,
580 NamedDecl
*Param
, ArrayRef
<TemplateArgument
> TemplateArgs
,
581 SourceRange InstantiationRange
)
582 : InstantiatingTemplate(
583 SemaRef
, CodeSynthesisContext::DefaultTemplateArgumentChecking
,
584 PointOfInstantiation
, InstantiationRange
, Param
, Template
,
587 Sema::InstantiatingTemplate::InstantiatingTemplate(
588 Sema
&SemaRef
, SourceLocation PointOfInstantiation
,
589 concepts::Requirement
*Req
, sema::TemplateDeductionInfo
&DeductionInfo
,
590 SourceRange InstantiationRange
)
591 : InstantiatingTemplate(
592 SemaRef
, CodeSynthesisContext::RequirementInstantiation
,
593 PointOfInstantiation
, InstantiationRange
, /*Entity=*/nullptr,
594 /*Template=*/nullptr, /*TemplateArgs=*/std::nullopt
, &DeductionInfo
) {
597 Sema::InstantiatingTemplate::InstantiatingTemplate(
598 Sema
&SemaRef
, SourceLocation PointOfInstantiation
,
599 concepts::NestedRequirement
*Req
, ConstraintsCheck
,
600 SourceRange InstantiationRange
)
601 : InstantiatingTemplate(
602 SemaRef
, CodeSynthesisContext::NestedRequirementConstraintsCheck
,
603 PointOfInstantiation
, InstantiationRange
, /*Entity=*/nullptr,
604 /*Template=*/nullptr, /*TemplateArgs=*/std::nullopt
) {}
606 Sema::InstantiatingTemplate::InstantiatingTemplate(
607 Sema
&SemaRef
, SourceLocation PointOfInstantiation
, const RequiresExpr
*RE
,
608 sema::TemplateDeductionInfo
&DeductionInfo
, SourceRange InstantiationRange
)
609 : InstantiatingTemplate(
610 SemaRef
, CodeSynthesisContext::RequirementParameterInstantiation
,
611 PointOfInstantiation
, InstantiationRange
, /*Entity=*/nullptr,
612 /*Template=*/nullptr, /*TemplateArgs=*/std::nullopt
, &DeductionInfo
) {
615 Sema::InstantiatingTemplate::InstantiatingTemplate(
616 Sema
&SemaRef
, SourceLocation PointOfInstantiation
,
617 ConstraintsCheck
, NamedDecl
*Template
,
618 ArrayRef
<TemplateArgument
> TemplateArgs
, SourceRange InstantiationRange
)
619 : InstantiatingTemplate(
620 SemaRef
, CodeSynthesisContext::ConstraintsCheck
,
621 PointOfInstantiation
, InstantiationRange
, Template
, nullptr,
624 Sema::InstantiatingTemplate::InstantiatingTemplate(
625 Sema
&SemaRef
, SourceLocation PointOfInstantiation
,
626 ConstraintSubstitution
, NamedDecl
*Template
,
627 sema::TemplateDeductionInfo
&DeductionInfo
, SourceRange InstantiationRange
)
628 : InstantiatingTemplate(
629 SemaRef
, CodeSynthesisContext::ConstraintSubstitution
,
630 PointOfInstantiation
, InstantiationRange
, Template
, nullptr,
631 {}, &DeductionInfo
) {}
633 Sema::InstantiatingTemplate::InstantiatingTemplate(
634 Sema
&SemaRef
, SourceLocation PointOfInstantiation
,
635 ConstraintNormalization
, NamedDecl
*Template
,
636 SourceRange InstantiationRange
)
637 : InstantiatingTemplate(
638 SemaRef
, CodeSynthesisContext::ConstraintNormalization
,
639 PointOfInstantiation
, InstantiationRange
, Template
) {}
641 Sema::InstantiatingTemplate::InstantiatingTemplate(
642 Sema
&SemaRef
, SourceLocation PointOfInstantiation
,
643 ParameterMappingSubstitution
, NamedDecl
*Template
,
644 SourceRange InstantiationRange
)
645 : InstantiatingTemplate(
646 SemaRef
, CodeSynthesisContext::ParameterMappingSubstitution
,
647 PointOfInstantiation
, InstantiationRange
, Template
) {}
649 Sema::InstantiatingTemplate::InstantiatingTemplate(
650 Sema
&SemaRef
, SourceLocation PointOfInstantiation
, TemplateDecl
*Entity
,
651 BuildingDeductionGuidesTag
, SourceRange InstantiationRange
)
652 : InstantiatingTemplate(
653 SemaRef
, CodeSynthesisContext::BuildingDeductionGuides
,
654 PointOfInstantiation
, InstantiationRange
, Entity
) {}
657 void Sema::pushCodeSynthesisContext(CodeSynthesisContext Ctx
) {
658 Ctx
.SavedInNonInstantiationSFINAEContext
= InNonInstantiationSFINAEContext
;
659 InNonInstantiationSFINAEContext
= false;
661 CodeSynthesisContexts
.push_back(Ctx
);
663 if (!Ctx
.isInstantiationRecord())
664 ++NonInstantiationEntries
;
666 // Check to see if we're low on stack space. We can't do anything about this
667 // from here, but we can at least warn the user.
668 if (isStackNearlyExhausted())
669 warnStackExhausted(Ctx
.PointOfInstantiation
);
672 void Sema::popCodeSynthesisContext() {
673 auto &Active
= CodeSynthesisContexts
.back();
674 if (!Active
.isInstantiationRecord()) {
675 assert(NonInstantiationEntries
> 0);
676 --NonInstantiationEntries
;
679 InNonInstantiationSFINAEContext
= Active
.SavedInNonInstantiationSFINAEContext
;
681 // Name lookup no longer looks in this template's defining module.
682 assert(CodeSynthesisContexts
.size() >=
683 CodeSynthesisContextLookupModules
.size() &&
684 "forgot to remove a lookup module for a template instantiation");
685 if (CodeSynthesisContexts
.size() ==
686 CodeSynthesisContextLookupModules
.size()) {
687 if (Module
*M
= CodeSynthesisContextLookupModules
.back())
688 LookupModulesCache
.erase(M
);
689 CodeSynthesisContextLookupModules
.pop_back();
692 // If we've left the code synthesis context for the current context stack,
693 // stop remembering that we've emitted that stack.
694 if (CodeSynthesisContexts
.size() ==
695 LastEmittedCodeSynthesisContextDepth
)
696 LastEmittedCodeSynthesisContextDepth
= 0;
698 CodeSynthesisContexts
.pop_back();
701 void Sema::InstantiatingTemplate::Clear() {
703 if (!AlreadyInstantiating
) {
704 auto &Active
= SemaRef
.CodeSynthesisContexts
.back();
706 SemaRef
.InstantiatingSpecializations
.erase(
707 {Active
.Entity
->getCanonicalDecl(), Active
.Kind
});
710 atTemplateEnd(SemaRef
.TemplateInstCallbacks
, SemaRef
,
711 SemaRef
.CodeSynthesisContexts
.back());
713 SemaRef
.popCodeSynthesisContext();
718 static std::string
convertCallArgsToString(Sema
&S
,
719 llvm::ArrayRef
<const Expr
*> Args
) {
721 llvm::raw_string_ostream
OS(Result
);
722 llvm::ListSeparator Comma
;
723 for (const Expr
*Arg
: Args
) {
725 Arg
->IgnoreParens()->printPretty(OS
, nullptr,
726 S
.Context
.getPrintingPolicy());
731 bool Sema::InstantiatingTemplate::CheckInstantiationDepth(
732 SourceLocation PointOfInstantiation
,
733 SourceRange InstantiationRange
) {
734 assert(SemaRef
.NonInstantiationEntries
<=
735 SemaRef
.CodeSynthesisContexts
.size());
736 if ((SemaRef
.CodeSynthesisContexts
.size() -
737 SemaRef
.NonInstantiationEntries
)
738 <= SemaRef
.getLangOpts().InstantiationDepth
)
741 SemaRef
.Diag(PointOfInstantiation
,
742 diag::err_template_recursion_depth_exceeded
)
743 << SemaRef
.getLangOpts().InstantiationDepth
744 << InstantiationRange
;
745 SemaRef
.Diag(PointOfInstantiation
, diag::note_template_recursion_depth
)
746 << SemaRef
.getLangOpts().InstantiationDepth
;
750 /// Prints the current instantiation stack through a series of
752 void Sema::PrintInstantiationStack() {
753 // Determine which template instantiations to skip, if any.
754 unsigned SkipStart
= CodeSynthesisContexts
.size(), SkipEnd
= SkipStart
;
755 unsigned Limit
= Diags
.getTemplateBacktraceLimit();
756 if (Limit
&& Limit
< CodeSynthesisContexts
.size()) {
757 SkipStart
= Limit
/ 2 + Limit
% 2;
758 SkipEnd
= CodeSynthesisContexts
.size() - Limit
/ 2;
761 // FIXME: In all of these cases, we need to show the template arguments
762 unsigned InstantiationIdx
= 0;
763 for (SmallVectorImpl
<CodeSynthesisContext
>::reverse_iterator
764 Active
= CodeSynthesisContexts
.rbegin(),
765 ActiveEnd
= CodeSynthesisContexts
.rend();
767 ++Active
, ++InstantiationIdx
) {
768 // Skip this instantiation?
769 if (InstantiationIdx
>= SkipStart
&& InstantiationIdx
< SkipEnd
) {
770 if (InstantiationIdx
== SkipStart
) {
771 // Note that we're skipping instantiations.
772 Diags
.Report(Active
->PointOfInstantiation
,
773 diag::note_instantiation_contexts_suppressed
)
774 << unsigned(CodeSynthesisContexts
.size() - Limit
);
779 switch (Active
->Kind
) {
780 case CodeSynthesisContext::TemplateInstantiation
: {
781 Decl
*D
= Active
->Entity
;
782 if (CXXRecordDecl
*Record
= dyn_cast
<CXXRecordDecl
>(D
)) {
783 unsigned DiagID
= diag::note_template_member_class_here
;
784 if (isa
<ClassTemplateSpecializationDecl
>(Record
))
785 DiagID
= diag::note_template_class_instantiation_here
;
786 Diags
.Report(Active
->PointOfInstantiation
, DiagID
)
787 << Record
<< Active
->InstantiationRange
;
788 } else if (FunctionDecl
*Function
= dyn_cast
<FunctionDecl
>(D
)) {
790 if (Function
->getPrimaryTemplate())
791 DiagID
= diag::note_function_template_spec_here
;
793 DiagID
= diag::note_template_member_function_here
;
794 Diags
.Report(Active
->PointOfInstantiation
, DiagID
)
796 << Active
->InstantiationRange
;
797 } else if (VarDecl
*VD
= dyn_cast
<VarDecl
>(D
)) {
798 Diags
.Report(Active
->PointOfInstantiation
,
799 VD
->isStaticDataMember()?
800 diag::note_template_static_data_member_def_here
801 : diag::note_template_variable_def_here
)
803 << Active
->InstantiationRange
;
804 } else if (EnumDecl
*ED
= dyn_cast
<EnumDecl
>(D
)) {
805 Diags
.Report(Active
->PointOfInstantiation
,
806 diag::note_template_enum_def_here
)
808 << Active
->InstantiationRange
;
809 } else if (FieldDecl
*FD
= dyn_cast
<FieldDecl
>(D
)) {
810 Diags
.Report(Active
->PointOfInstantiation
,
811 diag::note_template_nsdmi_here
)
812 << FD
<< Active
->InstantiationRange
;
814 Diags
.Report(Active
->PointOfInstantiation
,
815 diag::note_template_type_alias_instantiation_here
)
816 << cast
<TypeAliasTemplateDecl
>(D
)
817 << Active
->InstantiationRange
;
822 case CodeSynthesisContext::DefaultTemplateArgumentInstantiation
: {
823 TemplateDecl
*Template
= cast
<TemplateDecl
>(Active
->Template
);
824 SmallString
<128> TemplateArgsStr
;
825 llvm::raw_svector_ostream
OS(TemplateArgsStr
);
826 Template
->printName(OS
, getPrintingPolicy());
827 printTemplateArgumentList(OS
, Active
->template_arguments(),
828 getPrintingPolicy());
829 Diags
.Report(Active
->PointOfInstantiation
,
830 diag::note_default_arg_instantiation_here
)
832 << Active
->InstantiationRange
;
836 case CodeSynthesisContext::ExplicitTemplateArgumentSubstitution
: {
837 FunctionTemplateDecl
*FnTmpl
= cast
<FunctionTemplateDecl
>(Active
->Entity
);
838 Diags
.Report(Active
->PointOfInstantiation
,
839 diag::note_explicit_template_arg_substitution_here
)
841 << getTemplateArgumentBindingsText(FnTmpl
->getTemplateParameters(),
842 Active
->TemplateArgs
,
843 Active
->NumTemplateArgs
)
844 << Active
->InstantiationRange
;
848 case CodeSynthesisContext::DeducedTemplateArgumentSubstitution
: {
849 if (FunctionTemplateDecl
*FnTmpl
=
850 dyn_cast
<FunctionTemplateDecl
>(Active
->Entity
)) {
851 Diags
.Report(Active
->PointOfInstantiation
,
852 diag::note_function_template_deduction_instantiation_here
)
854 << getTemplateArgumentBindingsText(FnTmpl
->getTemplateParameters(),
855 Active
->TemplateArgs
,
856 Active
->NumTemplateArgs
)
857 << Active
->InstantiationRange
;
859 bool IsVar
= isa
<VarTemplateDecl
>(Active
->Entity
) ||
860 isa
<VarTemplateSpecializationDecl
>(Active
->Entity
);
861 bool IsTemplate
= false;
862 TemplateParameterList
*Params
;
863 if (auto *D
= dyn_cast
<TemplateDecl
>(Active
->Entity
)) {
865 Params
= D
->getTemplateParameters();
866 } else if (auto *D
= dyn_cast
<ClassTemplatePartialSpecializationDecl
>(
868 Params
= D
->getTemplateParameters();
869 } else if (auto *D
= dyn_cast
<VarTemplatePartialSpecializationDecl
>(
871 Params
= D
->getTemplateParameters();
873 llvm_unreachable("unexpected template kind");
876 Diags
.Report(Active
->PointOfInstantiation
,
877 diag::note_deduced_template_arg_substitution_here
)
878 << IsVar
<< IsTemplate
<< cast
<NamedDecl
>(Active
->Entity
)
879 << getTemplateArgumentBindingsText(Params
, Active
->TemplateArgs
,
880 Active
->NumTemplateArgs
)
881 << Active
->InstantiationRange
;
886 case CodeSynthesisContext::DefaultFunctionArgumentInstantiation
: {
887 ParmVarDecl
*Param
= cast
<ParmVarDecl
>(Active
->Entity
);
888 FunctionDecl
*FD
= cast
<FunctionDecl
>(Param
->getDeclContext());
890 SmallString
<128> TemplateArgsStr
;
891 llvm::raw_svector_ostream
OS(TemplateArgsStr
);
892 FD
->printName(OS
, getPrintingPolicy());
893 printTemplateArgumentList(OS
, Active
->template_arguments(),
894 getPrintingPolicy());
895 Diags
.Report(Active
->PointOfInstantiation
,
896 diag::note_default_function_arg_instantiation_here
)
898 << Active
->InstantiationRange
;
902 case CodeSynthesisContext::PriorTemplateArgumentSubstitution
: {
903 NamedDecl
*Parm
= cast
<NamedDecl
>(Active
->Entity
);
905 if (!Parm
->getName().empty())
906 Name
= std::string(" '") + Parm
->getName().str() + "'";
908 TemplateParameterList
*TemplateParams
= nullptr;
909 if (TemplateDecl
*Template
= dyn_cast
<TemplateDecl
>(Active
->Template
))
910 TemplateParams
= Template
->getTemplateParameters();
913 cast
<ClassTemplatePartialSpecializationDecl
>(Active
->Template
)
914 ->getTemplateParameters();
915 Diags
.Report(Active
->PointOfInstantiation
,
916 diag::note_prior_template_arg_substitution
)
917 << isa
<TemplateTemplateParmDecl
>(Parm
)
919 << getTemplateArgumentBindingsText(TemplateParams
,
920 Active
->TemplateArgs
,
921 Active
->NumTemplateArgs
)
922 << Active
->InstantiationRange
;
926 case CodeSynthesisContext::DefaultTemplateArgumentChecking
: {
927 TemplateParameterList
*TemplateParams
= nullptr;
928 if (TemplateDecl
*Template
= dyn_cast
<TemplateDecl
>(Active
->Template
))
929 TemplateParams
= Template
->getTemplateParameters();
932 cast
<ClassTemplatePartialSpecializationDecl
>(Active
->Template
)
933 ->getTemplateParameters();
935 Diags
.Report(Active
->PointOfInstantiation
,
936 diag::note_template_default_arg_checking
)
937 << getTemplateArgumentBindingsText(TemplateParams
,
938 Active
->TemplateArgs
,
939 Active
->NumTemplateArgs
)
940 << Active
->InstantiationRange
;
944 case CodeSynthesisContext::ExceptionSpecEvaluation
:
945 Diags
.Report(Active
->PointOfInstantiation
,
946 diag::note_evaluating_exception_spec_here
)
947 << cast
<FunctionDecl
>(Active
->Entity
);
950 case CodeSynthesisContext::ExceptionSpecInstantiation
:
951 Diags
.Report(Active
->PointOfInstantiation
,
952 diag::note_template_exception_spec_instantiation_here
)
953 << cast
<FunctionDecl
>(Active
->Entity
)
954 << Active
->InstantiationRange
;
957 case CodeSynthesisContext::RequirementInstantiation
:
958 Diags
.Report(Active
->PointOfInstantiation
,
959 diag::note_template_requirement_instantiation_here
)
960 << Active
->InstantiationRange
;
962 case CodeSynthesisContext::RequirementParameterInstantiation
:
963 Diags
.Report(Active
->PointOfInstantiation
,
964 diag::note_template_requirement_params_instantiation_here
)
965 << Active
->InstantiationRange
;
968 case CodeSynthesisContext::NestedRequirementConstraintsCheck
:
969 Diags
.Report(Active
->PointOfInstantiation
,
970 diag::note_nested_requirement_here
)
971 << Active
->InstantiationRange
;
974 case CodeSynthesisContext::DeclaringSpecialMember
:
975 Diags
.Report(Active
->PointOfInstantiation
,
976 diag::note_in_declaration_of_implicit_special_member
)
977 << cast
<CXXRecordDecl
>(Active
->Entity
) << Active
->SpecialMember
;
980 case CodeSynthesisContext::DeclaringImplicitEqualityComparison
:
981 Diags
.Report(Active
->Entity
->getLocation(),
982 diag::note_in_declaration_of_implicit_equality_comparison
);
985 case CodeSynthesisContext::DefiningSynthesizedFunction
: {
986 // FIXME: For synthesized functions that are not defaulted,
988 auto *FD
= dyn_cast
<FunctionDecl
>(Active
->Entity
);
989 DefaultedFunctionKind DFK
=
990 FD
? getDefaultedFunctionKind(FD
) : DefaultedFunctionKind();
991 if (DFK
.isSpecialMember()) {
992 auto *MD
= cast
<CXXMethodDecl
>(FD
);
993 Diags
.Report(Active
->PointOfInstantiation
,
994 diag::note_member_synthesized_at
)
995 << MD
->isExplicitlyDefaulted() << DFK
.asSpecialMember()
996 << Context
.getTagDeclType(MD
->getParent());
997 } else if (DFK
.isComparison()) {
998 QualType RecordType
= FD
->getParamDecl(0)
1000 .getNonReferenceType()
1001 .getUnqualifiedType();
1002 Diags
.Report(Active
->PointOfInstantiation
,
1003 diag::note_comparison_synthesized_at
)
1004 << (int)DFK
.asComparison() << RecordType
;
1009 case CodeSynthesisContext::RewritingOperatorAsSpaceship
:
1010 Diags
.Report(Active
->Entity
->getLocation(),
1011 diag::note_rewriting_operator_as_spaceship
);
1014 case CodeSynthesisContext::InitializingStructuredBinding
:
1015 Diags
.Report(Active
->PointOfInstantiation
,
1016 diag::note_in_binding_decl_init
)
1017 << cast
<BindingDecl
>(Active
->Entity
);
1020 case CodeSynthesisContext::MarkingClassDllexported
:
1021 Diags
.Report(Active
->PointOfInstantiation
,
1022 diag::note_due_to_dllexported_class
)
1023 << cast
<CXXRecordDecl
>(Active
->Entity
) << !getLangOpts().CPlusPlus11
;
1026 case CodeSynthesisContext::BuildingBuiltinDumpStructCall
:
1027 Diags
.Report(Active
->PointOfInstantiation
,
1028 diag::note_building_builtin_dump_struct_call
)
1029 << convertCallArgsToString(
1030 *this, llvm::ArrayRef(Active
->CallArgs
, Active
->NumCallArgs
));
1033 case CodeSynthesisContext::Memoization
:
1036 case CodeSynthesisContext::LambdaExpressionSubstitution
:
1037 Diags
.Report(Active
->PointOfInstantiation
,
1038 diag::note_lambda_substitution_here
);
1040 case CodeSynthesisContext::ConstraintsCheck
: {
1041 unsigned DiagID
= 0;
1042 if (!Active
->Entity
) {
1043 Diags
.Report(Active
->PointOfInstantiation
,
1044 diag::note_nested_requirement_here
)
1045 << Active
->InstantiationRange
;
1048 if (isa
<ConceptDecl
>(Active
->Entity
))
1049 DiagID
= diag::note_concept_specialization_here
;
1050 else if (isa
<TemplateDecl
>(Active
->Entity
))
1051 DiagID
= diag::note_checking_constraints_for_template_id_here
;
1052 else if (isa
<VarTemplatePartialSpecializationDecl
>(Active
->Entity
))
1053 DiagID
= diag::note_checking_constraints_for_var_spec_id_here
;
1054 else if (isa
<ClassTemplatePartialSpecializationDecl
>(Active
->Entity
))
1055 DiagID
= diag::note_checking_constraints_for_class_spec_id_here
;
1057 assert(isa
<FunctionDecl
>(Active
->Entity
));
1058 DiagID
= diag::note_checking_constraints_for_function_here
;
1060 SmallString
<128> TemplateArgsStr
;
1061 llvm::raw_svector_ostream
OS(TemplateArgsStr
);
1062 cast
<NamedDecl
>(Active
->Entity
)->printName(OS
, getPrintingPolicy());
1063 if (!isa
<FunctionDecl
>(Active
->Entity
)) {
1064 printTemplateArgumentList(OS
, Active
->template_arguments(),
1065 getPrintingPolicy());
1067 Diags
.Report(Active
->PointOfInstantiation
, DiagID
) << OS
.str()
1068 << Active
->InstantiationRange
;
1071 case CodeSynthesisContext::ConstraintSubstitution
:
1072 Diags
.Report(Active
->PointOfInstantiation
,
1073 diag::note_constraint_substitution_here
)
1074 << Active
->InstantiationRange
;
1076 case CodeSynthesisContext::ConstraintNormalization
:
1077 Diags
.Report(Active
->PointOfInstantiation
,
1078 diag::note_constraint_normalization_here
)
1079 << cast
<NamedDecl
>(Active
->Entity
)->getName()
1080 << Active
->InstantiationRange
;
1082 case CodeSynthesisContext::ParameterMappingSubstitution
:
1083 Diags
.Report(Active
->PointOfInstantiation
,
1084 diag::note_parameter_mapping_substitution_here
)
1085 << Active
->InstantiationRange
;
1087 case CodeSynthesisContext::BuildingDeductionGuides
:
1088 Diags
.Report(Active
->PointOfInstantiation
,
1089 diag::note_building_deduction_guide_here
);
1095 std::optional
<TemplateDeductionInfo
*> Sema::isSFINAEContext() const {
1096 if (InNonInstantiationSFINAEContext
)
1097 return std::optional
<TemplateDeductionInfo
*>(nullptr);
1099 for (SmallVectorImpl
<CodeSynthesisContext
>::const_reverse_iterator
1100 Active
= CodeSynthesisContexts
.rbegin(),
1101 ActiveEnd
= CodeSynthesisContexts
.rend();
1102 Active
!= ActiveEnd
;
1105 switch (Active
->Kind
) {
1106 case CodeSynthesisContext::TemplateInstantiation
:
1107 // An instantiation of an alias template may or may not be a SFINAE
1108 // context, depending on what else is on the stack.
1109 if (isa
<TypeAliasTemplateDecl
>(Active
->Entity
))
1112 case CodeSynthesisContext::DefaultFunctionArgumentInstantiation
:
1113 case CodeSynthesisContext::ExceptionSpecInstantiation
:
1114 case CodeSynthesisContext::ConstraintsCheck
:
1115 case CodeSynthesisContext::ParameterMappingSubstitution
:
1116 case CodeSynthesisContext::ConstraintNormalization
:
1117 case CodeSynthesisContext::NestedRequirementConstraintsCheck
:
1118 // This is a template instantiation, so there is no SFINAE.
1119 return std::nullopt
;
1120 case CodeSynthesisContext::LambdaExpressionSubstitution
:
1122 // A lambda-expression appearing in a function type or a template
1123 // parameter is not considered part of the immediate context for the
1124 // purposes of template argument deduction.
1125 // CWG2672: A lambda-expression body is never in the immediate context.
1126 return std::nullopt
;
1128 case CodeSynthesisContext::DefaultTemplateArgumentInstantiation
:
1129 case CodeSynthesisContext::PriorTemplateArgumentSubstitution
:
1130 case CodeSynthesisContext::DefaultTemplateArgumentChecking
:
1131 case CodeSynthesisContext::RewritingOperatorAsSpaceship
:
1132 // A default template argument instantiation and substitution into
1133 // template parameters with arguments for prior parameters may or may
1134 // not be a SFINAE context; look further up the stack.
1137 case CodeSynthesisContext::ExplicitTemplateArgumentSubstitution
:
1138 case CodeSynthesisContext::DeducedTemplateArgumentSubstitution
:
1139 // We're either substituting explicitly-specified template arguments,
1140 // deduced template arguments. SFINAE applies unless we are in a lambda
1141 // expression, see [temp.deduct]p9.
1143 case CodeSynthesisContext::ConstraintSubstitution
:
1144 case CodeSynthesisContext::RequirementInstantiation
:
1145 case CodeSynthesisContext::RequirementParameterInstantiation
:
1146 // SFINAE always applies in a constraint expression or a requirement
1147 // in a requires expression.
1148 assert(Active
->DeductionInfo
&& "Missing deduction info pointer");
1149 return Active
->DeductionInfo
;
1151 case CodeSynthesisContext::DeclaringSpecialMember
:
1152 case CodeSynthesisContext::DeclaringImplicitEqualityComparison
:
1153 case CodeSynthesisContext::DefiningSynthesizedFunction
:
1154 case CodeSynthesisContext::InitializingStructuredBinding
:
1155 case CodeSynthesisContext::MarkingClassDllexported
:
1156 case CodeSynthesisContext::BuildingBuiltinDumpStructCall
:
1157 case CodeSynthesisContext::BuildingDeductionGuides
:
1158 // This happens in a context unrelated to template instantiation, so
1159 // there is no SFINAE.
1160 return std::nullopt
;
1162 case CodeSynthesisContext::ExceptionSpecEvaluation
:
1163 // FIXME: This should not be treated as a SFINAE context, because
1164 // we will cache an incorrect exception specification. However, clang
1165 // bootstrap relies this! See PR31692.
1168 case CodeSynthesisContext::Memoization
:
1172 // The inner context was transparent for SFINAE. If it occurred within a
1173 // non-instantiation SFINAE context, then SFINAE applies.
1174 if (Active
->SavedInNonInstantiationSFINAEContext
)
1175 return std::optional
<TemplateDeductionInfo
*>(nullptr);
1178 return std::nullopt
;
1181 //===----------------------------------------------------------------------===/
1182 // Template Instantiation for Types
1183 //===----------------------------------------------------------------------===/
1185 class TemplateInstantiator
: public TreeTransform
<TemplateInstantiator
> {
1186 const MultiLevelTemplateArgumentList
&TemplateArgs
;
1188 DeclarationName Entity
;
1189 bool EvaluateConstraints
= true;
1192 typedef TreeTransform
<TemplateInstantiator
> inherited
;
1194 TemplateInstantiator(Sema
&SemaRef
,
1195 const MultiLevelTemplateArgumentList
&TemplateArgs
,
1196 SourceLocation Loc
, DeclarationName Entity
)
1197 : inherited(SemaRef
), TemplateArgs(TemplateArgs
), Loc(Loc
),
1200 void setEvaluateConstraints(bool B
) {
1201 EvaluateConstraints
= B
;
1203 bool getEvaluateConstraints() {
1204 return EvaluateConstraints
;
1207 /// Determine whether the given type \p T has already been
1210 /// For the purposes of template instantiation, a type has already been
1211 /// transformed if it is NULL or if it is not dependent.
1212 bool AlreadyTransformed(QualType T
);
1214 /// Returns the location of the entity being instantiated, if known.
1215 SourceLocation
getBaseLocation() { return Loc
; }
1217 /// Returns the name of the entity being instantiated, if any.
1218 DeclarationName
getBaseEntity() { return Entity
; }
1220 /// Sets the "base" location and entity when that
1221 /// information is known based on another transformation.
1222 void setBase(SourceLocation Loc
, DeclarationName Entity
) {
1224 this->Entity
= Entity
;
1227 unsigned TransformTemplateDepth(unsigned Depth
) {
1228 return TemplateArgs
.getNewDepth(Depth
);
1231 std::optional
<unsigned> getPackIndex(TemplateArgument Pack
) {
1232 int Index
= getSema().ArgumentPackSubstitutionIndex
;
1234 return std::nullopt
;
1235 return Pack
.pack_size() - 1 - Index
;
1238 bool TryExpandParameterPacks(SourceLocation EllipsisLoc
,
1239 SourceRange PatternRange
,
1240 ArrayRef
<UnexpandedParameterPack
> Unexpanded
,
1241 bool &ShouldExpand
, bool &RetainExpansion
,
1242 std::optional
<unsigned> &NumExpansions
) {
1243 return getSema().CheckParameterPacksForExpansion(EllipsisLoc
,
1244 PatternRange
, Unexpanded
,
1251 void ExpandingFunctionParameterPack(ParmVarDecl
*Pack
) {
1252 SemaRef
.CurrentInstantiationScope
->MakeInstantiatedLocalArgPack(Pack
);
1255 TemplateArgument
ForgetPartiallySubstitutedPack() {
1256 TemplateArgument Result
;
1257 if (NamedDecl
*PartialPack
1258 = SemaRef
.CurrentInstantiationScope
->getPartiallySubstitutedPack()){
1259 MultiLevelTemplateArgumentList
&TemplateArgs
1260 = const_cast<MultiLevelTemplateArgumentList
&>(this->TemplateArgs
);
1261 unsigned Depth
, Index
;
1262 std::tie(Depth
, Index
) = getDepthAndIndex(PartialPack
);
1263 if (TemplateArgs
.hasTemplateArgument(Depth
, Index
)) {
1264 Result
= TemplateArgs(Depth
, Index
);
1265 TemplateArgs
.setArgument(Depth
, Index
, TemplateArgument());
1272 void RememberPartiallySubstitutedPack(TemplateArgument Arg
) {
1276 if (NamedDecl
*PartialPack
1277 = SemaRef
.CurrentInstantiationScope
->getPartiallySubstitutedPack()){
1278 MultiLevelTemplateArgumentList
&TemplateArgs
1279 = const_cast<MultiLevelTemplateArgumentList
&>(this->TemplateArgs
);
1280 unsigned Depth
, Index
;
1281 std::tie(Depth
, Index
) = getDepthAndIndex(PartialPack
);
1282 TemplateArgs
.setArgument(Depth
, Index
, Arg
);
1286 /// Transform the given declaration by instantiating a reference to
1287 /// this declaration.
1288 Decl
*TransformDecl(SourceLocation Loc
, Decl
*D
);
1290 void transformAttrs(Decl
*Old
, Decl
*New
) {
1291 SemaRef
.InstantiateAttrs(TemplateArgs
, Old
, New
);
1294 void transformedLocalDecl(Decl
*Old
, ArrayRef
<Decl
*> NewDecls
) {
1295 if (Old
->isParameterPack()) {
1296 SemaRef
.CurrentInstantiationScope
->MakeInstantiatedLocalArgPack(Old
);
1297 for (auto *New
: NewDecls
)
1298 SemaRef
.CurrentInstantiationScope
->InstantiatedLocalPackArg(
1299 Old
, cast
<VarDecl
>(New
));
1303 assert(NewDecls
.size() == 1 &&
1304 "should only have multiple expansions for a pack");
1305 Decl
*New
= NewDecls
.front();
1307 // If we've instantiated the call operator of a lambda or the call
1308 // operator template of a generic lambda, update the "instantiation of"
1310 auto *NewMD
= dyn_cast
<CXXMethodDecl
>(New
);
1311 if (NewMD
&& isLambdaCallOperator(NewMD
)) {
1312 auto *OldMD
= dyn_cast
<CXXMethodDecl
>(Old
);
1313 if (auto *NewTD
= NewMD
->getDescribedFunctionTemplate())
1314 NewTD
->setInstantiatedFromMemberTemplate(
1315 OldMD
->getDescribedFunctionTemplate());
1317 NewMD
->setInstantiationOfMemberFunction(OldMD
,
1318 TSK_ImplicitInstantiation
);
1321 SemaRef
.CurrentInstantiationScope
->InstantiatedLocal(Old
, New
);
1323 // We recreated a local declaration, but not by instantiating it. There
1324 // may be pending dependent diagnostics to produce.
1325 if (auto *DC
= dyn_cast
<DeclContext
>(Old
);
1326 DC
&& DC
->isDependentContext() && DC
->isFunctionOrMethod())
1327 SemaRef
.PerformDependentDiagnostics(DC
, TemplateArgs
);
1330 /// Transform the definition of the given declaration by
1331 /// instantiating it.
1332 Decl
*TransformDefinition(SourceLocation Loc
, Decl
*D
);
1334 /// Transform the first qualifier within a scope by instantiating the
1336 NamedDecl
*TransformFirstQualifierInScope(NamedDecl
*D
, SourceLocation Loc
);
1338 bool TransformExceptionSpec(SourceLocation Loc
,
1339 FunctionProtoType::ExceptionSpecInfo
&ESI
,
1340 SmallVectorImpl
<QualType
> &Exceptions
,
1343 /// Rebuild the exception declaration and register the declaration
1344 /// as an instantiated local.
1345 VarDecl
*RebuildExceptionDecl(VarDecl
*ExceptionDecl
,
1346 TypeSourceInfo
*Declarator
,
1347 SourceLocation StartLoc
,
1348 SourceLocation NameLoc
,
1349 IdentifierInfo
*Name
);
1351 /// Rebuild the Objective-C exception declaration and register the
1352 /// declaration as an instantiated local.
1353 VarDecl
*RebuildObjCExceptionDecl(VarDecl
*ExceptionDecl
,
1354 TypeSourceInfo
*TSInfo
, QualType T
);
1356 /// Check for tag mismatches when instantiating an
1357 /// elaborated type.
1358 QualType
RebuildElaboratedType(SourceLocation KeywordLoc
,
1359 ElaboratedTypeKeyword Keyword
,
1360 NestedNameSpecifierLoc QualifierLoc
,
1364 TransformTemplateName(CXXScopeSpec
&SS
, TemplateName Name
,
1365 SourceLocation NameLoc
,
1366 QualType ObjectType
= QualType(),
1367 NamedDecl
*FirstQualifierInScope
= nullptr,
1368 bool AllowInjectedClassName
= false);
1370 const LoopHintAttr
*TransformLoopHintAttr(const LoopHintAttr
*LH
);
1371 const NoInlineAttr
*TransformStmtNoInlineAttr(const Stmt
*OrigS
,
1373 const NoInlineAttr
*A
);
1374 const AlwaysInlineAttr
*
1375 TransformStmtAlwaysInlineAttr(const Stmt
*OrigS
, const Stmt
*InstS
,
1376 const AlwaysInlineAttr
*A
);
1378 ExprResult
TransformPredefinedExpr(PredefinedExpr
*E
);
1379 ExprResult
TransformDeclRefExpr(DeclRefExpr
*E
);
1380 ExprResult
TransformCXXDefaultArgExpr(CXXDefaultArgExpr
*E
);
1382 ExprResult
TransformTemplateParmRefExpr(DeclRefExpr
*E
,
1383 NonTypeTemplateParmDecl
*D
);
1384 ExprResult
TransformSubstNonTypeTemplateParmPackExpr(
1385 SubstNonTypeTemplateParmPackExpr
*E
);
1386 ExprResult
TransformSubstNonTypeTemplateParmExpr(
1387 SubstNonTypeTemplateParmExpr
*E
);
1389 /// Rebuild a DeclRefExpr for a VarDecl reference.
1390 ExprResult
RebuildVarDeclRefExpr(VarDecl
*PD
, SourceLocation Loc
);
1392 /// Transform a reference to a function or init-capture parameter pack.
1393 ExprResult
TransformFunctionParmPackRefExpr(DeclRefExpr
*E
, VarDecl
*PD
);
1395 /// Transform a FunctionParmPackExpr which was built when we couldn't
1396 /// expand a function parameter pack reference which refers to an expanded
1398 ExprResult
TransformFunctionParmPackExpr(FunctionParmPackExpr
*E
);
1400 QualType
TransformFunctionProtoType(TypeLocBuilder
&TLB
,
1401 FunctionProtoTypeLoc TL
) {
1402 // Call the base version; it will forward to our overridden version below.
1403 return inherited::TransformFunctionProtoType(TLB
, TL
);
1406 template<typename Fn
>
1407 QualType
TransformFunctionProtoType(TypeLocBuilder
&TLB
,
1408 FunctionProtoTypeLoc TL
,
1409 CXXRecordDecl
*ThisContext
,
1410 Qualifiers ThisTypeQuals
,
1411 Fn TransformExceptionSpec
);
1414 TransformFunctionTypeParam(ParmVarDecl
*OldParm
, int indexAdjustment
,
1415 std::optional
<unsigned> NumExpansions
,
1416 bool ExpectParameterPack
);
1418 using inherited::TransformTemplateTypeParmType
;
1419 /// Transforms a template type parameter type by performing
1420 /// substitution of the corresponding template type argument.
1421 QualType
TransformTemplateTypeParmType(TypeLocBuilder
&TLB
,
1422 TemplateTypeParmTypeLoc TL
,
1423 bool SuppressObjCLifetime
);
1425 QualType
BuildSubstTemplateTypeParmType(
1426 TypeLocBuilder
&TLB
, bool SuppressObjCLifetime
, bool Final
,
1427 Decl
*AssociatedDecl
, unsigned Index
, std::optional
<unsigned> PackIndex
,
1428 TemplateArgument Arg
, SourceLocation NameLoc
);
1430 /// Transforms an already-substituted template type parameter pack
1431 /// into either itself (if we aren't substituting into its pack expansion)
1432 /// or the appropriate substituted argument.
1433 using inherited::TransformSubstTemplateTypeParmPackType
;
1435 TransformSubstTemplateTypeParmPackType(TypeLocBuilder
&TLB
,
1436 SubstTemplateTypeParmPackTypeLoc TL
,
1437 bool SuppressObjCLifetime
);
1439 ExprResult
TransformLambdaExpr(LambdaExpr
*E
) {
1440 LocalInstantiationScope
Scope(SemaRef
, /*CombineWithOuterScope=*/true);
1441 Sema::ConstraintEvalRAII
<TemplateInstantiator
> RAII(*this);
1443 Sema::CodeSynthesisContext C
;
1444 C
.Kind
= clang::Sema::CodeSynthesisContext::LambdaExpressionSubstitution
;
1445 C
.PointOfInstantiation
= E
->getBeginLoc();
1446 SemaRef
.pushCodeSynthesisContext(C
);
1448 llvm::make_scope_exit([this] { SemaRef
.popCodeSynthesisContext(); });
1450 ExprResult Result
= inherited::TransformLambdaExpr(E
);
1451 if (Result
.isInvalid())
1454 CXXMethodDecl
*MD
= Result
.getAs
<LambdaExpr
>()->getCallOperator();
1455 for (ParmVarDecl
*PVD
: MD
->parameters()) {
1456 assert(PVD
&& "null in a parameter list");
1457 if (!PVD
->hasDefaultArg())
1459 Expr
*UninstExpr
= PVD
->getUninstantiatedDefaultArg();
1460 // FIXME: Obtain the source location for the '=' token.
1461 SourceLocation EqualLoc
= UninstExpr
->getBeginLoc();
1462 if (SemaRef
.SubstDefaultArgument(EqualLoc
, PVD
, TemplateArgs
)) {
1463 // If substitution fails, the default argument is set to a
1464 // RecoveryExpr that wraps the uninstantiated default argument so
1465 // that downstream diagnostics are omitted.
1466 ExprResult ErrorResult
= SemaRef
.CreateRecoveryExpr(
1467 UninstExpr
->getBeginLoc(), UninstExpr
->getEndLoc(),
1468 { UninstExpr
}, UninstExpr
->getType());
1469 if (ErrorResult
.isUsable())
1470 PVD
->setDefaultArg(ErrorResult
.get());
1477 ExprResult
TransformRequiresExpr(RequiresExpr
*E
) {
1478 LocalInstantiationScope
Scope(SemaRef
, /*CombineWithOuterScope=*/true);
1479 ExprResult TransReq
= inherited::TransformRequiresExpr(E
);
1480 if (TransReq
.isInvalid())
1482 assert(TransReq
.get() != E
&&
1483 "Do not change value of isSatisfied for the existing expression. "
1484 "Create a new expression instead.");
1485 if (E
->getBody()->isDependentContext()) {
1486 Sema::SFINAETrap
Trap(SemaRef
);
1487 // We recreate the RequiresExpr body, but not by instantiating it.
1488 // Produce pending diagnostics for dependent access check.
1489 SemaRef
.PerformDependentDiagnostics(E
->getBody(), TemplateArgs
);
1490 // FIXME: Store SFINAE diagnostics in RequiresExpr for diagnosis.
1491 if (Trap
.hasErrorOccurred())
1492 TransReq
.getAs
<RequiresExpr
>()->setSatisfied(false);
1497 bool TransformRequiresExprRequirements(
1498 ArrayRef
<concepts::Requirement
*> Reqs
,
1499 SmallVectorImpl
<concepts::Requirement
*> &Transformed
) {
1500 bool SatisfactionDetermined
= false;
1501 for (concepts::Requirement
*Req
: Reqs
) {
1502 concepts::Requirement
*TransReq
= nullptr;
1503 if (!SatisfactionDetermined
) {
1504 if (auto *TypeReq
= dyn_cast
<concepts::TypeRequirement
>(Req
))
1505 TransReq
= TransformTypeRequirement(TypeReq
);
1506 else if (auto *ExprReq
= dyn_cast
<concepts::ExprRequirement
>(Req
))
1507 TransReq
= TransformExprRequirement(ExprReq
);
1509 TransReq
= TransformNestedRequirement(
1510 cast
<concepts::NestedRequirement
>(Req
));
1513 if (!TransReq
->isDependent() && !TransReq
->isSatisfied())
1514 // [expr.prim.req]p6
1515 // [...] The substitution and semantic constraint checking
1516 // proceeds in lexical order and stops when a condition that
1517 // determines the result of the requires-expression is
1518 // encountered. [..]
1519 SatisfactionDetermined
= true;
1522 Transformed
.push_back(TransReq
);
1527 TemplateParameterList
*TransformTemplateParameterList(
1528 TemplateParameterList
*OrigTPL
) {
1529 if (!OrigTPL
|| !OrigTPL
->size()) return OrigTPL
;
1531 DeclContext
*Owner
= OrigTPL
->getParam(0)->getDeclContext();
1532 TemplateDeclInstantiator
DeclInstantiator(getSema(),
1533 /* DeclContext *Owner */ Owner
, TemplateArgs
);
1534 DeclInstantiator
.setEvaluateConstraints(EvaluateConstraints
);
1535 return DeclInstantiator
.SubstTemplateParams(OrigTPL
);
1538 concepts::TypeRequirement
*
1539 TransformTypeRequirement(concepts::TypeRequirement
*Req
);
1540 concepts::ExprRequirement
*
1541 TransformExprRequirement(concepts::ExprRequirement
*Req
);
1542 concepts::NestedRequirement
*
1543 TransformNestedRequirement(concepts::NestedRequirement
*Req
);
1544 ExprResult
TransformRequiresTypeParams(
1545 SourceLocation KWLoc
, SourceLocation RBraceLoc
, const RequiresExpr
*RE
,
1546 RequiresExprBodyDecl
*Body
, ArrayRef
<ParmVarDecl
*> Params
,
1547 SmallVectorImpl
<QualType
> &PTypes
,
1548 SmallVectorImpl
<ParmVarDecl
*> &TransParams
,
1549 Sema::ExtParameterInfoBuilder
&PInfos
);
1553 transformNonTypeTemplateParmRef(Decl
*AssociatedDecl
,
1554 const NonTypeTemplateParmDecl
*parm
,
1555 SourceLocation loc
, TemplateArgument arg
,
1556 std::optional
<unsigned> PackIndex
);
1560 bool TemplateInstantiator::AlreadyTransformed(QualType T
) {
1564 if (T
->isInstantiationDependentType() || T
->isVariablyModifiedType())
1567 getSema().MarkDeclarationsReferencedInType(Loc
, T
);
1571 static TemplateArgument
1572 getPackSubstitutedTemplateArgument(Sema
&S
, TemplateArgument Arg
) {
1573 assert(S
.ArgumentPackSubstitutionIndex
>= 0);
1574 assert(S
.ArgumentPackSubstitutionIndex
< (int)Arg
.pack_size());
1575 Arg
= Arg
.pack_begin()[S
.ArgumentPackSubstitutionIndex
];
1576 if (Arg
.isPackExpansion())
1577 Arg
= Arg
.getPackExpansionPattern();
1581 Decl
*TemplateInstantiator::TransformDecl(SourceLocation Loc
, Decl
*D
) {
1585 if (TemplateTemplateParmDecl
*TTP
= dyn_cast
<TemplateTemplateParmDecl
>(D
)) {
1586 if (TTP
->getDepth() < TemplateArgs
.getNumLevels()) {
1587 // If the corresponding template argument is NULL or non-existent, it's
1588 // because we are performing instantiation from explicitly-specified
1589 // template arguments in a function template, but there were some
1590 // arguments left unspecified.
1591 if (!TemplateArgs
.hasTemplateArgument(TTP
->getDepth(),
1592 TTP
->getPosition()))
1595 TemplateArgument Arg
= TemplateArgs(TTP
->getDepth(), TTP
->getPosition());
1597 if (TTP
->isParameterPack()) {
1598 assert(Arg
.getKind() == TemplateArgument::Pack
&&
1599 "Missing argument pack");
1600 Arg
= getPackSubstitutedTemplateArgument(getSema(), Arg
);
1603 TemplateName Template
= Arg
.getAsTemplate().getNameToSubstitute();
1604 assert(!Template
.isNull() && Template
.getAsTemplateDecl() &&
1605 "Wrong kind of template template argument");
1606 return Template
.getAsTemplateDecl();
1609 // Fall through to find the instantiated declaration for this template
1610 // template parameter.
1613 return SemaRef
.FindInstantiatedDecl(Loc
, cast
<NamedDecl
>(D
), TemplateArgs
);
1616 Decl
*TemplateInstantiator::TransformDefinition(SourceLocation Loc
, Decl
*D
) {
1617 Decl
*Inst
= getSema().SubstDecl(D
, getSema().CurContext
, TemplateArgs
);
1621 getSema().CurrentInstantiationScope
->InstantiatedLocal(D
, Inst
);
1625 bool TemplateInstantiator::TransformExceptionSpec(
1626 SourceLocation Loc
, FunctionProtoType::ExceptionSpecInfo
&ESI
,
1627 SmallVectorImpl
<QualType
> &Exceptions
, bool &Changed
) {
1628 if (ESI
.Type
== EST_Uninstantiated
) {
1629 ESI
.NoexceptExpr
= cast
<FunctionProtoType
>(ESI
.SourceTemplate
->getType())
1630 ->getNoexceptExpr();
1631 ESI
.Type
= EST_DependentNoexcept
;
1634 return inherited::TransformExceptionSpec(Loc
, ESI
, Exceptions
, Changed
);
1638 TemplateInstantiator::TransformFirstQualifierInScope(NamedDecl
*D
,
1639 SourceLocation Loc
) {
1640 // If the first part of the nested-name-specifier was a template type
1641 // parameter, instantiate that type parameter down to a tag type.
1642 if (TemplateTypeParmDecl
*TTPD
= dyn_cast_or_null
<TemplateTypeParmDecl
>(D
)) {
1643 const TemplateTypeParmType
*TTP
1644 = cast
<TemplateTypeParmType
>(getSema().Context
.getTypeDeclType(TTPD
));
1646 if (TTP
->getDepth() < TemplateArgs
.getNumLevels()) {
1647 // FIXME: This needs testing w/ member access expressions.
1648 TemplateArgument Arg
= TemplateArgs(TTP
->getDepth(), TTP
->getIndex());
1650 if (TTP
->isParameterPack()) {
1651 assert(Arg
.getKind() == TemplateArgument::Pack
&&
1652 "Missing argument pack");
1654 if (getSema().ArgumentPackSubstitutionIndex
== -1)
1657 Arg
= getPackSubstitutedTemplateArgument(getSema(), Arg
);
1660 QualType T
= Arg
.getAsType();
1662 return cast_or_null
<NamedDecl
>(TransformDecl(Loc
, D
));
1664 if (const TagType
*Tag
= T
->getAs
<TagType
>())
1665 return Tag
->getDecl();
1667 // The resulting type is not a tag; complain.
1668 getSema().Diag(Loc
, diag::err_nested_name_spec_non_tag
) << T
;
1673 return cast_or_null
<NamedDecl
>(TransformDecl(Loc
, D
));
1677 TemplateInstantiator::RebuildExceptionDecl(VarDecl
*ExceptionDecl
,
1678 TypeSourceInfo
*Declarator
,
1679 SourceLocation StartLoc
,
1680 SourceLocation NameLoc
,
1681 IdentifierInfo
*Name
) {
1682 VarDecl
*Var
= inherited::RebuildExceptionDecl(ExceptionDecl
, Declarator
,
1683 StartLoc
, NameLoc
, Name
);
1685 getSema().CurrentInstantiationScope
->InstantiatedLocal(ExceptionDecl
, Var
);
1689 VarDecl
*TemplateInstantiator::RebuildObjCExceptionDecl(VarDecl
*ExceptionDecl
,
1690 TypeSourceInfo
*TSInfo
,
1692 VarDecl
*Var
= inherited::RebuildObjCExceptionDecl(ExceptionDecl
, TSInfo
, T
);
1694 getSema().CurrentInstantiationScope
->InstantiatedLocal(ExceptionDecl
, Var
);
1699 TemplateInstantiator::RebuildElaboratedType(SourceLocation KeywordLoc
,
1700 ElaboratedTypeKeyword Keyword
,
1701 NestedNameSpecifierLoc QualifierLoc
,
1703 if (const TagType
*TT
= T
->getAs
<TagType
>()) {
1704 TagDecl
* TD
= TT
->getDecl();
1706 SourceLocation TagLocation
= KeywordLoc
;
1708 IdentifierInfo
*Id
= TD
->getIdentifier();
1710 // TODO: should we even warn on struct/class mismatches for this? Seems
1711 // like it's likely to produce a lot of spurious errors.
1712 if (Id
&& Keyword
!= ElaboratedTypeKeyword::None
&&
1713 Keyword
!= ElaboratedTypeKeyword::Typename
) {
1714 TagTypeKind Kind
= TypeWithKeyword::getTagTypeKindForKeyword(Keyword
);
1715 if (!SemaRef
.isAcceptableTagRedeclaration(TD
, Kind
, /*isDefinition*/false,
1717 SemaRef
.Diag(TagLocation
, diag::err_use_with_wrong_tag
)
1719 << FixItHint::CreateReplacement(SourceRange(TagLocation
),
1721 SemaRef
.Diag(TD
->getLocation(), diag::note_previous_use
);
1726 return inherited::RebuildElaboratedType(KeywordLoc
, Keyword
, QualifierLoc
, T
);
1729 TemplateName
TemplateInstantiator::TransformTemplateName(
1730 CXXScopeSpec
&SS
, TemplateName Name
, SourceLocation NameLoc
,
1731 QualType ObjectType
, NamedDecl
*FirstQualifierInScope
,
1732 bool AllowInjectedClassName
) {
1733 if (TemplateTemplateParmDecl
*TTP
1734 = dyn_cast_or_null
<TemplateTemplateParmDecl
>(Name
.getAsTemplateDecl())) {
1735 if (TTP
->getDepth() < TemplateArgs
.getNumLevels()) {
1736 // If the corresponding template argument is NULL or non-existent, it's
1737 // because we are performing instantiation from explicitly-specified
1738 // template arguments in a function template, but there were some
1739 // arguments left unspecified.
1740 if (!TemplateArgs
.hasTemplateArgument(TTP
->getDepth(),
1741 TTP
->getPosition()))
1744 TemplateArgument Arg
= TemplateArgs(TTP
->getDepth(), TTP
->getPosition());
1746 if (TemplateArgs
.isRewrite()) {
1747 // We're rewriting the template parameter as a reference to another
1748 // template parameter.
1749 if (Arg
.getKind() == TemplateArgument::Pack
) {
1750 assert(Arg
.pack_size() == 1 && Arg
.pack_begin()->isPackExpansion() &&
1751 "unexpected pack arguments in template rewrite");
1752 Arg
= Arg
.pack_begin()->getPackExpansionPattern();
1754 assert(Arg
.getKind() == TemplateArgument::Template
&&
1755 "unexpected nontype template argument kind in template rewrite");
1756 return Arg
.getAsTemplate();
1759 auto [AssociatedDecl
, Final
] =
1760 TemplateArgs
.getAssociatedDecl(TTP
->getDepth());
1761 std::optional
<unsigned> PackIndex
;
1762 if (TTP
->isParameterPack()) {
1763 assert(Arg
.getKind() == TemplateArgument::Pack
&&
1764 "Missing argument pack");
1766 if (getSema().ArgumentPackSubstitutionIndex
== -1) {
1767 // We have the template argument pack to substitute, but we're not
1768 // actually expanding the enclosing pack expansion yet. So, just
1769 // keep the entire argument pack.
1770 return getSema().Context
.getSubstTemplateTemplateParmPack(
1771 Arg
, AssociatedDecl
, TTP
->getIndex(), Final
);
1774 PackIndex
= getPackIndex(Arg
);
1775 Arg
= getPackSubstitutedTemplateArgument(getSema(), Arg
);
1778 TemplateName Template
= Arg
.getAsTemplate().getNameToSubstitute();
1779 assert(!Template
.isNull() && "Null template template argument");
1780 assert(!Template
.getAsQualifiedTemplateName() &&
1781 "template decl to substitute is qualified?");
1785 return getSema().Context
.getSubstTemplateTemplateParm(
1786 Template
, AssociatedDecl
, TTP
->getIndex(), PackIndex
);
1790 if (SubstTemplateTemplateParmPackStorage
*SubstPack
1791 = Name
.getAsSubstTemplateTemplateParmPack()) {
1792 if (getSema().ArgumentPackSubstitutionIndex
== -1)
1795 TemplateArgument Pack
= SubstPack
->getArgumentPack();
1796 TemplateName Template
=
1797 getPackSubstitutedTemplateArgument(getSema(), Pack
).getAsTemplate();
1798 if (SubstPack
->getFinal())
1800 return getSema().Context
.getSubstTemplateTemplateParm(
1801 Template
.getNameToSubstitute(), SubstPack
->getAssociatedDecl(),
1802 SubstPack
->getIndex(), getPackIndex(Pack
));
1805 return inherited::TransformTemplateName(SS
, Name
, NameLoc
, ObjectType
,
1806 FirstQualifierInScope
,
1807 AllowInjectedClassName
);
1811 TemplateInstantiator::TransformPredefinedExpr(PredefinedExpr
*E
) {
1812 if (!E
->isTypeDependent())
1815 return getSema().BuildPredefinedExpr(E
->getLocation(), E
->getIdentKind());
1819 TemplateInstantiator::TransformTemplateParmRefExpr(DeclRefExpr
*E
,
1820 NonTypeTemplateParmDecl
*NTTP
) {
1821 // If the corresponding template argument is NULL or non-existent, it's
1822 // because we are performing instantiation from explicitly-specified
1823 // template arguments in a function template, but there were some
1824 // arguments left unspecified.
1825 if (!TemplateArgs
.hasTemplateArgument(NTTP
->getDepth(),
1826 NTTP
->getPosition()))
1829 TemplateArgument Arg
= TemplateArgs(NTTP
->getDepth(), NTTP
->getPosition());
1831 if (TemplateArgs
.isRewrite()) {
1832 // We're rewriting the template parameter as a reference to another
1833 // template parameter.
1834 if (Arg
.getKind() == TemplateArgument::Pack
) {
1835 assert(Arg
.pack_size() == 1 && Arg
.pack_begin()->isPackExpansion() &&
1836 "unexpected pack arguments in template rewrite");
1837 Arg
= Arg
.pack_begin()->getPackExpansionPattern();
1839 assert(Arg
.getKind() == TemplateArgument::Expression
&&
1840 "unexpected nontype template argument kind in template rewrite");
1841 // FIXME: This can lead to the same subexpression appearing multiple times
1842 // in a complete expression.
1843 return Arg
.getAsExpr();
1846 auto [AssociatedDecl
, _
] = TemplateArgs
.getAssociatedDecl(NTTP
->getDepth());
1847 std::optional
<unsigned> PackIndex
;
1848 if (NTTP
->isParameterPack()) {
1849 assert(Arg
.getKind() == TemplateArgument::Pack
&&
1850 "Missing argument pack");
1852 if (getSema().ArgumentPackSubstitutionIndex
== -1) {
1853 // We have an argument pack, but we can't select a particular argument
1854 // out of it yet. Therefore, we'll build an expression to hold on to that
1856 QualType TargetType
= SemaRef
.SubstType(NTTP
->getType(), TemplateArgs
,
1858 NTTP
->getDeclName());
1859 if (TargetType
.isNull())
1862 QualType ExprType
= TargetType
.getNonLValueExprType(SemaRef
.Context
);
1863 if (TargetType
->isRecordType())
1864 ExprType
.addConst();
1865 // FIXME: Pass in Final.
1866 return new (SemaRef
.Context
) SubstNonTypeTemplateParmPackExpr(
1867 ExprType
, TargetType
->isReferenceType() ? VK_LValue
: VK_PRValue
,
1868 E
->getLocation(), Arg
, AssociatedDecl
, NTTP
->getPosition());
1870 PackIndex
= getPackIndex(Arg
);
1871 Arg
= getPackSubstitutedTemplateArgument(getSema(), Arg
);
1873 // FIXME: Don't put subst node on Final replacement.
1874 return transformNonTypeTemplateParmRef(AssociatedDecl
, NTTP
, E
->getLocation(),
1878 const LoopHintAttr
*
1879 TemplateInstantiator::TransformLoopHintAttr(const LoopHintAttr
*LH
) {
1880 Expr
*TransformedExpr
= getDerived().TransformExpr(LH
->getValue()).get();
1882 if (TransformedExpr
== LH
->getValue())
1885 // Generate error if there is a problem with the value.
1886 if (getSema().CheckLoopHintExpr(TransformedExpr
, LH
->getLocation()))
1889 // Create new LoopHintValueAttr with integral expression in place of the
1890 // non-type template parameter.
1891 return LoopHintAttr::CreateImplicit(getSema().Context
, LH
->getOption(),
1892 LH
->getState(), TransformedExpr
, *LH
);
1894 const NoInlineAttr
*TemplateInstantiator::TransformStmtNoInlineAttr(
1895 const Stmt
*OrigS
, const Stmt
*InstS
, const NoInlineAttr
*A
) {
1896 if (!A
|| getSema().CheckNoInlineAttr(OrigS
, InstS
, *A
))
1901 const AlwaysInlineAttr
*TemplateInstantiator::TransformStmtAlwaysInlineAttr(
1902 const Stmt
*OrigS
, const Stmt
*InstS
, const AlwaysInlineAttr
*A
) {
1903 if (!A
|| getSema().CheckAlwaysInlineAttr(OrigS
, InstS
, *A
))
1909 ExprResult
TemplateInstantiator::transformNonTypeTemplateParmRef(
1910 Decl
*AssociatedDecl
, const NonTypeTemplateParmDecl
*parm
,
1911 SourceLocation loc
, TemplateArgument arg
,
1912 std::optional
<unsigned> PackIndex
) {
1915 // Determine the substituted parameter type. We can usually infer this from
1916 // the template argument, but not always.
1917 auto SubstParamType
= [&] {
1919 if (parm
->isExpandedParameterPack())
1920 T
= parm
->getExpansionType(SemaRef
.ArgumentPackSubstitutionIndex
);
1922 T
= parm
->getType();
1923 if (parm
->isParameterPack() && isa
<PackExpansionType
>(T
))
1924 T
= cast
<PackExpansionType
>(T
)->getPattern();
1925 return SemaRef
.SubstType(T
, TemplateArgs
, loc
, parm
->getDeclName());
1928 bool refParam
= false;
1930 // The template argument itself might be an expression, in which case we just
1931 // return that expression. This happens when substituting into an alias
1933 if (arg
.getKind() == TemplateArgument::Expression
) {
1934 Expr
*argExpr
= arg
.getAsExpr();
1936 if (argExpr
->isLValue()) {
1937 if (argExpr
->getType()->isRecordType()) {
1938 // Check whether the parameter was actually a reference.
1939 QualType paramType
= SubstParamType();
1940 if (paramType
.isNull())
1942 refParam
= paramType
->isReferenceType();
1947 } else if (arg
.getKind() == TemplateArgument::Declaration
||
1948 arg
.getKind() == TemplateArgument::NullPtr
) {
1950 if (arg
.getKind() == TemplateArgument::Declaration
) {
1951 VD
= arg
.getAsDecl();
1953 // Find the instantiation of the template argument. This is
1954 // required for nested templates.
1955 VD
= cast_or_null
<ValueDecl
>(
1956 getSema().FindInstantiatedDecl(loc
, VD
, TemplateArgs
));
1960 // Propagate NULL template argument.
1964 QualType paramType
= VD
? arg
.getParamTypeForDecl() : arg
.getNullPtrType();
1965 assert(!paramType
.isNull() && "type substitution failed for param type");
1966 assert(!paramType
->isDependentType() && "param type still dependent");
1967 result
= SemaRef
.BuildExpressionFromDeclTemplateArgument(arg
, paramType
, loc
);
1968 refParam
= paramType
->isReferenceType();
1970 result
= SemaRef
.BuildExpressionFromIntegralTemplateArgument(arg
, loc
);
1971 assert(result
.isInvalid() ||
1972 SemaRef
.Context
.hasSameType(result
.get()->getType(),
1973 arg
.getIntegralType()));
1976 if (result
.isInvalid())
1979 Expr
*resultExpr
= result
.get();
1980 // FIXME: Don't put subst node on final replacement.
1981 return new (SemaRef
.Context
) SubstNonTypeTemplateParmExpr(
1982 resultExpr
->getType(), resultExpr
->getValueKind(), loc
, resultExpr
,
1983 AssociatedDecl
, parm
->getIndex(), PackIndex
, refParam
);
1987 TemplateInstantiator::TransformSubstNonTypeTemplateParmPackExpr(
1988 SubstNonTypeTemplateParmPackExpr
*E
) {
1989 if (getSema().ArgumentPackSubstitutionIndex
== -1) {
1990 // We aren't expanding the parameter pack, so just return ourselves.
1994 TemplateArgument Pack
= E
->getArgumentPack();
1995 TemplateArgument Arg
= getPackSubstitutedTemplateArgument(getSema(), Pack
);
1996 // FIXME: Don't put subst node on final replacement.
1997 return transformNonTypeTemplateParmRef(
1998 E
->getAssociatedDecl(), E
->getParameterPack(),
1999 E
->getParameterPackLocation(), Arg
, getPackIndex(Pack
));
2003 TemplateInstantiator::TransformSubstNonTypeTemplateParmExpr(
2004 SubstNonTypeTemplateParmExpr
*E
) {
2005 ExprResult SubstReplacement
= E
->getReplacement();
2006 if (!isa
<ConstantExpr
>(SubstReplacement
.get()))
2007 SubstReplacement
= TransformExpr(E
->getReplacement());
2008 if (SubstReplacement
.isInvalid())
2010 QualType SubstType
= TransformType(E
->getParameterType(getSema().Context
));
2011 if (SubstType
.isNull())
2013 // The type may have been previously dependent and not now, which means we
2014 // might have to implicit cast the argument to the new type, for example:
2015 // template<auto T, decltype(T) U>
2016 // concept C = sizeof(U) == 4;
2017 // void foo() requires C<2, 'a'> { }
2018 // When normalizing foo(), we first form the normalized constraints of C:
2019 // AtomicExpr(sizeof(U) == 4,
2020 // U=SubstNonTypeTemplateParmExpr(Param=U,
2022 // Type=decltype(T)))
2023 // Then we substitute T = 2, U = 'a' into the parameter mapping, and need to
2025 // AtomicExpr(sizeof(U) == 4,
2026 // U=SubstNonTypeTemplateParmExpr(Param=U,
2029 // SubstNTTPE(Param=U, Expr='a',
2031 // Type=decltype(2)))
2032 // The call to CheckTemplateArgument here produces the ImpCast.
2033 TemplateArgument SugaredConverted
, CanonicalConverted
;
2035 .CheckTemplateArgument(E
->getParameter(), SubstType
,
2036 SubstReplacement
.get(), SugaredConverted
,
2037 CanonicalConverted
, Sema::CTAK_Specified
)
2040 return transformNonTypeTemplateParmRef(E
->getAssociatedDecl(),
2041 E
->getParameter(), E
->getExprLoc(),
2042 SugaredConverted
, E
->getPackIndex());
2045 ExprResult
TemplateInstantiator::RebuildVarDeclRefExpr(VarDecl
*PD
,
2046 SourceLocation Loc
) {
2047 DeclarationNameInfo
NameInfo(PD
->getDeclName(), Loc
);
2048 return getSema().BuildDeclarationNameExpr(CXXScopeSpec(), NameInfo
, PD
);
2052 TemplateInstantiator::TransformFunctionParmPackExpr(FunctionParmPackExpr
*E
) {
2053 if (getSema().ArgumentPackSubstitutionIndex
!= -1) {
2054 // We can expand this parameter pack now.
2055 VarDecl
*D
= E
->getExpansion(getSema().ArgumentPackSubstitutionIndex
);
2056 VarDecl
*VD
= cast_or_null
<VarDecl
>(TransformDecl(E
->getExprLoc(), D
));
2059 return RebuildVarDeclRefExpr(VD
, E
->getExprLoc());
2062 QualType T
= TransformType(E
->getType());
2066 // Transform each of the parameter expansions into the corresponding
2067 // parameters in the instantiation of the function decl.
2068 SmallVector
<VarDecl
*, 8> Vars
;
2069 Vars
.reserve(E
->getNumExpansions());
2070 for (FunctionParmPackExpr::iterator I
= E
->begin(), End
= E
->end();
2072 VarDecl
*D
= cast_or_null
<VarDecl
>(TransformDecl(E
->getExprLoc(), *I
));
2079 FunctionParmPackExpr::Create(getSema().Context
, T
, E
->getParameterPack(),
2080 E
->getParameterPackLocation(), Vars
);
2081 getSema().MarkFunctionParmPackReferenced(PackExpr
);
2086 TemplateInstantiator::TransformFunctionParmPackRefExpr(DeclRefExpr
*E
,
2088 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack
;
2089 llvm::PointerUnion
<Decl
*, DeclArgumentPack
*> *Found
2090 = getSema().CurrentInstantiationScope
->findInstantiationOf(PD
);
2091 assert(Found
&& "no instantiation for parameter pack");
2093 Decl
*TransformedDecl
;
2094 if (DeclArgumentPack
*Pack
= Found
->dyn_cast
<DeclArgumentPack
*>()) {
2095 // If this is a reference to a function parameter pack which we can
2096 // substitute but can't yet expand, build a FunctionParmPackExpr for it.
2097 if (getSema().ArgumentPackSubstitutionIndex
== -1) {
2098 QualType T
= TransformType(E
->getType());
2101 auto *PackExpr
= FunctionParmPackExpr::Create(getSema().Context
, T
, PD
,
2102 E
->getExprLoc(), *Pack
);
2103 getSema().MarkFunctionParmPackReferenced(PackExpr
);
2107 TransformedDecl
= (*Pack
)[getSema().ArgumentPackSubstitutionIndex
];
2109 TransformedDecl
= Found
->get
<Decl
*>();
2112 // We have either an unexpanded pack or a specific expansion.
2113 return RebuildVarDeclRefExpr(cast
<VarDecl
>(TransformedDecl
), E
->getExprLoc());
2117 TemplateInstantiator::TransformDeclRefExpr(DeclRefExpr
*E
) {
2118 NamedDecl
*D
= E
->getDecl();
2120 // Handle references to non-type template parameters and non-type template
2122 if (NonTypeTemplateParmDecl
*NTTP
= dyn_cast
<NonTypeTemplateParmDecl
>(D
)) {
2123 if (NTTP
->getDepth() < TemplateArgs
.getNumLevels())
2124 return TransformTemplateParmRefExpr(E
, NTTP
);
2126 // We have a non-type template parameter that isn't fully substituted;
2127 // FindInstantiatedDecl will find it in the local instantiation scope.
2130 // Handle references to function parameter packs.
2131 if (VarDecl
*PD
= dyn_cast
<VarDecl
>(D
))
2132 if (PD
->isParameterPack())
2133 return TransformFunctionParmPackRefExpr(E
, PD
);
2135 return inherited::TransformDeclRefExpr(E
);
2138 ExprResult
TemplateInstantiator::TransformCXXDefaultArgExpr(
2139 CXXDefaultArgExpr
*E
) {
2140 assert(!cast
<FunctionDecl
>(E
->getParam()->getDeclContext())->
2141 getDescribedFunctionTemplate() &&
2142 "Default arg expressions are never formed in dependent cases.");
2143 return SemaRef
.BuildCXXDefaultArgExpr(
2144 E
->getUsedLocation(), cast
<FunctionDecl
>(E
->getParam()->getDeclContext()),
2148 template<typename Fn
>
2149 QualType
TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder
&TLB
,
2150 FunctionProtoTypeLoc TL
,
2151 CXXRecordDecl
*ThisContext
,
2152 Qualifiers ThisTypeQuals
,
2153 Fn TransformExceptionSpec
) {
2154 // We need a local instantiation scope for this function prototype.
2155 LocalInstantiationScope
Scope(SemaRef
, /*CombineWithOuterScope=*/true);
2156 return inherited::TransformFunctionProtoType(
2157 TLB
, TL
, ThisContext
, ThisTypeQuals
, TransformExceptionSpec
);
2160 ParmVarDecl
*TemplateInstantiator::TransformFunctionTypeParam(
2161 ParmVarDecl
*OldParm
, int indexAdjustment
,
2162 std::optional
<unsigned> NumExpansions
, bool ExpectParameterPack
) {
2163 auto NewParm
= SemaRef
.SubstParmVarDecl(
2164 OldParm
, TemplateArgs
, indexAdjustment
, NumExpansions
,
2165 ExpectParameterPack
, EvaluateConstraints
);
2166 if (NewParm
&& SemaRef
.getLangOpts().OpenCL
)
2167 SemaRef
.deduceOpenCLAddressSpace(NewParm
);
2171 QualType
TemplateInstantiator::BuildSubstTemplateTypeParmType(
2172 TypeLocBuilder
&TLB
, bool SuppressObjCLifetime
, bool Final
,
2173 Decl
*AssociatedDecl
, unsigned Index
, std::optional
<unsigned> PackIndex
,
2174 TemplateArgument Arg
, SourceLocation NameLoc
) {
2175 QualType Replacement
= Arg
.getAsType();
2177 // If the template parameter had ObjC lifetime qualifiers,
2178 // then any such qualifiers on the replacement type are ignored.
2179 if (SuppressObjCLifetime
) {
2181 RQs
= Replacement
.getQualifiers();
2182 RQs
.removeObjCLifetime();
2184 SemaRef
.Context
.getQualifiedType(Replacement
.getUnqualifiedType(), RQs
);
2188 TLB
.pushTrivial(SemaRef
.Context
, Replacement
, NameLoc
);
2191 // TODO: only do this uniquing once, at the start of instantiation.
2192 QualType Result
= getSema().Context
.getSubstTemplateTypeParmType(
2193 Replacement
, AssociatedDecl
, Index
, PackIndex
);
2194 SubstTemplateTypeParmTypeLoc NewTL
=
2195 TLB
.push
<SubstTemplateTypeParmTypeLoc
>(Result
);
2196 NewTL
.setNameLoc(NameLoc
);
2201 TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder
&TLB
,
2202 TemplateTypeParmTypeLoc TL
,
2203 bool SuppressObjCLifetime
) {
2204 const TemplateTypeParmType
*T
= TL
.getTypePtr();
2205 if (T
->getDepth() < TemplateArgs
.getNumLevels()) {
2206 // Replace the template type parameter with its corresponding
2207 // template argument.
2209 // If the corresponding template argument is NULL or doesn't exist, it's
2210 // because we are performing instantiation from explicitly-specified
2211 // template arguments in a function template class, but there were some
2212 // arguments left unspecified.
2213 if (!TemplateArgs
.hasTemplateArgument(T
->getDepth(), T
->getIndex())) {
2214 TemplateTypeParmTypeLoc NewTL
2215 = TLB
.push
<TemplateTypeParmTypeLoc
>(TL
.getType());
2216 NewTL
.setNameLoc(TL
.getNameLoc());
2217 return TL
.getType();
2220 TemplateArgument Arg
= TemplateArgs(T
->getDepth(), T
->getIndex());
2222 if (TemplateArgs
.isRewrite()) {
2223 // We're rewriting the template parameter as a reference to another
2224 // template parameter.
2225 if (Arg
.getKind() == TemplateArgument::Pack
) {
2226 assert(Arg
.pack_size() == 1 && Arg
.pack_begin()->isPackExpansion() &&
2227 "unexpected pack arguments in template rewrite");
2228 Arg
= Arg
.pack_begin()->getPackExpansionPattern();
2230 assert(Arg
.getKind() == TemplateArgument::Type
&&
2231 "unexpected nontype template argument kind in template rewrite");
2232 QualType NewT
= Arg
.getAsType();
2233 assert(isa
<TemplateTypeParmType
>(NewT
) &&
2234 "type parm not rewritten to type parm");
2235 auto NewTL
= TLB
.push
<TemplateTypeParmTypeLoc
>(NewT
);
2236 NewTL
.setNameLoc(TL
.getNameLoc());
2240 auto [AssociatedDecl
, Final
] =
2241 TemplateArgs
.getAssociatedDecl(T
->getDepth());
2242 std::optional
<unsigned> PackIndex
;
2243 if (T
->isParameterPack()) {
2244 assert(Arg
.getKind() == TemplateArgument::Pack
&&
2245 "Missing argument pack");
2247 if (getSema().ArgumentPackSubstitutionIndex
== -1) {
2248 // We have the template argument pack, but we're not expanding the
2249 // enclosing pack expansion yet. Just save the template argument
2250 // pack for later substitution.
2251 QualType Result
= getSema().Context
.getSubstTemplateTypeParmPackType(
2252 AssociatedDecl
, T
->getIndex(), Final
, Arg
);
2253 SubstTemplateTypeParmPackTypeLoc NewTL
2254 = TLB
.push
<SubstTemplateTypeParmPackTypeLoc
>(Result
);
2255 NewTL
.setNameLoc(TL
.getNameLoc());
2259 // PackIndex starts from last element.
2260 PackIndex
= getPackIndex(Arg
);
2261 Arg
= getPackSubstitutedTemplateArgument(getSema(), Arg
);
2264 assert(Arg
.getKind() == TemplateArgument::Type
&&
2265 "Template argument kind mismatch");
2267 return BuildSubstTemplateTypeParmType(TLB
, SuppressObjCLifetime
, Final
,
2268 AssociatedDecl
, T
->getIndex(),
2269 PackIndex
, Arg
, TL
.getNameLoc());
2272 // The template type parameter comes from an inner template (e.g.,
2273 // the template parameter list of a member template inside the
2274 // template we are instantiating). Create a new template type
2275 // parameter with the template "level" reduced by one.
2276 TemplateTypeParmDecl
*NewTTPDecl
= nullptr;
2277 if (TemplateTypeParmDecl
*OldTTPDecl
= T
->getDecl())
2278 NewTTPDecl
= cast_or_null
<TemplateTypeParmDecl
>(
2279 TransformDecl(TL
.getNameLoc(), OldTTPDecl
));
2280 QualType Result
= getSema().Context
.getTemplateTypeParmType(
2281 T
->getDepth() - TemplateArgs
.getNumSubstitutedLevels(), T
->getIndex(),
2282 T
->isParameterPack(), NewTTPDecl
);
2283 TemplateTypeParmTypeLoc NewTL
= TLB
.push
<TemplateTypeParmTypeLoc
>(Result
);
2284 NewTL
.setNameLoc(TL
.getNameLoc());
2288 QualType
TemplateInstantiator::TransformSubstTemplateTypeParmPackType(
2289 TypeLocBuilder
&TLB
, SubstTemplateTypeParmPackTypeLoc TL
,
2290 bool SuppressObjCLifetime
) {
2291 const SubstTemplateTypeParmPackType
*T
= TL
.getTypePtr();
2293 Decl
*NewReplaced
= TransformDecl(TL
.getNameLoc(), T
->getAssociatedDecl());
2295 if (getSema().ArgumentPackSubstitutionIndex
== -1) {
2296 // We aren't expanding the parameter pack, so just return ourselves.
2297 QualType Result
= TL
.getType();
2298 if (NewReplaced
!= T
->getAssociatedDecl())
2299 Result
= getSema().Context
.getSubstTemplateTypeParmPackType(
2300 NewReplaced
, T
->getIndex(), T
->getFinal(), T
->getArgumentPack());
2301 SubstTemplateTypeParmPackTypeLoc NewTL
=
2302 TLB
.push
<SubstTemplateTypeParmPackTypeLoc
>(Result
);
2303 NewTL
.setNameLoc(TL
.getNameLoc());
2307 TemplateArgument Pack
= T
->getArgumentPack();
2308 TemplateArgument Arg
= getPackSubstitutedTemplateArgument(getSema(), Pack
);
2309 return BuildSubstTemplateTypeParmType(
2310 TLB
, SuppressObjCLifetime
, T
->getFinal(), NewReplaced
, T
->getIndex(),
2311 getPackIndex(Pack
), Arg
, TL
.getNameLoc());
2314 static concepts::Requirement::SubstitutionDiagnostic
*
2315 createSubstDiag(Sema
&S
, TemplateDeductionInfo
&Info
,
2316 concepts::EntityPrinter Printer
) {
2317 SmallString
<128> Message
;
2318 SourceLocation ErrorLoc
;
2319 if (Info
.hasSFINAEDiagnostic()) {
2320 PartialDiagnosticAt
PDA(SourceLocation(),
2321 PartialDiagnostic::NullDiagnostic
{});
2322 Info
.takeSFINAEDiagnostic(PDA
);
2323 PDA
.second
.EmitToString(S
.getDiagnostics(), Message
);
2324 ErrorLoc
= PDA
.first
;
2326 ErrorLoc
= Info
.getLocation();
2328 char *MessageBuf
= new (S
.Context
) char[Message
.size()];
2329 std::copy(Message
.begin(), Message
.end(), MessageBuf
);
2330 SmallString
<128> Entity
;
2331 llvm::raw_svector_ostream
OS(Entity
);
2333 char *EntityBuf
= new (S
.Context
) char[Entity
.size()];
2334 std::copy(Entity
.begin(), Entity
.end(), EntityBuf
);
2335 return new (S
.Context
) concepts::Requirement::SubstitutionDiagnostic
{
2336 StringRef(EntityBuf
, Entity
.size()), ErrorLoc
,
2337 StringRef(MessageBuf
, Message
.size())};
2340 concepts::Requirement::SubstitutionDiagnostic
*
2341 concepts::createSubstDiagAt(Sema
&S
, SourceLocation Location
,
2342 EntityPrinter Printer
) {
2343 SmallString
<128> Entity
;
2344 llvm::raw_svector_ostream
OS(Entity
);
2346 char *EntityBuf
= new (S
.Context
) char[Entity
.size()];
2347 llvm::copy(Entity
, EntityBuf
);
2348 return new (S
.Context
) concepts::Requirement::SubstitutionDiagnostic
{
2349 /*SubstitutedEntity=*/StringRef(EntityBuf
, Entity
.size()),
2350 /*DiagLoc=*/Location
, /*DiagMessage=*/StringRef()};
2353 ExprResult
TemplateInstantiator::TransformRequiresTypeParams(
2354 SourceLocation KWLoc
, SourceLocation RBraceLoc
, const RequiresExpr
*RE
,
2355 RequiresExprBodyDecl
*Body
, ArrayRef
<ParmVarDecl
*> Params
,
2356 SmallVectorImpl
<QualType
> &PTypes
,
2357 SmallVectorImpl
<ParmVarDecl
*> &TransParams
,
2358 Sema::ExtParameterInfoBuilder
&PInfos
) {
2360 TemplateDeductionInfo
Info(KWLoc
);
2361 Sema::InstantiatingTemplate
TypeInst(SemaRef
, KWLoc
,
2363 SourceRange
{KWLoc
, RBraceLoc
});
2364 Sema::SFINAETrap
Trap(SemaRef
);
2367 if (getDerived().TransformFunctionTypeParams(
2368 KWLoc
, Params
, /*ParamTypes=*/nullptr, /*ParamInfos=*/nullptr, PTypes
,
2369 &TransParams
, PInfos
, &ErrorIdx
) ||
2370 Trap
.hasErrorOccurred()) {
2371 SmallVector
<concepts::Requirement
*, 4> TransReqs
;
2372 ParmVarDecl
*FailedDecl
= Params
[ErrorIdx
];
2373 // Add a 'failed' Requirement to contain the error that caused the failure
2375 TransReqs
.push_back(RebuildTypeRequirement(createSubstDiag(
2376 SemaRef
, Info
, [&](llvm::raw_ostream
&OS
) { OS
<< *FailedDecl
; })));
2377 return getDerived().RebuildRequiresExpr(KWLoc
, Body
, RE
->getLParenLoc(),
2378 TransParams
, RE
->getRParenLoc(),
2379 TransReqs
, RBraceLoc
);
2382 return ExprResult
{};
2385 concepts::TypeRequirement
*
2386 TemplateInstantiator::TransformTypeRequirement(concepts::TypeRequirement
*Req
) {
2387 if (!Req
->isDependent() && !AlwaysRebuild())
2389 if (Req
->isSubstitutionFailure()) {
2390 if (AlwaysRebuild())
2391 return RebuildTypeRequirement(
2392 Req
->getSubstitutionDiagnostic());
2396 Sema::SFINAETrap
Trap(SemaRef
);
2397 TemplateDeductionInfo
Info(Req
->getType()->getTypeLoc().getBeginLoc());
2398 Sema::InstantiatingTemplate
TypeInst(SemaRef
,
2399 Req
->getType()->getTypeLoc().getBeginLoc(), Req
, Info
,
2400 Req
->getType()->getTypeLoc().getSourceRange());
2401 if (TypeInst
.isInvalid())
2403 TypeSourceInfo
*TransType
= TransformType(Req
->getType());
2404 if (!TransType
|| Trap
.hasErrorOccurred())
2405 return RebuildTypeRequirement(createSubstDiag(SemaRef
, Info
,
2406 [&] (llvm::raw_ostream
& OS
) {
2407 Req
->getType()->getType().print(OS
, SemaRef
.getPrintingPolicy());
2409 return RebuildTypeRequirement(TransType
);
2412 concepts::ExprRequirement
*
2413 TemplateInstantiator::TransformExprRequirement(concepts::ExprRequirement
*Req
) {
2414 if (!Req
->isDependent() && !AlwaysRebuild())
2417 Sema::SFINAETrap
Trap(SemaRef
);
2419 llvm::PointerUnion
<Expr
*, concepts::Requirement::SubstitutionDiagnostic
*>
2421 if (Req
->isExprSubstitutionFailure())
2422 TransExpr
= Req
->getExprSubstitutionDiagnostic();
2424 Expr
*E
= Req
->getExpr();
2425 TemplateDeductionInfo
Info(E
->getBeginLoc());
2426 Sema::InstantiatingTemplate
ExprInst(SemaRef
, E
->getBeginLoc(), Req
, Info
,
2427 E
->getSourceRange());
2428 if (ExprInst
.isInvalid())
2430 ExprResult TransExprRes
= TransformExpr(E
);
2431 if (!TransExprRes
.isInvalid() && !Trap
.hasErrorOccurred() &&
2432 TransExprRes
.get()->hasPlaceholderType())
2433 TransExprRes
= SemaRef
.CheckPlaceholderExpr(TransExprRes
.get());
2434 if (TransExprRes
.isInvalid() || Trap
.hasErrorOccurred())
2435 TransExpr
= createSubstDiag(SemaRef
, Info
, [&](llvm::raw_ostream
&OS
) {
2436 E
->printPretty(OS
, nullptr, SemaRef
.getPrintingPolicy());
2439 TransExpr
= TransExprRes
.get();
2442 std::optional
<concepts::ExprRequirement::ReturnTypeRequirement
> TransRetReq
;
2443 const auto &RetReq
= Req
->getReturnTypeRequirement();
2444 if (RetReq
.isEmpty())
2445 TransRetReq
.emplace();
2446 else if (RetReq
.isSubstitutionFailure())
2447 TransRetReq
.emplace(RetReq
.getSubstitutionDiagnostic());
2448 else if (RetReq
.isTypeConstraint()) {
2449 TemplateParameterList
*OrigTPL
=
2450 RetReq
.getTypeConstraintTemplateParameterList();
2451 TemplateDeductionInfo
Info(OrigTPL
->getTemplateLoc());
2452 Sema::InstantiatingTemplate
TPLInst(SemaRef
, OrigTPL
->getTemplateLoc(),
2453 Req
, Info
, OrigTPL
->getSourceRange());
2454 if (TPLInst
.isInvalid())
2456 TemplateParameterList
*TPL
= TransformTemplateParameterList(OrigTPL
);
2458 TransRetReq
.emplace(createSubstDiag(SemaRef
, Info
,
2459 [&] (llvm::raw_ostream
& OS
) {
2460 RetReq
.getTypeConstraint()->getImmediatelyDeclaredConstraint()
2461 ->printPretty(OS
, nullptr, SemaRef
.getPrintingPolicy());
2465 TransRetReq
.emplace(TPL
);
2468 assert(TransRetReq
&& "All code paths leading here must set TransRetReq");
2469 if (Expr
*E
= TransExpr
.dyn_cast
<Expr
*>())
2470 return RebuildExprRequirement(E
, Req
->isSimple(), Req
->getNoexceptLoc(),
2471 std::move(*TransRetReq
));
2472 return RebuildExprRequirement(
2473 TransExpr
.get
<concepts::Requirement::SubstitutionDiagnostic
*>(),
2474 Req
->isSimple(), Req
->getNoexceptLoc(), std::move(*TransRetReq
));
2477 concepts::NestedRequirement
*
2478 TemplateInstantiator::TransformNestedRequirement(
2479 concepts::NestedRequirement
*Req
) {
2480 if (!Req
->isDependent() && !AlwaysRebuild())
2482 if (Req
->hasInvalidConstraint()) {
2483 if (AlwaysRebuild())
2484 return RebuildNestedRequirement(Req
->getInvalidConstraintEntity(),
2485 Req
->getConstraintSatisfaction());
2488 Sema::InstantiatingTemplate
ReqInst(SemaRef
,
2489 Req
->getConstraintExpr()->getBeginLoc(), Req
,
2490 Sema::InstantiatingTemplate::ConstraintsCheck
{},
2491 Req
->getConstraintExpr()->getSourceRange());
2493 ExprResult TransConstraint
;
2494 ConstraintSatisfaction Satisfaction
;
2495 TemplateDeductionInfo
Info(Req
->getConstraintExpr()->getBeginLoc());
2497 EnterExpressionEvaluationContext
ContextRAII(
2498 SemaRef
, Sema::ExpressionEvaluationContext::ConstantEvaluated
);
2499 Sema::SFINAETrap
Trap(SemaRef
);
2500 Sema::InstantiatingTemplate
ConstrInst(SemaRef
,
2501 Req
->getConstraintExpr()->getBeginLoc(), Req
, Info
,
2502 Req
->getConstraintExpr()->getSourceRange());
2503 if (ConstrInst
.isInvalid())
2505 llvm::SmallVector
<Expr
*> Result
;
2506 if (!SemaRef
.CheckConstraintSatisfaction(
2507 nullptr, {Req
->getConstraintExpr()}, Result
, TemplateArgs
,
2508 Req
->getConstraintExpr()->getSourceRange(), Satisfaction
) &&
2510 TransConstraint
= Result
[0];
2511 assert(!Trap
.hasErrorOccurred() && "Substitution failures must be handled "
2512 "by CheckConstraintSatisfaction.");
2514 if (TransConstraint
.isUsable() &&
2515 TransConstraint
.get()->isInstantiationDependent())
2516 return new (SemaRef
.Context
)
2517 concepts::NestedRequirement(TransConstraint
.get());
2518 if (TransConstraint
.isInvalid() || !TransConstraint
.get() ||
2519 Satisfaction
.HasSubstitutionFailure()) {
2520 SmallString
<128> Entity
;
2521 llvm::raw_svector_ostream
OS(Entity
);
2522 Req
->getConstraintExpr()->printPretty(OS
, nullptr,
2523 SemaRef
.getPrintingPolicy());
2524 char *EntityBuf
= new (SemaRef
.Context
) char[Entity
.size()];
2525 std::copy(Entity
.begin(), Entity
.end(), EntityBuf
);
2526 return new (SemaRef
.Context
) concepts::NestedRequirement(
2527 SemaRef
.Context
, StringRef(EntityBuf
, Entity
.size()), Satisfaction
);
2529 return new (SemaRef
.Context
) concepts::NestedRequirement(
2530 SemaRef
.Context
, TransConstraint
.get(), Satisfaction
);
2534 /// Perform substitution on the type T with a given set of template
2537 /// This routine substitutes the given template arguments into the
2538 /// type T and produces the instantiated type.
2540 /// \param T the type into which the template arguments will be
2541 /// substituted. If this type is not dependent, it will be returned
2544 /// \param Args the template arguments that will be
2545 /// substituted for the top-level template parameters within T.
2547 /// \param Loc the location in the source code where this substitution
2548 /// is being performed. It will typically be the location of the
2549 /// declarator (if we're instantiating the type of some declaration)
2550 /// or the location of the type in the source code (if, e.g., we're
2551 /// instantiating the type of a cast expression).
2553 /// \param Entity the name of the entity associated with a declaration
2554 /// being instantiated (if any). May be empty to indicate that there
2555 /// is no such entity (if, e.g., this is a type that occurs as part of
2556 /// a cast expression) or that the entity has no name (e.g., an
2557 /// unnamed function parameter).
2559 /// \param AllowDeducedTST Whether a DeducedTemplateSpecializationType is
2560 /// acceptable as the top level type of the result.
2562 /// \returns If the instantiation succeeds, the instantiated
2563 /// type. Otherwise, produces diagnostics and returns a NULL type.
2564 TypeSourceInfo
*Sema::SubstType(TypeSourceInfo
*T
,
2565 const MultiLevelTemplateArgumentList
&Args
,
2567 DeclarationName Entity
,
2568 bool AllowDeducedTST
) {
2569 assert(!CodeSynthesisContexts
.empty() &&
2570 "Cannot perform an instantiation without some context on the "
2571 "instantiation stack");
2573 if (!T
->getType()->isInstantiationDependentType() &&
2574 !T
->getType()->isVariablyModifiedType())
2577 TemplateInstantiator
Instantiator(*this, Args
, Loc
, Entity
);
2578 return AllowDeducedTST
? Instantiator
.TransformTypeWithDeducedTST(T
)
2579 : Instantiator
.TransformType(T
);
2582 TypeSourceInfo
*Sema::SubstType(TypeLoc TL
,
2583 const MultiLevelTemplateArgumentList
&Args
,
2585 DeclarationName Entity
) {
2586 assert(!CodeSynthesisContexts
.empty() &&
2587 "Cannot perform an instantiation without some context on the "
2588 "instantiation stack");
2590 if (TL
.getType().isNull())
2593 if (!TL
.getType()->isInstantiationDependentType() &&
2594 !TL
.getType()->isVariablyModifiedType()) {
2595 // FIXME: Make a copy of the TypeLoc data here, so that we can
2596 // return a new TypeSourceInfo. Inefficient!
2598 TLB
.pushFullCopy(TL
);
2599 return TLB
.getTypeSourceInfo(Context
, TL
.getType());
2602 TemplateInstantiator
Instantiator(*this, Args
, Loc
, Entity
);
2604 TLB
.reserve(TL
.getFullDataSize());
2605 QualType Result
= Instantiator
.TransformType(TLB
, TL
);
2606 if (Result
.isNull())
2609 return TLB
.getTypeSourceInfo(Context
, Result
);
2612 /// Deprecated form of the above.
2613 QualType
Sema::SubstType(QualType T
,
2614 const MultiLevelTemplateArgumentList
&TemplateArgs
,
2615 SourceLocation Loc
, DeclarationName Entity
) {
2616 assert(!CodeSynthesisContexts
.empty() &&
2617 "Cannot perform an instantiation without some context on the "
2618 "instantiation stack");
2620 // If T is not a dependent type or a variably-modified type, there
2621 // is nothing to do.
2622 if (!T
->isInstantiationDependentType() && !T
->isVariablyModifiedType())
2625 TemplateInstantiator
Instantiator(*this, TemplateArgs
, Loc
, Entity
);
2626 return Instantiator
.TransformType(T
);
2629 static bool NeedsInstantiationAsFunctionType(TypeSourceInfo
*T
) {
2630 if (T
->getType()->isInstantiationDependentType() ||
2631 T
->getType()->isVariablyModifiedType())
2634 TypeLoc TL
= T
->getTypeLoc().IgnoreParens();
2635 if (!TL
.getAs
<FunctionProtoTypeLoc
>())
2638 FunctionProtoTypeLoc FP
= TL
.castAs
<FunctionProtoTypeLoc
>();
2639 for (ParmVarDecl
*P
: FP
.getParams()) {
2640 // This must be synthesized from a typedef.
2643 // If there are any parameters, a new TypeSourceInfo that refers to the
2644 // instantiated parameters must be built.
2651 /// A form of SubstType intended specifically for instantiating the
2652 /// type of a FunctionDecl. Its purpose is solely to force the
2653 /// instantiation of default-argument expressions and to avoid
2654 /// instantiating an exception-specification.
2655 TypeSourceInfo
*Sema::SubstFunctionDeclType(TypeSourceInfo
*T
,
2656 const MultiLevelTemplateArgumentList
&Args
,
2658 DeclarationName Entity
,
2659 CXXRecordDecl
*ThisContext
,
2660 Qualifiers ThisTypeQuals
,
2661 bool EvaluateConstraints
) {
2662 assert(!CodeSynthesisContexts
.empty() &&
2663 "Cannot perform an instantiation without some context on the "
2664 "instantiation stack");
2666 if (!NeedsInstantiationAsFunctionType(T
))
2669 TemplateInstantiator
Instantiator(*this, Args
, Loc
, Entity
);
2670 Instantiator
.setEvaluateConstraints(EvaluateConstraints
);
2674 TypeLoc TL
= T
->getTypeLoc();
2675 TLB
.reserve(TL
.getFullDataSize());
2679 if (FunctionProtoTypeLoc Proto
=
2680 TL
.IgnoreParens().getAs
<FunctionProtoTypeLoc
>()) {
2681 // Instantiate the type, other than its exception specification. The
2682 // exception specification is instantiated in InitFunctionInstantiation
2683 // once we've built the FunctionDecl.
2684 // FIXME: Set the exception specification to EST_Uninstantiated here,
2685 // instead of rebuilding the function type again later.
2686 Result
= Instantiator
.TransformFunctionProtoType(
2687 TLB
, Proto
, ThisContext
, ThisTypeQuals
,
2688 [](FunctionProtoType::ExceptionSpecInfo
&ESI
,
2689 bool &Changed
) { return false; });
2691 Result
= Instantiator
.TransformType(TLB
, TL
);
2693 // When there are errors resolving types, clang may use IntTy as a fallback,
2694 // breaking our assumption that function declarations have function types.
2695 if (Result
.isNull() || !Result
->isFunctionType())
2698 return TLB
.getTypeSourceInfo(Context
, Result
);
2701 bool Sema::SubstExceptionSpec(SourceLocation Loc
,
2702 FunctionProtoType::ExceptionSpecInfo
&ESI
,
2703 SmallVectorImpl
<QualType
> &ExceptionStorage
,
2704 const MultiLevelTemplateArgumentList
&Args
) {
2705 bool Changed
= false;
2706 TemplateInstantiator
Instantiator(*this, Args
, Loc
, DeclarationName());
2707 return Instantiator
.TransformExceptionSpec(Loc
, ESI
, ExceptionStorage
,
2711 void Sema::SubstExceptionSpec(FunctionDecl
*New
, const FunctionProtoType
*Proto
,
2712 const MultiLevelTemplateArgumentList
&Args
) {
2713 FunctionProtoType::ExceptionSpecInfo ESI
=
2714 Proto
->getExtProtoInfo().ExceptionSpec
;
2716 SmallVector
<QualType
, 4> ExceptionStorage
;
2717 if (SubstExceptionSpec(New
->getTypeSourceInfo()->getTypeLoc().getEndLoc(),
2718 ESI
, ExceptionStorage
, Args
))
2719 // On error, recover by dropping the exception specification.
2720 ESI
.Type
= EST_None
;
2722 UpdateExceptionSpec(New
, ESI
);
2727 struct GetContainedInventedTypeParmVisitor
:
2728 public TypeVisitor
<GetContainedInventedTypeParmVisitor
,
2729 TemplateTypeParmDecl
*> {
2730 using TypeVisitor
<GetContainedInventedTypeParmVisitor
,
2731 TemplateTypeParmDecl
*>::Visit
;
2733 TemplateTypeParmDecl
*Visit(QualType T
) {
2736 return Visit(T
.getTypePtr());
2738 // The deduced type itself.
2739 TemplateTypeParmDecl
*VisitTemplateTypeParmType(
2740 const TemplateTypeParmType
*T
) {
2741 if (!T
->getDecl() || !T
->getDecl()->isImplicit())
2743 return T
->getDecl();
2746 // Only these types can contain 'auto' types, and subsequently be replaced
2747 // by references to invented parameters.
2749 TemplateTypeParmDecl
*VisitElaboratedType(const ElaboratedType
*T
) {
2750 return Visit(T
->getNamedType());
2753 TemplateTypeParmDecl
*VisitPointerType(const PointerType
*T
) {
2754 return Visit(T
->getPointeeType());
2757 TemplateTypeParmDecl
*VisitBlockPointerType(const BlockPointerType
*T
) {
2758 return Visit(T
->getPointeeType());
2761 TemplateTypeParmDecl
*VisitReferenceType(const ReferenceType
*T
) {
2762 return Visit(T
->getPointeeTypeAsWritten());
2765 TemplateTypeParmDecl
*VisitMemberPointerType(const MemberPointerType
*T
) {
2766 return Visit(T
->getPointeeType());
2769 TemplateTypeParmDecl
*VisitArrayType(const ArrayType
*T
) {
2770 return Visit(T
->getElementType());
2773 TemplateTypeParmDecl
*VisitDependentSizedExtVectorType(
2774 const DependentSizedExtVectorType
*T
) {
2775 return Visit(T
->getElementType());
2778 TemplateTypeParmDecl
*VisitVectorType(const VectorType
*T
) {
2779 return Visit(T
->getElementType());
2782 TemplateTypeParmDecl
*VisitFunctionProtoType(const FunctionProtoType
*T
) {
2783 return VisitFunctionType(T
);
2786 TemplateTypeParmDecl
*VisitFunctionType(const FunctionType
*T
) {
2787 return Visit(T
->getReturnType());
2790 TemplateTypeParmDecl
*VisitParenType(const ParenType
*T
) {
2791 return Visit(T
->getInnerType());
2794 TemplateTypeParmDecl
*VisitAttributedType(const AttributedType
*T
) {
2795 return Visit(T
->getModifiedType());
2798 TemplateTypeParmDecl
*VisitMacroQualifiedType(const MacroQualifiedType
*T
) {
2799 return Visit(T
->getUnderlyingType());
2802 TemplateTypeParmDecl
*VisitAdjustedType(const AdjustedType
*T
) {
2803 return Visit(T
->getOriginalType());
2806 TemplateTypeParmDecl
*VisitPackExpansionType(const PackExpansionType
*T
) {
2807 return Visit(T
->getPattern());
2813 bool Sema::SubstTypeConstraint(
2814 TemplateTypeParmDecl
*Inst
, const TypeConstraint
*TC
,
2815 const MultiLevelTemplateArgumentList
&TemplateArgs
,
2816 bool EvaluateConstraints
) {
2817 const ASTTemplateArgumentListInfo
*TemplArgInfo
=
2818 TC
->getTemplateArgsAsWritten();
2820 if (!EvaluateConstraints
) {
2821 Inst
->setTypeConstraint(TC
->getConceptReference(),
2822 TC
->getImmediatelyDeclaredConstraint());
2826 TemplateArgumentListInfo InstArgs
;
2829 InstArgs
.setLAngleLoc(TemplArgInfo
->LAngleLoc
);
2830 InstArgs
.setRAngleLoc(TemplArgInfo
->RAngleLoc
);
2831 if (SubstTemplateArguments(TemplArgInfo
->arguments(), TemplateArgs
,
2835 return AttachTypeConstraint(
2836 TC
->getNestedNameSpecifierLoc(), TC
->getConceptNameInfo(),
2837 TC
->getNamedConcept(), &InstArgs
, Inst
,
2838 Inst
->isParameterPack()
2839 ? cast
<CXXFoldExpr
>(TC
->getImmediatelyDeclaredConstraint())
2841 : SourceLocation());
2844 ParmVarDecl
*Sema::SubstParmVarDecl(
2845 ParmVarDecl
*OldParm
, const MultiLevelTemplateArgumentList
&TemplateArgs
,
2846 int indexAdjustment
, std::optional
<unsigned> NumExpansions
,
2847 bool ExpectParameterPack
, bool EvaluateConstraint
) {
2848 TypeSourceInfo
*OldDI
= OldParm
->getTypeSourceInfo();
2849 TypeSourceInfo
*NewDI
= nullptr;
2851 TypeLoc OldTL
= OldDI
->getTypeLoc();
2852 if (PackExpansionTypeLoc ExpansionTL
= OldTL
.getAs
<PackExpansionTypeLoc
>()) {
2854 // We have a function parameter pack. Substitute into the pattern of the
2856 NewDI
= SubstType(ExpansionTL
.getPatternLoc(), TemplateArgs
,
2857 OldParm
->getLocation(), OldParm
->getDeclName());
2861 if (NewDI
->getType()->containsUnexpandedParameterPack()) {
2862 // We still have unexpanded parameter packs, which means that
2863 // our function parameter is still a function parameter pack.
2864 // Therefore, make its type a pack expansion type.
2865 NewDI
= CheckPackExpansion(NewDI
, ExpansionTL
.getEllipsisLoc(),
2867 } else if (ExpectParameterPack
) {
2868 // We expected to get a parameter pack but didn't (because the type
2869 // itself is not a pack expansion type), so complain. This can occur when
2870 // the substitution goes through an alias template that "loses" the
2872 Diag(OldParm
->getLocation(),
2873 diag::err_function_parameter_pack_without_parameter_packs
)
2874 << NewDI
->getType();
2878 NewDI
= SubstType(OldDI
, TemplateArgs
, OldParm
->getLocation(),
2879 OldParm
->getDeclName());
2885 if (NewDI
->getType()->isVoidType()) {
2886 Diag(OldParm
->getLocation(), diag::err_param_with_void_type
);
2890 // In abbreviated templates, TemplateTypeParmDecls with possible
2891 // TypeConstraints are created when the parameter list is originally parsed.
2892 // The TypeConstraints can therefore reference other functions parameters in
2893 // the abbreviated function template, which is why we must instantiate them
2894 // here, when the instantiated versions of those referenced parameters are in
2896 if (TemplateTypeParmDecl
*TTP
=
2897 GetContainedInventedTypeParmVisitor().Visit(OldDI
->getType())) {
2898 if (const TypeConstraint
*TC
= TTP
->getTypeConstraint()) {
2899 auto *Inst
= cast_or_null
<TemplateTypeParmDecl
>(
2900 FindInstantiatedDecl(TTP
->getLocation(), TTP
, TemplateArgs
));
2901 // We will first get here when instantiating the abbreviated function
2902 // template's described function, but we might also get here later.
2903 // Make sure we do not instantiate the TypeConstraint more than once.
2904 if (Inst
&& !Inst
->getTypeConstraint()) {
2905 if (SubstTypeConstraint(Inst
, TC
, TemplateArgs
, EvaluateConstraint
))
2911 ParmVarDecl
*NewParm
= CheckParameter(Context
.getTranslationUnitDecl(),
2912 OldParm
->getInnerLocStart(),
2913 OldParm
->getLocation(),
2914 OldParm
->getIdentifier(),
2915 NewDI
->getType(), NewDI
,
2916 OldParm
->getStorageClass());
2920 // Mark the (new) default argument as uninstantiated (if any).
2921 if (OldParm
->hasUninstantiatedDefaultArg()) {
2922 Expr
*Arg
= OldParm
->getUninstantiatedDefaultArg();
2923 NewParm
->setUninstantiatedDefaultArg(Arg
);
2924 } else if (OldParm
->hasUnparsedDefaultArg()) {
2925 NewParm
->setUnparsedDefaultArg();
2926 UnparsedDefaultArgInstantiations
[OldParm
].push_back(NewParm
);
2927 } else if (Expr
*Arg
= OldParm
->getDefaultArg()) {
2928 // Default arguments cannot be substituted until the declaration context
2929 // for the associated function or lambda capture class is available.
2930 // This is necessary for cases like the following where construction of
2931 // the lambda capture class for the outer lambda is dependent on the
2932 // parameter types but where the default argument is dependent on the
2933 // outer lambda's declaration context.
2934 // template <typename T>
2936 // return [](T = []{ return T{}; }()) { return 0; };
2938 NewParm
->setUninstantiatedDefaultArg(Arg
);
2941 NewParm
->setExplicitObjectParameterLoc(
2942 OldParm
->getExplicitObjectParamThisLoc());
2943 NewParm
->setHasInheritedDefaultArg(OldParm
->hasInheritedDefaultArg());
2945 if (OldParm
->isParameterPack() && !NewParm
->isParameterPack()) {
2946 // Add the new parameter to the instantiated parameter pack.
2947 CurrentInstantiationScope
->InstantiatedLocalPackArg(OldParm
, NewParm
);
2949 // Introduce an Old -> New mapping
2950 CurrentInstantiationScope
->InstantiatedLocal(OldParm
, NewParm
);
2953 // FIXME: OldParm may come from a FunctionProtoType, in which case CurContext
2954 // can be anything, is this right ?
2955 NewParm
->setDeclContext(CurContext
);
2957 NewParm
->setScopeInfo(OldParm
->getFunctionScopeDepth(),
2958 OldParm
->getFunctionScopeIndex() + indexAdjustment
);
2960 InstantiateAttrs(TemplateArgs
, OldParm
, NewParm
);
2965 /// Substitute the given template arguments into the given set of
2966 /// parameters, producing the set of parameter types that would be generated
2967 /// from such a substitution.
2968 bool Sema::SubstParmTypes(
2969 SourceLocation Loc
, ArrayRef
<ParmVarDecl
*> Params
,
2970 const FunctionProtoType::ExtParameterInfo
*ExtParamInfos
,
2971 const MultiLevelTemplateArgumentList
&TemplateArgs
,
2972 SmallVectorImpl
<QualType
> &ParamTypes
,
2973 SmallVectorImpl
<ParmVarDecl
*> *OutParams
,
2974 ExtParameterInfoBuilder
&ParamInfos
) {
2975 assert(!CodeSynthesisContexts
.empty() &&
2976 "Cannot perform an instantiation without some context on the "
2977 "instantiation stack");
2979 TemplateInstantiator
Instantiator(*this, TemplateArgs
, Loc
,
2981 return Instantiator
.TransformFunctionTypeParams(
2982 Loc
, Params
, nullptr, ExtParamInfos
, ParamTypes
, OutParams
, ParamInfos
);
2985 /// Substitute the given template arguments into the default argument.
2986 bool Sema::SubstDefaultArgument(
2989 const MultiLevelTemplateArgumentList
&TemplateArgs
,
2991 FunctionDecl
*FD
= cast
<FunctionDecl
>(Param
->getDeclContext());
2992 Expr
*PatternExpr
= Param
->getUninstantiatedDefaultArg();
2994 EnterExpressionEvaluationContext
EvalContext(
2995 *this, ExpressionEvaluationContext::PotentiallyEvaluated
, Param
);
2997 InstantiatingTemplate
Inst(*this, Loc
, Param
, TemplateArgs
.getInnermost());
2998 if (Inst
.isInvalid())
3000 if (Inst
.isAlreadyInstantiating()) {
3001 Diag(Param
->getBeginLoc(), diag::err_recursive_default_argument
) << FD
;
3002 Param
->setInvalidDecl();
3008 // C++ [dcl.fct.default]p5:
3009 // The names in the [default argument] expression are bound, and
3010 // the semantic constraints are checked, at the point where the
3011 // default argument expression appears.
3012 ContextRAII
SavedContext(*this, FD
);
3013 std::unique_ptr
<LocalInstantiationScope
> LIS
;
3016 // When instantiating a default argument due to use in a call expression,
3017 // an instantiation scope that includes the parameters of the callee is
3018 // required to satisfy references from the default argument. For example:
3019 // template<typename T> void f(T a, int = decltype(a)());
3020 // void g() { f(0); }
3021 LIS
= std::make_unique
<LocalInstantiationScope
>(*this);
3022 FunctionDecl
*PatternFD
= FD
->getTemplateInstantiationPattern(
3023 /*ForDefinition*/ false);
3024 if (addInstantiatedParametersToScope(FD
, PatternFD
, *LIS
, TemplateArgs
))
3028 runWithSufficientStackSpace(Loc
, [&] {
3029 Result
= SubstInitializer(PatternExpr
, TemplateArgs
,
3030 /*DirectInit*/false);
3033 if (Result
.isInvalid())
3037 // Check the expression as an initializer for the parameter.
3038 InitializedEntity Entity
3039 = InitializedEntity::InitializeParameter(Context
, Param
);
3040 InitializationKind Kind
= InitializationKind::CreateCopy(
3041 Param
->getLocation(),
3042 /*FIXME:EqualLoc*/ PatternExpr
->getBeginLoc());
3043 Expr
*ResultE
= Result
.getAs
<Expr
>();
3045 InitializationSequence
InitSeq(*this, Entity
, Kind
, ResultE
);
3046 Result
= InitSeq
.Perform(*this, Entity
, Kind
, ResultE
);
3047 if (Result
.isInvalid())
3051 ActOnFinishFullExpr(Result
.getAs
<Expr
>(), Param
->getOuterLocStart(),
3052 /*DiscardedValue*/ false);
3054 // FIXME: Obtain the source location for the '=' token.
3055 SourceLocation EqualLoc
= PatternExpr
->getBeginLoc();
3056 Result
= ConvertParamDefaultArgument(Param
, Result
.getAs
<Expr
>(), EqualLoc
);
3058 if (Result
.isInvalid())
3061 // Remember the instantiated default argument.
3062 Param
->setDefaultArg(Result
.getAs
<Expr
>());
3067 /// Perform substitution on the base class specifiers of the
3068 /// given class template specialization.
3070 /// Produces a diagnostic and returns true on error, returns false and
3071 /// attaches the instantiated base classes to the class template
3072 /// specialization if successful.
3074 Sema::SubstBaseSpecifiers(CXXRecordDecl
*Instantiation
,
3075 CXXRecordDecl
*Pattern
,
3076 const MultiLevelTemplateArgumentList
&TemplateArgs
) {
3077 bool Invalid
= false;
3078 SmallVector
<CXXBaseSpecifier
*, 4> InstantiatedBases
;
3079 for (const auto &Base
: Pattern
->bases()) {
3080 if (!Base
.getType()->isDependentType()) {
3081 if (const CXXRecordDecl
*RD
= Base
.getType()->getAsCXXRecordDecl()) {
3082 if (RD
->isInvalidDecl())
3083 Instantiation
->setInvalidDecl();
3085 InstantiatedBases
.push_back(new (Context
) CXXBaseSpecifier(Base
));
3089 SourceLocation EllipsisLoc
;
3090 TypeSourceInfo
*BaseTypeLoc
;
3091 if (Base
.isPackExpansion()) {
3092 // This is a pack expansion. See whether we should expand it now, or
3093 // wait until later.
3094 SmallVector
<UnexpandedParameterPack
, 2> Unexpanded
;
3095 collectUnexpandedParameterPacks(Base
.getTypeSourceInfo()->getTypeLoc(),
3097 bool ShouldExpand
= false;
3098 bool RetainExpansion
= false;
3099 std::optional
<unsigned> NumExpansions
;
3100 if (CheckParameterPacksForExpansion(Base
.getEllipsisLoc(),
3101 Base
.getSourceRange(),
3103 TemplateArgs
, ShouldExpand
,
3110 // If we should expand this pack expansion now, do so.
3112 for (unsigned I
= 0; I
!= *NumExpansions
; ++I
) {
3113 Sema::ArgumentPackSubstitutionIndexRAII
SubstIndex(*this, I
);
3115 TypeSourceInfo
*BaseTypeLoc
= SubstType(Base
.getTypeSourceInfo(),
3117 Base
.getSourceRange().getBegin(),
3124 if (CXXBaseSpecifier
*InstantiatedBase
3125 = CheckBaseSpecifier(Instantiation
,
3126 Base
.getSourceRange(),
3128 Base
.getAccessSpecifierAsWritten(),
3131 InstantiatedBases
.push_back(InstantiatedBase
);
3139 // The resulting base specifier will (still) be a pack expansion.
3140 EllipsisLoc
= Base
.getEllipsisLoc();
3141 Sema::ArgumentPackSubstitutionIndexRAII
SubstIndex(*this, -1);
3142 BaseTypeLoc
= SubstType(Base
.getTypeSourceInfo(),
3144 Base
.getSourceRange().getBegin(),
3147 BaseTypeLoc
= SubstType(Base
.getTypeSourceInfo(),
3149 Base
.getSourceRange().getBegin(),
3158 if (CXXBaseSpecifier
*InstantiatedBase
3159 = CheckBaseSpecifier(Instantiation
,
3160 Base
.getSourceRange(),
3162 Base
.getAccessSpecifierAsWritten(),
3165 InstantiatedBases
.push_back(InstantiatedBase
);
3170 if (!Invalid
&& AttachBaseSpecifiers(Instantiation
, InstantiatedBases
))
3176 // Defined via #include from SemaTemplateInstantiateDecl.cpp
3179 Attr
*instantiateTemplateAttribute(const Attr
*At
, ASTContext
&C
, Sema
&S
,
3180 const MultiLevelTemplateArgumentList
&TemplateArgs
);
3181 Attr
*instantiateTemplateAttributeForDecl(
3182 const Attr
*At
, ASTContext
&C
, Sema
&S
,
3183 const MultiLevelTemplateArgumentList
&TemplateArgs
);
3187 /// Instantiate the definition of a class from a given pattern.
3189 /// \param PointOfInstantiation The point of instantiation within the
3192 /// \param Instantiation is the declaration whose definition is being
3193 /// instantiated. This will be either a class template specialization
3194 /// or a member class of a class template specialization.
3196 /// \param Pattern is the pattern from which the instantiation
3197 /// occurs. This will be either the declaration of a class template or
3198 /// the declaration of a member class of a class template.
3200 /// \param TemplateArgs The template arguments to be substituted into
3203 /// \param TSK the kind of implicit or explicit instantiation to perform.
3205 /// \param Complain whether to complain if the class cannot be instantiated due
3206 /// to the lack of a definition.
3208 /// \returns true if an error occurred, false otherwise.
3210 Sema::InstantiateClass(SourceLocation PointOfInstantiation
,
3211 CXXRecordDecl
*Instantiation
, CXXRecordDecl
*Pattern
,
3212 const MultiLevelTemplateArgumentList
&TemplateArgs
,
3213 TemplateSpecializationKind TSK
,
3215 CXXRecordDecl
*PatternDef
3216 = cast_or_null
<CXXRecordDecl
>(Pattern
->getDefinition());
3217 if (DiagnoseUninstantiableTemplate(PointOfInstantiation
, Instantiation
,
3218 Instantiation
->getInstantiatedFromMemberClass(),
3219 Pattern
, PatternDef
, TSK
, Complain
))
3222 llvm::TimeTraceScope
TimeScope("InstantiateClass", [&]() {
3224 llvm::raw_string_ostream
OS(Name
);
3225 Instantiation
->getNameForDiagnostic(OS
, getPrintingPolicy(),
3226 /*Qualified=*/true);
3230 Pattern
= PatternDef
;
3232 // Record the point of instantiation.
3233 if (MemberSpecializationInfo
*MSInfo
3234 = Instantiation
->getMemberSpecializationInfo()) {
3235 MSInfo
->setTemplateSpecializationKind(TSK
);
3236 MSInfo
->setPointOfInstantiation(PointOfInstantiation
);
3237 } else if (ClassTemplateSpecializationDecl
*Spec
3238 = dyn_cast
<ClassTemplateSpecializationDecl
>(Instantiation
)) {
3239 Spec
->setTemplateSpecializationKind(TSK
);
3240 Spec
->setPointOfInstantiation(PointOfInstantiation
);
3243 InstantiatingTemplate
Inst(*this, PointOfInstantiation
, Instantiation
);
3244 if (Inst
.isInvalid())
3246 assert(!Inst
.isAlreadyInstantiating() && "should have been caught by caller");
3247 PrettyDeclStackTraceEntry
CrashInfo(Context
, Instantiation
, SourceLocation(),
3248 "instantiating class definition");
3250 // Enter the scope of this instantiation. We don't use
3251 // PushDeclContext because we don't have a scope.
3252 ContextRAII
SavedContext(*this, Instantiation
);
3253 EnterExpressionEvaluationContext
EvalContext(
3254 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated
);
3256 // If this is an instantiation of a local class, merge this local
3257 // instantiation scope with the enclosing scope. Otherwise, every
3258 // instantiation of a class has its own local instantiation scope.
3259 bool MergeWithParentScope
= !Instantiation
->isDefinedOutsideFunctionOrMethod();
3260 LocalInstantiationScope
Scope(*this, MergeWithParentScope
);
3262 // Some class state isn't processed immediately but delayed till class
3263 // instantiation completes. We may not be ready to handle any delayed state
3264 // already on the stack as it might correspond to a different class, so save
3265 // it now and put it back later.
3266 SavePendingParsedClassStateRAII
SavedPendingParsedClassState(*this);
3268 // Pull attributes from the pattern onto the instantiation.
3269 InstantiateAttrs(TemplateArgs
, Pattern
, Instantiation
);
3271 // Start the definition of this instantiation.
3272 Instantiation
->startDefinition();
3274 // The instantiation is visible here, even if it was first declared in an
3275 // unimported module.
3276 Instantiation
->setVisibleDespiteOwningModule();
3278 // FIXME: This loses the as-written tag kind for an explicit instantiation.
3279 Instantiation
->setTagKind(Pattern
->getTagKind());
3281 // Do substitution on the base class specifiers.
3282 if (SubstBaseSpecifiers(Instantiation
, Pattern
, TemplateArgs
))
3283 Instantiation
->setInvalidDecl();
3285 TemplateDeclInstantiator
Instantiator(*this, Instantiation
, TemplateArgs
);
3286 Instantiator
.setEvaluateConstraints(false);
3287 SmallVector
<Decl
*, 4> Fields
;
3288 // Delay instantiation of late parsed attributes.
3289 LateInstantiatedAttrVec LateAttrs
;
3290 Instantiator
.enableLateAttributeInstantiation(&LateAttrs
);
3292 bool MightHaveConstexprVirtualFunctions
= false;
3293 for (auto *Member
: Pattern
->decls()) {
3294 // Don't instantiate members not belonging in this semantic context.
3297 // template <int i> class A {
3301 // 'class B' has the template as lexical context but semantically it is
3302 // introduced in namespace scope.
3303 if (Member
->getDeclContext() != Pattern
)
3306 // BlockDecls can appear in a default-member-initializer. They must be the
3307 // child of a BlockExpr, so we only know how to instantiate them from there.
3308 // Similarly, lambda closure types are recreated when instantiating the
3309 // corresponding LambdaExpr.
3310 if (isa
<BlockDecl
>(Member
) ||
3311 (isa
<CXXRecordDecl
>(Member
) && cast
<CXXRecordDecl
>(Member
)->isLambda()))
3314 if (Member
->isInvalidDecl()) {
3315 Instantiation
->setInvalidDecl();
3319 Decl
*NewMember
= Instantiator
.Visit(Member
);
3321 if (FieldDecl
*Field
= dyn_cast
<FieldDecl
>(NewMember
)) {
3322 Fields
.push_back(Field
);
3323 } else if (EnumDecl
*Enum
= dyn_cast
<EnumDecl
>(NewMember
)) {
3324 // C++11 [temp.inst]p1: The implicit instantiation of a class template
3325 // specialization causes the implicit instantiation of the definitions
3326 // of unscoped member enumerations.
3327 // Record a point of instantiation for this implicit instantiation.
3328 if (TSK
== TSK_ImplicitInstantiation
&& !Enum
->isScoped() &&
3329 Enum
->isCompleteDefinition()) {
3330 MemberSpecializationInfo
*MSInfo
=Enum
->getMemberSpecializationInfo();
3331 assert(MSInfo
&& "no spec info for member enum specialization");
3332 MSInfo
->setTemplateSpecializationKind(TSK_ImplicitInstantiation
);
3333 MSInfo
->setPointOfInstantiation(PointOfInstantiation
);
3335 } else if (StaticAssertDecl
*SA
= dyn_cast
<StaticAssertDecl
>(NewMember
)) {
3336 if (SA
->isFailed()) {
3337 // A static_assert failed. Bail out; instantiating this
3338 // class is probably not meaningful.
3339 Instantiation
->setInvalidDecl();
3342 } else if (CXXMethodDecl
*MD
= dyn_cast
<CXXMethodDecl
>(NewMember
)) {
3343 if (MD
->isConstexpr() && !MD
->getFriendObjectKind() &&
3344 (MD
->isVirtualAsWritten() || Instantiation
->getNumBases()))
3345 MightHaveConstexprVirtualFunctions
= true;
3348 if (NewMember
->isInvalidDecl())
3349 Instantiation
->setInvalidDecl();
3351 // FIXME: Eventually, a NULL return will mean that one of the
3352 // instantiations was a semantic disaster, and we'll want to mark the
3353 // declaration invalid.
3354 // For now, we expect to skip some members that we can't yet handle.
3358 // Finish checking fields.
3359 ActOnFields(nullptr, Instantiation
->getLocation(), Instantiation
, Fields
,
3360 SourceLocation(), SourceLocation(), ParsedAttributesView());
3361 CheckCompletedCXXClass(nullptr, Instantiation
);
3363 // Default arguments are parsed, if not instantiated. We can go instantiate
3364 // default arg exprs for default constructors if necessary now. Unless we're
3365 // parsing a class, in which case wait until that's finished.
3366 if (ParsingClassDepth
== 0)
3367 ActOnFinishCXXNonNestedClass();
3369 // Instantiate late parsed attributes, and attach them to their decls.
3370 // See Sema::InstantiateAttrs
3371 for (LateInstantiatedAttrVec::iterator I
= LateAttrs
.begin(),
3372 E
= LateAttrs
.end(); I
!= E
; ++I
) {
3373 assert(CurrentInstantiationScope
== Instantiator
.getStartingScope());
3374 CurrentInstantiationScope
= I
->Scope
;
3376 // Allow 'this' within late-parsed attributes.
3377 auto *ND
= cast
<NamedDecl
>(I
->NewDecl
);
3378 auto *ThisContext
= dyn_cast_or_null
<CXXRecordDecl
>(ND
->getDeclContext());
3379 CXXThisScopeRAII
ThisScope(*this, ThisContext
, Qualifiers(),
3380 ND
->isCXXInstanceMember());
3383 instantiateTemplateAttribute(I
->TmplAttr
, Context
, *this, TemplateArgs
);
3385 I
->NewDecl
->addAttr(NewAttr
);
3386 LocalInstantiationScope::deleteScopes(I
->Scope
,
3387 Instantiator
.getStartingScope());
3389 Instantiator
.disableLateAttributeInstantiation();
3392 ActOnFinishDelayedMemberInitializers(Instantiation
);
3394 // FIXME: We should do something similar for explicit instantiations so they
3395 // end up in the right module.
3396 if (TSK
== TSK_ImplicitInstantiation
) {
3397 Instantiation
->setLocation(Pattern
->getLocation());
3398 Instantiation
->setLocStart(Pattern
->getInnerLocStart());
3399 Instantiation
->setBraceRange(Pattern
->getBraceRange());
3402 if (!Instantiation
->isInvalidDecl()) {
3403 // Perform any dependent diagnostics from the pattern.
3404 if (Pattern
->isDependentContext())
3405 PerformDependentDiagnostics(Pattern
, TemplateArgs
);
3407 // Instantiate any out-of-line class template partial
3408 // specializations now.
3409 for (TemplateDeclInstantiator::delayed_partial_spec_iterator
3410 P
= Instantiator
.delayed_partial_spec_begin(),
3411 PEnd
= Instantiator
.delayed_partial_spec_end();
3413 if (!Instantiator
.InstantiateClassTemplatePartialSpecialization(
3414 P
->first
, P
->second
)) {
3415 Instantiation
->setInvalidDecl();
3420 // Instantiate any out-of-line variable template partial
3421 // specializations now.
3422 for (TemplateDeclInstantiator::delayed_var_partial_spec_iterator
3423 P
= Instantiator
.delayed_var_partial_spec_begin(),
3424 PEnd
= Instantiator
.delayed_var_partial_spec_end();
3426 if (!Instantiator
.InstantiateVarTemplatePartialSpecialization(
3427 P
->first
, P
->second
)) {
3428 Instantiation
->setInvalidDecl();
3434 // Exit the scope of this instantiation.
3437 if (!Instantiation
->isInvalidDecl()) {
3438 // Always emit the vtable for an explicit instantiation definition
3439 // of a polymorphic class template specialization. Otherwise, eagerly
3440 // instantiate only constexpr virtual functions in preparation for their use
3441 // in constant evaluation.
3442 if (TSK
== TSK_ExplicitInstantiationDefinition
)
3443 MarkVTableUsed(PointOfInstantiation
, Instantiation
, true);
3444 else if (MightHaveConstexprVirtualFunctions
)
3445 MarkVirtualMembersReferenced(PointOfInstantiation
, Instantiation
,
3446 /*ConstexprOnly*/ true);
3449 Consumer
.HandleTagDeclDefinition(Instantiation
);
3451 return Instantiation
->isInvalidDecl();
3454 /// Instantiate the definition of an enum from a given pattern.
3456 /// \param PointOfInstantiation The point of instantiation within the
3458 /// \param Instantiation is the declaration whose definition is being
3459 /// instantiated. This will be a member enumeration of a class
3460 /// temploid specialization, or a local enumeration within a
3461 /// function temploid specialization.
3462 /// \param Pattern The templated declaration from which the instantiation
3464 /// \param TemplateArgs The template arguments to be substituted into
3466 /// \param TSK The kind of implicit or explicit instantiation to perform.
3468 /// \return \c true if an error occurred, \c false otherwise.
3469 bool Sema::InstantiateEnum(SourceLocation PointOfInstantiation
,
3470 EnumDecl
*Instantiation
, EnumDecl
*Pattern
,
3471 const MultiLevelTemplateArgumentList
&TemplateArgs
,
3472 TemplateSpecializationKind TSK
) {
3473 EnumDecl
*PatternDef
= Pattern
->getDefinition();
3474 if (DiagnoseUninstantiableTemplate(PointOfInstantiation
, Instantiation
,
3475 Instantiation
->getInstantiatedFromMemberEnum(),
3476 Pattern
, PatternDef
, TSK
,/*Complain*/true))
3478 Pattern
= PatternDef
;
3480 // Record the point of instantiation.
3481 if (MemberSpecializationInfo
*MSInfo
3482 = Instantiation
->getMemberSpecializationInfo()) {
3483 MSInfo
->setTemplateSpecializationKind(TSK
);
3484 MSInfo
->setPointOfInstantiation(PointOfInstantiation
);
3487 InstantiatingTemplate
Inst(*this, PointOfInstantiation
, Instantiation
);
3488 if (Inst
.isInvalid())
3490 if (Inst
.isAlreadyInstantiating())
3492 PrettyDeclStackTraceEntry
CrashInfo(Context
, Instantiation
, SourceLocation(),
3493 "instantiating enum definition");
3495 // The instantiation is visible here, even if it was first declared in an
3496 // unimported module.
3497 Instantiation
->setVisibleDespiteOwningModule();
3499 // Enter the scope of this instantiation. We don't use
3500 // PushDeclContext because we don't have a scope.
3501 ContextRAII
SavedContext(*this, Instantiation
);
3502 EnterExpressionEvaluationContext
EvalContext(
3503 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated
);
3505 LocalInstantiationScope
Scope(*this, /*MergeWithParentScope*/true);
3507 // Pull attributes from the pattern onto the instantiation.
3508 InstantiateAttrs(TemplateArgs
, Pattern
, Instantiation
);
3510 TemplateDeclInstantiator
Instantiator(*this, Instantiation
, TemplateArgs
);
3511 Instantiator
.InstantiateEnumDefinition(Instantiation
, Pattern
);
3513 // Exit the scope of this instantiation.
3516 return Instantiation
->isInvalidDecl();
3520 /// Instantiate the definition of a field from the given pattern.
3522 /// \param PointOfInstantiation The point of instantiation within the
3524 /// \param Instantiation is the declaration whose definition is being
3525 /// instantiated. This will be a class of a class temploid
3526 /// specialization, or a local enumeration within a function temploid
3528 /// \param Pattern The templated declaration from which the instantiation
3530 /// \param TemplateArgs The template arguments to be substituted into
3533 /// \return \c true if an error occurred, \c false otherwise.
3534 bool Sema::InstantiateInClassInitializer(
3535 SourceLocation PointOfInstantiation
, FieldDecl
*Instantiation
,
3536 FieldDecl
*Pattern
, const MultiLevelTemplateArgumentList
&TemplateArgs
) {
3537 // If there is no initializer, we don't need to do anything.
3538 if (!Pattern
->hasInClassInitializer())
3541 assert(Instantiation
->getInClassInitStyle() ==
3542 Pattern
->getInClassInitStyle() &&
3543 "pattern and instantiation disagree about init style");
3545 // Error out if we haven't parsed the initializer of the pattern yet because
3546 // we are waiting for the closing brace of the outer class.
3547 Expr
*OldInit
= Pattern
->getInClassInitializer();
3549 RecordDecl
*PatternRD
= Pattern
->getParent();
3550 RecordDecl
*OutermostClass
= PatternRD
->getOuterLexicalRecordContext();
3551 Diag(PointOfInstantiation
,
3552 diag::err_default_member_initializer_not_yet_parsed
)
3553 << OutermostClass
<< Pattern
;
3554 Diag(Pattern
->getEndLoc(),
3555 diag::note_default_member_initializer_not_yet_parsed
);
3556 Instantiation
->setInvalidDecl();
3560 InstantiatingTemplate
Inst(*this, PointOfInstantiation
, Instantiation
);
3561 if (Inst
.isInvalid())
3563 if (Inst
.isAlreadyInstantiating()) {
3564 // Error out if we hit an instantiation cycle for this initializer.
3565 Diag(PointOfInstantiation
, diag::err_default_member_initializer_cycle
)
3569 PrettyDeclStackTraceEntry
CrashInfo(Context
, Instantiation
, SourceLocation(),
3570 "instantiating default member init");
3572 // Enter the scope of this instantiation. We don't use PushDeclContext because
3573 // we don't have a scope.
3574 ContextRAII
SavedContext(*this, Instantiation
->getParent());
3575 EnterExpressionEvaluationContext
EvalContext(
3576 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated
);
3577 ExprEvalContexts
.back().DelayedDefaultInitializationContext
= {
3578 PointOfInstantiation
, Instantiation
, CurContext
};
3580 LocalInstantiationScope
Scope(*this, true);
3582 // Instantiate the initializer.
3583 ActOnStartCXXInClassMemberInitializer();
3584 CXXThisScopeRAII
ThisScope(*this, Instantiation
->getParent(), Qualifiers());
3586 ExprResult NewInit
= SubstInitializer(OldInit
, TemplateArgs
,
3587 /*CXXDirectInit=*/false);
3588 Expr
*Init
= NewInit
.get();
3589 assert((!Init
|| !isa
<ParenListExpr
>(Init
)) && "call-style init in class");
3590 ActOnFinishCXXInClassMemberInitializer(
3591 Instantiation
, Init
? Init
->getBeginLoc() : SourceLocation(), Init
);
3593 if (auto *L
= getASTMutationListener())
3594 L
->DefaultMemberInitializerInstantiated(Instantiation
);
3596 // Return true if the in-class initializer is still missing.
3597 return !Instantiation
->getInClassInitializer();
3601 /// A partial specialization whose template arguments have matched
3602 /// a given template-id.
3603 struct PartialSpecMatchResult
{
3604 ClassTemplatePartialSpecializationDecl
*Partial
;
3605 TemplateArgumentList
*Args
;
3609 bool Sema::usesPartialOrExplicitSpecialization(
3610 SourceLocation Loc
, ClassTemplateSpecializationDecl
*ClassTemplateSpec
) {
3611 if (ClassTemplateSpec
->getTemplateSpecializationKind() ==
3612 TSK_ExplicitSpecialization
)
3615 SmallVector
<ClassTemplatePartialSpecializationDecl
*, 4> PartialSpecs
;
3616 ClassTemplateSpec
->getSpecializedTemplate()
3617 ->getPartialSpecializations(PartialSpecs
);
3618 for (unsigned I
= 0, N
= PartialSpecs
.size(); I
!= N
; ++I
) {
3619 TemplateDeductionInfo
Info(Loc
);
3620 if (!DeduceTemplateArguments(PartialSpecs
[I
],
3621 ClassTemplateSpec
->getTemplateArgs(), Info
))
3628 /// Get the instantiation pattern to use to instantiate the definition of a
3629 /// given ClassTemplateSpecializationDecl (either the pattern of the primary
3630 /// template or of a partial specialization).
3631 static ActionResult
<CXXRecordDecl
*>
3632 getPatternForClassTemplateSpecialization(
3633 Sema
&S
, SourceLocation PointOfInstantiation
,
3634 ClassTemplateSpecializationDecl
*ClassTemplateSpec
,
3635 TemplateSpecializationKind TSK
) {
3636 Sema::InstantiatingTemplate
Inst(S
, PointOfInstantiation
, ClassTemplateSpec
);
3637 if (Inst
.isInvalid())
3638 return {/*Invalid=*/true};
3639 if (Inst
.isAlreadyInstantiating())
3640 return {/*Invalid=*/false};
3642 llvm::PointerUnion
<ClassTemplateDecl
*,
3643 ClassTemplatePartialSpecializationDecl
*>
3644 Specialized
= ClassTemplateSpec
->getSpecializedTemplateOrPartial();
3645 if (!Specialized
.is
<ClassTemplatePartialSpecializationDecl
*>()) {
3646 // Find best matching specialization.
3647 ClassTemplateDecl
*Template
= ClassTemplateSpec
->getSpecializedTemplate();
3649 // C++ [temp.class.spec.match]p1:
3650 // When a class template is used in a context that requires an
3651 // instantiation of the class, it is necessary to determine
3652 // whether the instantiation is to be generated using the primary
3653 // template or one of the partial specializations. This is done by
3654 // matching the template arguments of the class template
3655 // specialization with the template argument lists of the partial
3657 typedef PartialSpecMatchResult MatchResult
;
3658 SmallVector
<MatchResult
, 4> Matched
;
3659 SmallVector
<ClassTemplatePartialSpecializationDecl
*, 4> PartialSpecs
;
3660 Template
->getPartialSpecializations(PartialSpecs
);
3661 TemplateSpecCandidateSet
FailedCandidates(PointOfInstantiation
);
3662 for (unsigned I
= 0, N
= PartialSpecs
.size(); I
!= N
; ++I
) {
3663 ClassTemplatePartialSpecializationDecl
*Partial
= PartialSpecs
[I
];
3664 TemplateDeductionInfo
Info(FailedCandidates
.getLocation());
3665 if (Sema::TemplateDeductionResult Result
= S
.DeduceTemplateArguments(
3666 Partial
, ClassTemplateSpec
->getTemplateArgs(), Info
)) {
3667 // Store the failed-deduction information for use in diagnostics, later.
3668 // TODO: Actually use the failed-deduction info?
3669 FailedCandidates
.addCandidate().set(
3670 DeclAccessPair::make(Template
, AS_public
), Partial
,
3671 MakeDeductionFailureInfo(S
.Context
, Result
, Info
));
3674 Matched
.push_back(PartialSpecMatchResult());
3675 Matched
.back().Partial
= Partial
;
3676 Matched
.back().Args
= Info
.takeCanonical();
3680 // If we're dealing with a member template where the template parameters
3681 // have been instantiated, this provides the original template parameters
3682 // from which the member template's parameters were instantiated.
3684 if (Matched
.size() >= 1) {
3685 SmallVectorImpl
<MatchResult
>::iterator Best
= Matched
.begin();
3686 if (Matched
.size() == 1) {
3687 // -- If exactly one matching specialization is found, the
3688 // instantiation is generated from that specialization.
3689 // We don't need to do anything for this.
3691 // -- If more than one matching specialization is found, the
3692 // partial order rules (14.5.4.2) are used to determine
3693 // whether one of the specializations is more specialized
3694 // than the others. If none of the specializations is more
3695 // specialized than all of the other matching
3696 // specializations, then the use of the class template is
3697 // ambiguous and the program is ill-formed.
3698 for (SmallVectorImpl
<MatchResult
>::iterator P
= Best
+ 1,
3699 PEnd
= Matched
.end();
3701 if (S
.getMoreSpecializedPartialSpecialization(
3702 P
->Partial
, Best
->Partial
, PointOfInstantiation
) ==
3707 // Determine if the best partial specialization is more specialized than
3709 bool Ambiguous
= false;
3710 for (SmallVectorImpl
<MatchResult
>::iterator P
= Matched
.begin(),
3711 PEnd
= Matched
.end();
3713 if (P
!= Best
&& S
.getMoreSpecializedPartialSpecialization(
3714 P
->Partial
, Best
->Partial
,
3715 PointOfInstantiation
) != Best
->Partial
) {
3722 // Partial ordering did not produce a clear winner. Complain.
3724 ClassTemplateSpec
->setInvalidDecl();
3725 S
.Diag(PointOfInstantiation
,
3726 diag::err_partial_spec_ordering_ambiguous
)
3727 << ClassTemplateSpec
;
3729 // Print the matching partial specializations.
3730 for (SmallVectorImpl
<MatchResult
>::iterator P
= Matched
.begin(),
3731 PEnd
= Matched
.end();
3733 S
.Diag(P
->Partial
->getLocation(), diag::note_partial_spec_match
)
3734 << S
.getTemplateArgumentBindingsText(
3735 P
->Partial
->getTemplateParameters(), *P
->Args
);
3737 return {/*Invalid=*/true};
3741 ClassTemplateSpec
->setInstantiationOf(Best
->Partial
, Best
->Args
);
3743 // -- If no matches are found, the instantiation is generated
3744 // from the primary template.
3748 CXXRecordDecl
*Pattern
= nullptr;
3749 Specialized
= ClassTemplateSpec
->getSpecializedTemplateOrPartial();
3750 if (auto *PartialSpec
=
3751 Specialized
.dyn_cast
<ClassTemplatePartialSpecializationDecl
*>()) {
3752 // Instantiate using the best class template partial specialization.
3753 while (PartialSpec
->getInstantiatedFromMember()) {
3754 // If we've found an explicit specialization of this class template,
3755 // stop here and use that as the pattern.
3756 if (PartialSpec
->isMemberSpecialization())
3759 PartialSpec
= PartialSpec
->getInstantiatedFromMember();
3761 Pattern
= PartialSpec
;
3763 ClassTemplateDecl
*Template
= ClassTemplateSpec
->getSpecializedTemplate();
3764 while (Template
->getInstantiatedFromMemberTemplate()) {
3765 // If we've found an explicit specialization of this class template,
3766 // stop here and use that as the pattern.
3767 if (Template
->isMemberSpecialization())
3770 Template
= Template
->getInstantiatedFromMemberTemplate();
3772 Pattern
= Template
->getTemplatedDecl();
3778 bool Sema::InstantiateClassTemplateSpecialization(
3779 SourceLocation PointOfInstantiation
,
3780 ClassTemplateSpecializationDecl
*ClassTemplateSpec
,
3781 TemplateSpecializationKind TSK
, bool Complain
) {
3782 // Perform the actual instantiation on the canonical declaration.
3783 ClassTemplateSpec
= cast
<ClassTemplateSpecializationDecl
>(
3784 ClassTemplateSpec
->getCanonicalDecl());
3785 if (ClassTemplateSpec
->isInvalidDecl())
3788 ActionResult
<CXXRecordDecl
*> Pattern
=
3789 getPatternForClassTemplateSpecialization(*this, PointOfInstantiation
,
3790 ClassTemplateSpec
, TSK
);
3791 if (!Pattern
.isUsable())
3792 return Pattern
.isInvalid();
3794 return InstantiateClass(
3795 PointOfInstantiation
, ClassTemplateSpec
, Pattern
.get(),
3796 getTemplateInstantiationArgs(ClassTemplateSpec
), TSK
, Complain
);
3799 /// Instantiates the definitions of all of the member
3800 /// of the given class, which is an instantiation of a class template
3801 /// or a member class of a template.
3803 Sema::InstantiateClassMembers(SourceLocation PointOfInstantiation
,
3804 CXXRecordDecl
*Instantiation
,
3805 const MultiLevelTemplateArgumentList
&TemplateArgs
,
3806 TemplateSpecializationKind TSK
) {
3807 // FIXME: We need to notify the ASTMutationListener that we did all of these
3808 // things, in case we have an explicit instantiation definition in a PCM, a
3809 // module, or preamble, and the declaration is in an imported AST.
3811 (TSK
== TSK_ExplicitInstantiationDefinition
||
3812 TSK
== TSK_ExplicitInstantiationDeclaration
||
3813 (TSK
== TSK_ImplicitInstantiation
&& Instantiation
->isLocalClass())) &&
3814 "Unexpected template specialization kind!");
3815 for (auto *D
: Instantiation
->decls()) {
3816 bool SuppressNew
= false;
3817 if (auto *Function
= dyn_cast
<FunctionDecl
>(D
)) {
3818 if (FunctionDecl
*Pattern
=
3819 Function
->getInstantiatedFromMemberFunction()) {
3821 if (Function
->isIneligibleOrNotSelected())
3824 if (Function
->getTrailingRequiresClause()) {
3825 ConstraintSatisfaction Satisfaction
;
3826 if (CheckFunctionConstraints(Function
, Satisfaction
) ||
3827 !Satisfaction
.IsSatisfied
) {
3832 if (Function
->hasAttr
<ExcludeFromExplicitInstantiationAttr
>())
3835 MemberSpecializationInfo
*MSInfo
=
3836 Function
->getMemberSpecializationInfo();
3837 assert(MSInfo
&& "No member specialization information?");
3838 if (MSInfo
->getTemplateSpecializationKind()
3839 == TSK_ExplicitSpecialization
)
3842 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation
, TSK
,
3844 MSInfo
->getTemplateSpecializationKind(),
3845 MSInfo
->getPointOfInstantiation(),
3850 // C++11 [temp.explicit]p8:
3851 // An explicit instantiation definition that names a class template
3852 // specialization explicitly instantiates the class template
3853 // specialization and is only an explicit instantiation definition
3854 // of members whose definition is visible at the point of
3856 if (TSK
== TSK_ExplicitInstantiationDefinition
&& !Pattern
->isDefined())
3859 Function
->setTemplateSpecializationKind(TSK
, PointOfInstantiation
);
3861 if (Function
->isDefined()) {
3862 // Let the ASTConsumer know that this function has been explicitly
3863 // instantiated now, and its linkage might have changed.
3864 Consumer
.HandleTopLevelDecl(DeclGroupRef(Function
));
3865 } else if (TSK
== TSK_ExplicitInstantiationDefinition
) {
3866 InstantiateFunctionDefinition(PointOfInstantiation
, Function
);
3867 } else if (TSK
== TSK_ImplicitInstantiation
) {
3868 PendingLocalImplicitInstantiations
.push_back(
3869 std::make_pair(Function
, PointOfInstantiation
));
3872 } else if (auto *Var
= dyn_cast
<VarDecl
>(D
)) {
3873 if (isa
<VarTemplateSpecializationDecl
>(Var
))
3876 if (Var
->isStaticDataMember()) {
3877 if (Var
->hasAttr
<ExcludeFromExplicitInstantiationAttr
>())
3880 MemberSpecializationInfo
*MSInfo
= Var
->getMemberSpecializationInfo();
3881 assert(MSInfo
&& "No member specialization information?");
3882 if (MSInfo
->getTemplateSpecializationKind()
3883 == TSK_ExplicitSpecialization
)
3886 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation
, TSK
,
3888 MSInfo
->getTemplateSpecializationKind(),
3889 MSInfo
->getPointOfInstantiation(),
3894 if (TSK
== TSK_ExplicitInstantiationDefinition
) {
3895 // C++0x [temp.explicit]p8:
3896 // An explicit instantiation definition that names a class template
3897 // specialization explicitly instantiates the class template
3898 // specialization and is only an explicit instantiation definition
3899 // of members whose definition is visible at the point of
3901 if (!Var
->getInstantiatedFromStaticDataMember()->getDefinition())
3904 Var
->setTemplateSpecializationKind(TSK
, PointOfInstantiation
);
3905 InstantiateVariableDefinition(PointOfInstantiation
, Var
);
3907 Var
->setTemplateSpecializationKind(TSK
, PointOfInstantiation
);
3910 } else if (auto *Record
= dyn_cast
<CXXRecordDecl
>(D
)) {
3911 if (Record
->hasAttr
<ExcludeFromExplicitInstantiationAttr
>())
3914 // Always skip the injected-class-name, along with any
3915 // redeclarations of nested classes, since both would cause us
3916 // to try to instantiate the members of a class twice.
3917 // Skip closure types; they'll get instantiated when we instantiate
3918 // the corresponding lambda-expression.
3919 if (Record
->isInjectedClassName() || Record
->getPreviousDecl() ||
3923 MemberSpecializationInfo
*MSInfo
= Record
->getMemberSpecializationInfo();
3924 assert(MSInfo
&& "No member specialization information?");
3926 if (MSInfo
->getTemplateSpecializationKind()
3927 == TSK_ExplicitSpecialization
)
3930 if (Context
.getTargetInfo().getTriple().isOSWindows() &&
3931 TSK
== TSK_ExplicitInstantiationDeclaration
) {
3932 // On Windows, explicit instantiation decl of the outer class doesn't
3933 // affect the inner class. Typically extern template declarations are
3934 // used in combination with dll import/export annotations, but those
3935 // are not propagated from the outer class templates to inner classes.
3936 // Therefore, do not instantiate inner classes on this platform, so
3937 // that users don't end up with undefined symbols during linking.
3941 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation
, TSK
,
3943 MSInfo
->getTemplateSpecializationKind(),
3944 MSInfo
->getPointOfInstantiation(),
3949 CXXRecordDecl
*Pattern
= Record
->getInstantiatedFromMemberClass();
3950 assert(Pattern
&& "Missing instantiated-from-template information");
3952 if (!Record
->getDefinition()) {
3953 if (!Pattern
->getDefinition()) {
3954 // C++0x [temp.explicit]p8:
3955 // An explicit instantiation definition that names a class template
3956 // specialization explicitly instantiates the class template
3957 // specialization and is only an explicit instantiation definition
3958 // of members whose definition is visible at the point of
3960 if (TSK
== TSK_ExplicitInstantiationDeclaration
) {
3961 MSInfo
->setTemplateSpecializationKind(TSK
);
3962 MSInfo
->setPointOfInstantiation(PointOfInstantiation
);
3968 InstantiateClass(PointOfInstantiation
, Record
, Pattern
,
3972 if (TSK
== TSK_ExplicitInstantiationDefinition
&&
3973 Record
->getTemplateSpecializationKind() ==
3974 TSK_ExplicitInstantiationDeclaration
) {
3975 Record
->setTemplateSpecializationKind(TSK
);
3976 MarkVTableUsed(PointOfInstantiation
, Record
, true);
3980 Pattern
= cast_or_null
<CXXRecordDecl
>(Record
->getDefinition());
3982 InstantiateClassMembers(PointOfInstantiation
, Pattern
, TemplateArgs
,
3984 } else if (auto *Enum
= dyn_cast
<EnumDecl
>(D
)) {
3985 MemberSpecializationInfo
*MSInfo
= Enum
->getMemberSpecializationInfo();
3986 assert(MSInfo
&& "No member specialization information?");
3988 if (MSInfo
->getTemplateSpecializationKind()
3989 == TSK_ExplicitSpecialization
)
3992 if (CheckSpecializationInstantiationRedecl(
3993 PointOfInstantiation
, TSK
, Enum
,
3994 MSInfo
->getTemplateSpecializationKind(),
3995 MSInfo
->getPointOfInstantiation(), SuppressNew
) ||
3999 if (Enum
->getDefinition())
4002 EnumDecl
*Pattern
= Enum
->getTemplateInstantiationPattern();
4003 assert(Pattern
&& "Missing instantiated-from-template information");
4005 if (TSK
== TSK_ExplicitInstantiationDefinition
) {
4006 if (!Pattern
->getDefinition())
4009 InstantiateEnum(PointOfInstantiation
, Enum
, Pattern
, TemplateArgs
, TSK
);
4011 MSInfo
->setTemplateSpecializationKind(TSK
);
4012 MSInfo
->setPointOfInstantiation(PointOfInstantiation
);
4014 } else if (auto *Field
= dyn_cast
<FieldDecl
>(D
)) {
4015 // No need to instantiate in-class initializers during explicit
4017 if (Field
->hasInClassInitializer() && TSK
== TSK_ImplicitInstantiation
) {
4018 CXXRecordDecl
*ClassPattern
=
4019 Instantiation
->getTemplateInstantiationPattern();
4020 DeclContext::lookup_result Lookup
=
4021 ClassPattern
->lookup(Field
->getDeclName());
4022 FieldDecl
*Pattern
= Lookup
.find_first
<FieldDecl
>();
4024 InstantiateInClassInitializer(PointOfInstantiation
, Field
, Pattern
,
4031 /// Instantiate the definitions of all of the members of the
4032 /// given class template specialization, which was named as part of an
4033 /// explicit instantiation.
4035 Sema::InstantiateClassTemplateSpecializationMembers(
4036 SourceLocation PointOfInstantiation
,
4037 ClassTemplateSpecializationDecl
*ClassTemplateSpec
,
4038 TemplateSpecializationKind TSK
) {
4039 // C++0x [temp.explicit]p7:
4040 // An explicit instantiation that names a class template
4041 // specialization is an explicit instantion of the same kind
4042 // (declaration or definition) of each of its members (not
4043 // including members inherited from base classes) that has not
4044 // been previously explicitly specialized in the translation unit
4045 // containing the explicit instantiation, except as described
4047 InstantiateClassMembers(PointOfInstantiation
, ClassTemplateSpec
,
4048 getTemplateInstantiationArgs(ClassTemplateSpec
),
4053 Sema::SubstStmt(Stmt
*S
, const MultiLevelTemplateArgumentList
&TemplateArgs
) {
4057 TemplateInstantiator
Instantiator(*this, TemplateArgs
,
4060 return Instantiator
.TransformStmt(S
);
4063 bool Sema::SubstTemplateArguments(
4064 ArrayRef
<TemplateArgumentLoc
> Args
,
4065 const MultiLevelTemplateArgumentList
&TemplateArgs
,
4066 TemplateArgumentListInfo
&Out
) {
4067 TemplateInstantiator
Instantiator(*this, TemplateArgs
, SourceLocation(),
4069 return Instantiator
.TransformTemplateArguments(Args
.begin(), Args
.end(), Out
);
4073 Sema::SubstExpr(Expr
*E
, const MultiLevelTemplateArgumentList
&TemplateArgs
) {
4077 TemplateInstantiator
Instantiator(*this, TemplateArgs
,
4080 return Instantiator
.TransformExpr(E
);
4084 Sema::SubstConstraintExpr(Expr
*E
,
4085 const MultiLevelTemplateArgumentList
&TemplateArgs
) {
4089 // This is where we need to make sure we 'know' constraint checking needs to
4091 TemplateInstantiator
Instantiator(*this, TemplateArgs
, SourceLocation(),
4093 return Instantiator
.TransformExpr(E
);
4096 ExprResult
Sema::SubstInitializer(Expr
*Init
,
4097 const MultiLevelTemplateArgumentList
&TemplateArgs
,
4098 bool CXXDirectInit
) {
4099 TemplateInstantiator
Instantiator(*this, TemplateArgs
, SourceLocation(),
4101 return Instantiator
.TransformInitializer(Init
, CXXDirectInit
);
4104 bool Sema::SubstExprs(ArrayRef
<Expr
*> Exprs
, bool IsCall
,
4105 const MultiLevelTemplateArgumentList
&TemplateArgs
,
4106 SmallVectorImpl
<Expr
*> &Outputs
) {
4110 TemplateInstantiator
Instantiator(*this, TemplateArgs
,
4113 return Instantiator
.TransformExprs(Exprs
.data(), Exprs
.size(),
4117 NestedNameSpecifierLoc
4118 Sema::SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS
,
4119 const MultiLevelTemplateArgumentList
&TemplateArgs
) {
4121 return NestedNameSpecifierLoc();
4123 TemplateInstantiator
Instantiator(*this, TemplateArgs
, NNS
.getBeginLoc(),
4125 return Instantiator
.TransformNestedNameSpecifierLoc(NNS
);
4128 /// Do template substitution on declaration name info.
4130 Sema::SubstDeclarationNameInfo(const DeclarationNameInfo
&NameInfo
,
4131 const MultiLevelTemplateArgumentList
&TemplateArgs
) {
4132 TemplateInstantiator
Instantiator(*this, TemplateArgs
, NameInfo
.getLoc(),
4133 NameInfo
.getName());
4134 return Instantiator
.TransformDeclarationNameInfo(NameInfo
);
4138 Sema::SubstTemplateName(NestedNameSpecifierLoc QualifierLoc
,
4139 TemplateName Name
, SourceLocation Loc
,
4140 const MultiLevelTemplateArgumentList
&TemplateArgs
) {
4141 TemplateInstantiator
Instantiator(*this, TemplateArgs
, Loc
,
4144 SS
.Adopt(QualifierLoc
);
4145 return Instantiator
.TransformTemplateName(SS
, Name
, Loc
);
4148 static const Decl
*getCanonicalParmVarDecl(const Decl
*D
) {
4149 // When storing ParmVarDecls in the local instantiation scope, we always
4150 // want to use the ParmVarDecl from the canonical function declaration,
4151 // since the map is then valid for any redeclaration or definition of that
4153 if (const ParmVarDecl
*PV
= dyn_cast
<ParmVarDecl
>(D
)) {
4154 if (const FunctionDecl
*FD
= dyn_cast
<FunctionDecl
>(PV
->getDeclContext())) {
4155 unsigned i
= PV
->getFunctionScopeIndex();
4156 // This parameter might be from a freestanding function type within the
4157 // function and isn't necessarily referring to one of FD's parameters.
4158 if (i
< FD
->getNumParams() && FD
->getParamDecl(i
) == PV
)
4159 return FD
->getCanonicalDecl()->getParamDecl(i
);
4166 llvm::PointerUnion
<Decl
*, LocalInstantiationScope::DeclArgumentPack
*> *
4167 LocalInstantiationScope::findInstantiationOf(const Decl
*D
) {
4168 D
= getCanonicalParmVarDecl(D
);
4169 for (LocalInstantiationScope
*Current
= this; Current
;
4170 Current
= Current
->Outer
) {
4172 // Check if we found something within this scope.
4173 const Decl
*CheckD
= D
;
4175 LocalDeclsMap::iterator Found
= Current
->LocalDecls
.find(CheckD
);
4176 if (Found
!= Current
->LocalDecls
.end())
4177 return &Found
->second
;
4179 // If this is a tag declaration, it's possible that we need to look for
4180 // a previous declaration.
4181 if (const TagDecl
*Tag
= dyn_cast
<TagDecl
>(CheckD
))
4182 CheckD
= Tag
->getPreviousDecl();
4187 // If we aren't combined with our outer scope, we're done.
4188 if (!Current
->CombineWithOuterScope
)
4192 // If we're performing a partial substitution during template argument
4193 // deduction, we may not have values for template parameters yet.
4194 if (isa
<NonTypeTemplateParmDecl
>(D
) || isa
<TemplateTypeParmDecl
>(D
) ||
4195 isa
<TemplateTemplateParmDecl
>(D
))
4198 // Local types referenced prior to definition may require instantiation.
4199 if (const CXXRecordDecl
*RD
= dyn_cast
<CXXRecordDecl
>(D
))
4200 if (RD
->isLocalClass())
4203 // Enumeration types referenced prior to definition may appear as a result of
4205 if (isa
<EnumDecl
>(D
))
4208 // Materialized typedefs/type alias for implicit deduction guides may require
4210 if (isa
<TypedefNameDecl
>(D
) &&
4211 isa
<CXXDeductionGuideDecl
>(D
->getDeclContext()))
4214 // If we didn't find the decl, then we either have a sema bug, or we have a
4215 // forward reference to a label declaration. Return null to indicate that
4216 // we have an uninstantiated label.
4217 assert(isa
<LabelDecl
>(D
) && "declaration not instantiated in this scope");
4221 void LocalInstantiationScope::InstantiatedLocal(const Decl
*D
, Decl
*Inst
) {
4222 D
= getCanonicalParmVarDecl(D
);
4223 llvm::PointerUnion
<Decl
*, DeclArgumentPack
*> &Stored
= LocalDecls
[D
];
4224 if (Stored
.isNull()) {
4226 // It should not be present in any surrounding scope either.
4227 LocalInstantiationScope
*Current
= this;
4228 while (Current
->CombineWithOuterScope
&& Current
->Outer
) {
4229 Current
= Current
->Outer
;
4230 assert(!Current
->LocalDecls
.contains(D
) &&
4231 "Instantiated local in inner and outer scopes");
4235 } else if (DeclArgumentPack
*Pack
= Stored
.dyn_cast
<DeclArgumentPack
*>()) {
4236 Pack
->push_back(cast
<VarDecl
>(Inst
));
4238 assert(Stored
.get
<Decl
*>() == Inst
&& "Already instantiated this local");
4242 void LocalInstantiationScope::InstantiatedLocalPackArg(const Decl
*D
,
4244 D
= getCanonicalParmVarDecl(D
);
4245 DeclArgumentPack
*Pack
= LocalDecls
[D
].get
<DeclArgumentPack
*>();
4246 Pack
->push_back(Inst
);
4249 void LocalInstantiationScope::MakeInstantiatedLocalArgPack(const Decl
*D
) {
4251 // This should be the first time we've been told about this decl.
4252 for (LocalInstantiationScope
*Current
= this;
4253 Current
&& Current
->CombineWithOuterScope
; Current
= Current
->Outer
)
4254 assert(!Current
->LocalDecls
.contains(D
) &&
4255 "Creating local pack after instantiation of local");
4258 D
= getCanonicalParmVarDecl(D
);
4259 llvm::PointerUnion
<Decl
*, DeclArgumentPack
*> &Stored
= LocalDecls
[D
];
4260 DeclArgumentPack
*Pack
= new DeclArgumentPack
;
4262 ArgumentPacks
.push_back(Pack
);
4265 bool LocalInstantiationScope::isLocalPackExpansion(const Decl
*D
) {
4266 for (DeclArgumentPack
*Pack
: ArgumentPacks
)
4267 if (llvm::is_contained(*Pack
, D
))
4272 void LocalInstantiationScope::SetPartiallySubstitutedPack(NamedDecl
*Pack
,
4273 const TemplateArgument
*ExplicitArgs
,
4274 unsigned NumExplicitArgs
) {
4275 assert((!PartiallySubstitutedPack
|| PartiallySubstitutedPack
== Pack
) &&
4276 "Already have a partially-substituted pack");
4277 assert((!PartiallySubstitutedPack
4278 || NumArgsInPartiallySubstitutedPack
== NumExplicitArgs
) &&
4279 "Wrong number of arguments in partially-substituted pack");
4280 PartiallySubstitutedPack
= Pack
;
4281 ArgsInPartiallySubstitutedPack
= ExplicitArgs
;
4282 NumArgsInPartiallySubstitutedPack
= NumExplicitArgs
;
4285 NamedDecl
*LocalInstantiationScope::getPartiallySubstitutedPack(
4286 const TemplateArgument
**ExplicitArgs
,
4287 unsigned *NumExplicitArgs
) const {
4289 *ExplicitArgs
= nullptr;
4290 if (NumExplicitArgs
)
4291 *NumExplicitArgs
= 0;
4293 for (const LocalInstantiationScope
*Current
= this; Current
;
4294 Current
= Current
->Outer
) {
4295 if (Current
->PartiallySubstitutedPack
) {
4297 *ExplicitArgs
= Current
->ArgsInPartiallySubstitutedPack
;
4298 if (NumExplicitArgs
)
4299 *NumExplicitArgs
= Current
->NumArgsInPartiallySubstitutedPack
;
4301 return Current
->PartiallySubstitutedPack
;
4304 if (!Current
->CombineWithOuterScope
)