[HLSL] Implement RWBuffer::operator[] via __builtin_hlsl_resource_getpointer (#117017)
[llvm-project.git] / clang / lib / Sema / SemaTemplateInstantiate.cpp
blobfb0f38df62a7446a7f0b58071ad63f1edee88148
1 //===------- SemaTemplateInstantiate.cpp - C++ Template Instantiation ------===/
2 //
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 //===----------------------------------------------------------------------===/
7 //
8 // This file implements C++ template instantiation.
9 //
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/DynamicRecursiveASTVisitor.h"
21 #include "clang/AST/Expr.h"
22 #include "clang/AST/ExprConcepts.h"
23 #include "clang/AST/PrettyDeclStackTrace.h"
24 #include "clang/AST/Type.h"
25 #include "clang/AST/TypeLoc.h"
26 #include "clang/AST/TypeVisitor.h"
27 #include "clang/Basic/LangOptions.h"
28 #include "clang/Basic/TargetInfo.h"
29 #include "clang/Sema/DeclSpec.h"
30 #include "clang/Sema/EnterExpressionEvaluationContext.h"
31 #include "clang/Sema/Initialization.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/STLForwardCompat.h"
39 #include "llvm/ADT/StringExtras.h"
40 #include "llvm/Support/ErrorHandling.h"
41 #include "llvm/Support/SaveAndRestore.h"
42 #include "llvm/Support/TimeProfiler.h"
43 #include <optional>
45 using namespace clang;
46 using namespace sema;
48 //===----------------------------------------------------------------------===/
49 // Template Instantiation Support
50 //===----------------------------------------------------------------------===/
52 namespace {
53 namespace TemplateInstArgsHelpers {
54 struct Response {
55 const Decl *NextDecl = nullptr;
56 bool IsDone = false;
57 bool ClearRelativeToPrimary = true;
58 static Response Done() {
59 Response R;
60 R.IsDone = true;
61 return R;
63 static Response ChangeDecl(const Decl *ND) {
64 Response R;
65 R.NextDecl = ND;
66 return R;
68 static Response ChangeDecl(const DeclContext *Ctx) {
69 Response R;
70 R.NextDecl = Decl::castFromDeclContext(Ctx);
71 return R;
74 static Response UseNextDecl(const Decl *CurDecl) {
75 return ChangeDecl(CurDecl->getDeclContext());
78 static Response DontClearRelativeToPrimaryNextDecl(const Decl *CurDecl) {
79 Response R = Response::UseNextDecl(CurDecl);
80 R.ClearRelativeToPrimary = false;
81 return R;
85 // Retrieve the primary template for a lambda call operator. It's
86 // unfortunate that we only have the mappings of call operators rather
87 // than lambda classes.
88 const FunctionDecl *
89 getPrimaryTemplateOfGenericLambda(const FunctionDecl *LambdaCallOperator) {
90 if (!isLambdaCallOperator(LambdaCallOperator))
91 return LambdaCallOperator;
92 while (true) {
93 if (auto *FTD = dyn_cast_if_present<FunctionTemplateDecl>(
94 LambdaCallOperator->getDescribedTemplate());
95 FTD && FTD->getInstantiatedFromMemberTemplate()) {
96 LambdaCallOperator =
97 FTD->getInstantiatedFromMemberTemplate()->getTemplatedDecl();
98 } else if (LambdaCallOperator->getPrimaryTemplate()) {
99 // Cases where the lambda operator is instantiated in
100 // TemplateDeclInstantiator::VisitCXXMethodDecl.
101 LambdaCallOperator =
102 LambdaCallOperator->getPrimaryTemplate()->getTemplatedDecl();
103 } else if (auto *Prev = cast<CXXMethodDecl>(LambdaCallOperator)
104 ->getInstantiatedFromMemberFunction())
105 LambdaCallOperator = Prev;
106 else
107 break;
109 return LambdaCallOperator;
112 struct EnclosingTypeAliasTemplateDetails {
113 TypeAliasTemplateDecl *Template = nullptr;
114 TypeAliasTemplateDecl *PrimaryTypeAliasDecl = nullptr;
115 ArrayRef<TemplateArgument> AssociatedTemplateArguments;
117 explicit operator bool() noexcept { return Template; }
120 // Find the enclosing type alias template Decl from CodeSynthesisContexts, as
121 // well as its primary template and instantiating template arguments.
122 EnclosingTypeAliasTemplateDetails
123 getEnclosingTypeAliasTemplateDecl(Sema &SemaRef) {
124 for (auto &CSC : llvm::reverse(SemaRef.CodeSynthesisContexts)) {
125 if (CSC.Kind != Sema::CodeSynthesisContext::SynthesisKind::
126 TypeAliasTemplateInstantiation)
127 continue;
128 EnclosingTypeAliasTemplateDetails Result;
129 auto *TATD = cast<TypeAliasTemplateDecl>(CSC.Entity),
130 *Next = TATD->getInstantiatedFromMemberTemplate();
131 Result = {
132 /*Template=*/TATD,
133 /*PrimaryTypeAliasDecl=*/TATD,
134 /*AssociatedTemplateArguments=*/CSC.template_arguments(),
136 while (Next) {
137 Result.PrimaryTypeAliasDecl = Next;
138 Next = Next->getInstantiatedFromMemberTemplate();
140 return Result;
142 return {};
145 // Check if we are currently inside of a lambda expression that is
146 // surrounded by a using alias declaration. e.g.
147 // template <class> using type = decltype([](auto) { ^ }());
148 // We have to do so since a TypeAliasTemplateDecl (or a TypeAliasDecl) is never
149 // a DeclContext, nor does it have an associated specialization Decl from which
150 // we could collect these template arguments.
151 bool isLambdaEnclosedByTypeAliasDecl(
152 const FunctionDecl *LambdaCallOperator,
153 const TypeAliasTemplateDecl *PrimaryTypeAliasDecl) {
154 struct Visitor : DynamicRecursiveASTVisitor {
155 Visitor(const FunctionDecl *CallOperator) : CallOperator(CallOperator) {}
156 bool VisitLambdaExpr(LambdaExpr *LE) override {
157 // Return true to bail out of the traversal, implying the Decl contains
158 // the lambda.
159 return getPrimaryTemplateOfGenericLambda(LE->getCallOperator()) !=
160 CallOperator;
162 const FunctionDecl *CallOperator;
165 QualType Underlying =
166 PrimaryTypeAliasDecl->getTemplatedDecl()->getUnderlyingType();
168 return !Visitor(getPrimaryTemplateOfGenericLambda(LambdaCallOperator))
169 .TraverseType(Underlying);
172 // Add template arguments from a variable template instantiation.
173 Response
174 HandleVarTemplateSpec(const VarTemplateSpecializationDecl *VarTemplSpec,
175 MultiLevelTemplateArgumentList &Result,
176 bool SkipForSpecialization) {
177 // For a class-scope explicit specialization, there are no template arguments
178 // at this level, but there may be enclosing template arguments.
179 if (VarTemplSpec->isClassScopeExplicitSpecialization())
180 return Response::DontClearRelativeToPrimaryNextDecl(VarTemplSpec);
182 // We're done when we hit an explicit specialization.
183 if (VarTemplSpec->getSpecializationKind() == TSK_ExplicitSpecialization &&
184 !isa<VarTemplatePartialSpecializationDecl>(VarTemplSpec))
185 return Response::Done();
187 // If this variable template specialization was instantiated from a
188 // specialized member that is a variable template, we're done.
189 assert(VarTemplSpec->getSpecializedTemplate() && "No variable template?");
190 llvm::PointerUnion<VarTemplateDecl *, VarTemplatePartialSpecializationDecl *>
191 Specialized = VarTemplSpec->getSpecializedTemplateOrPartial();
192 if (VarTemplatePartialSpecializationDecl *Partial =
193 Specialized.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
194 if (!SkipForSpecialization)
195 Result.addOuterTemplateArguments(
196 Partial, VarTemplSpec->getTemplateInstantiationArgs().asArray(),
197 /*Final=*/false);
198 if (Partial->isMemberSpecialization())
199 return Response::Done();
200 } else {
201 VarTemplateDecl *Tmpl = cast<VarTemplateDecl *>(Specialized);
202 if (!SkipForSpecialization)
203 Result.addOuterTemplateArguments(
204 Tmpl, VarTemplSpec->getTemplateInstantiationArgs().asArray(),
205 /*Final=*/false);
206 if (Tmpl->isMemberSpecialization())
207 return Response::Done();
209 return Response::DontClearRelativeToPrimaryNextDecl(VarTemplSpec);
212 // If we have a template template parameter with translation unit context,
213 // then we're performing substitution into a default template argument of
214 // this template template parameter before we've constructed the template
215 // that will own this template template parameter. In this case, we
216 // use empty template parameter lists for all of the outer templates
217 // to avoid performing any substitutions.
218 Response
219 HandleDefaultTempArgIntoTempTempParam(const TemplateTemplateParmDecl *TTP,
220 MultiLevelTemplateArgumentList &Result) {
221 for (unsigned I = 0, N = TTP->getDepth() + 1; I != N; ++I)
222 Result.addOuterTemplateArguments(std::nullopt);
223 return Response::Done();
226 Response HandlePartialClassTemplateSpec(
227 const ClassTemplatePartialSpecializationDecl *PartialClassTemplSpec,
228 MultiLevelTemplateArgumentList &Result, bool SkipForSpecialization) {
229 if (!SkipForSpecialization)
230 Result.addOuterRetainedLevels(PartialClassTemplSpec->getTemplateDepth());
231 return Response::Done();
234 // Add template arguments from a class template instantiation.
235 Response
236 HandleClassTemplateSpec(const ClassTemplateSpecializationDecl *ClassTemplSpec,
237 MultiLevelTemplateArgumentList &Result,
238 bool SkipForSpecialization) {
239 if (!ClassTemplSpec->isClassScopeExplicitSpecialization()) {
240 // We're done when we hit an explicit specialization.
241 if (ClassTemplSpec->getSpecializationKind() == TSK_ExplicitSpecialization &&
242 !isa<ClassTemplatePartialSpecializationDecl>(ClassTemplSpec))
243 return Response::Done();
245 if (!SkipForSpecialization)
246 Result.addOuterTemplateArguments(
247 const_cast<ClassTemplateSpecializationDecl *>(ClassTemplSpec),
248 ClassTemplSpec->getTemplateInstantiationArgs().asArray(),
249 /*Final=*/false);
251 // If this class template specialization was instantiated from a
252 // specialized member that is a class template, we're done.
253 assert(ClassTemplSpec->getSpecializedTemplate() && "No class template?");
254 if (ClassTemplSpec->getSpecializedTemplate()->isMemberSpecialization())
255 return Response::Done();
257 // If this was instantiated from a partial template specialization, we need
258 // to get the next level of declaration context from the partial
259 // specialization, as the ClassTemplateSpecializationDecl's
260 // DeclContext/LexicalDeclContext will be for the primary template.
261 if (auto *InstFromPartialTempl =
262 ClassTemplSpec->getSpecializedTemplateOrPartial()
263 .dyn_cast<ClassTemplatePartialSpecializationDecl *>())
264 return Response::ChangeDecl(
265 InstFromPartialTempl->getLexicalDeclContext());
267 return Response::UseNextDecl(ClassTemplSpec);
270 Response HandleFunction(Sema &SemaRef, const FunctionDecl *Function,
271 MultiLevelTemplateArgumentList &Result,
272 const FunctionDecl *Pattern, bool RelativeToPrimary,
273 bool ForConstraintInstantiation,
274 bool ForDefaultArgumentSubstitution) {
275 // Add template arguments from a function template specialization.
276 if (!RelativeToPrimary &&
277 Function->getTemplateSpecializationKindForInstantiation() ==
278 TSK_ExplicitSpecialization)
279 return Response::Done();
281 if (!RelativeToPrimary &&
282 Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) {
283 // This is an implicit instantiation of an explicit specialization. We
284 // don't get any template arguments from this function but might get
285 // some from an enclosing template.
286 return Response::UseNextDecl(Function);
287 } else if (const TemplateArgumentList *TemplateArgs =
288 Function->getTemplateSpecializationArgs()) {
289 // Add the template arguments for this specialization.
290 Result.addOuterTemplateArguments(const_cast<FunctionDecl *>(Function),
291 TemplateArgs->asArray(),
292 /*Final=*/false);
294 if (RelativeToPrimary &&
295 (Function->getTemplateSpecializationKind() ==
296 TSK_ExplicitSpecialization ||
297 (Function->getFriendObjectKind() &&
298 !Function->getPrimaryTemplate()->getFriendObjectKind())))
299 return Response::UseNextDecl(Function);
301 // If this function was instantiated from a specialized member that is
302 // a function template, we're done.
303 assert(Function->getPrimaryTemplate() && "No function template?");
304 if (!ForDefaultArgumentSubstitution &&
305 Function->getPrimaryTemplate()->isMemberSpecialization())
306 return Response::Done();
308 // If this function is a generic lambda specialization, we are done.
309 if (!ForConstraintInstantiation &&
310 isGenericLambdaCallOperatorOrStaticInvokerSpecialization(Function))
311 return Response::Done();
313 } else if (Function->getDescribedFunctionTemplate()) {
314 assert(
315 (ForConstraintInstantiation || Result.getNumSubstitutedLevels() == 0) &&
316 "Outer template not instantiated?");
318 // If this is a friend or local declaration and it declares an entity at
319 // namespace scope, take arguments from its lexical parent
320 // instead of its semantic parent, unless of course the pattern we're
321 // instantiating actually comes from the file's context!
322 if ((Function->getFriendObjectKind() || Function->isLocalExternDecl()) &&
323 Function->getNonTransparentDeclContext()->isFileContext() &&
324 (!Pattern || !Pattern->getLexicalDeclContext()->isFileContext())) {
325 return Response::ChangeDecl(Function->getLexicalDeclContext());
328 if (ForConstraintInstantiation && Function->getFriendObjectKind())
329 return Response::ChangeDecl(Function->getLexicalDeclContext());
330 return Response::UseNextDecl(Function);
333 Response HandleFunctionTemplateDecl(Sema &SemaRef,
334 const FunctionTemplateDecl *FTD,
335 MultiLevelTemplateArgumentList &Result) {
336 if (!isa<ClassTemplateSpecializationDecl>(FTD->getDeclContext())) {
337 Result.addOuterTemplateArguments(
338 const_cast<FunctionTemplateDecl *>(FTD),
339 const_cast<FunctionTemplateDecl *>(FTD)->getInjectedTemplateArgs(
340 SemaRef.Context),
341 /*Final=*/false);
343 NestedNameSpecifier *NNS = FTD->getTemplatedDecl()->getQualifier();
345 while (const Type *Ty = NNS ? NNS->getAsType() : nullptr) {
346 if (NNS->isInstantiationDependent()) {
347 if (const auto *TSTy = Ty->getAs<TemplateSpecializationType>()) {
348 ArrayRef<TemplateArgument> Arguments = TSTy->template_arguments();
349 // Prefer template arguments from the injected-class-type if possible.
350 // For example,
351 // ```cpp
352 // template <class... Pack> struct S {
353 // template <class T> void foo();
354 // };
355 // template <class... Pack> template <class T>
356 // ^^^^^^^^^^^^^ InjectedTemplateArgs
357 // They're of kind TemplateArgument::Pack, not of
358 // TemplateArgument::Type.
359 // void S<Pack...>::foo() {}
360 // ^^^^^^^
361 // TSTy->template_arguments() (which are of PackExpansionType)
362 // ```
363 // This meets the contract in
364 // TreeTransform::TryExpandParameterPacks that the template arguments
365 // for unexpanded parameters should be of a Pack kind.
366 if (TSTy->isCurrentInstantiation()) {
367 auto *RD = TSTy->getCanonicalTypeInternal()->getAsCXXRecordDecl();
368 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
369 Arguments = CTD->getInjectedTemplateArgs(SemaRef.Context);
370 else if (auto *Specialization =
371 dyn_cast<ClassTemplateSpecializationDecl>(RD))
372 Arguments =
373 Specialization->getTemplateInstantiationArgs().asArray();
375 Result.addOuterTemplateArguments(
376 TSTy->getTemplateName().getAsTemplateDecl(), Arguments,
377 /*Final=*/false);
381 NNS = NNS->getPrefix();
385 return Response::ChangeDecl(FTD->getLexicalDeclContext());
388 Response HandleRecordDecl(Sema &SemaRef, const CXXRecordDecl *Rec,
389 MultiLevelTemplateArgumentList &Result,
390 ASTContext &Context,
391 bool ForConstraintInstantiation) {
392 if (ClassTemplateDecl *ClassTemplate = Rec->getDescribedClassTemplate()) {
393 assert(
394 (ForConstraintInstantiation || Result.getNumSubstitutedLevels() == 0) &&
395 "Outer template not instantiated?");
396 if (ClassTemplate->isMemberSpecialization())
397 return Response::Done();
398 if (ForConstraintInstantiation)
399 Result.addOuterTemplateArguments(
400 const_cast<CXXRecordDecl *>(Rec),
401 ClassTemplate->getInjectedTemplateArgs(SemaRef.Context),
402 /*Final=*/false);
405 if (const MemberSpecializationInfo *MSInfo =
406 Rec->getMemberSpecializationInfo())
407 if (MSInfo->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
408 return Response::Done();
410 bool IsFriend = Rec->getFriendObjectKind() ||
411 (Rec->getDescribedClassTemplate() &&
412 Rec->getDescribedClassTemplate()->getFriendObjectKind());
413 if (ForConstraintInstantiation && IsFriend &&
414 Rec->getNonTransparentDeclContext()->isFileContext()) {
415 return Response::ChangeDecl(Rec->getLexicalDeclContext());
418 // This is to make sure we pick up the VarTemplateSpecializationDecl or the
419 // TypeAliasTemplateDecl that this lambda is defined inside of.
420 if (Rec->isLambda()) {
421 if (const Decl *LCD = Rec->getLambdaContextDecl())
422 return Response::ChangeDecl(LCD);
423 // Retrieve the template arguments for a using alias declaration.
424 // This is necessary for constraint checking, since we always keep
425 // constraints relative to the primary template.
426 if (auto TypeAlias = getEnclosingTypeAliasTemplateDecl(SemaRef);
427 ForConstraintInstantiation && TypeAlias) {
428 if (isLambdaEnclosedByTypeAliasDecl(Rec->getLambdaCallOperator(),
429 TypeAlias.PrimaryTypeAliasDecl)) {
430 Result.addOuterTemplateArguments(TypeAlias.Template,
431 TypeAlias.AssociatedTemplateArguments,
432 /*Final=*/false);
433 // Visit the parent of the current type alias declaration rather than
434 // the lambda thereof.
435 // E.g., in the following example:
436 // struct S {
437 // template <class> using T = decltype([]<Concept> {} ());
438 // };
439 // void foo() {
440 // S::T var;
441 // }
442 // The instantiated lambda expression (which we're visiting at 'var')
443 // has a function DeclContext 'foo' rather than the Record DeclContext
444 // S. This seems to be an oversight to me that we may want to set a
445 // Sema Context from the CXXScopeSpec before substituting into T.
446 return Response::ChangeDecl(TypeAlias.Template->getDeclContext());
451 return Response::UseNextDecl(Rec);
454 Response HandleImplicitConceptSpecializationDecl(
455 const ImplicitConceptSpecializationDecl *CSD,
456 MultiLevelTemplateArgumentList &Result) {
457 Result.addOuterTemplateArguments(
458 const_cast<ImplicitConceptSpecializationDecl *>(CSD),
459 CSD->getTemplateArguments(),
460 /*Final=*/false);
461 return Response::UseNextDecl(CSD);
464 Response HandleGenericDeclContext(const Decl *CurDecl) {
465 return Response::UseNextDecl(CurDecl);
467 } // namespace TemplateInstArgsHelpers
468 } // namespace
470 MultiLevelTemplateArgumentList Sema::getTemplateInstantiationArgs(
471 const NamedDecl *ND, const DeclContext *DC, bool Final,
472 std::optional<ArrayRef<TemplateArgument>> Innermost, bool RelativeToPrimary,
473 const FunctionDecl *Pattern, bool ForConstraintInstantiation,
474 bool SkipForSpecialization, bool ForDefaultArgumentSubstitution) {
475 assert((ND || DC) && "Can't find arguments for a decl if one isn't provided");
476 // Accumulate the set of template argument lists in this structure.
477 MultiLevelTemplateArgumentList Result;
479 using namespace TemplateInstArgsHelpers;
480 const Decl *CurDecl = ND;
482 if (!CurDecl)
483 CurDecl = Decl::castFromDeclContext(DC);
485 if (Innermost) {
486 Result.addOuterTemplateArguments(const_cast<NamedDecl *>(ND), *Innermost,
487 Final);
488 // Populate placeholder template arguments for TemplateTemplateParmDecls.
489 // This is essential for the case e.g.
491 // template <class> concept Concept = false;
492 // template <template <Concept C> class T> void foo(T<int>)
494 // where parameter C has a depth of 1 but the substituting argument `int`
495 // has a depth of 0.
496 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(CurDecl))
497 HandleDefaultTempArgIntoTempTempParam(TTP, Result);
498 CurDecl = Response::UseNextDecl(CurDecl).NextDecl;
501 while (!CurDecl->isFileContextDecl()) {
502 Response R;
503 if (const auto *VarTemplSpec =
504 dyn_cast<VarTemplateSpecializationDecl>(CurDecl)) {
505 R = HandleVarTemplateSpec(VarTemplSpec, Result, SkipForSpecialization);
506 } else if (const auto *PartialClassTemplSpec =
507 dyn_cast<ClassTemplatePartialSpecializationDecl>(CurDecl)) {
508 R = HandlePartialClassTemplateSpec(PartialClassTemplSpec, Result,
509 SkipForSpecialization);
510 } else if (const auto *ClassTemplSpec =
511 dyn_cast<ClassTemplateSpecializationDecl>(CurDecl)) {
512 R = HandleClassTemplateSpec(ClassTemplSpec, Result,
513 SkipForSpecialization);
514 } else if (const auto *Function = dyn_cast<FunctionDecl>(CurDecl)) {
515 R = HandleFunction(*this, Function, Result, Pattern, RelativeToPrimary,
516 ForConstraintInstantiation,
517 ForDefaultArgumentSubstitution);
518 } else if (const auto *Rec = dyn_cast<CXXRecordDecl>(CurDecl)) {
519 R = HandleRecordDecl(*this, Rec, Result, Context,
520 ForConstraintInstantiation);
521 } else if (const auto *CSD =
522 dyn_cast<ImplicitConceptSpecializationDecl>(CurDecl)) {
523 R = HandleImplicitConceptSpecializationDecl(CSD, Result);
524 } else if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(CurDecl)) {
525 R = HandleFunctionTemplateDecl(*this, FTD, Result);
526 } else if (const auto *CTD = dyn_cast<ClassTemplateDecl>(CurDecl)) {
527 R = Response::ChangeDecl(CTD->getLexicalDeclContext());
528 } else if (!isa<DeclContext>(CurDecl)) {
529 R = Response::DontClearRelativeToPrimaryNextDecl(CurDecl);
530 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(CurDecl)) {
531 R = HandleDefaultTempArgIntoTempTempParam(TTP, Result);
533 } else {
534 R = HandleGenericDeclContext(CurDecl);
537 if (R.IsDone)
538 return Result;
539 if (R.ClearRelativeToPrimary)
540 RelativeToPrimary = false;
541 assert(R.NextDecl);
542 CurDecl = R.NextDecl;
545 return Result;
548 bool Sema::CodeSynthesisContext::isInstantiationRecord() const {
549 switch (Kind) {
550 case TemplateInstantiation:
551 case ExceptionSpecInstantiation:
552 case DefaultTemplateArgumentInstantiation:
553 case DefaultFunctionArgumentInstantiation:
554 case ExplicitTemplateArgumentSubstitution:
555 case DeducedTemplateArgumentSubstitution:
556 case PriorTemplateArgumentSubstitution:
557 case ConstraintsCheck:
558 case NestedRequirementConstraintsCheck:
559 return true;
561 case RequirementInstantiation:
562 case RequirementParameterInstantiation:
563 case DefaultTemplateArgumentChecking:
564 case DeclaringSpecialMember:
565 case DeclaringImplicitEqualityComparison:
566 case DefiningSynthesizedFunction:
567 case ExceptionSpecEvaluation:
568 case ConstraintSubstitution:
569 case ParameterMappingSubstitution:
570 case ConstraintNormalization:
571 case RewritingOperatorAsSpaceship:
572 case InitializingStructuredBinding:
573 case MarkingClassDllexported:
574 case BuildingBuiltinDumpStructCall:
575 case LambdaExpressionSubstitution:
576 case BuildingDeductionGuides:
577 case TypeAliasTemplateInstantiation:
578 return false;
580 // This function should never be called when Kind's value is Memoization.
581 case Memoization:
582 break;
585 llvm_unreachable("Invalid SynthesisKind!");
588 Sema::InstantiatingTemplate::InstantiatingTemplate(
589 Sema &SemaRef, CodeSynthesisContext::SynthesisKind Kind,
590 SourceLocation PointOfInstantiation, SourceRange InstantiationRange,
591 Decl *Entity, NamedDecl *Template, ArrayRef<TemplateArgument> TemplateArgs,
592 sema::TemplateDeductionInfo *DeductionInfo)
593 : SemaRef(SemaRef) {
594 // Don't allow further instantiation if a fatal error and an uncompilable
595 // error have occurred. Any diagnostics we might have raised will not be
596 // visible, and we do not need to construct a correct AST.
597 if (SemaRef.Diags.hasFatalErrorOccurred() &&
598 SemaRef.hasUncompilableErrorOccurred()) {
599 Invalid = true;
600 return;
602 Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
603 if (!Invalid) {
604 CodeSynthesisContext Inst;
605 Inst.Kind = Kind;
606 Inst.PointOfInstantiation = PointOfInstantiation;
607 Inst.Entity = Entity;
608 Inst.Template = Template;
609 Inst.TemplateArgs = TemplateArgs.data();
610 Inst.NumTemplateArgs = TemplateArgs.size();
611 Inst.DeductionInfo = DeductionInfo;
612 Inst.InstantiationRange = InstantiationRange;
613 SemaRef.pushCodeSynthesisContext(Inst);
615 AlreadyInstantiating = !Inst.Entity ? false :
616 !SemaRef.InstantiatingSpecializations
617 .insert({Inst.Entity->getCanonicalDecl(), Inst.Kind})
618 .second;
619 atTemplateBegin(SemaRef.TemplateInstCallbacks, SemaRef, Inst);
623 Sema::InstantiatingTemplate::InstantiatingTemplate(
624 Sema &SemaRef, SourceLocation PointOfInstantiation, Decl *Entity,
625 SourceRange InstantiationRange)
626 : InstantiatingTemplate(SemaRef,
627 CodeSynthesisContext::TemplateInstantiation,
628 PointOfInstantiation, InstantiationRange, Entity) {}
630 Sema::InstantiatingTemplate::InstantiatingTemplate(
631 Sema &SemaRef, SourceLocation PointOfInstantiation, FunctionDecl *Entity,
632 ExceptionSpecification, SourceRange InstantiationRange)
633 : InstantiatingTemplate(
634 SemaRef, CodeSynthesisContext::ExceptionSpecInstantiation,
635 PointOfInstantiation, InstantiationRange, Entity) {}
637 Sema::InstantiatingTemplate::InstantiatingTemplate(
638 Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateParameter Param,
639 TemplateDecl *Template, ArrayRef<TemplateArgument> TemplateArgs,
640 SourceRange InstantiationRange)
641 : InstantiatingTemplate(
642 SemaRef,
643 CodeSynthesisContext::DefaultTemplateArgumentInstantiation,
644 PointOfInstantiation, InstantiationRange, getAsNamedDecl(Param),
645 Template, TemplateArgs) {}
647 Sema::InstantiatingTemplate::InstantiatingTemplate(
648 Sema &SemaRef, SourceLocation PointOfInstantiation,
649 FunctionTemplateDecl *FunctionTemplate,
650 ArrayRef<TemplateArgument> TemplateArgs,
651 CodeSynthesisContext::SynthesisKind Kind,
652 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
653 : InstantiatingTemplate(SemaRef, Kind, PointOfInstantiation,
654 InstantiationRange, FunctionTemplate, nullptr,
655 TemplateArgs, &DeductionInfo) {
656 assert(Kind == CodeSynthesisContext::ExplicitTemplateArgumentSubstitution ||
657 Kind == CodeSynthesisContext::DeducedTemplateArgumentSubstitution ||
658 Kind == CodeSynthesisContext::BuildingDeductionGuides);
661 Sema::InstantiatingTemplate::InstantiatingTemplate(
662 Sema &SemaRef, SourceLocation PointOfInstantiation,
663 TemplateDecl *Template,
664 ArrayRef<TemplateArgument> TemplateArgs,
665 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
666 : InstantiatingTemplate(
667 SemaRef,
668 CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
669 PointOfInstantiation, InstantiationRange, Template, nullptr,
670 TemplateArgs, &DeductionInfo) {}
672 Sema::InstantiatingTemplate::InstantiatingTemplate(
673 Sema &SemaRef, SourceLocation PointOfInstantiation,
674 ClassTemplatePartialSpecializationDecl *PartialSpec,
675 ArrayRef<TemplateArgument> TemplateArgs,
676 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
677 : InstantiatingTemplate(
678 SemaRef,
679 CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
680 PointOfInstantiation, InstantiationRange, PartialSpec, nullptr,
681 TemplateArgs, &DeductionInfo) {}
683 Sema::InstantiatingTemplate::InstantiatingTemplate(
684 Sema &SemaRef, SourceLocation PointOfInstantiation,
685 VarTemplatePartialSpecializationDecl *PartialSpec,
686 ArrayRef<TemplateArgument> TemplateArgs,
687 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
688 : InstantiatingTemplate(
689 SemaRef,
690 CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
691 PointOfInstantiation, InstantiationRange, PartialSpec, nullptr,
692 TemplateArgs, &DeductionInfo) {}
694 Sema::InstantiatingTemplate::InstantiatingTemplate(
695 Sema &SemaRef, SourceLocation PointOfInstantiation, ParmVarDecl *Param,
696 ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange)
697 : InstantiatingTemplate(
698 SemaRef,
699 CodeSynthesisContext::DefaultFunctionArgumentInstantiation,
700 PointOfInstantiation, InstantiationRange, Param, nullptr,
701 TemplateArgs) {}
703 Sema::InstantiatingTemplate::InstantiatingTemplate(
704 Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template,
705 NonTypeTemplateParmDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
706 SourceRange InstantiationRange)
707 : InstantiatingTemplate(
708 SemaRef,
709 CodeSynthesisContext::PriorTemplateArgumentSubstitution,
710 PointOfInstantiation, InstantiationRange, Param, Template,
711 TemplateArgs) {}
713 Sema::InstantiatingTemplate::InstantiatingTemplate(
714 Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template,
715 TemplateTemplateParmDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
716 SourceRange InstantiationRange)
717 : InstantiatingTemplate(
718 SemaRef,
719 CodeSynthesisContext::PriorTemplateArgumentSubstitution,
720 PointOfInstantiation, InstantiationRange, Param, Template,
721 TemplateArgs) {}
723 Sema::InstantiatingTemplate::InstantiatingTemplate(
724 Sema &SemaRef, SourceLocation PointOfInstantiation,
725 TypeAliasTemplateDecl *Entity, ArrayRef<TemplateArgument> TemplateArgs,
726 SourceRange InstantiationRange)
727 : InstantiatingTemplate(
728 SemaRef, CodeSynthesisContext::TypeAliasTemplateInstantiation,
729 PointOfInstantiation, InstantiationRange, /*Entity=*/Entity,
730 /*Template=*/nullptr, TemplateArgs) {}
732 Sema::InstantiatingTemplate::InstantiatingTemplate(
733 Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Template,
734 NamedDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
735 SourceRange InstantiationRange)
736 : InstantiatingTemplate(
737 SemaRef, CodeSynthesisContext::DefaultTemplateArgumentChecking,
738 PointOfInstantiation, InstantiationRange, Param, Template,
739 TemplateArgs) {}
741 Sema::InstantiatingTemplate::InstantiatingTemplate(
742 Sema &SemaRef, SourceLocation PointOfInstantiation,
743 concepts::Requirement *Req, sema::TemplateDeductionInfo &DeductionInfo,
744 SourceRange InstantiationRange)
745 : InstantiatingTemplate(
746 SemaRef, CodeSynthesisContext::RequirementInstantiation,
747 PointOfInstantiation, InstantiationRange, /*Entity=*/nullptr,
748 /*Template=*/nullptr, /*TemplateArgs=*/{}, &DeductionInfo) {}
750 Sema::InstantiatingTemplate::InstantiatingTemplate(
751 Sema &SemaRef, SourceLocation PointOfInstantiation,
752 concepts::NestedRequirement *Req, ConstraintsCheck,
753 SourceRange InstantiationRange)
754 : InstantiatingTemplate(
755 SemaRef, CodeSynthesisContext::NestedRequirementConstraintsCheck,
756 PointOfInstantiation, InstantiationRange, /*Entity=*/nullptr,
757 /*Template=*/nullptr, /*TemplateArgs=*/{}) {}
759 Sema::InstantiatingTemplate::InstantiatingTemplate(
760 Sema &SemaRef, SourceLocation PointOfInstantiation, const RequiresExpr *RE,
761 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
762 : InstantiatingTemplate(
763 SemaRef, CodeSynthesisContext::RequirementParameterInstantiation,
764 PointOfInstantiation, InstantiationRange, /*Entity=*/nullptr,
765 /*Template=*/nullptr, /*TemplateArgs=*/{}, &DeductionInfo) {}
767 Sema::InstantiatingTemplate::InstantiatingTemplate(
768 Sema &SemaRef, SourceLocation PointOfInstantiation,
769 ConstraintsCheck, NamedDecl *Template,
770 ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange)
771 : InstantiatingTemplate(
772 SemaRef, CodeSynthesisContext::ConstraintsCheck,
773 PointOfInstantiation, InstantiationRange, Template, nullptr,
774 TemplateArgs) {}
776 Sema::InstantiatingTemplate::InstantiatingTemplate(
777 Sema &SemaRef, SourceLocation PointOfInstantiation,
778 ConstraintSubstitution, NamedDecl *Template,
779 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
780 : InstantiatingTemplate(
781 SemaRef, CodeSynthesisContext::ConstraintSubstitution,
782 PointOfInstantiation, InstantiationRange, Template, nullptr,
783 {}, &DeductionInfo) {}
785 Sema::InstantiatingTemplate::InstantiatingTemplate(
786 Sema &SemaRef, SourceLocation PointOfInstantiation,
787 ConstraintNormalization, NamedDecl *Template,
788 SourceRange InstantiationRange)
789 : InstantiatingTemplate(
790 SemaRef, CodeSynthesisContext::ConstraintNormalization,
791 PointOfInstantiation, InstantiationRange, Template) {}
793 Sema::InstantiatingTemplate::InstantiatingTemplate(
794 Sema &SemaRef, SourceLocation PointOfInstantiation,
795 ParameterMappingSubstitution, NamedDecl *Template,
796 SourceRange InstantiationRange)
797 : InstantiatingTemplate(
798 SemaRef, CodeSynthesisContext::ParameterMappingSubstitution,
799 PointOfInstantiation, InstantiationRange, Template) {}
801 Sema::InstantiatingTemplate::InstantiatingTemplate(
802 Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Entity,
803 BuildingDeductionGuidesTag, SourceRange InstantiationRange)
804 : InstantiatingTemplate(
805 SemaRef, CodeSynthesisContext::BuildingDeductionGuides,
806 PointOfInstantiation, InstantiationRange, Entity) {}
809 void Sema::pushCodeSynthesisContext(CodeSynthesisContext Ctx) {
810 Ctx.SavedInNonInstantiationSFINAEContext = InNonInstantiationSFINAEContext;
811 InNonInstantiationSFINAEContext = false;
813 CodeSynthesisContexts.push_back(Ctx);
815 if (!Ctx.isInstantiationRecord())
816 ++NonInstantiationEntries;
818 // Check to see if we're low on stack space. We can't do anything about this
819 // from here, but we can at least warn the user.
820 StackHandler.warnOnStackNearlyExhausted(Ctx.PointOfInstantiation);
823 void Sema::popCodeSynthesisContext() {
824 auto &Active = CodeSynthesisContexts.back();
825 if (!Active.isInstantiationRecord()) {
826 assert(NonInstantiationEntries > 0);
827 --NonInstantiationEntries;
830 InNonInstantiationSFINAEContext = Active.SavedInNonInstantiationSFINAEContext;
832 // Name lookup no longer looks in this template's defining module.
833 assert(CodeSynthesisContexts.size() >=
834 CodeSynthesisContextLookupModules.size() &&
835 "forgot to remove a lookup module for a template instantiation");
836 if (CodeSynthesisContexts.size() ==
837 CodeSynthesisContextLookupModules.size()) {
838 if (Module *M = CodeSynthesisContextLookupModules.back())
839 LookupModulesCache.erase(M);
840 CodeSynthesisContextLookupModules.pop_back();
843 // If we've left the code synthesis context for the current context stack,
844 // stop remembering that we've emitted that stack.
845 if (CodeSynthesisContexts.size() ==
846 LastEmittedCodeSynthesisContextDepth)
847 LastEmittedCodeSynthesisContextDepth = 0;
849 CodeSynthesisContexts.pop_back();
852 void Sema::InstantiatingTemplate::Clear() {
853 if (!Invalid) {
854 if (!AlreadyInstantiating) {
855 auto &Active = SemaRef.CodeSynthesisContexts.back();
856 if (Active.Entity)
857 SemaRef.InstantiatingSpecializations.erase(
858 {Active.Entity->getCanonicalDecl(), Active.Kind});
861 atTemplateEnd(SemaRef.TemplateInstCallbacks, SemaRef,
862 SemaRef.CodeSynthesisContexts.back());
864 SemaRef.popCodeSynthesisContext();
865 Invalid = true;
869 static std::string convertCallArgsToString(Sema &S,
870 llvm::ArrayRef<const Expr *> Args) {
871 std::string Result;
872 llvm::raw_string_ostream OS(Result);
873 llvm::ListSeparator Comma;
874 for (const Expr *Arg : Args) {
875 OS << Comma;
876 Arg->IgnoreParens()->printPretty(OS, nullptr,
877 S.Context.getPrintingPolicy());
879 return Result;
882 bool Sema::InstantiatingTemplate::CheckInstantiationDepth(
883 SourceLocation PointOfInstantiation,
884 SourceRange InstantiationRange) {
885 assert(SemaRef.NonInstantiationEntries <=
886 SemaRef.CodeSynthesisContexts.size());
887 if ((SemaRef.CodeSynthesisContexts.size() -
888 SemaRef.NonInstantiationEntries)
889 <= SemaRef.getLangOpts().InstantiationDepth)
890 return false;
892 SemaRef.Diag(PointOfInstantiation,
893 diag::err_template_recursion_depth_exceeded)
894 << SemaRef.getLangOpts().InstantiationDepth
895 << InstantiationRange;
896 SemaRef.Diag(PointOfInstantiation, diag::note_template_recursion_depth)
897 << SemaRef.getLangOpts().InstantiationDepth;
898 return true;
901 void Sema::PrintInstantiationStack() {
902 // Determine which template instantiations to skip, if any.
903 unsigned SkipStart = CodeSynthesisContexts.size(), SkipEnd = SkipStart;
904 unsigned Limit = Diags.getTemplateBacktraceLimit();
905 if (Limit && Limit < CodeSynthesisContexts.size()) {
906 SkipStart = Limit / 2 + Limit % 2;
907 SkipEnd = CodeSynthesisContexts.size() - Limit / 2;
910 // FIXME: In all of these cases, we need to show the template arguments
911 unsigned InstantiationIdx = 0;
912 for (SmallVectorImpl<CodeSynthesisContext>::reverse_iterator
913 Active = CodeSynthesisContexts.rbegin(),
914 ActiveEnd = CodeSynthesisContexts.rend();
915 Active != ActiveEnd;
916 ++Active, ++InstantiationIdx) {
917 // Skip this instantiation?
918 if (InstantiationIdx >= SkipStart && InstantiationIdx < SkipEnd) {
919 if (InstantiationIdx == SkipStart) {
920 // Note that we're skipping instantiations.
921 Diags.Report(Active->PointOfInstantiation,
922 diag::note_instantiation_contexts_suppressed)
923 << unsigned(CodeSynthesisContexts.size() - Limit);
925 continue;
928 switch (Active->Kind) {
929 case CodeSynthesisContext::TemplateInstantiation: {
930 Decl *D = Active->Entity;
931 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
932 unsigned DiagID = diag::note_template_member_class_here;
933 if (isa<ClassTemplateSpecializationDecl>(Record))
934 DiagID = diag::note_template_class_instantiation_here;
935 Diags.Report(Active->PointOfInstantiation, DiagID)
936 << Record << Active->InstantiationRange;
937 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
938 unsigned DiagID;
939 if (Function->getPrimaryTemplate())
940 DiagID = diag::note_function_template_spec_here;
941 else
942 DiagID = diag::note_template_member_function_here;
943 Diags.Report(Active->PointOfInstantiation, DiagID)
944 << Function
945 << Active->InstantiationRange;
946 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
947 Diags.Report(Active->PointOfInstantiation,
948 VD->isStaticDataMember()?
949 diag::note_template_static_data_member_def_here
950 : diag::note_template_variable_def_here)
951 << VD
952 << Active->InstantiationRange;
953 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
954 Diags.Report(Active->PointOfInstantiation,
955 diag::note_template_enum_def_here)
956 << ED
957 << Active->InstantiationRange;
958 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
959 Diags.Report(Active->PointOfInstantiation,
960 diag::note_template_nsdmi_here)
961 << FD << Active->InstantiationRange;
962 } else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(D)) {
963 Diags.Report(Active->PointOfInstantiation,
964 diag::note_template_class_instantiation_here)
965 << CTD << Active->InstantiationRange;
967 break;
970 case CodeSynthesisContext::DefaultTemplateArgumentInstantiation: {
971 TemplateDecl *Template = cast<TemplateDecl>(Active->Template);
972 SmallString<128> TemplateArgsStr;
973 llvm::raw_svector_ostream OS(TemplateArgsStr);
974 Template->printName(OS, getPrintingPolicy());
975 printTemplateArgumentList(OS, Active->template_arguments(),
976 getPrintingPolicy());
977 Diags.Report(Active->PointOfInstantiation,
978 diag::note_default_arg_instantiation_here)
979 << OS.str()
980 << Active->InstantiationRange;
981 break;
984 case CodeSynthesisContext::ExplicitTemplateArgumentSubstitution: {
985 FunctionTemplateDecl *FnTmpl = cast<FunctionTemplateDecl>(Active->Entity);
986 Diags.Report(Active->PointOfInstantiation,
987 diag::note_explicit_template_arg_substitution_here)
988 << FnTmpl
989 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
990 Active->TemplateArgs,
991 Active->NumTemplateArgs)
992 << Active->InstantiationRange;
993 break;
996 case CodeSynthesisContext::DeducedTemplateArgumentSubstitution: {
997 if (FunctionTemplateDecl *FnTmpl =
998 dyn_cast<FunctionTemplateDecl>(Active->Entity)) {
999 Diags.Report(Active->PointOfInstantiation,
1000 diag::note_function_template_deduction_instantiation_here)
1001 << FnTmpl
1002 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
1003 Active->TemplateArgs,
1004 Active->NumTemplateArgs)
1005 << Active->InstantiationRange;
1006 } else {
1007 bool IsVar = isa<VarTemplateDecl>(Active->Entity) ||
1008 isa<VarTemplateSpecializationDecl>(Active->Entity);
1009 bool IsTemplate = false;
1010 TemplateParameterList *Params;
1011 if (auto *D = dyn_cast<TemplateDecl>(Active->Entity)) {
1012 IsTemplate = true;
1013 Params = D->getTemplateParameters();
1014 } else if (auto *D = dyn_cast<ClassTemplatePartialSpecializationDecl>(
1015 Active->Entity)) {
1016 Params = D->getTemplateParameters();
1017 } else if (auto *D = dyn_cast<VarTemplatePartialSpecializationDecl>(
1018 Active->Entity)) {
1019 Params = D->getTemplateParameters();
1020 } else {
1021 llvm_unreachable("unexpected template kind");
1024 Diags.Report(Active->PointOfInstantiation,
1025 diag::note_deduced_template_arg_substitution_here)
1026 << IsVar << IsTemplate << cast<NamedDecl>(Active->Entity)
1027 << getTemplateArgumentBindingsText(Params, Active->TemplateArgs,
1028 Active->NumTemplateArgs)
1029 << Active->InstantiationRange;
1031 break;
1034 case CodeSynthesisContext::DefaultFunctionArgumentInstantiation: {
1035 ParmVarDecl *Param = cast<ParmVarDecl>(Active->Entity);
1036 FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());
1038 SmallString<128> TemplateArgsStr;
1039 llvm::raw_svector_ostream OS(TemplateArgsStr);
1040 FD->printName(OS, getPrintingPolicy());
1041 printTemplateArgumentList(OS, Active->template_arguments(),
1042 getPrintingPolicy());
1043 Diags.Report(Active->PointOfInstantiation,
1044 diag::note_default_function_arg_instantiation_here)
1045 << OS.str()
1046 << Active->InstantiationRange;
1047 break;
1050 case CodeSynthesisContext::PriorTemplateArgumentSubstitution: {
1051 NamedDecl *Parm = cast<NamedDecl>(Active->Entity);
1052 std::string Name;
1053 if (!Parm->getName().empty())
1054 Name = std::string(" '") + Parm->getName().str() + "'";
1056 TemplateParameterList *TemplateParams = nullptr;
1057 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
1058 TemplateParams = Template->getTemplateParameters();
1059 else
1060 TemplateParams =
1061 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
1062 ->getTemplateParameters();
1063 Diags.Report(Active->PointOfInstantiation,
1064 diag::note_prior_template_arg_substitution)
1065 << isa<TemplateTemplateParmDecl>(Parm)
1066 << Name
1067 << getTemplateArgumentBindingsText(TemplateParams,
1068 Active->TemplateArgs,
1069 Active->NumTemplateArgs)
1070 << Active->InstantiationRange;
1071 break;
1074 case CodeSynthesisContext::DefaultTemplateArgumentChecking: {
1075 TemplateParameterList *TemplateParams = nullptr;
1076 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
1077 TemplateParams = Template->getTemplateParameters();
1078 else
1079 TemplateParams =
1080 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
1081 ->getTemplateParameters();
1083 Diags.Report(Active->PointOfInstantiation,
1084 diag::note_template_default_arg_checking)
1085 << getTemplateArgumentBindingsText(TemplateParams,
1086 Active->TemplateArgs,
1087 Active->NumTemplateArgs)
1088 << Active->InstantiationRange;
1089 break;
1092 case CodeSynthesisContext::ExceptionSpecEvaluation:
1093 Diags.Report(Active->PointOfInstantiation,
1094 diag::note_evaluating_exception_spec_here)
1095 << cast<FunctionDecl>(Active->Entity);
1096 break;
1098 case CodeSynthesisContext::ExceptionSpecInstantiation:
1099 Diags.Report(Active->PointOfInstantiation,
1100 diag::note_template_exception_spec_instantiation_here)
1101 << cast<FunctionDecl>(Active->Entity)
1102 << Active->InstantiationRange;
1103 break;
1105 case CodeSynthesisContext::RequirementInstantiation:
1106 Diags.Report(Active->PointOfInstantiation,
1107 diag::note_template_requirement_instantiation_here)
1108 << Active->InstantiationRange;
1109 break;
1110 case CodeSynthesisContext::RequirementParameterInstantiation:
1111 Diags.Report(Active->PointOfInstantiation,
1112 diag::note_template_requirement_params_instantiation_here)
1113 << Active->InstantiationRange;
1114 break;
1116 case CodeSynthesisContext::NestedRequirementConstraintsCheck:
1117 Diags.Report(Active->PointOfInstantiation,
1118 diag::note_nested_requirement_here)
1119 << Active->InstantiationRange;
1120 break;
1122 case CodeSynthesisContext::DeclaringSpecialMember:
1123 Diags.Report(Active->PointOfInstantiation,
1124 diag::note_in_declaration_of_implicit_special_member)
1125 << cast<CXXRecordDecl>(Active->Entity)
1126 << llvm::to_underlying(Active->SpecialMember);
1127 break;
1129 case CodeSynthesisContext::DeclaringImplicitEqualityComparison:
1130 Diags.Report(Active->Entity->getLocation(),
1131 diag::note_in_declaration_of_implicit_equality_comparison);
1132 break;
1134 case CodeSynthesisContext::DefiningSynthesizedFunction: {
1135 // FIXME: For synthesized functions that are not defaulted,
1136 // produce a note.
1137 auto *FD = dyn_cast<FunctionDecl>(Active->Entity);
1138 DefaultedFunctionKind DFK =
1139 FD ? getDefaultedFunctionKind(FD) : DefaultedFunctionKind();
1140 if (DFK.isSpecialMember()) {
1141 auto *MD = cast<CXXMethodDecl>(FD);
1142 Diags.Report(Active->PointOfInstantiation,
1143 diag::note_member_synthesized_at)
1144 << MD->isExplicitlyDefaulted()
1145 << llvm::to_underlying(DFK.asSpecialMember())
1146 << Context.getTagDeclType(MD->getParent());
1147 } else if (DFK.isComparison()) {
1148 QualType RecordType = FD->getParamDecl(0)
1149 ->getType()
1150 .getNonReferenceType()
1151 .getUnqualifiedType();
1152 Diags.Report(Active->PointOfInstantiation,
1153 diag::note_comparison_synthesized_at)
1154 << (int)DFK.asComparison() << RecordType;
1156 break;
1159 case CodeSynthesisContext::RewritingOperatorAsSpaceship:
1160 Diags.Report(Active->Entity->getLocation(),
1161 diag::note_rewriting_operator_as_spaceship);
1162 break;
1164 case CodeSynthesisContext::InitializingStructuredBinding:
1165 Diags.Report(Active->PointOfInstantiation,
1166 diag::note_in_binding_decl_init)
1167 << cast<BindingDecl>(Active->Entity);
1168 break;
1170 case CodeSynthesisContext::MarkingClassDllexported:
1171 Diags.Report(Active->PointOfInstantiation,
1172 diag::note_due_to_dllexported_class)
1173 << cast<CXXRecordDecl>(Active->Entity) << !getLangOpts().CPlusPlus11;
1174 break;
1176 case CodeSynthesisContext::BuildingBuiltinDumpStructCall:
1177 Diags.Report(Active->PointOfInstantiation,
1178 diag::note_building_builtin_dump_struct_call)
1179 << convertCallArgsToString(
1180 *this, llvm::ArrayRef(Active->CallArgs, Active->NumCallArgs));
1181 break;
1183 case CodeSynthesisContext::Memoization:
1184 break;
1186 case CodeSynthesisContext::LambdaExpressionSubstitution:
1187 Diags.Report(Active->PointOfInstantiation,
1188 diag::note_lambda_substitution_here);
1189 break;
1190 case CodeSynthesisContext::ConstraintsCheck: {
1191 unsigned DiagID = 0;
1192 if (!Active->Entity) {
1193 Diags.Report(Active->PointOfInstantiation,
1194 diag::note_nested_requirement_here)
1195 << Active->InstantiationRange;
1196 break;
1198 if (isa<ConceptDecl>(Active->Entity))
1199 DiagID = diag::note_concept_specialization_here;
1200 else if (isa<TemplateDecl>(Active->Entity))
1201 DiagID = diag::note_checking_constraints_for_template_id_here;
1202 else if (isa<VarTemplatePartialSpecializationDecl>(Active->Entity))
1203 DiagID = diag::note_checking_constraints_for_var_spec_id_here;
1204 else if (isa<ClassTemplatePartialSpecializationDecl>(Active->Entity))
1205 DiagID = diag::note_checking_constraints_for_class_spec_id_here;
1206 else {
1207 assert(isa<FunctionDecl>(Active->Entity));
1208 DiagID = diag::note_checking_constraints_for_function_here;
1210 SmallString<128> TemplateArgsStr;
1211 llvm::raw_svector_ostream OS(TemplateArgsStr);
1212 cast<NamedDecl>(Active->Entity)->printName(OS, getPrintingPolicy());
1213 if (!isa<FunctionDecl>(Active->Entity)) {
1214 printTemplateArgumentList(OS, Active->template_arguments(),
1215 getPrintingPolicy());
1217 Diags.Report(Active->PointOfInstantiation, DiagID) << OS.str()
1218 << Active->InstantiationRange;
1219 break;
1221 case CodeSynthesisContext::ConstraintSubstitution:
1222 Diags.Report(Active->PointOfInstantiation,
1223 diag::note_constraint_substitution_here)
1224 << Active->InstantiationRange;
1225 break;
1226 case CodeSynthesisContext::ConstraintNormalization:
1227 Diags.Report(Active->PointOfInstantiation,
1228 diag::note_constraint_normalization_here)
1229 << cast<NamedDecl>(Active->Entity) << Active->InstantiationRange;
1230 break;
1231 case CodeSynthesisContext::ParameterMappingSubstitution:
1232 Diags.Report(Active->PointOfInstantiation,
1233 diag::note_parameter_mapping_substitution_here)
1234 << Active->InstantiationRange;
1235 break;
1236 case CodeSynthesisContext::BuildingDeductionGuides:
1237 Diags.Report(Active->PointOfInstantiation,
1238 diag::note_building_deduction_guide_here);
1239 break;
1240 case CodeSynthesisContext::TypeAliasTemplateInstantiation:
1241 Diags.Report(Active->PointOfInstantiation,
1242 diag::note_template_type_alias_instantiation_here)
1243 << cast<TypeAliasTemplateDecl>(Active->Entity)
1244 << Active->InstantiationRange;
1245 break;
1250 std::optional<TemplateDeductionInfo *> Sema::isSFINAEContext() const {
1251 if (InNonInstantiationSFINAEContext)
1252 return std::optional<TemplateDeductionInfo *>(nullptr);
1254 for (SmallVectorImpl<CodeSynthesisContext>::const_reverse_iterator
1255 Active = CodeSynthesisContexts.rbegin(),
1256 ActiveEnd = CodeSynthesisContexts.rend();
1257 Active != ActiveEnd;
1258 ++Active)
1260 switch (Active->Kind) {
1261 case CodeSynthesisContext::TypeAliasTemplateInstantiation:
1262 // An instantiation of an alias template may or may not be a SFINAE
1263 // context, depending on what else is on the stack.
1264 if (isa<TypeAliasTemplateDecl>(Active->Entity))
1265 break;
1266 [[fallthrough]];
1267 case CodeSynthesisContext::TemplateInstantiation:
1268 case CodeSynthesisContext::DefaultFunctionArgumentInstantiation:
1269 case CodeSynthesisContext::ExceptionSpecInstantiation:
1270 case CodeSynthesisContext::ConstraintsCheck:
1271 case CodeSynthesisContext::ParameterMappingSubstitution:
1272 case CodeSynthesisContext::ConstraintNormalization:
1273 case CodeSynthesisContext::NestedRequirementConstraintsCheck:
1274 // This is a template instantiation, so there is no SFINAE.
1275 return std::nullopt;
1276 case CodeSynthesisContext::LambdaExpressionSubstitution:
1277 // [temp.deduct]p9
1278 // A lambda-expression appearing in a function type or a template
1279 // parameter is not considered part of the immediate context for the
1280 // purposes of template argument deduction.
1281 // CWG2672: A lambda-expression body is never in the immediate context.
1282 return std::nullopt;
1284 case CodeSynthesisContext::DefaultTemplateArgumentInstantiation:
1285 case CodeSynthesisContext::PriorTemplateArgumentSubstitution:
1286 case CodeSynthesisContext::DefaultTemplateArgumentChecking:
1287 case CodeSynthesisContext::RewritingOperatorAsSpaceship:
1288 // A default template argument instantiation and substitution into
1289 // template parameters with arguments for prior parameters may or may
1290 // not be a SFINAE context; look further up the stack.
1291 break;
1293 case CodeSynthesisContext::ExplicitTemplateArgumentSubstitution:
1294 case CodeSynthesisContext::DeducedTemplateArgumentSubstitution:
1295 // We're either substituting explicitly-specified template arguments,
1296 // deduced template arguments. SFINAE applies unless we are in a lambda
1297 // body, see [temp.deduct]p9.
1298 case CodeSynthesisContext::ConstraintSubstitution:
1299 case CodeSynthesisContext::RequirementInstantiation:
1300 case CodeSynthesisContext::RequirementParameterInstantiation:
1301 // SFINAE always applies in a constraint expression or a requirement
1302 // in a requires expression.
1303 assert(Active->DeductionInfo && "Missing deduction info pointer");
1304 return Active->DeductionInfo;
1306 case CodeSynthesisContext::DeclaringSpecialMember:
1307 case CodeSynthesisContext::DeclaringImplicitEqualityComparison:
1308 case CodeSynthesisContext::DefiningSynthesizedFunction:
1309 case CodeSynthesisContext::InitializingStructuredBinding:
1310 case CodeSynthesisContext::MarkingClassDllexported:
1311 case CodeSynthesisContext::BuildingBuiltinDumpStructCall:
1312 case CodeSynthesisContext::BuildingDeductionGuides:
1313 // This happens in a context unrelated to template instantiation, so
1314 // there is no SFINAE.
1315 return std::nullopt;
1317 case CodeSynthesisContext::ExceptionSpecEvaluation:
1318 // FIXME: This should not be treated as a SFINAE context, because
1319 // we will cache an incorrect exception specification. However, clang
1320 // bootstrap relies this! See PR31692.
1321 break;
1323 case CodeSynthesisContext::Memoization:
1324 break;
1327 // The inner context was transparent for SFINAE. If it occurred within a
1328 // non-instantiation SFINAE context, then SFINAE applies.
1329 if (Active->SavedInNonInstantiationSFINAEContext)
1330 return std::optional<TemplateDeductionInfo *>(nullptr);
1333 return std::nullopt;
1336 //===----------------------------------------------------------------------===/
1337 // Template Instantiation for Types
1338 //===----------------------------------------------------------------------===/
1339 namespace {
1340 class TemplateInstantiator : public TreeTransform<TemplateInstantiator> {
1341 const MultiLevelTemplateArgumentList &TemplateArgs;
1342 SourceLocation Loc;
1343 DeclarationName Entity;
1344 // Whether to evaluate the C++20 constraints or simply substitute into them.
1345 bool EvaluateConstraints = true;
1346 // Whether Substitution was Incomplete, that is, we tried to substitute in
1347 // any user provided template arguments which were null.
1348 bool IsIncomplete = false;
1349 // Whether an incomplete substituion should be treated as an error.
1350 bool BailOutOnIncomplete;
1352 public:
1353 typedef TreeTransform<TemplateInstantiator> inherited;
1355 TemplateInstantiator(Sema &SemaRef,
1356 const MultiLevelTemplateArgumentList &TemplateArgs,
1357 SourceLocation Loc, DeclarationName Entity,
1358 bool BailOutOnIncomplete = false)
1359 : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc),
1360 Entity(Entity), BailOutOnIncomplete(BailOutOnIncomplete) {}
1362 void setEvaluateConstraints(bool B) {
1363 EvaluateConstraints = B;
1365 bool getEvaluateConstraints() {
1366 return EvaluateConstraints;
1369 /// Determine whether the given type \p T has already been
1370 /// transformed.
1372 /// For the purposes of template instantiation, a type has already been
1373 /// transformed if it is NULL or if it is not dependent.
1374 bool AlreadyTransformed(QualType T);
1376 /// Returns the location of the entity being instantiated, if known.
1377 SourceLocation getBaseLocation() { return Loc; }
1379 /// Returns the name of the entity being instantiated, if any.
1380 DeclarationName getBaseEntity() { return Entity; }
1382 /// Returns whether any substitution so far was incomplete.
1383 bool getIsIncomplete() const { return IsIncomplete; }
1385 /// Sets the "base" location and entity when that
1386 /// information is known based on another transformation.
1387 void setBase(SourceLocation Loc, DeclarationName Entity) {
1388 this->Loc = Loc;
1389 this->Entity = Entity;
1392 unsigned TransformTemplateDepth(unsigned Depth) {
1393 return TemplateArgs.getNewDepth(Depth);
1396 std::optional<unsigned> getPackIndex(TemplateArgument Pack) {
1397 int Index = getSema().ArgumentPackSubstitutionIndex;
1398 if (Index == -1)
1399 return std::nullopt;
1400 return Pack.pack_size() - 1 - Index;
1403 bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
1404 SourceRange PatternRange,
1405 ArrayRef<UnexpandedParameterPack> Unexpanded,
1406 bool &ShouldExpand, bool &RetainExpansion,
1407 std::optional<unsigned> &NumExpansions) {
1408 return getSema().CheckParameterPacksForExpansion(EllipsisLoc,
1409 PatternRange, Unexpanded,
1410 TemplateArgs,
1411 ShouldExpand,
1412 RetainExpansion,
1413 NumExpansions);
1416 void ExpandingFunctionParameterPack(ParmVarDecl *Pack) {
1417 SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(Pack);
1420 TemplateArgument ForgetPartiallySubstitutedPack() {
1421 TemplateArgument Result;
1422 if (NamedDecl *PartialPack
1423 = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
1424 MultiLevelTemplateArgumentList &TemplateArgs
1425 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
1426 unsigned Depth, Index;
1427 std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
1428 if (TemplateArgs.hasTemplateArgument(Depth, Index)) {
1429 Result = TemplateArgs(Depth, Index);
1430 TemplateArgs.setArgument(Depth, Index, TemplateArgument());
1431 } else {
1432 IsIncomplete = true;
1433 if (BailOutOnIncomplete)
1434 return TemplateArgument();
1438 return Result;
1441 void RememberPartiallySubstitutedPack(TemplateArgument Arg) {
1442 if (Arg.isNull())
1443 return;
1445 if (NamedDecl *PartialPack
1446 = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
1447 MultiLevelTemplateArgumentList &TemplateArgs
1448 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
1449 unsigned Depth, Index;
1450 std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
1451 TemplateArgs.setArgument(Depth, Index, Arg);
1455 /// Transform the given declaration by instantiating a reference to
1456 /// this declaration.
1457 Decl *TransformDecl(SourceLocation Loc, Decl *D);
1459 void transformAttrs(Decl *Old, Decl *New) {
1460 SemaRef.InstantiateAttrs(TemplateArgs, Old, New);
1463 void transformedLocalDecl(Decl *Old, ArrayRef<Decl *> NewDecls) {
1464 if (Old->isParameterPack() &&
1465 (NewDecls.size() != 1 || !NewDecls.front()->isParameterPack())) {
1466 SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(Old);
1467 for (auto *New : NewDecls)
1468 SemaRef.CurrentInstantiationScope->InstantiatedLocalPackArg(
1469 Old, cast<VarDecl>(New));
1470 return;
1473 assert(NewDecls.size() == 1 &&
1474 "should only have multiple expansions for a pack");
1475 Decl *New = NewDecls.front();
1477 // If we've instantiated the call operator of a lambda or the call
1478 // operator template of a generic lambda, update the "instantiation of"
1479 // information.
1480 auto *NewMD = dyn_cast<CXXMethodDecl>(New);
1481 if (NewMD && isLambdaCallOperator(NewMD)) {
1482 auto *OldMD = dyn_cast<CXXMethodDecl>(Old);
1483 if (auto *NewTD = NewMD->getDescribedFunctionTemplate())
1484 NewTD->setInstantiatedFromMemberTemplate(
1485 OldMD->getDescribedFunctionTemplate());
1486 else
1487 NewMD->setInstantiationOfMemberFunction(OldMD,
1488 TSK_ImplicitInstantiation);
1491 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Old, New);
1493 // We recreated a local declaration, but not by instantiating it. There
1494 // may be pending dependent diagnostics to produce.
1495 if (auto *DC = dyn_cast<DeclContext>(Old);
1496 DC && DC->isDependentContext() && DC->isFunctionOrMethod())
1497 SemaRef.PerformDependentDiagnostics(DC, TemplateArgs);
1500 /// Transform the definition of the given declaration by
1501 /// instantiating it.
1502 Decl *TransformDefinition(SourceLocation Loc, Decl *D);
1504 /// Transform the first qualifier within a scope by instantiating the
1505 /// declaration.
1506 NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc);
1508 bool TransformExceptionSpec(SourceLocation Loc,
1509 FunctionProtoType::ExceptionSpecInfo &ESI,
1510 SmallVectorImpl<QualType> &Exceptions,
1511 bool &Changed);
1513 /// Rebuild the exception declaration and register the declaration
1514 /// as an instantiated local.
1515 VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
1516 TypeSourceInfo *Declarator,
1517 SourceLocation StartLoc,
1518 SourceLocation NameLoc,
1519 IdentifierInfo *Name);
1521 /// Rebuild the Objective-C exception declaration and register the
1522 /// declaration as an instantiated local.
1523 VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
1524 TypeSourceInfo *TSInfo, QualType T);
1526 /// Check for tag mismatches when instantiating an
1527 /// elaborated type.
1528 QualType RebuildElaboratedType(SourceLocation KeywordLoc,
1529 ElaboratedTypeKeyword Keyword,
1530 NestedNameSpecifierLoc QualifierLoc,
1531 QualType T);
1533 TemplateName
1534 TransformTemplateName(CXXScopeSpec &SS, TemplateName Name,
1535 SourceLocation NameLoc,
1536 QualType ObjectType = QualType(),
1537 NamedDecl *FirstQualifierInScope = nullptr,
1538 bool AllowInjectedClassName = false);
1540 const AnnotateAttr *TransformAnnotateAttr(const AnnotateAttr *AA);
1541 const CXXAssumeAttr *TransformCXXAssumeAttr(const CXXAssumeAttr *AA);
1542 const LoopHintAttr *TransformLoopHintAttr(const LoopHintAttr *LH);
1543 const NoInlineAttr *TransformStmtNoInlineAttr(const Stmt *OrigS,
1544 const Stmt *InstS,
1545 const NoInlineAttr *A);
1546 const AlwaysInlineAttr *
1547 TransformStmtAlwaysInlineAttr(const Stmt *OrigS, const Stmt *InstS,
1548 const AlwaysInlineAttr *A);
1549 const CodeAlignAttr *TransformCodeAlignAttr(const CodeAlignAttr *CA);
1550 ExprResult TransformPredefinedExpr(PredefinedExpr *E);
1551 ExprResult TransformDeclRefExpr(DeclRefExpr *E);
1552 ExprResult TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E);
1554 ExprResult TransformTemplateParmRefExpr(DeclRefExpr *E,
1555 NonTypeTemplateParmDecl *D);
1556 ExprResult TransformSubstNonTypeTemplateParmPackExpr(
1557 SubstNonTypeTemplateParmPackExpr *E);
1558 ExprResult TransformSubstNonTypeTemplateParmExpr(
1559 SubstNonTypeTemplateParmExpr *E);
1561 /// Rebuild a DeclRefExpr for a VarDecl reference.
1562 ExprResult RebuildVarDeclRefExpr(VarDecl *PD, SourceLocation Loc);
1564 /// Transform a reference to a function or init-capture parameter pack.
1565 ExprResult TransformFunctionParmPackRefExpr(DeclRefExpr *E, VarDecl *PD);
1567 /// Transform a FunctionParmPackExpr which was built when we couldn't
1568 /// expand a function parameter pack reference which refers to an expanded
1569 /// pack.
1570 ExprResult TransformFunctionParmPackExpr(FunctionParmPackExpr *E);
1572 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
1573 FunctionProtoTypeLoc TL) {
1574 // Call the base version; it will forward to our overridden version below.
1575 return inherited::TransformFunctionProtoType(TLB, TL);
1578 QualType TransformInjectedClassNameType(TypeLocBuilder &TLB,
1579 InjectedClassNameTypeLoc TL) {
1580 auto Type = inherited::TransformInjectedClassNameType(TLB, TL);
1581 // Special case for transforming a deduction guide, we return a
1582 // transformed TemplateSpecializationType.
1583 if (Type.isNull() &&
1584 SemaRef.CodeSynthesisContexts.back().Kind ==
1585 Sema::CodeSynthesisContext::BuildingDeductionGuides) {
1586 // Return a TemplateSpecializationType for transforming a deduction
1587 // guide.
1588 if (auto *ICT = TL.getType()->getAs<InjectedClassNameType>()) {
1589 auto Type =
1590 inherited::TransformType(ICT->getInjectedSpecializationType());
1591 TLB.pushTrivial(SemaRef.Context, Type, TL.getNameLoc());
1592 return Type;
1595 return Type;
1597 // Override the default version to handle a rewrite-template-arg-pack case
1598 // for building a deduction guide.
1599 bool TransformTemplateArgument(const TemplateArgumentLoc &Input,
1600 TemplateArgumentLoc &Output,
1601 bool Uneval = false) {
1602 const TemplateArgument &Arg = Input.getArgument();
1603 std::vector<TemplateArgument> TArgs;
1604 switch (Arg.getKind()) {
1605 case TemplateArgument::Pack:
1606 // Literally rewrite the template argument pack, instead of unpacking
1607 // it.
1608 for (auto &pack : Arg.getPackAsArray()) {
1609 TemplateArgumentLoc Input = SemaRef.getTrivialTemplateArgumentLoc(
1610 pack, QualType(), SourceLocation{});
1611 TemplateArgumentLoc Output;
1612 if (SemaRef.SubstTemplateArgument(Input, TemplateArgs, Output))
1613 return true; // fails
1614 TArgs.push_back(Output.getArgument());
1616 Output = SemaRef.getTrivialTemplateArgumentLoc(
1617 TemplateArgument(llvm::ArrayRef(TArgs).copy(SemaRef.Context)),
1618 QualType(), SourceLocation{});
1619 return false;
1620 default:
1621 break;
1623 return inherited::TransformTemplateArgument(Input, Output, Uneval);
1626 template<typename Fn>
1627 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
1628 FunctionProtoTypeLoc TL,
1629 CXXRecordDecl *ThisContext,
1630 Qualifiers ThisTypeQuals,
1631 Fn TransformExceptionSpec);
1633 ParmVarDecl *
1634 TransformFunctionTypeParam(ParmVarDecl *OldParm, int indexAdjustment,
1635 std::optional<unsigned> NumExpansions,
1636 bool ExpectParameterPack);
1638 using inherited::TransformTemplateTypeParmType;
1639 /// Transforms a template type parameter type by performing
1640 /// substitution of the corresponding template type argument.
1641 QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
1642 TemplateTypeParmTypeLoc TL,
1643 bool SuppressObjCLifetime);
1645 QualType BuildSubstTemplateTypeParmType(
1646 TypeLocBuilder &TLB, bool SuppressObjCLifetime, bool Final,
1647 Decl *AssociatedDecl, unsigned Index, std::optional<unsigned> PackIndex,
1648 TemplateArgument Arg, SourceLocation NameLoc);
1650 /// Transforms an already-substituted template type parameter pack
1651 /// into either itself (if we aren't substituting into its pack expansion)
1652 /// or the appropriate substituted argument.
1653 using inherited::TransformSubstTemplateTypeParmPackType;
1654 QualType
1655 TransformSubstTemplateTypeParmPackType(TypeLocBuilder &TLB,
1656 SubstTemplateTypeParmPackTypeLoc TL,
1657 bool SuppressObjCLifetime);
1659 QualType
1660 TransformSubstTemplateTypeParmType(TypeLocBuilder &TLB,
1661 SubstTemplateTypeParmTypeLoc TL) {
1662 const SubstTemplateTypeParmType *Type = TL.getTypePtr();
1663 if (Type->getSubstitutionFlag() !=
1664 SubstTemplateTypeParmTypeFlag::ExpandPacksInPlace)
1665 return inherited::TransformSubstTemplateTypeParmType(TLB, TL);
1667 assert(Type->getPackIndex());
1668 TemplateArgument TA = TemplateArgs(
1669 Type->getReplacedParameter()->getDepth(), Type->getIndex());
1670 assert(*Type->getPackIndex() + 1 <= TA.pack_size());
1671 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(
1672 SemaRef, TA.pack_size() - 1 - *Type->getPackIndex());
1674 return inherited::TransformSubstTemplateTypeParmType(TLB, TL);
1677 CXXRecordDecl::LambdaDependencyKind
1678 ComputeLambdaDependency(LambdaScopeInfo *LSI) {
1679 if (auto TypeAlias =
1680 TemplateInstArgsHelpers::getEnclosingTypeAliasTemplateDecl(
1681 getSema());
1682 TypeAlias && TemplateInstArgsHelpers::isLambdaEnclosedByTypeAliasDecl(
1683 LSI->CallOperator, TypeAlias.PrimaryTypeAliasDecl)) {
1684 unsigned TypeAliasDeclDepth = TypeAlias.Template->getTemplateDepth();
1685 if (TypeAliasDeclDepth >= TemplateArgs.getNumSubstitutedLevels())
1686 return CXXRecordDecl::LambdaDependencyKind::LDK_AlwaysDependent;
1687 for (const TemplateArgument &TA : TypeAlias.AssociatedTemplateArguments)
1688 if (TA.isDependent())
1689 return CXXRecordDecl::LambdaDependencyKind::LDK_AlwaysDependent;
1691 return inherited::ComputeLambdaDependency(LSI);
1694 ExprResult TransformLambdaExpr(LambdaExpr *E) {
1695 // Do not rebuild lambdas to avoid creating a new type.
1696 // Lambdas have already been processed inside their eval contexts.
1697 if (SemaRef.RebuildingImmediateInvocation)
1698 return E;
1699 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true,
1700 /*InstantiatingLambdaOrBlock=*/true);
1701 Sema::ConstraintEvalRAII<TemplateInstantiator> RAII(*this);
1703 return inherited::TransformLambdaExpr(E);
1706 ExprResult TransformBlockExpr(BlockExpr *E) {
1707 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true,
1708 /*InstantiatingLambdaOrBlock=*/true);
1709 return inherited::TransformBlockExpr(E);
1712 ExprResult RebuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc,
1713 LambdaScopeInfo *LSI) {
1714 CXXMethodDecl *MD = LSI->CallOperator;
1715 for (ParmVarDecl *PVD : MD->parameters()) {
1716 assert(PVD && "null in a parameter list");
1717 if (!PVD->hasDefaultArg())
1718 continue;
1719 Expr *UninstExpr = PVD->getUninstantiatedDefaultArg();
1720 // FIXME: Obtain the source location for the '=' token.
1721 SourceLocation EqualLoc = UninstExpr->getBeginLoc();
1722 if (SemaRef.SubstDefaultArgument(EqualLoc, PVD, TemplateArgs)) {
1723 // If substitution fails, the default argument is set to a
1724 // RecoveryExpr that wraps the uninstantiated default argument so
1725 // that downstream diagnostics are omitted.
1726 ExprResult ErrorResult = SemaRef.CreateRecoveryExpr(
1727 UninstExpr->getBeginLoc(), UninstExpr->getEndLoc(), {UninstExpr},
1728 UninstExpr->getType());
1729 if (ErrorResult.isUsable())
1730 PVD->setDefaultArg(ErrorResult.get());
1733 return inherited::RebuildLambdaExpr(StartLoc, EndLoc, LSI);
1736 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
1737 // Currently, we instantiate the body when instantiating the lambda
1738 // expression. However, `EvaluateConstraints` is disabled during the
1739 // instantiation of the lambda expression, causing the instantiation
1740 // failure of the return type requirement in the body. If p0588r1 is fully
1741 // implemented, the body will be lazily instantiated, and this problem
1742 // will not occur. Here, `EvaluateConstraints` is temporarily set to
1743 // `true` to temporarily fix this issue.
1744 // FIXME: This temporary fix can be removed after fully implementing
1745 // p0588r1.
1746 llvm::SaveAndRestore _(EvaluateConstraints, true);
1747 return inherited::TransformLambdaBody(E, Body);
1750 ExprResult TransformSizeOfPackExpr(SizeOfPackExpr *E) {
1751 ExprResult Transformed = inherited::TransformSizeOfPackExpr(E);
1752 if (!Transformed.isUsable())
1753 return Transformed;
1754 auto *TransformedExpr = cast<SizeOfPackExpr>(Transformed.get());
1755 if (SemaRef.CodeSynthesisContexts.back().Kind ==
1756 Sema::CodeSynthesisContext::ConstraintNormalization &&
1757 TransformedExpr->getPack() == E->getPack()) {
1758 Decl *NewPack =
1759 TransformDecl(E->getPackLoc(), TransformedExpr->getPack());
1760 if (!NewPack)
1761 return ExprError();
1762 TransformedExpr->setPack(cast<NamedDecl>(NewPack));
1764 return TransformedExpr;
1767 ExprResult TransformRequiresExpr(RequiresExpr *E) {
1768 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
1769 ExprResult TransReq = inherited::TransformRequiresExpr(E);
1770 if (TransReq.isInvalid())
1771 return TransReq;
1772 assert(TransReq.get() != E &&
1773 "Do not change value of isSatisfied for the existing expression. "
1774 "Create a new expression instead.");
1775 if (E->getBody()->isDependentContext()) {
1776 Sema::SFINAETrap Trap(SemaRef);
1777 // We recreate the RequiresExpr body, but not by instantiating it.
1778 // Produce pending diagnostics for dependent access check.
1779 SemaRef.PerformDependentDiagnostics(E->getBody(), TemplateArgs);
1780 // FIXME: Store SFINAE diagnostics in RequiresExpr for diagnosis.
1781 if (Trap.hasErrorOccurred())
1782 TransReq.getAs<RequiresExpr>()->setSatisfied(false);
1784 return TransReq;
1787 bool TransformRequiresExprRequirements(
1788 ArrayRef<concepts::Requirement *> Reqs,
1789 SmallVectorImpl<concepts::Requirement *> &Transformed) {
1790 bool SatisfactionDetermined = false;
1791 for (concepts::Requirement *Req : Reqs) {
1792 concepts::Requirement *TransReq = nullptr;
1793 if (!SatisfactionDetermined) {
1794 if (auto *TypeReq = dyn_cast<concepts::TypeRequirement>(Req))
1795 TransReq = TransformTypeRequirement(TypeReq);
1796 else if (auto *ExprReq = dyn_cast<concepts::ExprRequirement>(Req))
1797 TransReq = TransformExprRequirement(ExprReq);
1798 else
1799 TransReq = TransformNestedRequirement(
1800 cast<concepts::NestedRequirement>(Req));
1801 if (!TransReq)
1802 return true;
1803 if (!TransReq->isDependent() && !TransReq->isSatisfied())
1804 // [expr.prim.req]p6
1805 // [...] The substitution and semantic constraint checking
1806 // proceeds in lexical order and stops when a condition that
1807 // determines the result of the requires-expression is
1808 // encountered. [..]
1809 SatisfactionDetermined = true;
1810 } else
1811 TransReq = Req;
1812 Transformed.push_back(TransReq);
1814 return false;
1817 TemplateParameterList *TransformTemplateParameterList(
1818 TemplateParameterList *OrigTPL) {
1819 if (!OrigTPL || !OrigTPL->size()) return OrigTPL;
1821 DeclContext *Owner = OrigTPL->getParam(0)->getDeclContext();
1822 TemplateDeclInstantiator DeclInstantiator(getSema(),
1823 /* DeclContext *Owner */ Owner, TemplateArgs);
1824 DeclInstantiator.setEvaluateConstraints(EvaluateConstraints);
1825 return DeclInstantiator.SubstTemplateParams(OrigTPL);
1828 concepts::TypeRequirement *
1829 TransformTypeRequirement(concepts::TypeRequirement *Req);
1830 concepts::ExprRequirement *
1831 TransformExprRequirement(concepts::ExprRequirement *Req);
1832 concepts::NestedRequirement *
1833 TransformNestedRequirement(concepts::NestedRequirement *Req);
1834 ExprResult TransformRequiresTypeParams(
1835 SourceLocation KWLoc, SourceLocation RBraceLoc, const RequiresExpr *RE,
1836 RequiresExprBodyDecl *Body, ArrayRef<ParmVarDecl *> Params,
1837 SmallVectorImpl<QualType> &PTypes,
1838 SmallVectorImpl<ParmVarDecl *> &TransParams,
1839 Sema::ExtParameterInfoBuilder &PInfos);
1841 private:
1842 ExprResult
1843 transformNonTypeTemplateParmRef(Decl *AssociatedDecl,
1844 const NonTypeTemplateParmDecl *parm,
1845 SourceLocation loc, TemplateArgument arg,
1846 std::optional<unsigned> PackIndex);
1850 bool TemplateInstantiator::AlreadyTransformed(QualType T) {
1851 if (T.isNull())
1852 return true;
1854 if (T->isInstantiationDependentType() || T->isVariablyModifiedType())
1855 return false;
1857 getSema().MarkDeclarationsReferencedInType(Loc, T);
1858 return true;
1861 static TemplateArgument
1862 getPackSubstitutedTemplateArgument(Sema &S, TemplateArgument Arg) {
1863 assert(S.ArgumentPackSubstitutionIndex >= 0);
1864 assert(S.ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
1865 Arg = Arg.pack_begin()[S.ArgumentPackSubstitutionIndex];
1866 if (Arg.isPackExpansion())
1867 Arg = Arg.getPackExpansionPattern();
1868 return Arg;
1871 Decl *TemplateInstantiator::TransformDecl(SourceLocation Loc, Decl *D) {
1872 if (!D)
1873 return nullptr;
1875 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(D)) {
1876 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1877 // If the corresponding template argument is NULL or non-existent, it's
1878 // because we are performing instantiation from explicitly-specified
1879 // template arguments in a function template, but there were some
1880 // arguments left unspecified.
1881 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
1882 TTP->getPosition())) {
1883 IsIncomplete = true;
1884 return BailOutOnIncomplete ? nullptr : D;
1887 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
1889 if (TTP->isParameterPack()) {
1890 // We might not have an index for pack expansion when normalizing
1891 // constraint expressions. In that case, resort to instantiation scopes
1892 // for the transformed declarations.
1893 if (SemaRef.ArgumentPackSubstitutionIndex == -1 &&
1894 SemaRef.CodeSynthesisContexts.back().Kind ==
1895 Sema::CodeSynthesisContext::ConstraintNormalization) {
1896 return SemaRef.FindInstantiatedDecl(Loc, cast<NamedDecl>(D),
1897 TemplateArgs);
1899 assert(Arg.getKind() == TemplateArgument::Pack &&
1900 "Missing argument pack");
1901 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1904 TemplateName Template = Arg.getAsTemplate();
1905 assert(!Template.isNull() && Template.getAsTemplateDecl() &&
1906 "Wrong kind of template template argument");
1907 return Template.getAsTemplateDecl();
1910 // Fall through to find the instantiated declaration for this template
1911 // template parameter.
1914 return SemaRef.FindInstantiatedDecl(Loc, cast<NamedDecl>(D), TemplateArgs);
1917 Decl *TemplateInstantiator::TransformDefinition(SourceLocation Loc, Decl *D) {
1918 Decl *Inst = getSema().SubstDecl(D, getSema().CurContext, TemplateArgs);
1919 if (!Inst)
1920 return nullptr;
1922 getSema().CurrentInstantiationScope->InstantiatedLocal(D, Inst);
1923 return Inst;
1926 bool TemplateInstantiator::TransformExceptionSpec(
1927 SourceLocation Loc, FunctionProtoType::ExceptionSpecInfo &ESI,
1928 SmallVectorImpl<QualType> &Exceptions, bool &Changed) {
1929 if (ESI.Type == EST_Uninstantiated) {
1930 ESI.instantiate();
1931 Changed = true;
1933 return inherited::TransformExceptionSpec(Loc, ESI, Exceptions, Changed);
1936 NamedDecl *
1937 TemplateInstantiator::TransformFirstQualifierInScope(NamedDecl *D,
1938 SourceLocation Loc) {
1939 // If the first part of the nested-name-specifier was a template type
1940 // parameter, instantiate that type parameter down to a tag type.
1941 if (TemplateTypeParmDecl *TTPD = dyn_cast_or_null<TemplateTypeParmDecl>(D)) {
1942 const TemplateTypeParmType *TTP
1943 = cast<TemplateTypeParmType>(getSema().Context.getTypeDeclType(TTPD));
1945 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1946 // FIXME: This needs testing w/ member access expressions.
1947 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getIndex());
1949 if (TTP->isParameterPack()) {
1950 assert(Arg.getKind() == TemplateArgument::Pack &&
1951 "Missing argument pack");
1953 if (getSema().ArgumentPackSubstitutionIndex == -1)
1954 return nullptr;
1956 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1959 QualType T = Arg.getAsType();
1960 if (T.isNull())
1961 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
1963 if (const TagType *Tag = T->getAs<TagType>())
1964 return Tag->getDecl();
1966 // The resulting type is not a tag; complain.
1967 getSema().Diag(Loc, diag::err_nested_name_spec_non_tag) << T;
1968 return nullptr;
1972 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
1975 VarDecl *
1976 TemplateInstantiator::RebuildExceptionDecl(VarDecl *ExceptionDecl,
1977 TypeSourceInfo *Declarator,
1978 SourceLocation StartLoc,
1979 SourceLocation NameLoc,
1980 IdentifierInfo *Name) {
1981 VarDecl *Var = inherited::RebuildExceptionDecl(ExceptionDecl, Declarator,
1982 StartLoc, NameLoc, Name);
1983 if (Var)
1984 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
1985 return Var;
1988 VarDecl *TemplateInstantiator::RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
1989 TypeSourceInfo *TSInfo,
1990 QualType T) {
1991 VarDecl *Var = inherited::RebuildObjCExceptionDecl(ExceptionDecl, TSInfo, T);
1992 if (Var)
1993 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
1994 return Var;
1997 QualType
1998 TemplateInstantiator::RebuildElaboratedType(SourceLocation KeywordLoc,
1999 ElaboratedTypeKeyword Keyword,
2000 NestedNameSpecifierLoc QualifierLoc,
2001 QualType T) {
2002 if (const TagType *TT = T->getAs<TagType>()) {
2003 TagDecl* TD = TT->getDecl();
2005 SourceLocation TagLocation = KeywordLoc;
2007 IdentifierInfo *Id = TD->getIdentifier();
2009 // TODO: should we even warn on struct/class mismatches for this? Seems
2010 // like it's likely to produce a lot of spurious errors.
2011 if (Id && Keyword != ElaboratedTypeKeyword::None &&
2012 Keyword != ElaboratedTypeKeyword::Typename) {
2013 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForKeyword(Keyword);
2014 if (!SemaRef.isAcceptableTagRedeclaration(TD, Kind, /*isDefinition*/false,
2015 TagLocation, Id)) {
2016 SemaRef.Diag(TagLocation, diag::err_use_with_wrong_tag)
2017 << Id
2018 << FixItHint::CreateReplacement(SourceRange(TagLocation),
2019 TD->getKindName());
2020 SemaRef.Diag(TD->getLocation(), diag::note_previous_use);
2025 return inherited::RebuildElaboratedType(KeywordLoc, Keyword, QualifierLoc, T);
2028 TemplateName TemplateInstantiator::TransformTemplateName(
2029 CXXScopeSpec &SS, TemplateName Name, SourceLocation NameLoc,
2030 QualType ObjectType, NamedDecl *FirstQualifierInScope,
2031 bool AllowInjectedClassName) {
2032 if (TemplateTemplateParmDecl *TTP
2033 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl())) {
2034 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
2035 // If the corresponding template argument is NULL or non-existent, it's
2036 // because we are performing instantiation from explicitly-specified
2037 // template arguments in a function template, but there were some
2038 // arguments left unspecified.
2039 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
2040 TTP->getPosition())) {
2041 IsIncomplete = true;
2042 return BailOutOnIncomplete ? TemplateName() : Name;
2045 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
2047 if (TemplateArgs.isRewrite()) {
2048 // We're rewriting the template parameter as a reference to another
2049 // template parameter.
2050 if (Arg.getKind() == TemplateArgument::Pack) {
2051 assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() &&
2052 "unexpected pack arguments in template rewrite");
2053 Arg = Arg.pack_begin()->getPackExpansionPattern();
2055 assert(Arg.getKind() == TemplateArgument::Template &&
2056 "unexpected nontype template argument kind in template rewrite");
2057 return Arg.getAsTemplate();
2060 auto [AssociatedDecl, Final] =
2061 TemplateArgs.getAssociatedDecl(TTP->getDepth());
2062 std::optional<unsigned> PackIndex;
2063 if (TTP->isParameterPack()) {
2064 assert(Arg.getKind() == TemplateArgument::Pack &&
2065 "Missing argument pack");
2067 if (getSema().ArgumentPackSubstitutionIndex == -1) {
2068 // We have the template argument pack to substitute, but we're not
2069 // actually expanding the enclosing pack expansion yet. So, just
2070 // keep the entire argument pack.
2071 return getSema().Context.getSubstTemplateTemplateParmPack(
2072 Arg, AssociatedDecl, TTP->getIndex(), Final);
2075 PackIndex = getPackIndex(Arg);
2076 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
2079 TemplateName Template = Arg.getAsTemplate();
2080 assert(!Template.isNull() && "Null template template argument");
2082 if (Final)
2083 return Template;
2084 return getSema().Context.getSubstTemplateTemplateParm(
2085 Template, AssociatedDecl, TTP->getIndex(), PackIndex);
2089 if (SubstTemplateTemplateParmPackStorage *SubstPack
2090 = Name.getAsSubstTemplateTemplateParmPack()) {
2091 if (getSema().ArgumentPackSubstitutionIndex == -1)
2092 return Name;
2094 TemplateArgument Pack = SubstPack->getArgumentPack();
2095 TemplateName Template =
2096 getPackSubstitutedTemplateArgument(getSema(), Pack).getAsTemplate();
2097 if (SubstPack->getFinal())
2098 return Template;
2099 return getSema().Context.getSubstTemplateTemplateParm(
2100 Template, SubstPack->getAssociatedDecl(), SubstPack->getIndex(),
2101 getPackIndex(Pack));
2104 return inherited::TransformTemplateName(SS, Name, NameLoc, ObjectType,
2105 FirstQualifierInScope,
2106 AllowInjectedClassName);
2109 ExprResult
2110 TemplateInstantiator::TransformPredefinedExpr(PredefinedExpr *E) {
2111 if (!E->isTypeDependent())
2112 return E;
2114 return getSema().BuildPredefinedExpr(E->getLocation(), E->getIdentKind());
2117 ExprResult
2118 TemplateInstantiator::TransformTemplateParmRefExpr(DeclRefExpr *E,
2119 NonTypeTemplateParmDecl *NTTP) {
2120 // If the corresponding template argument is NULL or non-existent, it's
2121 // because we are performing instantiation from explicitly-specified
2122 // template arguments in a function template, but there were some
2123 // arguments left unspecified.
2124 if (!TemplateArgs.hasTemplateArgument(NTTP->getDepth(),
2125 NTTP->getPosition())) {
2126 IsIncomplete = true;
2127 return BailOutOnIncomplete ? ExprError() : E;
2130 TemplateArgument Arg = TemplateArgs(NTTP->getDepth(), NTTP->getPosition());
2132 if (TemplateArgs.isRewrite()) {
2133 // We're rewriting the template parameter as a reference to another
2134 // template parameter.
2135 if (Arg.getKind() == TemplateArgument::Pack) {
2136 assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() &&
2137 "unexpected pack arguments in template rewrite");
2138 Arg = Arg.pack_begin()->getPackExpansionPattern();
2140 assert(Arg.getKind() == TemplateArgument::Expression &&
2141 "unexpected nontype template argument kind in template rewrite");
2142 // FIXME: This can lead to the same subexpression appearing multiple times
2143 // in a complete expression.
2144 return Arg.getAsExpr();
2147 auto [AssociatedDecl, _] = TemplateArgs.getAssociatedDecl(NTTP->getDepth());
2148 std::optional<unsigned> PackIndex;
2149 if (NTTP->isParameterPack()) {
2150 assert(Arg.getKind() == TemplateArgument::Pack &&
2151 "Missing argument pack");
2153 if (getSema().ArgumentPackSubstitutionIndex == -1) {
2154 // We have an argument pack, but we can't select a particular argument
2155 // out of it yet. Therefore, we'll build an expression to hold on to that
2156 // argument pack.
2157 QualType TargetType = SemaRef.SubstType(NTTP->getType(), TemplateArgs,
2158 E->getLocation(),
2159 NTTP->getDeclName());
2160 if (TargetType.isNull())
2161 return ExprError();
2163 QualType ExprType = TargetType.getNonLValueExprType(SemaRef.Context);
2164 if (TargetType->isRecordType())
2165 ExprType.addConst();
2166 // FIXME: Pass in Final.
2167 return new (SemaRef.Context) SubstNonTypeTemplateParmPackExpr(
2168 ExprType, TargetType->isReferenceType() ? VK_LValue : VK_PRValue,
2169 E->getLocation(), Arg, AssociatedDecl, NTTP->getPosition());
2171 PackIndex = getPackIndex(Arg);
2172 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
2174 // FIXME: Don't put subst node on Final replacement.
2175 return transformNonTypeTemplateParmRef(AssociatedDecl, NTTP, E->getLocation(),
2176 Arg, PackIndex);
2179 const AnnotateAttr *
2180 TemplateInstantiator::TransformAnnotateAttr(const AnnotateAttr *AA) {
2181 SmallVector<Expr *> Args;
2182 for (Expr *Arg : AA->args()) {
2183 ExprResult Res = getDerived().TransformExpr(Arg);
2184 if (Res.isUsable())
2185 Args.push_back(Res.get());
2187 return AnnotateAttr::CreateImplicit(getSema().Context, AA->getAnnotation(),
2188 Args.data(), Args.size(), AA->getRange());
2191 const CXXAssumeAttr *
2192 TemplateInstantiator::TransformCXXAssumeAttr(const CXXAssumeAttr *AA) {
2193 ExprResult Res = getDerived().TransformExpr(AA->getAssumption());
2194 if (!Res.isUsable())
2195 return AA;
2197 Res = getSema().ActOnFinishFullExpr(Res.get(),
2198 /*DiscardedValue=*/false);
2199 if (!Res.isUsable())
2200 return AA;
2202 if (!(Res.get()->getDependence() & ExprDependence::TypeValueInstantiation)) {
2203 Res = getSema().BuildCXXAssumeExpr(Res.get(), AA->getAttrName(),
2204 AA->getRange());
2205 if (!Res.isUsable())
2206 return AA;
2209 return CXXAssumeAttr::CreateImplicit(getSema().Context, Res.get(),
2210 AA->getRange());
2213 const LoopHintAttr *
2214 TemplateInstantiator::TransformLoopHintAttr(const LoopHintAttr *LH) {
2215 Expr *TransformedExpr = getDerived().TransformExpr(LH->getValue()).get();
2217 if (TransformedExpr == LH->getValue())
2218 return LH;
2220 // Generate error if there is a problem with the value.
2221 if (getSema().CheckLoopHintExpr(TransformedExpr, LH->getLocation(),
2222 LH->getSemanticSpelling() ==
2223 LoopHintAttr::Pragma_unroll))
2224 return LH;
2226 LoopHintAttr::OptionType Option = LH->getOption();
2227 LoopHintAttr::LoopHintState State = LH->getState();
2229 llvm::APSInt ValueAPS =
2230 TransformedExpr->EvaluateKnownConstInt(getSema().getASTContext());
2231 // The values of 0 and 1 block any unrolling of the loop.
2232 if (ValueAPS.isZero() || ValueAPS.isOne()) {
2233 Option = LoopHintAttr::Unroll;
2234 State = LoopHintAttr::Disable;
2237 // Create new LoopHintValueAttr with integral expression in place of the
2238 // non-type template parameter.
2239 return LoopHintAttr::CreateImplicit(getSema().Context, Option, State,
2240 TransformedExpr, *LH);
2242 const NoInlineAttr *TemplateInstantiator::TransformStmtNoInlineAttr(
2243 const Stmt *OrigS, const Stmt *InstS, const NoInlineAttr *A) {
2244 if (!A || getSema().CheckNoInlineAttr(OrigS, InstS, *A))
2245 return nullptr;
2247 return A;
2249 const AlwaysInlineAttr *TemplateInstantiator::TransformStmtAlwaysInlineAttr(
2250 const Stmt *OrigS, const Stmt *InstS, const AlwaysInlineAttr *A) {
2251 if (!A || getSema().CheckAlwaysInlineAttr(OrigS, InstS, *A))
2252 return nullptr;
2254 return A;
2257 const CodeAlignAttr *
2258 TemplateInstantiator::TransformCodeAlignAttr(const CodeAlignAttr *CA) {
2259 Expr *TransformedExpr = getDerived().TransformExpr(CA->getAlignment()).get();
2260 return getSema().BuildCodeAlignAttr(*CA, TransformedExpr);
2263 ExprResult TemplateInstantiator::transformNonTypeTemplateParmRef(
2264 Decl *AssociatedDecl, const NonTypeTemplateParmDecl *parm,
2265 SourceLocation loc, TemplateArgument arg,
2266 std::optional<unsigned> PackIndex) {
2267 ExprResult result;
2269 // Determine the substituted parameter type. We can usually infer this from
2270 // the template argument, but not always.
2271 auto SubstParamType = [&] {
2272 QualType T;
2273 if (parm->isExpandedParameterPack())
2274 T = parm->getExpansionType(SemaRef.ArgumentPackSubstitutionIndex);
2275 else
2276 T = parm->getType();
2277 if (parm->isParameterPack() && isa<PackExpansionType>(T))
2278 T = cast<PackExpansionType>(T)->getPattern();
2279 return SemaRef.SubstType(T, TemplateArgs, loc, parm->getDeclName());
2282 bool refParam = false;
2284 // The template argument itself might be an expression, in which case we just
2285 // return that expression. This happens when substituting into an alias
2286 // template.
2287 if (arg.getKind() == TemplateArgument::Expression) {
2288 Expr *argExpr = arg.getAsExpr();
2289 result = argExpr;
2290 if (argExpr->isLValue()) {
2291 if (argExpr->getType()->isRecordType()) {
2292 // Check whether the parameter was actually a reference.
2293 QualType paramType = SubstParamType();
2294 if (paramType.isNull())
2295 return ExprError();
2296 refParam = paramType->isReferenceType();
2297 } else {
2298 refParam = true;
2301 } else if (arg.getKind() == TemplateArgument::Declaration ||
2302 arg.getKind() == TemplateArgument::NullPtr) {
2303 if (arg.getKind() == TemplateArgument::Declaration) {
2304 ValueDecl *VD = arg.getAsDecl();
2306 // Find the instantiation of the template argument. This is
2307 // required for nested templates.
2308 VD = cast_or_null<ValueDecl>(
2309 getSema().FindInstantiatedDecl(loc, VD, TemplateArgs));
2310 if (!VD)
2311 return ExprError();
2314 QualType paramType = arg.getNonTypeTemplateArgumentType();
2315 assert(!paramType.isNull() && "type substitution failed for param type");
2316 assert(!paramType->isDependentType() && "param type still dependent");
2317 result = SemaRef.BuildExpressionFromDeclTemplateArgument(arg, paramType, loc);
2318 refParam = paramType->isReferenceType();
2319 } else {
2320 QualType paramType = arg.getNonTypeTemplateArgumentType();
2321 result = SemaRef.BuildExpressionFromNonTypeTemplateArgument(arg, loc);
2322 refParam = paramType->isReferenceType();
2323 assert(result.isInvalid() ||
2324 SemaRef.Context.hasSameType(result.get()->getType(),
2325 paramType.getNonReferenceType()));
2328 if (result.isInvalid())
2329 return ExprError();
2331 Expr *resultExpr = result.get();
2332 // FIXME: Don't put subst node on final replacement.
2333 return new (SemaRef.Context) SubstNonTypeTemplateParmExpr(
2334 resultExpr->getType(), resultExpr->getValueKind(), loc, resultExpr,
2335 AssociatedDecl, parm->getIndex(), PackIndex, refParam);
2338 ExprResult
2339 TemplateInstantiator::TransformSubstNonTypeTemplateParmPackExpr(
2340 SubstNonTypeTemplateParmPackExpr *E) {
2341 if (getSema().ArgumentPackSubstitutionIndex == -1) {
2342 // We aren't expanding the parameter pack, so just return ourselves.
2343 return E;
2346 TemplateArgument Pack = E->getArgumentPack();
2347 TemplateArgument Arg = getPackSubstitutedTemplateArgument(getSema(), Pack);
2348 // FIXME: Don't put subst node on final replacement.
2349 return transformNonTypeTemplateParmRef(
2350 E->getAssociatedDecl(), E->getParameterPack(),
2351 E->getParameterPackLocation(), Arg, getPackIndex(Pack));
2354 ExprResult
2355 TemplateInstantiator::TransformSubstNonTypeTemplateParmExpr(
2356 SubstNonTypeTemplateParmExpr *E) {
2357 ExprResult SubstReplacement = E->getReplacement();
2358 if (!isa<ConstantExpr>(SubstReplacement.get()))
2359 SubstReplacement = TransformExpr(E->getReplacement());
2360 if (SubstReplacement.isInvalid())
2361 return true;
2362 QualType SubstType = TransformType(E->getParameterType(getSema().Context));
2363 if (SubstType.isNull())
2364 return true;
2365 // The type may have been previously dependent and not now, which means we
2366 // might have to implicit cast the argument to the new type, for example:
2367 // template<auto T, decltype(T) U>
2368 // concept C = sizeof(U) == 4;
2369 // void foo() requires C<2, 'a'> { }
2370 // When normalizing foo(), we first form the normalized constraints of C:
2371 // AtomicExpr(sizeof(U) == 4,
2372 // U=SubstNonTypeTemplateParmExpr(Param=U,
2373 // Expr=DeclRef(U),
2374 // Type=decltype(T)))
2375 // Then we substitute T = 2, U = 'a' into the parameter mapping, and need to
2376 // produce:
2377 // AtomicExpr(sizeof(U) == 4,
2378 // U=SubstNonTypeTemplateParmExpr(Param=U,
2379 // Expr=ImpCast(
2380 // decltype(2),
2381 // SubstNTTPE(Param=U, Expr='a',
2382 // Type=char)),
2383 // Type=decltype(2)))
2384 // The call to CheckTemplateArgument here produces the ImpCast.
2385 TemplateArgument SugaredConverted, CanonicalConverted;
2386 if (SemaRef
2387 .CheckTemplateArgument(E->getParameter(), SubstType,
2388 SubstReplacement.get(), SugaredConverted,
2389 CanonicalConverted, Sema::CTAK_Specified)
2390 .isInvalid())
2391 return true;
2392 return transformNonTypeTemplateParmRef(E->getAssociatedDecl(),
2393 E->getParameter(), E->getExprLoc(),
2394 SugaredConverted, E->getPackIndex());
2397 ExprResult TemplateInstantiator::RebuildVarDeclRefExpr(VarDecl *PD,
2398 SourceLocation Loc) {
2399 DeclarationNameInfo NameInfo(PD->getDeclName(), Loc);
2400 return getSema().BuildDeclarationNameExpr(CXXScopeSpec(), NameInfo, PD);
2403 ExprResult
2404 TemplateInstantiator::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {
2405 if (getSema().ArgumentPackSubstitutionIndex != -1) {
2406 // We can expand this parameter pack now.
2407 VarDecl *D = E->getExpansion(getSema().ArgumentPackSubstitutionIndex);
2408 VarDecl *VD = cast_or_null<VarDecl>(TransformDecl(E->getExprLoc(), D));
2409 if (!VD)
2410 return ExprError();
2411 return RebuildVarDeclRefExpr(VD, E->getExprLoc());
2414 QualType T = TransformType(E->getType());
2415 if (T.isNull())
2416 return ExprError();
2418 // Transform each of the parameter expansions into the corresponding
2419 // parameters in the instantiation of the function decl.
2420 SmallVector<VarDecl *, 8> Vars;
2421 Vars.reserve(E->getNumExpansions());
2422 for (FunctionParmPackExpr::iterator I = E->begin(), End = E->end();
2423 I != End; ++I) {
2424 VarDecl *D = cast_or_null<VarDecl>(TransformDecl(E->getExprLoc(), *I));
2425 if (!D)
2426 return ExprError();
2427 Vars.push_back(D);
2430 auto *PackExpr =
2431 FunctionParmPackExpr::Create(getSema().Context, T, E->getParameterPack(),
2432 E->getParameterPackLocation(), Vars);
2433 getSema().MarkFunctionParmPackReferenced(PackExpr);
2434 return PackExpr;
2437 ExprResult
2438 TemplateInstantiator::TransformFunctionParmPackRefExpr(DeclRefExpr *E,
2439 VarDecl *PD) {
2440 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
2441 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
2442 = getSema().CurrentInstantiationScope->findInstantiationOf(PD);
2443 assert(Found && "no instantiation for parameter pack");
2445 Decl *TransformedDecl;
2446 if (DeclArgumentPack *Pack = Found->dyn_cast<DeclArgumentPack *>()) {
2447 // If this is a reference to a function parameter pack which we can
2448 // substitute but can't yet expand, build a FunctionParmPackExpr for it.
2449 if (getSema().ArgumentPackSubstitutionIndex == -1) {
2450 QualType T = TransformType(E->getType());
2451 if (T.isNull())
2452 return ExprError();
2453 auto *PackExpr = FunctionParmPackExpr::Create(getSema().Context, T, PD,
2454 E->getExprLoc(), *Pack);
2455 getSema().MarkFunctionParmPackReferenced(PackExpr);
2456 return PackExpr;
2459 TransformedDecl = (*Pack)[getSema().ArgumentPackSubstitutionIndex];
2460 } else {
2461 TransformedDecl = cast<Decl *>(*Found);
2464 // We have either an unexpanded pack or a specific expansion.
2465 return RebuildVarDeclRefExpr(cast<VarDecl>(TransformedDecl), E->getExprLoc());
2468 ExprResult
2469 TemplateInstantiator::TransformDeclRefExpr(DeclRefExpr *E) {
2470 NamedDecl *D = E->getDecl();
2472 // Handle references to non-type template parameters and non-type template
2473 // parameter packs.
2474 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) {
2475 if (NTTP->getDepth() < TemplateArgs.getNumLevels())
2476 return TransformTemplateParmRefExpr(E, NTTP);
2478 // We have a non-type template parameter that isn't fully substituted;
2479 // FindInstantiatedDecl will find it in the local instantiation scope.
2482 // Handle references to function parameter packs.
2483 if (VarDecl *PD = dyn_cast<VarDecl>(D))
2484 if (PD->isParameterPack())
2485 return TransformFunctionParmPackRefExpr(E, PD);
2487 return inherited::TransformDeclRefExpr(E);
2490 ExprResult TemplateInstantiator::TransformCXXDefaultArgExpr(
2491 CXXDefaultArgExpr *E) {
2492 assert(!cast<FunctionDecl>(E->getParam()->getDeclContext())->
2493 getDescribedFunctionTemplate() &&
2494 "Default arg expressions are never formed in dependent cases.");
2495 return SemaRef.BuildCXXDefaultArgExpr(
2496 E->getUsedLocation(), cast<FunctionDecl>(E->getParam()->getDeclContext()),
2497 E->getParam());
2500 template<typename Fn>
2501 QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB,
2502 FunctionProtoTypeLoc TL,
2503 CXXRecordDecl *ThisContext,
2504 Qualifiers ThisTypeQuals,
2505 Fn TransformExceptionSpec) {
2506 // If this is a lambda or block, the transformation MUST be done in the
2507 // CurrentInstantiationScope since it introduces a mapping of
2508 // the original to the newly created transformed parameters.
2510 // In that case, TemplateInstantiator::TransformLambdaExpr will
2511 // have already pushed a scope for this prototype, so don't create
2512 // a second one.
2513 LocalInstantiationScope *Current = getSema().CurrentInstantiationScope;
2514 std::optional<LocalInstantiationScope> Scope;
2515 if (!Current || !Current->isLambdaOrBlock())
2516 Scope.emplace(SemaRef, /*CombineWithOuterScope=*/true);
2518 return inherited::TransformFunctionProtoType(
2519 TLB, TL, ThisContext, ThisTypeQuals, TransformExceptionSpec);
2522 ParmVarDecl *TemplateInstantiator::TransformFunctionTypeParam(
2523 ParmVarDecl *OldParm, int indexAdjustment,
2524 std::optional<unsigned> NumExpansions, bool ExpectParameterPack) {
2525 auto NewParm = SemaRef.SubstParmVarDecl(
2526 OldParm, TemplateArgs, indexAdjustment, NumExpansions,
2527 ExpectParameterPack, EvaluateConstraints);
2528 if (NewParm && SemaRef.getLangOpts().OpenCL)
2529 SemaRef.deduceOpenCLAddressSpace(NewParm);
2530 return NewParm;
2533 QualType TemplateInstantiator::BuildSubstTemplateTypeParmType(
2534 TypeLocBuilder &TLB, bool SuppressObjCLifetime, bool Final,
2535 Decl *AssociatedDecl, unsigned Index, std::optional<unsigned> PackIndex,
2536 TemplateArgument Arg, SourceLocation NameLoc) {
2537 QualType Replacement = Arg.getAsType();
2539 // If the template parameter had ObjC lifetime qualifiers,
2540 // then any such qualifiers on the replacement type are ignored.
2541 if (SuppressObjCLifetime) {
2542 Qualifiers RQs;
2543 RQs = Replacement.getQualifiers();
2544 RQs.removeObjCLifetime();
2545 Replacement =
2546 SemaRef.Context.getQualifiedType(Replacement.getUnqualifiedType(), RQs);
2549 if (Final) {
2550 TLB.pushTrivial(SemaRef.Context, Replacement, NameLoc);
2551 return Replacement;
2553 // TODO: only do this uniquing once, at the start of instantiation.
2554 QualType Result = getSema().Context.getSubstTemplateTypeParmType(
2555 Replacement, AssociatedDecl, Index, PackIndex);
2556 SubstTemplateTypeParmTypeLoc NewTL =
2557 TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
2558 NewTL.setNameLoc(NameLoc);
2559 return Result;
2562 QualType
2563 TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB,
2564 TemplateTypeParmTypeLoc TL,
2565 bool SuppressObjCLifetime) {
2566 const TemplateTypeParmType *T = TL.getTypePtr();
2567 if (T->getDepth() < TemplateArgs.getNumLevels()) {
2568 // Replace the template type parameter with its corresponding
2569 // template argument.
2571 // If the corresponding template argument is NULL or doesn't exist, it's
2572 // because we are performing instantiation from explicitly-specified
2573 // template arguments in a function template class, but there were some
2574 // arguments left unspecified.
2575 if (!TemplateArgs.hasTemplateArgument(T->getDepth(), T->getIndex())) {
2576 IsIncomplete = true;
2577 if (BailOutOnIncomplete)
2578 return QualType();
2580 TemplateTypeParmTypeLoc NewTL
2581 = TLB.push<TemplateTypeParmTypeLoc>(TL.getType());
2582 NewTL.setNameLoc(TL.getNameLoc());
2583 return TL.getType();
2586 TemplateArgument Arg = TemplateArgs(T->getDepth(), T->getIndex());
2588 if (TemplateArgs.isRewrite()) {
2589 // We're rewriting the template parameter as a reference to another
2590 // template parameter.
2591 if (Arg.getKind() == TemplateArgument::Pack) {
2592 assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() &&
2593 "unexpected pack arguments in template rewrite");
2594 Arg = Arg.pack_begin()->getPackExpansionPattern();
2596 assert(Arg.getKind() == TemplateArgument::Type &&
2597 "unexpected nontype template argument kind in template rewrite");
2598 QualType NewT = Arg.getAsType();
2599 TLB.pushTrivial(SemaRef.Context, NewT, TL.getNameLoc());
2600 return NewT;
2603 auto [AssociatedDecl, Final] =
2604 TemplateArgs.getAssociatedDecl(T->getDepth());
2605 std::optional<unsigned> PackIndex;
2606 if (T->isParameterPack()) {
2607 assert(Arg.getKind() == TemplateArgument::Pack &&
2608 "Missing argument pack");
2610 if (getSema().ArgumentPackSubstitutionIndex == -1) {
2611 // We have the template argument pack, but we're not expanding the
2612 // enclosing pack expansion yet. Just save the template argument
2613 // pack for later substitution.
2614 QualType Result = getSema().Context.getSubstTemplateTypeParmPackType(
2615 AssociatedDecl, T->getIndex(), Final, Arg);
2616 SubstTemplateTypeParmPackTypeLoc NewTL
2617 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(Result);
2618 NewTL.setNameLoc(TL.getNameLoc());
2619 return Result;
2622 // PackIndex starts from last element.
2623 PackIndex = getPackIndex(Arg);
2624 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
2627 assert(Arg.getKind() == TemplateArgument::Type &&
2628 "Template argument kind mismatch");
2630 return BuildSubstTemplateTypeParmType(TLB, SuppressObjCLifetime, Final,
2631 AssociatedDecl, T->getIndex(),
2632 PackIndex, Arg, TL.getNameLoc());
2635 // The template type parameter comes from an inner template (e.g.,
2636 // the template parameter list of a member template inside the
2637 // template we are instantiating). Create a new template type
2638 // parameter with the template "level" reduced by one.
2639 TemplateTypeParmDecl *NewTTPDecl = nullptr;
2640 if (TemplateTypeParmDecl *OldTTPDecl = T->getDecl())
2641 NewTTPDecl = cast_or_null<TemplateTypeParmDecl>(
2642 TransformDecl(TL.getNameLoc(), OldTTPDecl));
2643 QualType Result = getSema().Context.getTemplateTypeParmType(
2644 T->getDepth() - TemplateArgs.getNumSubstitutedLevels(), T->getIndex(),
2645 T->isParameterPack(), NewTTPDecl);
2646 TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result);
2647 NewTL.setNameLoc(TL.getNameLoc());
2648 return Result;
2651 QualType TemplateInstantiator::TransformSubstTemplateTypeParmPackType(
2652 TypeLocBuilder &TLB, SubstTemplateTypeParmPackTypeLoc TL,
2653 bool SuppressObjCLifetime) {
2654 const SubstTemplateTypeParmPackType *T = TL.getTypePtr();
2656 Decl *NewReplaced = TransformDecl(TL.getNameLoc(), T->getAssociatedDecl());
2658 if (getSema().ArgumentPackSubstitutionIndex == -1) {
2659 // We aren't expanding the parameter pack, so just return ourselves.
2660 QualType Result = TL.getType();
2661 if (NewReplaced != T->getAssociatedDecl())
2662 Result = getSema().Context.getSubstTemplateTypeParmPackType(
2663 NewReplaced, T->getIndex(), T->getFinal(), T->getArgumentPack());
2664 SubstTemplateTypeParmPackTypeLoc NewTL =
2665 TLB.push<SubstTemplateTypeParmPackTypeLoc>(Result);
2666 NewTL.setNameLoc(TL.getNameLoc());
2667 return Result;
2670 TemplateArgument Pack = T->getArgumentPack();
2671 TemplateArgument Arg = getPackSubstitutedTemplateArgument(getSema(), Pack);
2672 return BuildSubstTemplateTypeParmType(
2673 TLB, SuppressObjCLifetime, T->getFinal(), NewReplaced, T->getIndex(),
2674 getPackIndex(Pack), Arg, TL.getNameLoc());
2677 static concepts::Requirement::SubstitutionDiagnostic *
2678 createSubstDiag(Sema &S, TemplateDeductionInfo &Info,
2679 Sema::EntityPrinter Printer) {
2680 SmallString<128> Message;
2681 SourceLocation ErrorLoc;
2682 if (Info.hasSFINAEDiagnostic()) {
2683 PartialDiagnosticAt PDA(SourceLocation(),
2684 PartialDiagnostic::NullDiagnostic{});
2685 Info.takeSFINAEDiagnostic(PDA);
2686 PDA.second.EmitToString(S.getDiagnostics(), Message);
2687 ErrorLoc = PDA.first;
2688 } else {
2689 ErrorLoc = Info.getLocation();
2691 SmallString<128> Entity;
2692 llvm::raw_svector_ostream OS(Entity);
2693 Printer(OS);
2694 const ASTContext &C = S.Context;
2695 return new (C) concepts::Requirement::SubstitutionDiagnostic{
2696 C.backupStr(Entity), ErrorLoc, C.backupStr(Message)};
2699 concepts::Requirement::SubstitutionDiagnostic *
2700 Sema::createSubstDiagAt(SourceLocation Location, EntityPrinter Printer) {
2701 SmallString<128> Entity;
2702 llvm::raw_svector_ostream OS(Entity);
2703 Printer(OS);
2704 const ASTContext &C = Context;
2705 return new (C) concepts::Requirement::SubstitutionDiagnostic{
2706 /*SubstitutedEntity=*/C.backupStr(Entity),
2707 /*DiagLoc=*/Location, /*DiagMessage=*/StringRef()};
2710 ExprResult TemplateInstantiator::TransformRequiresTypeParams(
2711 SourceLocation KWLoc, SourceLocation RBraceLoc, const RequiresExpr *RE,
2712 RequiresExprBodyDecl *Body, ArrayRef<ParmVarDecl *> Params,
2713 SmallVectorImpl<QualType> &PTypes,
2714 SmallVectorImpl<ParmVarDecl *> &TransParams,
2715 Sema::ExtParameterInfoBuilder &PInfos) {
2717 TemplateDeductionInfo Info(KWLoc);
2718 Sema::InstantiatingTemplate TypeInst(SemaRef, KWLoc,
2719 RE, Info,
2720 SourceRange{KWLoc, RBraceLoc});
2721 Sema::SFINAETrap Trap(SemaRef);
2723 unsigned ErrorIdx;
2724 if (getDerived().TransformFunctionTypeParams(
2725 KWLoc, Params, /*ParamTypes=*/nullptr, /*ParamInfos=*/nullptr, PTypes,
2726 &TransParams, PInfos, &ErrorIdx) ||
2727 Trap.hasErrorOccurred()) {
2728 SmallVector<concepts::Requirement *, 4> TransReqs;
2729 ParmVarDecl *FailedDecl = Params[ErrorIdx];
2730 // Add a 'failed' Requirement to contain the error that caused the failure
2731 // here.
2732 TransReqs.push_back(RebuildTypeRequirement(createSubstDiag(
2733 SemaRef, Info, [&](llvm::raw_ostream &OS) { OS << *FailedDecl; })));
2734 return getDerived().RebuildRequiresExpr(KWLoc, Body, RE->getLParenLoc(),
2735 TransParams, RE->getRParenLoc(),
2736 TransReqs, RBraceLoc);
2739 return ExprResult{};
2742 concepts::TypeRequirement *
2743 TemplateInstantiator::TransformTypeRequirement(concepts::TypeRequirement *Req) {
2744 if (!Req->isDependent() && !AlwaysRebuild())
2745 return Req;
2746 if (Req->isSubstitutionFailure()) {
2747 if (AlwaysRebuild())
2748 return RebuildTypeRequirement(
2749 Req->getSubstitutionDiagnostic());
2750 return Req;
2753 Sema::SFINAETrap Trap(SemaRef);
2754 TemplateDeductionInfo Info(Req->getType()->getTypeLoc().getBeginLoc());
2755 Sema::InstantiatingTemplate TypeInst(SemaRef,
2756 Req->getType()->getTypeLoc().getBeginLoc(), Req, Info,
2757 Req->getType()->getTypeLoc().getSourceRange());
2758 if (TypeInst.isInvalid())
2759 return nullptr;
2760 TypeSourceInfo *TransType = TransformType(Req->getType());
2761 if (!TransType || Trap.hasErrorOccurred())
2762 return RebuildTypeRequirement(createSubstDiag(SemaRef, Info,
2763 [&] (llvm::raw_ostream& OS) {
2764 Req->getType()->getType().print(OS, SemaRef.getPrintingPolicy());
2765 }));
2766 return RebuildTypeRequirement(TransType);
2769 concepts::ExprRequirement *
2770 TemplateInstantiator::TransformExprRequirement(concepts::ExprRequirement *Req) {
2771 if (!Req->isDependent() && !AlwaysRebuild())
2772 return Req;
2774 Sema::SFINAETrap Trap(SemaRef);
2776 llvm::PointerUnion<Expr *, concepts::Requirement::SubstitutionDiagnostic *>
2777 TransExpr;
2778 if (Req->isExprSubstitutionFailure())
2779 TransExpr = Req->getExprSubstitutionDiagnostic();
2780 else {
2781 Expr *E = Req->getExpr();
2782 TemplateDeductionInfo Info(E->getBeginLoc());
2783 Sema::InstantiatingTemplate ExprInst(SemaRef, E->getBeginLoc(), Req, Info,
2784 E->getSourceRange());
2785 if (ExprInst.isInvalid())
2786 return nullptr;
2787 ExprResult TransExprRes = TransformExpr(E);
2788 if (!TransExprRes.isInvalid() && !Trap.hasErrorOccurred() &&
2789 TransExprRes.get()->hasPlaceholderType())
2790 TransExprRes = SemaRef.CheckPlaceholderExpr(TransExprRes.get());
2791 if (TransExprRes.isInvalid() || Trap.hasErrorOccurred())
2792 TransExpr = createSubstDiag(SemaRef, Info, [&](llvm::raw_ostream &OS) {
2793 E->printPretty(OS, nullptr, SemaRef.getPrintingPolicy());
2795 else
2796 TransExpr = TransExprRes.get();
2799 std::optional<concepts::ExprRequirement::ReturnTypeRequirement> TransRetReq;
2800 const auto &RetReq = Req->getReturnTypeRequirement();
2801 if (RetReq.isEmpty())
2802 TransRetReq.emplace();
2803 else if (RetReq.isSubstitutionFailure())
2804 TransRetReq.emplace(RetReq.getSubstitutionDiagnostic());
2805 else if (RetReq.isTypeConstraint()) {
2806 TemplateParameterList *OrigTPL =
2807 RetReq.getTypeConstraintTemplateParameterList();
2808 TemplateDeductionInfo Info(OrigTPL->getTemplateLoc());
2809 Sema::InstantiatingTemplate TPLInst(SemaRef, OrigTPL->getTemplateLoc(),
2810 Req, Info, OrigTPL->getSourceRange());
2811 if (TPLInst.isInvalid())
2812 return nullptr;
2813 TemplateParameterList *TPL = TransformTemplateParameterList(OrigTPL);
2814 if (!TPL || Trap.hasErrorOccurred())
2815 TransRetReq.emplace(createSubstDiag(SemaRef, Info,
2816 [&] (llvm::raw_ostream& OS) {
2817 RetReq.getTypeConstraint()->getImmediatelyDeclaredConstraint()
2818 ->printPretty(OS, nullptr, SemaRef.getPrintingPolicy());
2819 }));
2820 else {
2821 TPLInst.Clear();
2822 TransRetReq.emplace(TPL);
2825 assert(TransRetReq && "All code paths leading here must set TransRetReq");
2826 if (Expr *E = TransExpr.dyn_cast<Expr *>())
2827 return RebuildExprRequirement(E, Req->isSimple(), Req->getNoexceptLoc(),
2828 std::move(*TransRetReq));
2829 return RebuildExprRequirement(
2830 cast<concepts::Requirement::SubstitutionDiagnostic *>(TransExpr),
2831 Req->isSimple(), Req->getNoexceptLoc(), std::move(*TransRetReq));
2834 concepts::NestedRequirement *
2835 TemplateInstantiator::TransformNestedRequirement(
2836 concepts::NestedRequirement *Req) {
2837 if (!Req->isDependent() && !AlwaysRebuild())
2838 return Req;
2839 if (Req->hasInvalidConstraint()) {
2840 if (AlwaysRebuild())
2841 return RebuildNestedRequirement(Req->getInvalidConstraintEntity(),
2842 Req->getConstraintSatisfaction());
2843 return Req;
2845 Sema::InstantiatingTemplate ReqInst(SemaRef,
2846 Req->getConstraintExpr()->getBeginLoc(), Req,
2847 Sema::InstantiatingTemplate::ConstraintsCheck{},
2848 Req->getConstraintExpr()->getSourceRange());
2849 if (!getEvaluateConstraints()) {
2850 ExprResult TransConstraint = TransformExpr(Req->getConstraintExpr());
2851 if (TransConstraint.isInvalid() || !TransConstraint.get())
2852 return nullptr;
2853 if (TransConstraint.get()->isInstantiationDependent())
2854 return new (SemaRef.Context)
2855 concepts::NestedRequirement(TransConstraint.get());
2856 ConstraintSatisfaction Satisfaction;
2857 return new (SemaRef.Context) concepts::NestedRequirement(
2858 SemaRef.Context, TransConstraint.get(), Satisfaction);
2861 ExprResult TransConstraint;
2862 ConstraintSatisfaction Satisfaction;
2863 TemplateDeductionInfo Info(Req->getConstraintExpr()->getBeginLoc());
2865 EnterExpressionEvaluationContext ContextRAII(
2866 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
2867 Sema::SFINAETrap Trap(SemaRef);
2868 Sema::InstantiatingTemplate ConstrInst(SemaRef,
2869 Req->getConstraintExpr()->getBeginLoc(), Req, Info,
2870 Req->getConstraintExpr()->getSourceRange());
2871 if (ConstrInst.isInvalid())
2872 return nullptr;
2873 llvm::SmallVector<Expr *> Result;
2874 if (!SemaRef.CheckConstraintSatisfaction(
2875 nullptr, {Req->getConstraintExpr()}, Result, TemplateArgs,
2876 Req->getConstraintExpr()->getSourceRange(), Satisfaction) &&
2877 !Result.empty())
2878 TransConstraint = Result[0];
2879 assert(!Trap.hasErrorOccurred() && "Substitution failures must be handled "
2880 "by CheckConstraintSatisfaction.");
2882 ASTContext &C = SemaRef.Context;
2883 if (TransConstraint.isUsable() &&
2884 TransConstraint.get()->isInstantiationDependent())
2885 return new (C) concepts::NestedRequirement(TransConstraint.get());
2886 if (TransConstraint.isInvalid() || !TransConstraint.get() ||
2887 Satisfaction.HasSubstitutionFailure()) {
2888 SmallString<128> Entity;
2889 llvm::raw_svector_ostream OS(Entity);
2890 Req->getConstraintExpr()->printPretty(OS, nullptr,
2891 SemaRef.getPrintingPolicy());
2892 return new (C) concepts::NestedRequirement(
2893 SemaRef.Context, C.backupStr(Entity), Satisfaction);
2895 return new (C)
2896 concepts::NestedRequirement(C, TransConstraint.get(), Satisfaction);
2899 TypeSourceInfo *Sema::SubstType(TypeSourceInfo *T,
2900 const MultiLevelTemplateArgumentList &Args,
2901 SourceLocation Loc,
2902 DeclarationName Entity,
2903 bool AllowDeducedTST) {
2904 assert(!CodeSynthesisContexts.empty() &&
2905 "Cannot perform an instantiation without some context on the "
2906 "instantiation stack");
2908 if (!T->getType()->isInstantiationDependentType() &&
2909 !T->getType()->isVariablyModifiedType())
2910 return T;
2912 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
2913 return AllowDeducedTST ? Instantiator.TransformTypeWithDeducedTST(T)
2914 : Instantiator.TransformType(T);
2917 TypeSourceInfo *Sema::SubstType(TypeLoc TL,
2918 const MultiLevelTemplateArgumentList &Args,
2919 SourceLocation Loc,
2920 DeclarationName Entity) {
2921 assert(!CodeSynthesisContexts.empty() &&
2922 "Cannot perform an instantiation without some context on the "
2923 "instantiation stack");
2925 if (TL.getType().isNull())
2926 return nullptr;
2928 if (!TL.getType()->isInstantiationDependentType() &&
2929 !TL.getType()->isVariablyModifiedType()) {
2930 // FIXME: Make a copy of the TypeLoc data here, so that we can
2931 // return a new TypeSourceInfo. Inefficient!
2932 TypeLocBuilder TLB;
2933 TLB.pushFullCopy(TL);
2934 return TLB.getTypeSourceInfo(Context, TL.getType());
2937 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
2938 TypeLocBuilder TLB;
2939 TLB.reserve(TL.getFullDataSize());
2940 QualType Result = Instantiator.TransformType(TLB, TL);
2941 if (Result.isNull())
2942 return nullptr;
2944 return TLB.getTypeSourceInfo(Context, Result);
2947 /// Deprecated form of the above.
2948 QualType Sema::SubstType(QualType T,
2949 const MultiLevelTemplateArgumentList &TemplateArgs,
2950 SourceLocation Loc, DeclarationName Entity,
2951 bool *IsIncompleteSubstitution) {
2952 assert(!CodeSynthesisContexts.empty() &&
2953 "Cannot perform an instantiation without some context on the "
2954 "instantiation stack");
2956 // If T is not a dependent type or a variably-modified type, there
2957 // is nothing to do.
2958 if (!T->isInstantiationDependentType() && !T->isVariablyModifiedType())
2959 return T;
2961 TemplateInstantiator Instantiator(
2962 *this, TemplateArgs, Loc, Entity,
2963 /*BailOutOnIncomplete=*/IsIncompleteSubstitution != nullptr);
2964 QualType QT = Instantiator.TransformType(T);
2965 if (IsIncompleteSubstitution && Instantiator.getIsIncomplete())
2966 *IsIncompleteSubstitution = true;
2967 return QT;
2970 static bool NeedsInstantiationAsFunctionType(TypeSourceInfo *T) {
2971 if (T->getType()->isInstantiationDependentType() ||
2972 T->getType()->isVariablyModifiedType())
2973 return true;
2975 TypeLoc TL = T->getTypeLoc().IgnoreParens();
2976 if (!TL.getAs<FunctionProtoTypeLoc>())
2977 return false;
2979 FunctionProtoTypeLoc FP = TL.castAs<FunctionProtoTypeLoc>();
2980 for (ParmVarDecl *P : FP.getParams()) {
2981 // This must be synthesized from a typedef.
2982 if (!P) continue;
2984 // If there are any parameters, a new TypeSourceInfo that refers to the
2985 // instantiated parameters must be built.
2986 return true;
2989 return false;
2992 TypeSourceInfo *Sema::SubstFunctionDeclType(TypeSourceInfo *T,
2993 const MultiLevelTemplateArgumentList &Args,
2994 SourceLocation Loc,
2995 DeclarationName Entity,
2996 CXXRecordDecl *ThisContext,
2997 Qualifiers ThisTypeQuals,
2998 bool EvaluateConstraints) {
2999 assert(!CodeSynthesisContexts.empty() &&
3000 "Cannot perform an instantiation without some context on the "
3001 "instantiation stack");
3003 if (!NeedsInstantiationAsFunctionType(T))
3004 return T;
3006 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
3007 Instantiator.setEvaluateConstraints(EvaluateConstraints);
3009 TypeLocBuilder TLB;
3011 TypeLoc TL = T->getTypeLoc();
3012 TLB.reserve(TL.getFullDataSize());
3014 QualType Result;
3016 if (FunctionProtoTypeLoc Proto =
3017 TL.IgnoreParens().getAs<FunctionProtoTypeLoc>()) {
3018 // Instantiate the type, other than its exception specification. The
3019 // exception specification is instantiated in InitFunctionInstantiation
3020 // once we've built the FunctionDecl.
3021 // FIXME: Set the exception specification to EST_Uninstantiated here,
3022 // instead of rebuilding the function type again later.
3023 Result = Instantiator.TransformFunctionProtoType(
3024 TLB, Proto, ThisContext, ThisTypeQuals,
3025 [](FunctionProtoType::ExceptionSpecInfo &ESI,
3026 bool &Changed) { return false; });
3027 } else {
3028 Result = Instantiator.TransformType(TLB, TL);
3030 // When there are errors resolving types, clang may use IntTy as a fallback,
3031 // breaking our assumption that function declarations have function types.
3032 if (Result.isNull() || !Result->isFunctionType())
3033 return nullptr;
3035 return TLB.getTypeSourceInfo(Context, Result);
3038 bool Sema::SubstExceptionSpec(SourceLocation Loc,
3039 FunctionProtoType::ExceptionSpecInfo &ESI,
3040 SmallVectorImpl<QualType> &ExceptionStorage,
3041 const MultiLevelTemplateArgumentList &Args) {
3042 bool Changed = false;
3043 TemplateInstantiator Instantiator(*this, Args, Loc, DeclarationName());
3044 return Instantiator.TransformExceptionSpec(Loc, ESI, ExceptionStorage,
3045 Changed);
3048 void Sema::SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto,
3049 const MultiLevelTemplateArgumentList &Args) {
3050 FunctionProtoType::ExceptionSpecInfo ESI =
3051 Proto->getExtProtoInfo().ExceptionSpec;
3053 SmallVector<QualType, 4> ExceptionStorage;
3054 if (SubstExceptionSpec(New->getTypeSourceInfo()->getTypeLoc().getEndLoc(),
3055 ESI, ExceptionStorage, Args))
3056 // On error, recover by dropping the exception specification.
3057 ESI.Type = EST_None;
3059 UpdateExceptionSpec(New, ESI);
3062 namespace {
3064 struct GetContainedInventedTypeParmVisitor :
3065 public TypeVisitor<GetContainedInventedTypeParmVisitor,
3066 TemplateTypeParmDecl *> {
3067 using TypeVisitor<GetContainedInventedTypeParmVisitor,
3068 TemplateTypeParmDecl *>::Visit;
3070 TemplateTypeParmDecl *Visit(QualType T) {
3071 if (T.isNull())
3072 return nullptr;
3073 return Visit(T.getTypePtr());
3075 // The deduced type itself.
3076 TemplateTypeParmDecl *VisitTemplateTypeParmType(
3077 const TemplateTypeParmType *T) {
3078 if (!T->getDecl() || !T->getDecl()->isImplicit())
3079 return nullptr;
3080 return T->getDecl();
3083 // Only these types can contain 'auto' types, and subsequently be replaced
3084 // by references to invented parameters.
3086 TemplateTypeParmDecl *VisitElaboratedType(const ElaboratedType *T) {
3087 return Visit(T->getNamedType());
3090 TemplateTypeParmDecl *VisitPointerType(const PointerType *T) {
3091 return Visit(T->getPointeeType());
3094 TemplateTypeParmDecl *VisitBlockPointerType(const BlockPointerType *T) {
3095 return Visit(T->getPointeeType());
3098 TemplateTypeParmDecl *VisitReferenceType(const ReferenceType *T) {
3099 return Visit(T->getPointeeTypeAsWritten());
3102 TemplateTypeParmDecl *VisitMemberPointerType(const MemberPointerType *T) {
3103 return Visit(T->getPointeeType());
3106 TemplateTypeParmDecl *VisitArrayType(const ArrayType *T) {
3107 return Visit(T->getElementType());
3110 TemplateTypeParmDecl *VisitDependentSizedExtVectorType(
3111 const DependentSizedExtVectorType *T) {
3112 return Visit(T->getElementType());
3115 TemplateTypeParmDecl *VisitVectorType(const VectorType *T) {
3116 return Visit(T->getElementType());
3119 TemplateTypeParmDecl *VisitFunctionProtoType(const FunctionProtoType *T) {
3120 return VisitFunctionType(T);
3123 TemplateTypeParmDecl *VisitFunctionType(const FunctionType *T) {
3124 return Visit(T->getReturnType());
3127 TemplateTypeParmDecl *VisitParenType(const ParenType *T) {
3128 return Visit(T->getInnerType());
3131 TemplateTypeParmDecl *VisitAttributedType(const AttributedType *T) {
3132 return Visit(T->getModifiedType());
3135 TemplateTypeParmDecl *VisitMacroQualifiedType(const MacroQualifiedType *T) {
3136 return Visit(T->getUnderlyingType());
3139 TemplateTypeParmDecl *VisitAdjustedType(const AdjustedType *T) {
3140 return Visit(T->getOriginalType());
3143 TemplateTypeParmDecl *VisitPackExpansionType(const PackExpansionType *T) {
3144 return Visit(T->getPattern());
3148 } // namespace
3150 namespace {
3152 struct ExpandPackedTypeConstraints
3153 : TreeTransform<ExpandPackedTypeConstraints> {
3155 using inherited = TreeTransform<ExpandPackedTypeConstraints>;
3157 const MultiLevelTemplateArgumentList &TemplateArgs;
3159 ExpandPackedTypeConstraints(
3160 Sema &SemaRef, const MultiLevelTemplateArgumentList &TemplateArgs)
3161 : inherited(SemaRef), TemplateArgs(TemplateArgs) {}
3163 using inherited::TransformTemplateTypeParmType;
3165 QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
3166 TemplateTypeParmTypeLoc TL, bool) {
3167 const TemplateTypeParmType *T = TL.getTypePtr();
3168 if (!T->isParameterPack()) {
3169 TemplateTypeParmTypeLoc NewTL =
3170 TLB.push<TemplateTypeParmTypeLoc>(TL.getType());
3171 NewTL.setNameLoc(TL.getNameLoc());
3172 return TL.getType();
3175 assert(SemaRef.ArgumentPackSubstitutionIndex != -1);
3177 TemplateArgument Arg = TemplateArgs(T->getDepth(), T->getIndex());
3179 std::optional<unsigned> PackIndex;
3180 if (Arg.getKind() == TemplateArgument::Pack)
3181 PackIndex = Arg.pack_size() - 1 - SemaRef.ArgumentPackSubstitutionIndex;
3183 QualType Result = SemaRef.Context.getSubstTemplateTypeParmType(
3184 TL.getType(), T->getDecl(), T->getIndex(), PackIndex,
3185 SubstTemplateTypeParmTypeFlag::ExpandPacksInPlace);
3186 SubstTemplateTypeParmTypeLoc NewTL =
3187 TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
3188 NewTL.setNameLoc(TL.getNameLoc());
3189 return Result;
3192 QualType TransformSubstTemplateTypeParmType(TypeLocBuilder &TLB,
3193 SubstTemplateTypeParmTypeLoc TL) {
3194 const SubstTemplateTypeParmType *T = TL.getTypePtr();
3195 if (T->getPackIndex()) {
3196 SubstTemplateTypeParmTypeLoc TypeLoc =
3197 TLB.push<SubstTemplateTypeParmTypeLoc>(TL.getType());
3198 TypeLoc.setNameLoc(TL.getNameLoc());
3199 return TypeLoc.getType();
3201 return inherited::TransformSubstTemplateTypeParmType(TLB, TL);
3204 bool SubstTemplateArguments(ArrayRef<TemplateArgumentLoc> Args,
3205 TemplateArgumentListInfo &Out) {
3206 return inherited::TransformTemplateArguments(Args.begin(), Args.end(), Out);
3210 } // namespace
3212 bool Sema::SubstTypeConstraint(
3213 TemplateTypeParmDecl *Inst, const TypeConstraint *TC,
3214 const MultiLevelTemplateArgumentList &TemplateArgs,
3215 bool EvaluateConstraints) {
3216 const ASTTemplateArgumentListInfo *TemplArgInfo =
3217 TC->getTemplateArgsAsWritten();
3219 if (!EvaluateConstraints) {
3220 bool ShouldExpandExplicitTemplateArgs =
3221 TemplArgInfo && ArgumentPackSubstitutionIndex != -1 &&
3222 llvm::any_of(TemplArgInfo->arguments(), [](auto &Arg) {
3223 return Arg.getArgument().containsUnexpandedParameterPack();
3226 // We want to transform the packs into Subst* nodes for type constraints
3227 // inside a pack expansion. For example,
3229 // template <class... Ts> void foo() {
3230 // bar([](C<Ts> auto value) {}...);
3231 // }
3233 // As we expand Ts in the process of instantiating foo(), and retain
3234 // the original template depths of Ts until the constraint evaluation, we
3235 // would otherwise have no chance to expand Ts by the time of evaluating
3236 // C<auto, Ts>.
3238 // So we form a Subst* node for Ts along with a proper substitution index
3239 // here, and substitute the node with a complete MLTAL later in evaluation.
3240 if (ShouldExpandExplicitTemplateArgs) {
3241 TemplateArgumentListInfo InstArgs;
3242 InstArgs.setLAngleLoc(TemplArgInfo->LAngleLoc);
3243 InstArgs.setRAngleLoc(TemplArgInfo->RAngleLoc);
3244 if (ExpandPackedTypeConstraints(*this, TemplateArgs)
3245 .SubstTemplateArguments(TemplArgInfo->arguments(), InstArgs))
3246 return true;
3248 // The type of the original parameter.
3249 auto *ConstraintExpr = TC->getImmediatelyDeclaredConstraint();
3250 QualType ConstrainedType;
3252 if (auto *FE = dyn_cast<CXXFoldExpr>(ConstraintExpr)) {
3253 assert(FE->getLHS());
3254 ConstraintExpr = FE->getLHS();
3256 auto *CSE = cast<ConceptSpecializationExpr>(ConstraintExpr);
3257 assert(!CSE->getTemplateArguments().empty() &&
3258 "Empty template arguments?");
3259 ConstrainedType = CSE->getTemplateArguments()[0].getAsType();
3260 assert(!ConstrainedType.isNull() &&
3261 "Failed to extract the original ConstrainedType?");
3263 return AttachTypeConstraint(
3264 TC->getNestedNameSpecifierLoc(), TC->getConceptNameInfo(),
3265 TC->getNamedConcept(),
3266 /*FoundDecl=*/TC->getConceptReference()->getFoundDecl(), &InstArgs,
3267 Inst, ConstrainedType,
3268 Inst->isParameterPack()
3269 ? cast<CXXFoldExpr>(TC->getImmediatelyDeclaredConstraint())
3270 ->getEllipsisLoc()
3271 : SourceLocation());
3273 Inst->setTypeConstraint(TC->getConceptReference(),
3274 TC->getImmediatelyDeclaredConstraint());
3275 return false;
3278 TemplateArgumentListInfo InstArgs;
3280 if (TemplArgInfo) {
3281 InstArgs.setLAngleLoc(TemplArgInfo->LAngleLoc);
3282 InstArgs.setRAngleLoc(TemplArgInfo->RAngleLoc);
3283 if (SubstTemplateArguments(TemplArgInfo->arguments(), TemplateArgs,
3284 InstArgs))
3285 return true;
3287 return AttachTypeConstraint(
3288 TC->getNestedNameSpecifierLoc(), TC->getConceptNameInfo(),
3289 TC->getNamedConcept(),
3290 /*FoundDecl=*/TC->getConceptReference()->getFoundDecl(), &InstArgs, Inst,
3291 Context.getTypeDeclType(Inst),
3292 Inst->isParameterPack()
3293 ? cast<CXXFoldExpr>(TC->getImmediatelyDeclaredConstraint())
3294 ->getEllipsisLoc()
3295 : SourceLocation());
3298 ParmVarDecl *Sema::SubstParmVarDecl(
3299 ParmVarDecl *OldParm, const MultiLevelTemplateArgumentList &TemplateArgs,
3300 int indexAdjustment, std::optional<unsigned> NumExpansions,
3301 bool ExpectParameterPack, bool EvaluateConstraint) {
3302 TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
3303 TypeSourceInfo *NewDI = nullptr;
3305 TypeLoc OldTL = OldDI->getTypeLoc();
3306 if (PackExpansionTypeLoc ExpansionTL = OldTL.getAs<PackExpansionTypeLoc>()) {
3308 // We have a function parameter pack. Substitute into the pattern of the
3309 // expansion.
3310 NewDI = SubstType(ExpansionTL.getPatternLoc(), TemplateArgs,
3311 OldParm->getLocation(), OldParm->getDeclName());
3312 if (!NewDI)
3313 return nullptr;
3315 if (NewDI->getType()->containsUnexpandedParameterPack()) {
3316 // We still have unexpanded parameter packs, which means that
3317 // our function parameter is still a function parameter pack.
3318 // Therefore, make its type a pack expansion type.
3319 NewDI = CheckPackExpansion(NewDI, ExpansionTL.getEllipsisLoc(),
3320 NumExpansions);
3321 } else if (ExpectParameterPack) {
3322 // We expected to get a parameter pack but didn't (because the type
3323 // itself is not a pack expansion type), so complain. This can occur when
3324 // the substitution goes through an alias template that "loses" the
3325 // pack expansion.
3326 Diag(OldParm->getLocation(),
3327 diag::err_function_parameter_pack_without_parameter_packs)
3328 << NewDI->getType();
3329 return nullptr;
3331 } else {
3332 NewDI = SubstType(OldDI, TemplateArgs, OldParm->getLocation(),
3333 OldParm->getDeclName());
3336 if (!NewDI)
3337 return nullptr;
3339 if (NewDI->getType()->isVoidType()) {
3340 Diag(OldParm->getLocation(), diag::err_param_with_void_type);
3341 return nullptr;
3344 // In abbreviated templates, TemplateTypeParmDecls with possible
3345 // TypeConstraints are created when the parameter list is originally parsed.
3346 // The TypeConstraints can therefore reference other functions parameters in
3347 // the abbreviated function template, which is why we must instantiate them
3348 // here, when the instantiated versions of those referenced parameters are in
3349 // scope.
3350 if (TemplateTypeParmDecl *TTP =
3351 GetContainedInventedTypeParmVisitor().Visit(OldDI->getType())) {
3352 if (const TypeConstraint *TC = TTP->getTypeConstraint()) {
3353 auto *Inst = cast_or_null<TemplateTypeParmDecl>(
3354 FindInstantiatedDecl(TTP->getLocation(), TTP, TemplateArgs));
3355 // We will first get here when instantiating the abbreviated function
3356 // template's described function, but we might also get here later.
3357 // Make sure we do not instantiate the TypeConstraint more than once.
3358 if (Inst && !Inst->getTypeConstraint()) {
3359 if (SubstTypeConstraint(Inst, TC, TemplateArgs, EvaluateConstraint))
3360 return nullptr;
3365 ParmVarDecl *NewParm = CheckParameter(Context.getTranslationUnitDecl(),
3366 OldParm->getInnerLocStart(),
3367 OldParm->getLocation(),
3368 OldParm->getIdentifier(),
3369 NewDI->getType(), NewDI,
3370 OldParm->getStorageClass());
3371 if (!NewParm)
3372 return nullptr;
3374 // Mark the (new) default argument as uninstantiated (if any).
3375 if (OldParm->hasUninstantiatedDefaultArg()) {
3376 Expr *Arg = OldParm->getUninstantiatedDefaultArg();
3377 NewParm->setUninstantiatedDefaultArg(Arg);
3378 } else if (OldParm->hasUnparsedDefaultArg()) {
3379 NewParm->setUnparsedDefaultArg();
3380 UnparsedDefaultArgInstantiations[OldParm].push_back(NewParm);
3381 } else if (Expr *Arg = OldParm->getDefaultArg()) {
3382 // Default arguments cannot be substituted until the declaration context
3383 // for the associated function or lambda capture class is available.
3384 // This is necessary for cases like the following where construction of
3385 // the lambda capture class for the outer lambda is dependent on the
3386 // parameter types but where the default argument is dependent on the
3387 // outer lambda's declaration context.
3388 // template <typename T>
3389 // auto f() {
3390 // return [](T = []{ return T{}; }()) { return 0; };
3391 // }
3392 NewParm->setUninstantiatedDefaultArg(Arg);
3395 NewParm->setExplicitObjectParameterLoc(
3396 OldParm->getExplicitObjectParamThisLoc());
3397 NewParm->setHasInheritedDefaultArg(OldParm->hasInheritedDefaultArg());
3399 if (OldParm->isParameterPack() && !NewParm->isParameterPack()) {
3400 // Add the new parameter to the instantiated parameter pack.
3401 CurrentInstantiationScope->InstantiatedLocalPackArg(OldParm, NewParm);
3402 } else {
3403 // Introduce an Old -> New mapping
3404 CurrentInstantiationScope->InstantiatedLocal(OldParm, NewParm);
3407 // FIXME: OldParm may come from a FunctionProtoType, in which case CurContext
3408 // can be anything, is this right ?
3409 NewParm->setDeclContext(CurContext);
3411 NewParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
3412 OldParm->getFunctionScopeIndex() + indexAdjustment);
3414 InstantiateAttrs(TemplateArgs, OldParm, NewParm);
3416 return NewParm;
3419 bool Sema::SubstParmTypes(
3420 SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
3421 const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
3422 const MultiLevelTemplateArgumentList &TemplateArgs,
3423 SmallVectorImpl<QualType> &ParamTypes,
3424 SmallVectorImpl<ParmVarDecl *> *OutParams,
3425 ExtParameterInfoBuilder &ParamInfos) {
3426 assert(!CodeSynthesisContexts.empty() &&
3427 "Cannot perform an instantiation without some context on the "
3428 "instantiation stack");
3430 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
3431 DeclarationName());
3432 return Instantiator.TransformFunctionTypeParams(
3433 Loc, Params, nullptr, ExtParamInfos, ParamTypes, OutParams, ParamInfos);
3436 bool Sema::SubstDefaultArgument(
3437 SourceLocation Loc,
3438 ParmVarDecl *Param,
3439 const MultiLevelTemplateArgumentList &TemplateArgs,
3440 bool ForCallExpr) {
3441 FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());
3442 Expr *PatternExpr = Param->getUninstantiatedDefaultArg();
3444 EnterExpressionEvaluationContext EvalContext(
3445 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
3447 InstantiatingTemplate Inst(*this, Loc, Param, TemplateArgs.getInnermost());
3448 if (Inst.isInvalid())
3449 return true;
3450 if (Inst.isAlreadyInstantiating()) {
3451 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
3452 Param->setInvalidDecl();
3453 return true;
3456 ExprResult Result;
3458 // C++ [dcl.fct.default]p5:
3459 // The names in the [default argument] expression are bound, and
3460 // the semantic constraints are checked, at the point where the
3461 // default argument expression appears.
3462 ContextRAII SavedContext(*this, FD);
3463 std::unique_ptr<LocalInstantiationScope> LIS;
3465 if (ForCallExpr) {
3466 // When instantiating a default argument due to use in a call expression,
3467 // an instantiation scope that includes the parameters of the callee is
3468 // required to satisfy references from the default argument. For example:
3469 // template<typename T> void f(T a, int = decltype(a)());
3470 // void g() { f(0); }
3471 LIS = std::make_unique<LocalInstantiationScope>(*this);
3472 FunctionDecl *PatternFD = FD->getTemplateInstantiationPattern(
3473 /*ForDefinition*/ false);
3474 if (addInstantiatedParametersToScope(FD, PatternFD, *LIS, TemplateArgs))
3475 return true;
3478 runWithSufficientStackSpace(Loc, [&] {
3479 Result = SubstInitializer(PatternExpr, TemplateArgs,
3480 /*DirectInit*/ false);
3483 if (Result.isInvalid())
3484 return true;
3486 if (ForCallExpr) {
3487 // Check the expression as an initializer for the parameter.
3488 InitializedEntity Entity
3489 = InitializedEntity::InitializeParameter(Context, Param);
3490 InitializationKind Kind = InitializationKind::CreateCopy(
3491 Param->getLocation(),
3492 /*FIXME:EqualLoc*/ PatternExpr->getBeginLoc());
3493 Expr *ResultE = Result.getAs<Expr>();
3495 InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
3496 Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
3497 if (Result.isInvalid())
3498 return true;
3500 Result =
3501 ActOnFinishFullExpr(Result.getAs<Expr>(), Param->getOuterLocStart(),
3502 /*DiscardedValue*/ false);
3503 } else {
3504 // FIXME: Obtain the source location for the '=' token.
3505 SourceLocation EqualLoc = PatternExpr->getBeginLoc();
3506 Result = ConvertParamDefaultArgument(Param, Result.getAs<Expr>(), EqualLoc);
3508 if (Result.isInvalid())
3509 return true;
3511 // Remember the instantiated default argument.
3512 Param->setDefaultArg(Result.getAs<Expr>());
3514 return false;
3517 bool
3518 Sema::SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
3519 CXXRecordDecl *Pattern,
3520 const MultiLevelTemplateArgumentList &TemplateArgs) {
3521 bool Invalid = false;
3522 SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases;
3523 for (const auto &Base : Pattern->bases()) {
3524 if (!Base.getType()->isDependentType()) {
3525 if (const CXXRecordDecl *RD = Base.getType()->getAsCXXRecordDecl()) {
3526 if (RD->isInvalidDecl())
3527 Instantiation->setInvalidDecl();
3529 InstantiatedBases.push_back(new (Context) CXXBaseSpecifier(Base));
3530 continue;
3533 SourceLocation EllipsisLoc;
3534 TypeSourceInfo *BaseTypeLoc;
3535 if (Base.isPackExpansion()) {
3536 // This is a pack expansion. See whether we should expand it now, or
3537 // wait until later.
3538 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
3539 collectUnexpandedParameterPacks(Base.getTypeSourceInfo()->getTypeLoc(),
3540 Unexpanded);
3541 bool ShouldExpand = false;
3542 bool RetainExpansion = false;
3543 std::optional<unsigned> NumExpansions;
3544 if (CheckParameterPacksForExpansion(Base.getEllipsisLoc(),
3545 Base.getSourceRange(),
3546 Unexpanded,
3547 TemplateArgs, ShouldExpand,
3548 RetainExpansion,
3549 NumExpansions)) {
3550 Invalid = true;
3551 continue;
3554 // If we should expand this pack expansion now, do so.
3555 if (ShouldExpand) {
3556 for (unsigned I = 0; I != *NumExpansions; ++I) {
3557 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
3559 TypeSourceInfo *BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
3560 TemplateArgs,
3561 Base.getSourceRange().getBegin(),
3562 DeclarationName());
3563 if (!BaseTypeLoc) {
3564 Invalid = true;
3565 continue;
3568 if (CXXBaseSpecifier *InstantiatedBase
3569 = CheckBaseSpecifier(Instantiation,
3570 Base.getSourceRange(),
3571 Base.isVirtual(),
3572 Base.getAccessSpecifierAsWritten(),
3573 BaseTypeLoc,
3574 SourceLocation()))
3575 InstantiatedBases.push_back(InstantiatedBase);
3576 else
3577 Invalid = true;
3580 continue;
3583 // The resulting base specifier will (still) be a pack expansion.
3584 EllipsisLoc = Base.getEllipsisLoc();
3585 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
3586 BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
3587 TemplateArgs,
3588 Base.getSourceRange().getBegin(),
3589 DeclarationName());
3590 } else {
3591 BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
3592 TemplateArgs,
3593 Base.getSourceRange().getBegin(),
3594 DeclarationName());
3597 if (!BaseTypeLoc) {
3598 Invalid = true;
3599 continue;
3602 if (CXXBaseSpecifier *InstantiatedBase
3603 = CheckBaseSpecifier(Instantiation,
3604 Base.getSourceRange(),
3605 Base.isVirtual(),
3606 Base.getAccessSpecifierAsWritten(),
3607 BaseTypeLoc,
3608 EllipsisLoc))
3609 InstantiatedBases.push_back(InstantiatedBase);
3610 else
3611 Invalid = true;
3614 if (!Invalid && AttachBaseSpecifiers(Instantiation, InstantiatedBases))
3615 Invalid = true;
3617 return Invalid;
3620 // Defined via #include from SemaTemplateInstantiateDecl.cpp
3621 namespace clang {
3622 namespace sema {
3623 Attr *instantiateTemplateAttribute(const Attr *At, ASTContext &C, Sema &S,
3624 const MultiLevelTemplateArgumentList &TemplateArgs);
3625 Attr *instantiateTemplateAttributeForDecl(
3626 const Attr *At, ASTContext &C, Sema &S,
3627 const MultiLevelTemplateArgumentList &TemplateArgs);
3631 bool
3632 Sema::InstantiateClass(SourceLocation PointOfInstantiation,
3633 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
3634 const MultiLevelTemplateArgumentList &TemplateArgs,
3635 TemplateSpecializationKind TSK,
3636 bool Complain) {
3637 CXXRecordDecl *PatternDef
3638 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
3639 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
3640 Instantiation->getInstantiatedFromMemberClass(),
3641 Pattern, PatternDef, TSK, Complain))
3642 return true;
3644 llvm::TimeTraceScope TimeScope("InstantiateClass", [&]() {
3645 llvm::TimeTraceMetadata M;
3646 llvm::raw_string_ostream OS(M.Detail);
3647 Instantiation->getNameForDiagnostic(OS, getPrintingPolicy(),
3648 /*Qualified=*/true);
3649 if (llvm::isTimeTraceVerbose()) {
3650 auto Loc = SourceMgr.getExpansionLoc(Instantiation->getLocation());
3651 M.File = SourceMgr.getFilename(Loc);
3652 M.Line = SourceMgr.getExpansionLineNumber(Loc);
3654 return M;
3657 Pattern = PatternDef;
3659 // Record the point of instantiation.
3660 if (MemberSpecializationInfo *MSInfo
3661 = Instantiation->getMemberSpecializationInfo()) {
3662 MSInfo->setTemplateSpecializationKind(TSK);
3663 MSInfo->setPointOfInstantiation(PointOfInstantiation);
3664 } else if (ClassTemplateSpecializationDecl *Spec
3665 = dyn_cast<ClassTemplateSpecializationDecl>(Instantiation)) {
3666 Spec->setTemplateSpecializationKind(TSK);
3667 Spec->setPointOfInstantiation(PointOfInstantiation);
3670 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
3671 if (Inst.isInvalid())
3672 return true;
3673 assert(!Inst.isAlreadyInstantiating() && "should have been caught by caller");
3674 PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
3675 "instantiating class definition");
3677 // Enter the scope of this instantiation. We don't use
3678 // PushDeclContext because we don't have a scope.
3679 ContextRAII SavedContext(*this, Instantiation);
3680 EnterExpressionEvaluationContext EvalContext(
3681 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
3683 // If this is an instantiation of a local class, merge this local
3684 // instantiation scope with the enclosing scope. Otherwise, every
3685 // instantiation of a class has its own local instantiation scope.
3686 bool MergeWithParentScope = !Instantiation->isDefinedOutsideFunctionOrMethod();
3687 LocalInstantiationScope Scope(*this, MergeWithParentScope);
3689 // Some class state isn't processed immediately but delayed till class
3690 // instantiation completes. We may not be ready to handle any delayed state
3691 // already on the stack as it might correspond to a different class, so save
3692 // it now and put it back later.
3693 SavePendingParsedClassStateRAII SavedPendingParsedClassState(*this);
3695 // Pull attributes from the pattern onto the instantiation.
3696 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
3698 // Start the definition of this instantiation.
3699 Instantiation->startDefinition();
3701 // The instantiation is visible here, even if it was first declared in an
3702 // unimported module.
3703 Instantiation->setVisibleDespiteOwningModule();
3705 // FIXME: This loses the as-written tag kind for an explicit instantiation.
3706 Instantiation->setTagKind(Pattern->getTagKind());
3708 // Do substitution on the base class specifiers.
3709 if (SubstBaseSpecifiers(Instantiation, Pattern, TemplateArgs))
3710 Instantiation->setInvalidDecl();
3712 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
3713 Instantiator.setEvaluateConstraints(false);
3714 SmallVector<Decl*, 4> Fields;
3715 // Delay instantiation of late parsed attributes.
3716 LateInstantiatedAttrVec LateAttrs;
3717 Instantiator.enableLateAttributeInstantiation(&LateAttrs);
3719 bool MightHaveConstexprVirtualFunctions = false;
3720 for (auto *Member : Pattern->decls()) {
3721 // Don't instantiate members not belonging in this semantic context.
3722 // e.g. for:
3723 // @code
3724 // template <int i> class A {
3725 // class B *g;
3726 // };
3727 // @endcode
3728 // 'class B' has the template as lexical context but semantically it is
3729 // introduced in namespace scope.
3730 if (Member->getDeclContext() != Pattern)
3731 continue;
3733 // BlockDecls can appear in a default-member-initializer. They must be the
3734 // child of a BlockExpr, so we only know how to instantiate them from there.
3735 // Similarly, lambda closure types are recreated when instantiating the
3736 // corresponding LambdaExpr.
3737 if (isa<BlockDecl>(Member) ||
3738 (isa<CXXRecordDecl>(Member) && cast<CXXRecordDecl>(Member)->isLambda()))
3739 continue;
3741 if (Member->isInvalidDecl()) {
3742 Instantiation->setInvalidDecl();
3743 continue;
3746 Decl *NewMember = Instantiator.Visit(Member);
3747 if (NewMember) {
3748 if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember)) {
3749 Fields.push_back(Field);
3750 } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(NewMember)) {
3751 // C++11 [temp.inst]p1: The implicit instantiation of a class template
3752 // specialization causes the implicit instantiation of the definitions
3753 // of unscoped member enumerations.
3754 // Record a point of instantiation for this implicit instantiation.
3755 if (TSK == TSK_ImplicitInstantiation && !Enum->isScoped() &&
3756 Enum->isCompleteDefinition()) {
3757 MemberSpecializationInfo *MSInfo =Enum->getMemberSpecializationInfo();
3758 assert(MSInfo && "no spec info for member enum specialization");
3759 MSInfo->setTemplateSpecializationKind(TSK_ImplicitInstantiation);
3760 MSInfo->setPointOfInstantiation(PointOfInstantiation);
3762 } else if (StaticAssertDecl *SA = dyn_cast<StaticAssertDecl>(NewMember)) {
3763 if (SA->isFailed()) {
3764 // A static_assert failed. Bail out; instantiating this
3765 // class is probably not meaningful.
3766 Instantiation->setInvalidDecl();
3767 break;
3769 } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewMember)) {
3770 if (MD->isConstexpr() && !MD->getFriendObjectKind() &&
3771 (MD->isVirtualAsWritten() || Instantiation->getNumBases()))
3772 MightHaveConstexprVirtualFunctions = true;
3775 if (NewMember->isInvalidDecl())
3776 Instantiation->setInvalidDecl();
3777 } else {
3778 // FIXME: Eventually, a NULL return will mean that one of the
3779 // instantiations was a semantic disaster, and we'll want to mark the
3780 // declaration invalid.
3781 // For now, we expect to skip some members that we can't yet handle.
3785 // Finish checking fields.
3786 ActOnFields(nullptr, Instantiation->getLocation(), Instantiation, Fields,
3787 SourceLocation(), SourceLocation(), ParsedAttributesView());
3788 CheckCompletedCXXClass(nullptr, Instantiation);
3790 // Default arguments are parsed, if not instantiated. We can go instantiate
3791 // default arg exprs for default constructors if necessary now. Unless we're
3792 // parsing a class, in which case wait until that's finished.
3793 if (ParsingClassDepth == 0)
3794 ActOnFinishCXXNonNestedClass();
3796 // Instantiate late parsed attributes, and attach them to their decls.
3797 // See Sema::InstantiateAttrs
3798 for (LateInstantiatedAttrVec::iterator I = LateAttrs.begin(),
3799 E = LateAttrs.end(); I != E; ++I) {
3800 assert(CurrentInstantiationScope == Instantiator.getStartingScope());
3801 CurrentInstantiationScope = I->Scope;
3803 // Allow 'this' within late-parsed attributes.
3804 auto *ND = cast<NamedDecl>(I->NewDecl);
3805 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
3806 CXXThisScopeRAII ThisScope(*this, ThisContext, Qualifiers(),
3807 ND->isCXXInstanceMember());
3809 Attr *NewAttr =
3810 instantiateTemplateAttribute(I->TmplAttr, Context, *this, TemplateArgs);
3811 if (NewAttr)
3812 I->NewDecl->addAttr(NewAttr);
3813 LocalInstantiationScope::deleteScopes(I->Scope,
3814 Instantiator.getStartingScope());
3816 Instantiator.disableLateAttributeInstantiation();
3817 LateAttrs.clear();
3819 ActOnFinishDelayedMemberInitializers(Instantiation);
3821 // FIXME: We should do something similar for explicit instantiations so they
3822 // end up in the right module.
3823 if (TSK == TSK_ImplicitInstantiation) {
3824 Instantiation->setLocation(Pattern->getLocation());
3825 Instantiation->setLocStart(Pattern->getInnerLocStart());
3826 Instantiation->setBraceRange(Pattern->getBraceRange());
3829 if (!Instantiation->isInvalidDecl()) {
3830 // Perform any dependent diagnostics from the pattern.
3831 if (Pattern->isDependentContext())
3832 PerformDependentDiagnostics(Pattern, TemplateArgs);
3834 // Instantiate any out-of-line class template partial
3835 // specializations now.
3836 for (TemplateDeclInstantiator::delayed_partial_spec_iterator
3837 P = Instantiator.delayed_partial_spec_begin(),
3838 PEnd = Instantiator.delayed_partial_spec_end();
3839 P != PEnd; ++P) {
3840 if (!Instantiator.InstantiateClassTemplatePartialSpecialization(
3841 P->first, P->second)) {
3842 Instantiation->setInvalidDecl();
3843 break;
3847 // Instantiate any out-of-line variable template partial
3848 // specializations now.
3849 for (TemplateDeclInstantiator::delayed_var_partial_spec_iterator
3850 P = Instantiator.delayed_var_partial_spec_begin(),
3851 PEnd = Instantiator.delayed_var_partial_spec_end();
3852 P != PEnd; ++P) {
3853 if (!Instantiator.InstantiateVarTemplatePartialSpecialization(
3854 P->first, P->second)) {
3855 Instantiation->setInvalidDecl();
3856 break;
3861 // Exit the scope of this instantiation.
3862 SavedContext.pop();
3864 if (!Instantiation->isInvalidDecl()) {
3865 // Always emit the vtable for an explicit instantiation definition
3866 // of a polymorphic class template specialization. Otherwise, eagerly
3867 // instantiate only constexpr virtual functions in preparation for their use
3868 // in constant evaluation.
3869 if (TSK == TSK_ExplicitInstantiationDefinition)
3870 MarkVTableUsed(PointOfInstantiation, Instantiation, true);
3871 else if (MightHaveConstexprVirtualFunctions)
3872 MarkVirtualMembersReferenced(PointOfInstantiation, Instantiation,
3873 /*ConstexprOnly*/ true);
3876 Consumer.HandleTagDeclDefinition(Instantiation);
3878 return Instantiation->isInvalidDecl();
3881 bool Sema::InstantiateEnum(SourceLocation PointOfInstantiation,
3882 EnumDecl *Instantiation, EnumDecl *Pattern,
3883 const MultiLevelTemplateArgumentList &TemplateArgs,
3884 TemplateSpecializationKind TSK) {
3885 EnumDecl *PatternDef = Pattern->getDefinition();
3886 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
3887 Instantiation->getInstantiatedFromMemberEnum(),
3888 Pattern, PatternDef, TSK,/*Complain*/true))
3889 return true;
3890 Pattern = PatternDef;
3892 // Record the point of instantiation.
3893 if (MemberSpecializationInfo *MSInfo
3894 = Instantiation->getMemberSpecializationInfo()) {
3895 MSInfo->setTemplateSpecializationKind(TSK);
3896 MSInfo->setPointOfInstantiation(PointOfInstantiation);
3899 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
3900 if (Inst.isInvalid())
3901 return true;
3902 if (Inst.isAlreadyInstantiating())
3903 return false;
3904 PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
3905 "instantiating enum definition");
3907 // The instantiation is visible here, even if it was first declared in an
3908 // unimported module.
3909 Instantiation->setVisibleDespiteOwningModule();
3911 // Enter the scope of this instantiation. We don't use
3912 // PushDeclContext because we don't have a scope.
3913 ContextRAII SavedContext(*this, Instantiation);
3914 EnterExpressionEvaluationContext EvalContext(
3915 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
3917 LocalInstantiationScope Scope(*this, /*MergeWithParentScope*/true);
3919 // Pull attributes from the pattern onto the instantiation.
3920 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
3922 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
3923 Instantiator.InstantiateEnumDefinition(Instantiation, Pattern);
3925 // Exit the scope of this instantiation.
3926 SavedContext.pop();
3928 return Instantiation->isInvalidDecl();
3931 bool Sema::InstantiateInClassInitializer(
3932 SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
3933 FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs) {
3934 // If there is no initializer, we don't need to do anything.
3935 if (!Pattern->hasInClassInitializer())
3936 return false;
3938 assert(Instantiation->getInClassInitStyle() ==
3939 Pattern->getInClassInitStyle() &&
3940 "pattern and instantiation disagree about init style");
3942 // Error out if we haven't parsed the initializer of the pattern yet because
3943 // we are waiting for the closing brace of the outer class.
3944 Expr *OldInit = Pattern->getInClassInitializer();
3945 if (!OldInit) {
3946 RecordDecl *PatternRD = Pattern->getParent();
3947 RecordDecl *OutermostClass = PatternRD->getOuterLexicalRecordContext();
3948 Diag(PointOfInstantiation,
3949 diag::err_default_member_initializer_not_yet_parsed)
3950 << OutermostClass << Pattern;
3951 Diag(Pattern->getEndLoc(),
3952 diag::note_default_member_initializer_not_yet_parsed);
3953 Instantiation->setInvalidDecl();
3954 return true;
3957 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
3958 if (Inst.isInvalid())
3959 return true;
3960 if (Inst.isAlreadyInstantiating()) {
3961 // Error out if we hit an instantiation cycle for this initializer.
3962 Diag(PointOfInstantiation, diag::err_default_member_initializer_cycle)
3963 << Instantiation;
3964 return true;
3966 PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
3967 "instantiating default member init");
3969 // Enter the scope of this instantiation. We don't use PushDeclContext because
3970 // we don't have a scope.
3971 ContextRAII SavedContext(*this, Instantiation->getParent());
3972 EnterExpressionEvaluationContext EvalContext(
3973 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
3974 ExprEvalContexts.back().DelayedDefaultInitializationContext = {
3975 PointOfInstantiation, Instantiation, CurContext};
3977 LocalInstantiationScope Scope(*this, true);
3979 // Instantiate the initializer.
3980 ActOnStartCXXInClassMemberInitializer();
3981 CXXThisScopeRAII ThisScope(*this, Instantiation->getParent(), Qualifiers());
3983 ExprResult NewInit = SubstInitializer(OldInit, TemplateArgs,
3984 /*CXXDirectInit=*/false);
3985 Expr *Init = NewInit.get();
3986 assert((!Init || !isa<ParenListExpr>(Init)) && "call-style init in class");
3987 ActOnFinishCXXInClassMemberInitializer(
3988 Instantiation, Init ? Init->getBeginLoc() : SourceLocation(), Init);
3990 if (auto *L = getASTMutationListener())
3991 L->DefaultMemberInitializerInstantiated(Instantiation);
3993 // Return true if the in-class initializer is still missing.
3994 return !Instantiation->getInClassInitializer();
3997 namespace {
3998 /// A partial specialization whose template arguments have matched
3999 /// a given template-id.
4000 struct PartialSpecMatchResult {
4001 ClassTemplatePartialSpecializationDecl *Partial;
4002 TemplateArgumentList *Args;
4006 bool Sema::usesPartialOrExplicitSpecialization(
4007 SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec) {
4008 if (ClassTemplateSpec->getTemplateSpecializationKind() ==
4009 TSK_ExplicitSpecialization)
4010 return true;
4012 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
4013 ClassTemplateDecl *CTD = ClassTemplateSpec->getSpecializedTemplate();
4014 CTD->getPartialSpecializations(PartialSpecs);
4015 for (ClassTemplatePartialSpecializationDecl *CTPSD : PartialSpecs) {
4016 // C++ [temp.spec.partial.member]p2:
4017 // If the primary member template is explicitly specialized for a given
4018 // (implicit) specialization of the enclosing class template, the partial
4019 // specializations of the member template are ignored for this
4020 // specialization of the enclosing class template. If a partial
4021 // specialization of the member template is explicitly specialized for a
4022 // given (implicit) specialization of the enclosing class template, the
4023 // primary member template and its other partial specializations are still
4024 // considered for this specialization of the enclosing class template.
4025 if (CTD->getMostRecentDecl()->isMemberSpecialization() &&
4026 !CTPSD->getMostRecentDecl()->isMemberSpecialization())
4027 continue;
4029 TemplateDeductionInfo Info(Loc);
4030 if (DeduceTemplateArguments(CTPSD,
4031 ClassTemplateSpec->getTemplateArgs().asArray(),
4032 Info) == TemplateDeductionResult::Success)
4033 return true;
4036 return false;
4039 /// Get the instantiation pattern to use to instantiate the definition of a
4040 /// given ClassTemplateSpecializationDecl (either the pattern of the primary
4041 /// template or of a partial specialization).
4042 static ActionResult<CXXRecordDecl *>
4043 getPatternForClassTemplateSpecialization(
4044 Sema &S, SourceLocation PointOfInstantiation,
4045 ClassTemplateSpecializationDecl *ClassTemplateSpec,
4046 TemplateSpecializationKind TSK) {
4047 Sema::InstantiatingTemplate Inst(S, PointOfInstantiation, ClassTemplateSpec);
4048 if (Inst.isInvalid())
4049 return {/*Invalid=*/true};
4050 if (Inst.isAlreadyInstantiating())
4051 return {/*Invalid=*/false};
4053 llvm::PointerUnion<ClassTemplateDecl *,
4054 ClassTemplatePartialSpecializationDecl *>
4055 Specialized = ClassTemplateSpec->getSpecializedTemplateOrPartial();
4056 if (!isa<ClassTemplatePartialSpecializationDecl *>(Specialized)) {
4057 // Find best matching specialization.
4058 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
4060 // C++ [temp.class.spec.match]p1:
4061 // When a class template is used in a context that requires an
4062 // instantiation of the class, it is necessary to determine
4063 // whether the instantiation is to be generated using the primary
4064 // template or one of the partial specializations. This is done by
4065 // matching the template arguments of the class template
4066 // specialization with the template argument lists of the partial
4067 // specializations.
4068 typedef PartialSpecMatchResult MatchResult;
4069 SmallVector<MatchResult, 4> Matched;
4070 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
4071 Template->getPartialSpecializations(PartialSpecs);
4072 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation);
4073 for (ClassTemplatePartialSpecializationDecl *Partial : PartialSpecs) {
4074 // C++ [temp.spec.partial.member]p2:
4075 // If the primary member template is explicitly specialized for a given
4076 // (implicit) specialization of the enclosing class template, the
4077 // partial specializations of the member template are ignored for this
4078 // specialization of the enclosing class template. If a partial
4079 // specialization of the member template is explicitly specialized for a
4080 // given (implicit) specialization of the enclosing class template, the
4081 // primary member template and its other partial specializations are
4082 // still considered for this specialization of the enclosing class
4083 // template.
4084 if (Template->getMostRecentDecl()->isMemberSpecialization() &&
4085 !Partial->getMostRecentDecl()->isMemberSpecialization())
4086 continue;
4088 TemplateDeductionInfo Info(FailedCandidates.getLocation());
4089 if (TemplateDeductionResult Result = S.DeduceTemplateArguments(
4090 Partial, ClassTemplateSpec->getTemplateArgs().asArray(), Info);
4091 Result != TemplateDeductionResult::Success) {
4092 // Store the failed-deduction information for use in diagnostics, later.
4093 // TODO: Actually use the failed-deduction info?
4094 FailedCandidates.addCandidate().set(
4095 DeclAccessPair::make(Template, AS_public), Partial,
4096 MakeDeductionFailureInfo(S.Context, Result, Info));
4097 (void)Result;
4098 } else {
4099 Matched.push_back(PartialSpecMatchResult());
4100 Matched.back().Partial = Partial;
4101 Matched.back().Args = Info.takeCanonical();
4105 // If we're dealing with a member template where the template parameters
4106 // have been instantiated, this provides the original template parameters
4107 // from which the member template's parameters were instantiated.
4109 if (Matched.size() >= 1) {
4110 SmallVectorImpl<MatchResult>::iterator Best = Matched.begin();
4111 if (Matched.size() == 1) {
4112 // -- If exactly one matching specialization is found, the
4113 // instantiation is generated from that specialization.
4114 // We don't need to do anything for this.
4115 } else {
4116 // -- If more than one matching specialization is found, the
4117 // partial order rules (14.5.4.2) are used to determine
4118 // whether one of the specializations is more specialized
4119 // than the others. If none of the specializations is more
4120 // specialized than all of the other matching
4121 // specializations, then the use of the class template is
4122 // ambiguous and the program is ill-formed.
4123 for (SmallVectorImpl<MatchResult>::iterator P = Best + 1,
4124 PEnd = Matched.end();
4125 P != PEnd; ++P) {
4126 if (S.getMoreSpecializedPartialSpecialization(
4127 P->Partial, Best->Partial, PointOfInstantiation) ==
4128 P->Partial)
4129 Best = P;
4132 // Determine if the best partial specialization is more specialized than
4133 // the others.
4134 bool Ambiguous = false;
4135 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
4136 PEnd = Matched.end();
4137 P != PEnd; ++P) {
4138 if (P != Best && S.getMoreSpecializedPartialSpecialization(
4139 P->Partial, Best->Partial,
4140 PointOfInstantiation) != Best->Partial) {
4141 Ambiguous = true;
4142 break;
4146 if (Ambiguous) {
4147 // Partial ordering did not produce a clear winner. Complain.
4148 Inst.Clear();
4149 ClassTemplateSpec->setInvalidDecl();
4150 S.Diag(PointOfInstantiation,
4151 diag::err_partial_spec_ordering_ambiguous)
4152 << ClassTemplateSpec;
4154 // Print the matching partial specializations.
4155 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
4156 PEnd = Matched.end();
4157 P != PEnd; ++P)
4158 S.Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
4159 << S.getTemplateArgumentBindingsText(
4160 P->Partial->getTemplateParameters(), *P->Args);
4162 return {/*Invalid=*/true};
4166 ClassTemplateSpec->setInstantiationOf(Best->Partial, Best->Args);
4167 } else {
4168 // -- If no matches are found, the instantiation is generated
4169 // from the primary template.
4173 CXXRecordDecl *Pattern = nullptr;
4174 Specialized = ClassTemplateSpec->getSpecializedTemplateOrPartial();
4175 if (auto *PartialSpec =
4176 Specialized.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
4177 // Instantiate using the best class template partial specialization.
4178 while (PartialSpec->getInstantiatedFromMember()) {
4179 // If we've found an explicit specialization of this class template,
4180 // stop here and use that as the pattern.
4181 if (PartialSpec->isMemberSpecialization())
4182 break;
4184 PartialSpec = PartialSpec->getInstantiatedFromMember();
4186 Pattern = PartialSpec;
4187 } else {
4188 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
4189 while (Template->getInstantiatedFromMemberTemplate()) {
4190 // If we've found an explicit specialization of this class template,
4191 // stop here and use that as the pattern.
4192 if (Template->isMemberSpecialization())
4193 break;
4195 Template = Template->getInstantiatedFromMemberTemplate();
4197 Pattern = Template->getTemplatedDecl();
4200 return Pattern;
4203 bool Sema::InstantiateClassTemplateSpecialization(
4204 SourceLocation PointOfInstantiation,
4205 ClassTemplateSpecializationDecl *ClassTemplateSpec,
4206 TemplateSpecializationKind TSK, bool Complain) {
4207 // Perform the actual instantiation on the canonical declaration.
4208 ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>(
4209 ClassTemplateSpec->getCanonicalDecl());
4210 if (ClassTemplateSpec->isInvalidDecl())
4211 return true;
4213 ActionResult<CXXRecordDecl *> Pattern =
4214 getPatternForClassTemplateSpecialization(*this, PointOfInstantiation,
4215 ClassTemplateSpec, TSK);
4216 if (!Pattern.isUsable())
4217 return Pattern.isInvalid();
4219 return InstantiateClass(
4220 PointOfInstantiation, ClassTemplateSpec, Pattern.get(),
4221 getTemplateInstantiationArgs(ClassTemplateSpec), TSK, Complain);
4224 void
4225 Sema::InstantiateClassMembers(SourceLocation PointOfInstantiation,
4226 CXXRecordDecl *Instantiation,
4227 const MultiLevelTemplateArgumentList &TemplateArgs,
4228 TemplateSpecializationKind TSK) {
4229 // FIXME: We need to notify the ASTMutationListener that we did all of these
4230 // things, in case we have an explicit instantiation definition in a PCM, a
4231 // module, or preamble, and the declaration is in an imported AST.
4232 assert(
4233 (TSK == TSK_ExplicitInstantiationDefinition ||
4234 TSK == TSK_ExplicitInstantiationDeclaration ||
4235 (TSK == TSK_ImplicitInstantiation && Instantiation->isLocalClass())) &&
4236 "Unexpected template specialization kind!");
4237 for (auto *D : Instantiation->decls()) {
4238 bool SuppressNew = false;
4239 if (auto *Function = dyn_cast<FunctionDecl>(D)) {
4240 if (FunctionDecl *Pattern =
4241 Function->getInstantiatedFromMemberFunction()) {
4243 if (Function->isIneligibleOrNotSelected())
4244 continue;
4246 if (Function->getTrailingRequiresClause()) {
4247 ConstraintSatisfaction Satisfaction;
4248 if (CheckFunctionConstraints(Function, Satisfaction) ||
4249 !Satisfaction.IsSatisfied) {
4250 continue;
4254 if (Function->hasAttr<ExcludeFromExplicitInstantiationAttr>())
4255 continue;
4257 TemplateSpecializationKind PrevTSK =
4258 Function->getTemplateSpecializationKind();
4259 if (PrevTSK == TSK_ExplicitSpecialization)
4260 continue;
4262 if (CheckSpecializationInstantiationRedecl(
4263 PointOfInstantiation, TSK, Function, PrevTSK,
4264 Function->getPointOfInstantiation(), SuppressNew) ||
4265 SuppressNew)
4266 continue;
4268 // C++11 [temp.explicit]p8:
4269 // An explicit instantiation definition that names a class template
4270 // specialization explicitly instantiates the class template
4271 // specialization and is only an explicit instantiation definition
4272 // of members whose definition is visible at the point of
4273 // instantiation.
4274 if (TSK == TSK_ExplicitInstantiationDefinition && !Pattern->isDefined())
4275 continue;
4277 Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
4279 if (Function->isDefined()) {
4280 // Let the ASTConsumer know that this function has been explicitly
4281 // instantiated now, and its linkage might have changed.
4282 Consumer.HandleTopLevelDecl(DeclGroupRef(Function));
4283 } else if (TSK == TSK_ExplicitInstantiationDefinition) {
4284 InstantiateFunctionDefinition(PointOfInstantiation, Function);
4285 } else if (TSK == TSK_ImplicitInstantiation) {
4286 PendingLocalImplicitInstantiations.push_back(
4287 std::make_pair(Function, PointOfInstantiation));
4290 } else if (auto *Var = dyn_cast<VarDecl>(D)) {
4291 if (isa<VarTemplateSpecializationDecl>(Var))
4292 continue;
4294 if (Var->isStaticDataMember()) {
4295 if (Var->hasAttr<ExcludeFromExplicitInstantiationAttr>())
4296 continue;
4298 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
4299 assert(MSInfo && "No member specialization information?");
4300 if (MSInfo->getTemplateSpecializationKind()
4301 == TSK_ExplicitSpecialization)
4302 continue;
4304 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
4305 Var,
4306 MSInfo->getTemplateSpecializationKind(),
4307 MSInfo->getPointOfInstantiation(),
4308 SuppressNew) ||
4309 SuppressNew)
4310 continue;
4312 if (TSK == TSK_ExplicitInstantiationDefinition) {
4313 // C++0x [temp.explicit]p8:
4314 // An explicit instantiation definition that names a class template
4315 // specialization explicitly instantiates the class template
4316 // specialization and is only an explicit instantiation definition
4317 // of members whose definition is visible at the point of
4318 // instantiation.
4319 if (!Var->getInstantiatedFromStaticDataMember()->getDefinition())
4320 continue;
4322 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
4323 InstantiateVariableDefinition(PointOfInstantiation, Var);
4324 } else {
4325 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
4328 } else if (auto *Record = dyn_cast<CXXRecordDecl>(D)) {
4329 if (Record->hasAttr<ExcludeFromExplicitInstantiationAttr>())
4330 continue;
4332 // Always skip the injected-class-name, along with any
4333 // redeclarations of nested classes, since both would cause us
4334 // to try to instantiate the members of a class twice.
4335 // Skip closure types; they'll get instantiated when we instantiate
4336 // the corresponding lambda-expression.
4337 if (Record->isInjectedClassName() || Record->getPreviousDecl() ||
4338 Record->isLambda())
4339 continue;
4341 MemberSpecializationInfo *MSInfo = Record->getMemberSpecializationInfo();
4342 assert(MSInfo && "No member specialization information?");
4344 if (MSInfo->getTemplateSpecializationKind()
4345 == TSK_ExplicitSpecialization)
4346 continue;
4348 if (Context.getTargetInfo().getTriple().isOSWindows() &&
4349 TSK == TSK_ExplicitInstantiationDeclaration) {
4350 // On Windows, explicit instantiation decl of the outer class doesn't
4351 // affect the inner class. Typically extern template declarations are
4352 // used in combination with dll import/export annotations, but those
4353 // are not propagated from the outer class templates to inner classes.
4354 // Therefore, do not instantiate inner classes on this platform, so
4355 // that users don't end up with undefined symbols during linking.
4356 continue;
4359 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
4360 Record,
4361 MSInfo->getTemplateSpecializationKind(),
4362 MSInfo->getPointOfInstantiation(),
4363 SuppressNew) ||
4364 SuppressNew)
4365 continue;
4367 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
4368 assert(Pattern && "Missing instantiated-from-template information");
4370 if (!Record->getDefinition()) {
4371 if (!Pattern->getDefinition()) {
4372 // C++0x [temp.explicit]p8:
4373 // An explicit instantiation definition that names a class template
4374 // specialization explicitly instantiates the class template
4375 // specialization and is only an explicit instantiation definition
4376 // of members whose definition is visible at the point of
4377 // instantiation.
4378 if (TSK == TSK_ExplicitInstantiationDeclaration) {
4379 MSInfo->setTemplateSpecializationKind(TSK);
4380 MSInfo->setPointOfInstantiation(PointOfInstantiation);
4383 continue;
4386 InstantiateClass(PointOfInstantiation, Record, Pattern,
4387 TemplateArgs,
4388 TSK);
4389 } else {
4390 if (TSK == TSK_ExplicitInstantiationDefinition &&
4391 Record->getTemplateSpecializationKind() ==
4392 TSK_ExplicitInstantiationDeclaration) {
4393 Record->setTemplateSpecializationKind(TSK);
4394 MarkVTableUsed(PointOfInstantiation, Record, true);
4398 Pattern = cast_or_null<CXXRecordDecl>(Record->getDefinition());
4399 if (Pattern)
4400 InstantiateClassMembers(PointOfInstantiation, Pattern, TemplateArgs,
4401 TSK);
4402 } else if (auto *Enum = dyn_cast<EnumDecl>(D)) {
4403 MemberSpecializationInfo *MSInfo = Enum->getMemberSpecializationInfo();
4404 assert(MSInfo && "No member specialization information?");
4406 if (MSInfo->getTemplateSpecializationKind()
4407 == TSK_ExplicitSpecialization)
4408 continue;
4410 if (CheckSpecializationInstantiationRedecl(
4411 PointOfInstantiation, TSK, Enum,
4412 MSInfo->getTemplateSpecializationKind(),
4413 MSInfo->getPointOfInstantiation(), SuppressNew) ||
4414 SuppressNew)
4415 continue;
4417 if (Enum->getDefinition())
4418 continue;
4420 EnumDecl *Pattern = Enum->getTemplateInstantiationPattern();
4421 assert(Pattern && "Missing instantiated-from-template information");
4423 if (TSK == TSK_ExplicitInstantiationDefinition) {
4424 if (!Pattern->getDefinition())
4425 continue;
4427 InstantiateEnum(PointOfInstantiation, Enum, Pattern, TemplateArgs, TSK);
4428 } else {
4429 MSInfo->setTemplateSpecializationKind(TSK);
4430 MSInfo->setPointOfInstantiation(PointOfInstantiation);
4432 } else if (auto *Field = dyn_cast<FieldDecl>(D)) {
4433 // No need to instantiate in-class initializers during explicit
4434 // instantiation.
4435 if (Field->hasInClassInitializer() && TSK == TSK_ImplicitInstantiation) {
4436 CXXRecordDecl *ClassPattern =
4437 Instantiation->getTemplateInstantiationPattern();
4438 DeclContext::lookup_result Lookup =
4439 ClassPattern->lookup(Field->getDeclName());
4440 FieldDecl *Pattern = Lookup.find_first<FieldDecl>();
4441 assert(Pattern);
4442 InstantiateInClassInitializer(PointOfInstantiation, Field, Pattern,
4443 TemplateArgs);
4449 void
4450 Sema::InstantiateClassTemplateSpecializationMembers(
4451 SourceLocation PointOfInstantiation,
4452 ClassTemplateSpecializationDecl *ClassTemplateSpec,
4453 TemplateSpecializationKind TSK) {
4454 // C++0x [temp.explicit]p7:
4455 // An explicit instantiation that names a class template
4456 // specialization is an explicit instantion of the same kind
4457 // (declaration or definition) of each of its members (not
4458 // including members inherited from base classes) that has not
4459 // been previously explicitly specialized in the translation unit
4460 // containing the explicit instantiation, except as described
4461 // below.
4462 InstantiateClassMembers(PointOfInstantiation, ClassTemplateSpec,
4463 getTemplateInstantiationArgs(ClassTemplateSpec),
4464 TSK);
4467 StmtResult
4468 Sema::SubstStmt(Stmt *S, const MultiLevelTemplateArgumentList &TemplateArgs) {
4469 if (!S)
4470 return S;
4472 TemplateInstantiator Instantiator(*this, TemplateArgs,
4473 SourceLocation(),
4474 DeclarationName());
4475 return Instantiator.TransformStmt(S);
4478 bool Sema::SubstTemplateArgument(
4479 const TemplateArgumentLoc &Input,
4480 const MultiLevelTemplateArgumentList &TemplateArgs,
4481 TemplateArgumentLoc &Output, SourceLocation Loc,
4482 const DeclarationName &Entity) {
4483 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity);
4484 return Instantiator.TransformTemplateArgument(Input, Output);
4487 bool Sema::SubstTemplateArguments(
4488 ArrayRef<TemplateArgumentLoc> Args,
4489 const MultiLevelTemplateArgumentList &TemplateArgs,
4490 TemplateArgumentListInfo &Out) {
4491 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
4492 DeclarationName());
4493 return Instantiator.TransformTemplateArguments(Args.begin(), Args.end(), Out);
4496 ExprResult
4497 Sema::SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs) {
4498 if (!E)
4499 return E;
4501 TemplateInstantiator Instantiator(*this, TemplateArgs,
4502 SourceLocation(),
4503 DeclarationName());
4504 return Instantiator.TransformExpr(E);
4507 ExprResult
4508 Sema::SubstConstraintExpr(Expr *E,
4509 const MultiLevelTemplateArgumentList &TemplateArgs) {
4510 // FIXME: should call SubstExpr directly if this function is equivalent or
4511 // should it be different?
4512 return SubstExpr(E, TemplateArgs);
4515 ExprResult Sema::SubstConstraintExprWithoutSatisfaction(
4516 Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs) {
4517 if (!E)
4518 return E;
4520 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
4521 DeclarationName());
4522 Instantiator.setEvaluateConstraints(false);
4523 return Instantiator.TransformExpr(E);
4526 ExprResult Sema::SubstInitializer(Expr *Init,
4527 const MultiLevelTemplateArgumentList &TemplateArgs,
4528 bool CXXDirectInit) {
4529 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
4530 DeclarationName());
4531 return Instantiator.TransformInitializer(Init, CXXDirectInit);
4534 bool Sema::SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
4535 const MultiLevelTemplateArgumentList &TemplateArgs,
4536 SmallVectorImpl<Expr *> &Outputs) {
4537 if (Exprs.empty())
4538 return false;
4540 TemplateInstantiator Instantiator(*this, TemplateArgs,
4541 SourceLocation(),
4542 DeclarationName());
4543 return Instantiator.TransformExprs(Exprs.data(), Exprs.size(),
4544 IsCall, Outputs);
4547 NestedNameSpecifierLoc
4548 Sema::SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
4549 const MultiLevelTemplateArgumentList &TemplateArgs) {
4550 if (!NNS)
4551 return NestedNameSpecifierLoc();
4553 TemplateInstantiator Instantiator(*this, TemplateArgs, NNS.getBeginLoc(),
4554 DeclarationName());
4555 return Instantiator.TransformNestedNameSpecifierLoc(NNS);
4558 DeclarationNameInfo
4559 Sema::SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
4560 const MultiLevelTemplateArgumentList &TemplateArgs) {
4561 TemplateInstantiator Instantiator(*this, TemplateArgs, NameInfo.getLoc(),
4562 NameInfo.getName());
4563 return Instantiator.TransformDeclarationNameInfo(NameInfo);
4566 TemplateName
4567 Sema::SubstTemplateName(NestedNameSpecifierLoc QualifierLoc,
4568 TemplateName Name, SourceLocation Loc,
4569 const MultiLevelTemplateArgumentList &TemplateArgs) {
4570 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
4571 DeclarationName());
4572 CXXScopeSpec SS;
4573 SS.Adopt(QualifierLoc);
4574 return Instantiator.TransformTemplateName(SS, Name, Loc);
4577 static const Decl *getCanonicalParmVarDecl(const Decl *D) {
4578 // When storing ParmVarDecls in the local instantiation scope, we always
4579 // want to use the ParmVarDecl from the canonical function declaration,
4580 // since the map is then valid for any redeclaration or definition of that
4581 // function.
4582 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(D)) {
4583 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
4584 unsigned i = PV->getFunctionScopeIndex();
4585 // This parameter might be from a freestanding function type within the
4586 // function and isn't necessarily referring to one of FD's parameters.
4587 if (i < FD->getNumParams() && FD->getParamDecl(i) == PV)
4588 return FD->getCanonicalDecl()->getParamDecl(i);
4591 return D;
4595 llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> *
4596 LocalInstantiationScope::findInstantiationOf(const Decl *D) {
4597 D = getCanonicalParmVarDecl(D);
4598 for (LocalInstantiationScope *Current = this; Current;
4599 Current = Current->Outer) {
4601 // Check if we found something within this scope.
4602 const Decl *CheckD = D;
4603 do {
4604 LocalDeclsMap::iterator Found = Current->LocalDecls.find(CheckD);
4605 if (Found != Current->LocalDecls.end())
4606 return &Found->second;
4608 // If this is a tag declaration, it's possible that we need to look for
4609 // a previous declaration.
4610 if (const TagDecl *Tag = dyn_cast<TagDecl>(CheckD))
4611 CheckD = Tag->getPreviousDecl();
4612 else
4613 CheckD = nullptr;
4614 } while (CheckD);
4616 // If we aren't combined with our outer scope, we're done.
4617 if (!Current->CombineWithOuterScope)
4618 break;
4621 // If we're performing a partial substitution during template argument
4622 // deduction, we may not have values for template parameters yet.
4623 if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
4624 isa<TemplateTemplateParmDecl>(D))
4625 return nullptr;
4627 // Local types referenced prior to definition may require instantiation.
4628 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
4629 if (RD->isLocalClass())
4630 return nullptr;
4632 // Enumeration types referenced prior to definition may appear as a result of
4633 // error recovery.
4634 if (isa<EnumDecl>(D))
4635 return nullptr;
4637 // Materialized typedefs/type alias for implicit deduction guides may require
4638 // instantiation.
4639 if (isa<TypedefNameDecl>(D) &&
4640 isa<CXXDeductionGuideDecl>(D->getDeclContext()))
4641 return nullptr;
4643 // If we didn't find the decl, then we either have a sema bug, or we have a
4644 // forward reference to a label declaration. Return null to indicate that
4645 // we have an uninstantiated label.
4646 assert(isa<LabelDecl>(D) && "declaration not instantiated in this scope");
4647 return nullptr;
4650 void LocalInstantiationScope::InstantiatedLocal(const Decl *D, Decl *Inst) {
4651 D = getCanonicalParmVarDecl(D);
4652 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
4653 if (Stored.isNull()) {
4654 #ifndef NDEBUG
4655 // It should not be present in any surrounding scope either.
4656 LocalInstantiationScope *Current = this;
4657 while (Current->CombineWithOuterScope && Current->Outer) {
4658 Current = Current->Outer;
4659 assert(!Current->LocalDecls.contains(D) &&
4660 "Instantiated local in inner and outer scopes");
4662 #endif
4663 Stored = Inst;
4664 } else if (DeclArgumentPack *Pack = Stored.dyn_cast<DeclArgumentPack *>()) {
4665 Pack->push_back(cast<VarDecl>(Inst));
4666 } else {
4667 assert(cast<Decl *>(Stored) == Inst && "Already instantiated this local");
4671 void LocalInstantiationScope::InstantiatedLocalPackArg(const Decl *D,
4672 VarDecl *Inst) {
4673 D = getCanonicalParmVarDecl(D);
4674 DeclArgumentPack *Pack = cast<DeclArgumentPack *>(LocalDecls[D]);
4675 Pack->push_back(Inst);
4678 void LocalInstantiationScope::MakeInstantiatedLocalArgPack(const Decl *D) {
4679 #ifndef NDEBUG
4680 // This should be the first time we've been told about this decl.
4681 for (LocalInstantiationScope *Current = this;
4682 Current && Current->CombineWithOuterScope; Current = Current->Outer)
4683 assert(!Current->LocalDecls.contains(D) &&
4684 "Creating local pack after instantiation of local");
4685 #endif
4687 D = getCanonicalParmVarDecl(D);
4688 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
4689 DeclArgumentPack *Pack = new DeclArgumentPack;
4690 Stored = Pack;
4691 ArgumentPacks.push_back(Pack);
4694 bool LocalInstantiationScope::isLocalPackExpansion(const Decl *D) {
4695 for (DeclArgumentPack *Pack : ArgumentPacks)
4696 if (llvm::is_contained(*Pack, D))
4697 return true;
4698 return false;
4701 void LocalInstantiationScope::SetPartiallySubstitutedPack(NamedDecl *Pack,
4702 const TemplateArgument *ExplicitArgs,
4703 unsigned NumExplicitArgs) {
4704 assert((!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack) &&
4705 "Already have a partially-substituted pack");
4706 assert((!PartiallySubstitutedPack
4707 || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) &&
4708 "Wrong number of arguments in partially-substituted pack");
4709 PartiallySubstitutedPack = Pack;
4710 ArgsInPartiallySubstitutedPack = ExplicitArgs;
4711 NumArgsInPartiallySubstitutedPack = NumExplicitArgs;
4714 NamedDecl *LocalInstantiationScope::getPartiallySubstitutedPack(
4715 const TemplateArgument **ExplicitArgs,
4716 unsigned *NumExplicitArgs) const {
4717 if (ExplicitArgs)
4718 *ExplicitArgs = nullptr;
4719 if (NumExplicitArgs)
4720 *NumExplicitArgs = 0;
4722 for (const LocalInstantiationScope *Current = this; Current;
4723 Current = Current->Outer) {
4724 if (Current->PartiallySubstitutedPack) {
4725 if (ExplicitArgs)
4726 *ExplicitArgs = Current->ArgsInPartiallySubstitutedPack;
4727 if (NumExplicitArgs)
4728 *NumExplicitArgs = Current->NumArgsInPartiallySubstitutedPack;
4730 return Current->PartiallySubstitutedPack;
4733 if (!Current->CombineWithOuterScope)
4734 break;
4737 return nullptr;