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//===----------------------------------------------------------------------===/
11
12#include "TreeTransform.h"
13#include "clang/AST/ASTConsumer.h"
14#include "clang/AST/ASTContext.h"
15#include "clang/AST/ASTLambda.h"
16#include "clang/AST/ASTMutationListener.h"
17#include "clang/AST/DeclBase.h"
18#include "clang/AST/DeclTemplate.h"
19#include "clang/AST/DynamicRecursiveASTVisitor.h"
20#include "clang/AST/Expr.h"
21#include "clang/AST/ExprConcepts.h"
22#include "clang/AST/PrettyDeclStackTrace.h"
23#include "clang/AST/Type.h"
24#include "clang/AST/TypeLoc.h"
25#include "clang/AST/TypeVisitor.h"
26#include "clang/Basic/LangOptions.h"
27#include "clang/Basic/TargetInfo.h"
28#include "clang/Sema/DeclSpec.h"
29#include "clang/Sema/EnterExpressionEvaluationContext.h"
30#include "clang/Sema/Initialization.h"
31#include "clang/Sema/Sema.h"
32#include "clang/Sema/SemaConcept.h"
33#include "clang/Sema/SemaInternal.h"
34#include "clang/Sema/Template.h"
35#include "clang/Sema/TemplateDeduction.h"
36#include "llvm/ADT/SmallVectorExtras.h"
37#include "llvm/ADT/StringExtras.h"
38#include "llvm/Support/ErrorHandling.h"
39#include "llvm/Support/SaveAndRestore.h"
40#include "llvm/Support/TimeProfiler.h"
41#include <optional>
42
43using namespace clang;
44using namespace sema;
45
46//===----------------------------------------------------------------------===/
47// Template Instantiation Support
48//===----------------------------------------------------------------------===/
49
50namespace {
51namespace TemplateInstArgsHelpers {
52struct Response {
53 const Decl *NextDecl = nullptr;
54 bool IsDone = false;
55 bool ClearRelativeToPrimary = true;
56 static Response Done() {
57 Response R;
58 R.IsDone = true;
59 return R;
60 }
61 static Response ChangeDecl(const Decl *ND) {
62 Response R;
63 R.NextDecl = ND;
64 return R;
65 }
66 static Response ChangeDecl(const DeclContext *Ctx) {
67 Response R;
68 R.NextDecl = Decl::castFromDeclContext(Ctx);
69 return R;
70 }
71
72 static Response UseNextDecl(const Decl *CurDecl) {
73 return ChangeDecl(Ctx: CurDecl->getDeclContext());
74 }
75
76 static Response DontClearRelativeToPrimaryNextDecl(const Decl *CurDecl) {
77 Response R = Response::UseNextDecl(CurDecl);
78 R.ClearRelativeToPrimary = false;
79 return R;
80 }
81};
82
83// Retrieve the primary template for a lambda call operator. It's
84// unfortunate that we only have the mappings of call operators rather
85// than lambda classes.
86const FunctionDecl *
87getPrimaryTemplateOfGenericLambda(const FunctionDecl *LambdaCallOperator) {
88 if (!isLambdaCallOperator(DC: LambdaCallOperator))
89 return LambdaCallOperator;
90 while (true) {
91 if (auto *FTD = dyn_cast_if_present<FunctionTemplateDecl>(
92 Val: LambdaCallOperator->getDescribedTemplate());
93 FTD && FTD->getInstantiatedFromMemberTemplate()) {
94 LambdaCallOperator =
95 FTD->getInstantiatedFromMemberTemplate()->getTemplatedDecl();
96 } else if (LambdaCallOperator->getPrimaryTemplate()) {
97 // Cases where the lambda operator is instantiated in
98 // TemplateDeclInstantiator::VisitCXXMethodDecl.
99 LambdaCallOperator =
100 LambdaCallOperator->getPrimaryTemplate()->getTemplatedDecl();
101 } else if (auto *Prev = cast<CXXMethodDecl>(Val: LambdaCallOperator)
102 ->getInstantiatedFromMemberFunction())
103 LambdaCallOperator = Prev;
104 else
105 break;
106 }
107 return LambdaCallOperator;
108}
109
110struct EnclosingTypeAliasTemplateDetails {
111 TypeAliasTemplateDecl *Template = nullptr;
112 TypeAliasTemplateDecl *PrimaryTypeAliasDecl = nullptr;
113 ArrayRef<TemplateArgument> AssociatedTemplateArguments;
114
115 explicit operator bool() noexcept { return Template; }
116};
117
118// Find the enclosing type alias template Decl from CodeSynthesisContexts, as
119// well as its primary template and instantiating template arguments.
120EnclosingTypeAliasTemplateDetails
121getEnclosingTypeAliasTemplateDecl(Sema &SemaRef) {
122 for (auto &CSC : llvm::reverse(C&: SemaRef.CodeSynthesisContexts)) {
123 if (CSC.Kind != Sema::CodeSynthesisContext::SynthesisKind::
124 TypeAliasTemplateInstantiation)
125 continue;
126 EnclosingTypeAliasTemplateDetails Result;
127 auto *TATD = cast<TypeAliasTemplateDecl>(Val: CSC.Entity),
128 *Next = TATD->getInstantiatedFromMemberTemplate();
129 Result = {
130 /*Template=*/TATD,
131 /*PrimaryTypeAliasDecl=*/TATD,
132 /*AssociatedTemplateArguments=*/CSC.template_arguments(),
133 };
134 while (Next) {
135 Result.PrimaryTypeAliasDecl = Next;
136 Next = Next->getInstantiatedFromMemberTemplate();
137 }
138 return Result;
139 }
140 return {};
141}
142
143// Check if we are currently inside of a lambda expression that is
144// surrounded by a using alias declaration. e.g.
145// template <class> using type = decltype([](auto) { ^ }());
146// We have to do so since a TypeAliasTemplateDecl (or a TypeAliasDecl) is never
147// a DeclContext, nor does it have an associated specialization Decl from which
148// we could collect these template arguments.
149bool isLambdaEnclosedByTypeAliasDecl(
150 const FunctionDecl *LambdaCallOperator,
151 const TypeAliasTemplateDecl *PrimaryTypeAliasDecl) {
152 struct Visitor : DynamicRecursiveASTVisitor {
153 Visitor(const FunctionDecl *CallOperator) : CallOperator(CallOperator) {}
154 bool VisitLambdaExpr(LambdaExpr *LE) override {
155 // Return true to bail out of the traversal, implying the Decl contains
156 // the lambda.
157 return getPrimaryTemplateOfGenericLambda(LambdaCallOperator: LE->getCallOperator()) !=
158 CallOperator;
159 }
160 const FunctionDecl *CallOperator;
161 };
162
163 QualType Underlying =
164 PrimaryTypeAliasDecl->getTemplatedDecl()->getUnderlyingType();
165
166 return !Visitor(getPrimaryTemplateOfGenericLambda(LambdaCallOperator))
167 .TraverseType(T: Underlying);
168}
169
170// Add template arguments from a variable template instantiation.
171Response
172HandleVarTemplateSpec(const VarTemplateSpecializationDecl *VarTemplSpec,
173 MultiLevelTemplateArgumentList &Result,
174 bool SkipForSpecialization) {
175 // For a class-scope explicit specialization, there are no template arguments
176 // at this level, but there may be enclosing template arguments.
177 if (VarTemplSpec->isClassScopeExplicitSpecialization())
178 return Response::DontClearRelativeToPrimaryNextDecl(CurDecl: VarTemplSpec);
179
180 // We're done when we hit an explicit specialization.
181 if (VarTemplSpec->getSpecializationKind() == TSK_ExplicitSpecialization &&
182 !isa<VarTemplatePartialSpecializationDecl>(Val: VarTemplSpec))
183 return Response::Done();
184
185 // If this variable template specialization was instantiated from a
186 // specialized member that is a variable template, we're done.
187 assert(VarTemplSpec->getSpecializedTemplate() && "No variable template?");
188 llvm::PointerUnion<VarTemplateDecl *, VarTemplatePartialSpecializationDecl *>
189 Specialized = VarTemplSpec->getSpecializedTemplateOrPartial();
190 if (VarTemplatePartialSpecializationDecl *Partial =
191 dyn_cast<VarTemplatePartialSpecializationDecl *>(Val&: Specialized)) {
192 if (!SkipForSpecialization)
193 Result.addOuterTemplateArguments(
194 AssociatedDecl: Partial, Args: VarTemplSpec->getTemplateInstantiationArgs().asArray(),
195 /*Final=*/false);
196 if (Partial->isMemberSpecialization())
197 return Response::Done();
198 } else {
199 VarTemplateDecl *Tmpl = cast<VarTemplateDecl *>(Val&: Specialized);
200 if (!SkipForSpecialization)
201 Result.addOuterTemplateArguments(
202 AssociatedDecl: Tmpl, Args: VarTemplSpec->getTemplateInstantiationArgs().asArray(),
203 /*Final=*/false);
204 if (Tmpl->isMemberSpecialization())
205 return Response::Done();
206 }
207 return Response::DontClearRelativeToPrimaryNextDecl(CurDecl: VarTemplSpec);
208}
209
210// If we have a template template parameter with translation unit context,
211// then we're performing substitution into a default template argument of
212// this template template parameter before we've constructed the template
213// that will own this template template parameter. In this case, we
214// use empty template parameter lists for all of the outer templates
215// to avoid performing any substitutions.
216Response
217HandleDefaultTempArgIntoTempTempParam(const TemplateTemplateParmDecl *TTP,
218 MultiLevelTemplateArgumentList &Result) {
219 for (unsigned I = 0, N = TTP->getDepth() + 1; I != N; ++I)
220 Result.addOuterTemplateArguments(std::nullopt);
221 return Response::Done();
222}
223
224Response HandlePartialClassTemplateSpec(
225 const ClassTemplatePartialSpecializationDecl *PartialClassTemplSpec,
226 MultiLevelTemplateArgumentList &Result, bool SkipForSpecialization) {
227 if (!SkipForSpecialization)
228 Result.addOuterRetainedLevels(Num: PartialClassTemplSpec->getTemplateDepth());
229 return Response::Done();
230}
231
232// Add template arguments from a class template instantiation.
233Response
234HandleClassTemplateSpec(const ClassTemplateSpecializationDecl *ClassTemplSpec,
235 MultiLevelTemplateArgumentList &Result,
236 bool SkipForSpecialization) {
237 if (!ClassTemplSpec->isClassScopeExplicitSpecialization()) {
238 // We're done when we hit an explicit specialization.
239 if (ClassTemplSpec->getSpecializationKind() == TSK_ExplicitSpecialization &&
240 !isa<ClassTemplatePartialSpecializationDecl>(Val: ClassTemplSpec))
241 return Response::Done();
242
243 if (!SkipForSpecialization)
244 Result.addOuterTemplateArguments(
245 AssociatedDecl: const_cast<ClassTemplateSpecializationDecl *>(ClassTemplSpec),
246 Args: ClassTemplSpec->getTemplateInstantiationArgs().asArray(),
247 /*Final=*/false);
248
249 // If this class template specialization was instantiated from a
250 // specialized member that is a class template, we're done.
251 assert(ClassTemplSpec->getSpecializedTemplate() && "No class template?");
252 if (ClassTemplSpec->getSpecializedTemplate()->isMemberSpecialization())
253 return Response::Done();
254
255 // If this was instantiated from a partial template specialization, we need
256 // to get the next level of declaration context from the partial
257 // specialization, as the ClassTemplateSpecializationDecl's
258 // DeclContext/LexicalDeclContext will be for the primary template.
259 if (auto *InstFromPartialTempl =
260 ClassTemplSpec->getSpecializedTemplateOrPartial()
261 .dyn_cast<ClassTemplatePartialSpecializationDecl *>())
262 return Response::ChangeDecl(
263 Ctx: InstFromPartialTempl->getLexicalDeclContext());
264 }
265 return Response::UseNextDecl(CurDecl: ClassTemplSpec);
266}
267
268Response HandleFunction(Sema &SemaRef, const FunctionDecl *Function,
269 MultiLevelTemplateArgumentList &Result,
270 const FunctionDecl *Pattern, bool RelativeToPrimary,
271 bool ForConstraintInstantiation,
272 bool ForDefaultArgumentSubstitution) {
273 // Add template arguments from a function template specialization.
274 if (!RelativeToPrimary &&
275 Function->getTemplateSpecializationKindForInstantiation() ==
276 TSK_ExplicitSpecialization)
277 return Response::Done();
278
279 if (!RelativeToPrimary &&
280 Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) {
281 // This is an implicit instantiation of an explicit specialization. We
282 // don't get any template arguments from this function but might get
283 // some from an enclosing template.
284 return Response::UseNextDecl(CurDecl: Function);
285 } else if (const TemplateArgumentList *TemplateArgs =
286 Function->getTemplateSpecializationArgs()) {
287 // Add the template arguments for this specialization.
288 Result.addOuterTemplateArguments(AssociatedDecl: const_cast<FunctionDecl *>(Function),
289 Args: TemplateArgs->asArray(),
290 /*Final=*/false);
291
292 if (RelativeToPrimary &&
293 (Function->getTemplateSpecializationKind() ==
294 TSK_ExplicitSpecialization ||
295 (Function->getFriendObjectKind() &&
296 !Function->getPrimaryTemplate()->getFriendObjectKind())))
297 return Response::UseNextDecl(CurDecl: Function);
298
299 // If this function was instantiated from a specialized member that is
300 // a function template, we're done.
301 assert(Function->getPrimaryTemplate() && "No function template?");
302 if (!ForDefaultArgumentSubstitution &&
303 Function->getPrimaryTemplate()->isMemberSpecialization())
304 return Response::Done();
305
306 // If this function is a generic lambda specialization, we are done.
307 if (!ForConstraintInstantiation &&
308 isGenericLambdaCallOperatorOrStaticInvokerSpecialization(DC: Function))
309 return Response::Done();
310
311 } else if (auto *Template = Function->getDescribedFunctionTemplate()) {
312 assert(
313 (ForConstraintInstantiation || Result.getNumSubstitutedLevels() == 0) &&
314 "Outer template not instantiated?");
315 if (ForConstraintInstantiation) {
316 for (auto &Inst : llvm::reverse(C&: SemaRef.CodeSynthesisContexts)) {
317 if (Inst.Kind == Sema::CodeSynthesisContext::ConstraintsCheck &&
318 Inst.Entity == Template) {
319 // After CWG2369, the outer templates are not instantiated when
320 // checking its associated constraints. So add them back through the
321 // synthesis context; this is useful for e.g. nested constraints
322 // involving lambdas.
323 Result.addOuterTemplateArguments(AssociatedDecl: Template, Args: Inst.template_arguments(),
324 /*Final=*/false);
325 break;
326 }
327 }
328 }
329 }
330 // If this is a friend or local declaration and it declares an entity at
331 // namespace scope, take arguments from its lexical parent
332 // instead of its semantic parent, unless of course the pattern we're
333 // instantiating actually comes from the file's context!
334 if ((Function->getFriendObjectKind() || Function->isLocalExternDecl()) &&
335 Function->getNonTransparentDeclContext()->isFileContext() &&
336 (!Pattern || !Pattern->getLexicalDeclContext()->isFileContext())) {
337 return Response::ChangeDecl(Ctx: Function->getLexicalDeclContext());
338 }
339
340 if (ForConstraintInstantiation && Function->getFriendObjectKind())
341 return Response::ChangeDecl(Ctx: Function->getLexicalDeclContext());
342 return Response::UseNextDecl(CurDecl: Function);
343}
344
345Response HandleFunctionTemplateDecl(Sema &SemaRef,
346 const FunctionTemplateDecl *FTD,
347 MultiLevelTemplateArgumentList &Result) {
348 if (!isa<ClassTemplateSpecializationDecl>(Val: FTD->getDeclContext())) {
349 Result.addOuterTemplateArguments(
350 AssociatedDecl: const_cast<FunctionTemplateDecl *>(FTD),
351 Args: const_cast<FunctionTemplateDecl *>(FTD)->getInjectedTemplateArgs(
352 Context: SemaRef.Context),
353 /*Final=*/false);
354
355 NestedNameSpecifier NNS = FTD->getTemplatedDecl()->getQualifier();
356
357 for (const Type *Ty = NNS.getKind() == NestedNameSpecifier::Kind::Type
358 ? NNS.getAsType()
359 : nullptr,
360 *NextTy = nullptr;
361 Ty && Ty->isInstantiationDependentType();
362 Ty = std::exchange(obj&: NextTy, new_val: nullptr)) {
363 if (NestedNameSpecifier P = Ty->getPrefix();
364 P.getKind() == NestedNameSpecifier::Kind::Type)
365 NextTy = P.getAsType();
366 const auto *TSTy = dyn_cast<TemplateSpecializationType>(Val: Ty);
367 if (!TSTy)
368 continue;
369
370 ArrayRef<TemplateArgument> Arguments = TSTy->template_arguments();
371 // Prefer template arguments from the injected-class-type if possible.
372 // For example,
373 // ```cpp
374 // template <class... Pack> struct S {
375 // template <class T> void foo();
376 // };
377 // template <class... Pack> template <class T>
378 // ^^^^^^^^^^^^^ InjectedTemplateArgs
379 // They're of kind TemplateArgument::Pack, not of
380 // TemplateArgument::Type.
381 // void S<Pack...>::foo() {}
382 // ^^^^^^^
383 // TSTy->template_arguments() (which are of PackExpansionType)
384 // ```
385 // This meets the contract in
386 // TreeTransform::TryExpandParameterPacks that the template arguments
387 // for unexpanded parameters should be of a Pack kind.
388 if (TSTy->isCurrentInstantiation()) {
389 auto *RD = TSTy->getCanonicalTypeInternal()->getAsCXXRecordDecl();
390 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
391 Arguments = CTD->getInjectedTemplateArgs(Context: SemaRef.Context);
392 else if (auto *Specialization =
393 dyn_cast<ClassTemplateSpecializationDecl>(Val: RD))
394 Arguments = Specialization->getTemplateInstantiationArgs().asArray();
395 }
396 Result.addOuterTemplateArguments(
397 AssociatedDecl: TSTy->getTemplateName().getAsTemplateDecl(), Args: Arguments,
398 /*Final=*/false);
399 }
400 }
401
402 return Response::ChangeDecl(Ctx: FTD->getLexicalDeclContext());
403}
404
405Response HandleRecordDecl(Sema &SemaRef, const CXXRecordDecl *Rec,
406 MultiLevelTemplateArgumentList &Result,
407 ASTContext &Context,
408 bool ForConstraintInstantiation) {
409 if (ClassTemplateDecl *ClassTemplate = Rec->getDescribedClassTemplate()) {
410 assert(
411 (ForConstraintInstantiation || Result.getNumSubstitutedLevels() == 0) &&
412 "Outer template not instantiated?");
413 if (ClassTemplate->isMemberSpecialization())
414 return Response::Done();
415 if (ForConstraintInstantiation)
416 Result.addOuterTemplateArguments(
417 AssociatedDecl: const_cast<CXXRecordDecl *>(Rec),
418 Args: ClassTemplate->getInjectedTemplateArgs(Context: SemaRef.Context),
419 /*Final=*/false);
420 }
421
422 if (const MemberSpecializationInfo *MSInfo =
423 Rec->getMemberSpecializationInfo())
424 if (MSInfo->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
425 return Response::Done();
426
427 bool IsFriend = Rec->getFriendObjectKind() ||
428 (Rec->getDescribedClassTemplate() &&
429 Rec->getDescribedClassTemplate()->getFriendObjectKind());
430 if (ForConstraintInstantiation && IsFriend &&
431 Rec->getNonTransparentDeclContext()->isFileContext()) {
432 return Response::ChangeDecl(Ctx: Rec->getLexicalDeclContext());
433 }
434
435 // This is to make sure we pick up the VarTemplateSpecializationDecl or the
436 // TypeAliasTemplateDecl that this lambda is defined inside of.
437 if (Rec->isLambda()) {
438 if (const Decl *LCD = Rec->getLambdaContextDecl())
439 return Response::ChangeDecl(ND: LCD);
440 // Retrieve the template arguments for a using alias declaration.
441 // This is necessary for constraint checking, since we always keep
442 // constraints relative to the primary template.
443 if (auto TypeAlias = getEnclosingTypeAliasTemplateDecl(SemaRef);
444 ForConstraintInstantiation && TypeAlias) {
445 if (isLambdaEnclosedByTypeAliasDecl(LambdaCallOperator: Rec->getLambdaCallOperator(),
446 PrimaryTypeAliasDecl: TypeAlias.PrimaryTypeAliasDecl)) {
447 Result.addOuterTemplateArguments(AssociatedDecl: TypeAlias.Template,
448 Args: TypeAlias.AssociatedTemplateArguments,
449 /*Final=*/false);
450 // Visit the parent of the current type alias declaration rather than
451 // the lambda thereof.
452 // E.g., in the following example:
453 // struct S {
454 // template <class> using T = decltype([]<Concept> {} ());
455 // };
456 // void foo() {
457 // S::T var;
458 // }
459 // The instantiated lambda expression (which we're visiting at 'var')
460 // has a function DeclContext 'foo' rather than the Record DeclContext
461 // S. This seems to be an oversight to me that we may want to set a
462 // Sema Context from the CXXScopeSpec before substituting into T.
463 return Response::ChangeDecl(Ctx: TypeAlias.Template->getDeclContext());
464 }
465 }
466 }
467
468 return Response::UseNextDecl(CurDecl: Rec);
469}
470
471Response HandleImplicitConceptSpecializationDecl(
472 const ImplicitConceptSpecializationDecl *CSD,
473 MultiLevelTemplateArgumentList &Result) {
474 Result.addOuterTemplateArguments(
475 AssociatedDecl: const_cast<ImplicitConceptSpecializationDecl *>(CSD),
476 Args: CSD->getTemplateArguments(),
477 /*Final=*/false);
478 return Response::UseNextDecl(CurDecl: CSD);
479}
480
481Response HandleGenericDeclContext(const Decl *CurDecl) {
482 return Response::UseNextDecl(CurDecl);
483}
484} // namespace TemplateInstArgsHelpers
485} // namespace
486
487MultiLevelTemplateArgumentList Sema::getTemplateInstantiationArgs(
488 const NamedDecl *ND, const DeclContext *DC, bool Final,
489 std::optional<ArrayRef<TemplateArgument>> Innermost, bool RelativeToPrimary,
490 const FunctionDecl *Pattern, bool ForConstraintInstantiation,
491 bool SkipForSpecialization, bool ForDefaultArgumentSubstitution) {
492 assert((ND || DC) && "Can't find arguments for a decl if one isn't provided");
493 // Accumulate the set of template argument lists in this structure.
494 MultiLevelTemplateArgumentList Result;
495
496 using namespace TemplateInstArgsHelpers;
497 const Decl *CurDecl = ND;
498
499 if (Innermost) {
500 Result.addOuterTemplateArguments(AssociatedDecl: const_cast<NamedDecl *>(ND), Args: *Innermost,
501 Final);
502 // Populate placeholder template arguments for TemplateTemplateParmDecls.
503 // This is essential for the case e.g.
504 //
505 // template <class> concept Concept = false;
506 // template <template <Concept C> class T> void foo(T<int>)
507 //
508 // where parameter C has a depth of 1 but the substituting argument `int`
509 // has a depth of 0.
510 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Val: CurDecl))
511 HandleDefaultTempArgIntoTempTempParam(TTP, Result);
512 CurDecl = DC ? Decl::castFromDeclContext(DC)
513 : Response::UseNextDecl(CurDecl).NextDecl;
514 } else if (!CurDecl)
515 CurDecl = Decl::castFromDeclContext(DC);
516
517 while (!CurDecl->isFileContextDecl()) {
518 Response R;
519 if (const auto *VarTemplSpec =
520 dyn_cast<VarTemplateSpecializationDecl>(Val: CurDecl)) {
521 R = HandleVarTemplateSpec(VarTemplSpec, Result, SkipForSpecialization);
522 } else if (const auto *PartialClassTemplSpec =
523 dyn_cast<ClassTemplatePartialSpecializationDecl>(Val: CurDecl)) {
524 R = HandlePartialClassTemplateSpec(PartialClassTemplSpec, Result,
525 SkipForSpecialization);
526 } else if (const auto *ClassTemplSpec =
527 dyn_cast<ClassTemplateSpecializationDecl>(Val: CurDecl)) {
528 R = HandleClassTemplateSpec(ClassTemplSpec, Result,
529 SkipForSpecialization);
530 } else if (const auto *Function = dyn_cast<FunctionDecl>(Val: CurDecl)) {
531 R = HandleFunction(SemaRef&: *this, Function, Result, Pattern, RelativeToPrimary,
532 ForConstraintInstantiation,
533 ForDefaultArgumentSubstitution);
534 } else if (const auto *Rec = dyn_cast<CXXRecordDecl>(Val: CurDecl)) {
535 R = HandleRecordDecl(SemaRef&: *this, Rec, Result, Context,
536 ForConstraintInstantiation);
537 } else if (const auto *CSD =
538 dyn_cast<ImplicitConceptSpecializationDecl>(Val: CurDecl)) {
539 R = HandleImplicitConceptSpecializationDecl(CSD, Result);
540 } else if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(Val: CurDecl)) {
541 R = HandleFunctionTemplateDecl(SemaRef&: *this, FTD, Result);
542 } else if (const auto *CTD = dyn_cast<ClassTemplateDecl>(Val: CurDecl)) {
543 R = Response::ChangeDecl(Ctx: CTD->getLexicalDeclContext());
544 } else if (!isa<DeclContext>(Val: CurDecl)) {
545 R = Response::DontClearRelativeToPrimaryNextDecl(CurDecl);
546 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Val: CurDecl)) {
547 R = HandleDefaultTempArgIntoTempTempParam(TTP, Result);
548 }
549 } else {
550 R = HandleGenericDeclContext(CurDecl);
551 }
552
553 if (R.IsDone)
554 return Result;
555 if (R.ClearRelativeToPrimary)
556 RelativeToPrimary = false;
557 assert(R.NextDecl);
558 CurDecl = R.NextDecl;
559 }
560 return Result;
561}
562
563bool Sema::CodeSynthesisContext::isInstantiationRecord() const {
564 switch (Kind) {
565 case TemplateInstantiation:
566 case ExceptionSpecInstantiation:
567 case DefaultTemplateArgumentInstantiation:
568 case DefaultFunctionArgumentInstantiation:
569 case ExplicitTemplateArgumentSubstitution:
570 case DeducedTemplateArgumentSubstitution:
571 case PriorTemplateArgumentSubstitution:
572 case ConstraintsCheck:
573 case NestedRequirementConstraintsCheck:
574 case ExpansionStmtInstantiation:
575 return true;
576
577 case RequirementInstantiation:
578 case RequirementParameterInstantiation:
579 case DefaultTemplateArgumentChecking:
580 case DeclaringSpecialMember:
581 case DeclaringImplicitEqualityComparison:
582 case DefiningSynthesizedFunction:
583 case ExceptionSpecEvaluation:
584 case ConstraintSubstitution:
585 case ParameterMappingSubstitution:
586 case RewritingOperatorAsSpaceship:
587 case InitializingStructuredBinding:
588 case MarkingClassDllexported:
589 case BuildingBuiltinDumpStructCall:
590 case LambdaExpressionSubstitution:
591 case BuildingDeductionGuides:
592 case TypeAliasTemplateInstantiation:
593 case PartialOrderingTTP:
594 case SYCLKernelLaunchLookup:
595 case SYCLKernelLaunchOverloadResolution:
596 return false;
597
598 // This function should never be called when Kind's value is Memoization.
599 case Memoization:
600 break;
601 }
602
603 llvm_unreachable("Invalid SynthesisKind!");
604}
605
606Sema::InstantiatingTemplate::InstantiatingTemplate(
607 Sema &SemaRef, CodeSynthesisContext::SynthesisKind Kind,
608 SourceLocation PointOfInstantiation, SourceRange InstantiationRange,
609 Decl *Entity, NamedDecl *Template, ArrayRef<TemplateArgument> TemplateArgs)
610 : SemaRef(SemaRef) {
611 // Don't allow further instantiation if a fatal error and an uncompilable
612 // error have occurred. Any diagnostics we might have raised will not be
613 // visible, and we do not need to construct a correct AST.
614 if (SemaRef.Diags.hasFatalErrorOccurred() &&
615 SemaRef.hasUncompilableErrorOccurred()) {
616 Invalid = true;
617 return;
618 }
619
620 CodeSynthesisContext Inst;
621 Inst.Kind = Kind;
622 Inst.PointOfInstantiation = PointOfInstantiation;
623 Inst.Entity = Entity;
624 Inst.Template = Template;
625 Inst.TemplateArgs = TemplateArgs.data();
626 Inst.NumTemplateArgs = TemplateArgs.size();
627 Inst.InstantiationRange = InstantiationRange;
628 Inst.InConstraintSubstitution =
629 Inst.Kind == CodeSynthesisContext::ConstraintSubstitution;
630 Inst.InParameterMappingSubstitution =
631 Inst.Kind == CodeSynthesisContext::ParameterMappingSubstitution;
632 if (!SemaRef.CodeSynthesisContexts.empty()) {
633 Inst.InConstraintSubstitution |=
634 SemaRef.CodeSynthesisContexts.back().InConstraintSubstitution;
635 Inst.InParameterMappingSubstitution |=
636 SemaRef.CodeSynthesisContexts.back().InParameterMappingSubstitution;
637 }
638
639 Invalid = SemaRef.pushCodeSynthesisContext(Ctx: Inst);
640}
641
642Sema::InstantiatingTemplate::InstantiatingTemplate(
643 Sema &SemaRef, SourceLocation PointOfInstantiation, Decl *Entity,
644 SourceRange InstantiationRange)
645 : InstantiatingTemplate(SemaRef,
646 CodeSynthesisContext::TemplateInstantiation,
647 PointOfInstantiation, InstantiationRange, Entity) {}
648
649Sema::InstantiatingTemplate::InstantiatingTemplate(
650 Sema &SemaRef, SourceLocation PointOfInstantiation, FunctionDecl *Entity,
651 ExceptionSpecification, SourceRange InstantiationRange)
652 : InstantiatingTemplate(
653 SemaRef, CodeSynthesisContext::ExceptionSpecInstantiation,
654 PointOfInstantiation, InstantiationRange, Entity) {}
655
656Sema::InstantiatingTemplate::InstantiatingTemplate(
657 Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateParameter Param,
658 TemplateDecl *Template, ArrayRef<TemplateArgument> TemplateArgs,
659 SourceRange InstantiationRange)
660 : InstantiatingTemplate(
661 SemaRef,
662 CodeSynthesisContext::DefaultTemplateArgumentInstantiation,
663 PointOfInstantiation, InstantiationRange, getAsNamedDecl(P: Param),
664 Template, TemplateArgs) {}
665
666Sema::InstantiatingTemplate::InstantiatingTemplate(
667 Sema &SemaRef, SourceLocation PointOfInstantiation,
668 FunctionTemplateDecl *FunctionTemplate,
669 ArrayRef<TemplateArgument> TemplateArgs,
670 CodeSynthesisContext::SynthesisKind Kind, SourceRange InstantiationRange)
671 : InstantiatingTemplate(SemaRef, Kind, PointOfInstantiation,
672 InstantiationRange, FunctionTemplate, nullptr,
673 TemplateArgs) {
674 assert(Kind == CodeSynthesisContext::ExplicitTemplateArgumentSubstitution ||
675 Kind == CodeSynthesisContext::DeducedTemplateArgumentSubstitution ||
676 Kind == CodeSynthesisContext::BuildingDeductionGuides);
677}
678
679Sema::InstantiatingTemplate::InstantiatingTemplate(
680 Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Template,
681 ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange)
682 : InstantiatingTemplate(
683 SemaRef, CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
684 PointOfInstantiation, InstantiationRange, Template, nullptr,
685 TemplateArgs) {}
686
687Sema::InstantiatingTemplate::InstantiatingTemplate(
688 Sema &SemaRef, SourceLocation PointOfInstantiation,
689 ClassTemplatePartialSpecializationDecl *PartialSpec,
690 ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange)
691 : InstantiatingTemplate(
692 SemaRef, CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
693 PointOfInstantiation, InstantiationRange, PartialSpec, nullptr,
694 TemplateArgs) {}
695
696Sema::InstantiatingTemplate::InstantiatingTemplate(
697 Sema &SemaRef, SourceLocation PointOfInstantiation,
698 VarTemplatePartialSpecializationDecl *PartialSpec,
699 ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange)
700 : InstantiatingTemplate(
701 SemaRef, CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
702 PointOfInstantiation, InstantiationRange, PartialSpec, nullptr,
703 TemplateArgs) {}
704
705Sema::InstantiatingTemplate::InstantiatingTemplate(
706 Sema &SemaRef, SourceLocation PointOfInstantiation, ParmVarDecl *Param,
707 ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange)
708 : InstantiatingTemplate(
709 SemaRef,
710 CodeSynthesisContext::DefaultFunctionArgumentInstantiation,
711 PointOfInstantiation, InstantiationRange, Param, nullptr,
712 TemplateArgs) {}
713
714Sema::InstantiatingTemplate::InstantiatingTemplate(
715 Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template,
716 NonTypeTemplateParmDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
717 SourceRange InstantiationRange)
718 : InstantiatingTemplate(
719 SemaRef,
720 CodeSynthesisContext::PriorTemplateArgumentSubstitution,
721 PointOfInstantiation, InstantiationRange, Param, Template,
722 TemplateArgs) {}
723
724Sema::InstantiatingTemplate::InstantiatingTemplate(
725 Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template,
726 TemplateTemplateParmDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
727 SourceRange InstantiationRange)
728 : InstantiatingTemplate(
729 SemaRef,
730 CodeSynthesisContext::PriorTemplateArgumentSubstitution,
731 PointOfInstantiation, InstantiationRange, Param, Template,
732 TemplateArgs) {}
733
734Sema::InstantiatingTemplate::InstantiatingTemplate(
735 Sema &SemaRef, SourceLocation PointOfInstantiation,
736 TypeAliasTemplateDecl *Entity, ArrayRef<TemplateArgument> TemplateArgs,
737 SourceRange InstantiationRange)
738 : InstantiatingTemplate(
739 SemaRef, CodeSynthesisContext::TypeAliasTemplateInstantiation,
740 PointOfInstantiation, InstantiationRange, /*Entity=*/Entity,
741 /*Template=*/nullptr, TemplateArgs) {}
742
743Sema::InstantiatingTemplate::InstantiatingTemplate(
744 Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Template,
745 NamedDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
746 SourceRange InstantiationRange)
747 : InstantiatingTemplate(
748 SemaRef, CodeSynthesisContext::DefaultTemplateArgumentChecking,
749 PointOfInstantiation, InstantiationRange, Param, Template,
750 TemplateArgs) {}
751
752Sema::InstantiatingTemplate::InstantiatingTemplate(
753 Sema &SemaRef, SourceLocation PointOfInstantiation,
754 concepts::Requirement *Req, SourceRange InstantiationRange)
755 : InstantiatingTemplate(
756 SemaRef, CodeSynthesisContext::RequirementInstantiation,
757 PointOfInstantiation, InstantiationRange, /*Entity=*/nullptr,
758 /*Template=*/nullptr, /*TemplateArgs=*/{}) {}
759
760Sema::InstantiatingTemplate::InstantiatingTemplate(
761 Sema &SemaRef, SourceLocation PointOfInstantiation,
762 CXXExpansionStmtPattern *ExpansionStmt, ArrayRef<TemplateArgument> TArgs,
763 SourceRange InstantiationRange)
764 : InstantiatingTemplate(
765 SemaRef, CodeSynthesisContext::ExpansionStmtInstantiation,
766 PointOfInstantiation, InstantiationRange, /*Entity=*/nullptr,
767 /*Template=*/nullptr, /*TemplateArgs=*/TArgs) {}
768
769Sema::InstantiatingTemplate::InstantiatingTemplate(
770 Sema &SemaRef, SourceLocation PointOfInstantiation,
771 concepts::NestedRequirement *Req, ConstraintsCheck,
772 SourceRange InstantiationRange)
773 : InstantiatingTemplate(
774 SemaRef, CodeSynthesisContext::NestedRequirementConstraintsCheck,
775 PointOfInstantiation, InstantiationRange, /*Entity=*/nullptr,
776 /*Template=*/nullptr, /*TemplateArgs=*/{}) {}
777
778Sema::InstantiatingTemplate::InstantiatingTemplate(
779 Sema &SemaRef, SourceLocation PointOfInstantiation, const RequiresExpr *RE,
780 SourceRange InstantiationRange)
781 : InstantiatingTemplate(
782 SemaRef, CodeSynthesisContext::RequirementParameterInstantiation,
783 PointOfInstantiation, InstantiationRange, /*Entity=*/nullptr,
784 /*Template=*/nullptr, /*TemplateArgs=*/{}) {}
785
786Sema::InstantiatingTemplate::InstantiatingTemplate(
787 Sema &SemaRef, SourceLocation PointOfInstantiation,
788 ConstraintsCheck, NamedDecl *Template,
789 ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange)
790 : InstantiatingTemplate(
791 SemaRef, CodeSynthesisContext::ConstraintsCheck,
792 PointOfInstantiation, InstantiationRange, Template, nullptr,
793 TemplateArgs) {}
794
795Sema::InstantiatingTemplate::InstantiatingTemplate(
796 Sema &SemaRef, SourceLocation PointOfInstantiation, ConstraintSubstitution,
797 NamedDecl *Template, SourceRange InstantiationRange)
798 : InstantiatingTemplate(
799 SemaRef, CodeSynthesisContext::ConstraintSubstitution,
800 PointOfInstantiation, InstantiationRange, Template, nullptr, {}) {}
801
802Sema::InstantiatingTemplate::InstantiatingTemplate(
803 Sema &SemaRef, SourceLocation PointOfInstantiation,
804 ParameterMappingSubstitution, NamedDecl *Template,
805 SourceRange InstantiationRange)
806 : InstantiatingTemplate(
807 SemaRef, CodeSynthesisContext::ParameterMappingSubstitution,
808 PointOfInstantiation, InstantiationRange, Template) {}
809
810Sema::InstantiatingTemplate::InstantiatingTemplate(
811 Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Entity,
812 BuildingDeductionGuidesTag, SourceRange InstantiationRange)
813 : InstantiatingTemplate(
814 SemaRef, CodeSynthesisContext::BuildingDeductionGuides,
815 PointOfInstantiation, InstantiationRange, Entity) {}
816
817Sema::InstantiatingTemplate::InstantiatingTemplate(
818 Sema &SemaRef, SourceLocation ArgLoc, PartialOrderingTTP,
819 TemplateDecl *PArg, SourceRange InstantiationRange)
820 : InstantiatingTemplate(SemaRef, CodeSynthesisContext::PartialOrderingTTP,
821 ArgLoc, InstantiationRange, PArg) {}
822
823bool Sema::pushCodeSynthesisContext(CodeSynthesisContext Ctx) {
824 if (!Ctx.isInstantiationRecord()) {
825 ++NonInstantiationEntries;
826 } else {
827 assert(SemaRef.NonInstantiationEntries <=
828 SemaRef.CodeSynthesisContexts.size());
829 if ((SemaRef.CodeSynthesisContexts.size() -
830 SemaRef.NonInstantiationEntries) >
831 SemaRef.getLangOpts().InstantiationDepth) {
832 SemaRef.Diag(Loc: Ctx.PointOfInstantiation,
833 DiagID: diag::err_template_recursion_depth_exceeded)
834 << SemaRef.getLangOpts().InstantiationDepth << Ctx.InstantiationRange;
835 SemaRef.Diag(Loc: Ctx.PointOfInstantiation,
836 DiagID: diag::note_template_recursion_depth)
837 << SemaRef.getLangOpts().InstantiationDepth;
838 return true;
839 }
840 }
841
842 CodeSynthesisContexts.push_back(Elt: Ctx);
843
844 // Check to see if we're low on stack space. We can't do anything about this
845 // from here, but we can at least warn the user.
846 StackHandler.warnOnStackNearlyExhausted(Loc: Ctx.PointOfInstantiation);
847 return false;
848}
849
850void Sema::popCodeSynthesisContext() {
851 auto &Active = CodeSynthesisContexts.back();
852 if (!Active.isInstantiationRecord()) {
853 assert(NonInstantiationEntries > 0);
854 --NonInstantiationEntries;
855 }
856
857 // Name lookup no longer looks in this template's defining module.
858 assert(CodeSynthesisContexts.size() >=
859 CodeSynthesisContextLookupModules.size() &&
860 "forgot to remove a lookup module for a template instantiation");
861 if (CodeSynthesisContexts.size() ==
862 CodeSynthesisContextLookupModules.size()) {
863 if (Module *M = CodeSynthesisContextLookupModules.back())
864 LookupModulesCache.erase(V: M);
865 CodeSynthesisContextLookupModules.pop_back();
866 }
867
868 // If we've left the code synthesis context for the current context stack,
869 // stop remembering that we've emitted that stack.
870 if (CodeSynthesisContexts.size() ==
871 LastEmittedCodeSynthesisContextDepth)
872 LastEmittedCodeSynthesisContextDepth = 0;
873
874 CodeSynthesisContexts.pop_back();
875}
876
877void Sema::InstantiatingTemplate::Clear() {
878 if (!Invalid) {
879 SemaRef.popCodeSynthesisContext();
880 Invalid = true;
881 }
882}
883
884static std::string convertCallArgsToString(Sema &S,
885 llvm::ArrayRef<const Expr *> Args) {
886 std::string Result;
887 llvm::raw_string_ostream OS(Result);
888 llvm::ListSeparator Comma;
889 for (const Expr *Arg : Args) {
890 OS << Comma;
891 Arg->IgnoreParens()->printPretty(OS, Helper: nullptr,
892 Policy: S.Context.getPrintingPolicy());
893 }
894 return Result;
895}
896
897static std::string
898convertCallArgsValueCategoryAndTypeToString(Sema &S,
899 llvm::ArrayRef<const Expr *> Args) {
900 std::string Result;
901 llvm::raw_string_ostream OS(Result);
902 llvm::ListSeparator Comma;
903 OS << "(";
904 for (const Expr *Arg : Args) {
905 ExprValueKind EVK = Arg->getValueKind();
906 const char *ValueCategory =
907 (EVK == VK_LValue ? "lvalue"
908 : (EVK == VK_XValue ? "xvalue" : "prvalue"));
909 OS << Comma << ValueCategory << " of type '";
910 Arg->getType().print(OS, Policy: S.getPrintingPolicy());
911 OS << "'";
912 }
913 OS << ")";
914 return Result;
915}
916
917void Sema::PrintInstantiationStack(InstantiationContextDiagFuncRef DiagFunc) {
918 // Determine which template instantiations to skip, if any.
919 unsigned SkipStart = CodeSynthesisContexts.size(), SkipEnd = SkipStart;
920 unsigned Limit = Diags.getTemplateBacktraceLimit();
921 if (Limit && Limit < CodeSynthesisContexts.size()) {
922 SkipStart = Limit / 2 + Limit % 2;
923 SkipEnd = CodeSynthesisContexts.size() - Limit / 2;
924 }
925
926 // FIXME: In all of these cases, we need to show the template arguments
927 unsigned InstantiationIdx = 0;
928 for (SmallVectorImpl<CodeSynthesisContext>::reverse_iterator
929 Active = CodeSynthesisContexts.rbegin(),
930 ActiveEnd = CodeSynthesisContexts.rend();
931 Active != ActiveEnd;
932 ++Active, ++InstantiationIdx) {
933 // Skip this instantiation?
934 if (InstantiationIdx >= SkipStart && InstantiationIdx < SkipEnd) {
935 if (InstantiationIdx == SkipStart) {
936 // Note that we're skipping instantiations.
937 DiagFunc(Active->PointOfInstantiation,
938 PDiag(DiagID: diag::note_instantiation_contexts_suppressed)
939 << unsigned(CodeSynthesisContexts.size() - Limit));
940 }
941 continue;
942 }
943
944 switch (Active->Kind) {
945 case CodeSynthesisContext::TemplateInstantiation: {
946 Decl *D = Active->Entity;
947 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Val: D)) {
948 unsigned DiagID = diag::note_template_member_class_here;
949 if (isa<ClassTemplateSpecializationDecl>(Val: Record))
950 DiagID = diag::note_template_class_instantiation_here;
951 DiagFunc(Active->PointOfInstantiation,
952 PDiag(DiagID) << Record << Active->InstantiationRange);
953 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Val: D)) {
954 unsigned DiagID;
955 if (Function->getPrimaryTemplate())
956 DiagID = diag::note_function_template_spec_here;
957 else
958 DiagID = diag::note_template_member_function_here;
959 DiagFunc(Active->PointOfInstantiation,
960 PDiag(DiagID) << Function << Active->InstantiationRange);
961 } else if (VarDecl *VD = dyn_cast<VarDecl>(Val: D)) {
962 DiagFunc(Active->PointOfInstantiation,
963 PDiag(DiagID: VD->isStaticDataMember()
964 ? diag::note_template_static_data_member_def_here
965 : diag::note_template_variable_def_here)
966 << VD << Active->InstantiationRange);
967 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(Val: D)) {
968 DiagFunc(Active->PointOfInstantiation,
969 PDiag(DiagID: diag::note_template_enum_def_here)
970 << ED << Active->InstantiationRange);
971 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(Val: D)) {
972 DiagFunc(Active->PointOfInstantiation,
973 PDiag(DiagID: diag::note_template_nsdmi_here)
974 << FD << Active->InstantiationRange);
975 } else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(Val: D)) {
976 DiagFunc(Active->PointOfInstantiation,
977 PDiag(DiagID: diag::note_template_class_instantiation_here)
978 << CTD << Active->InstantiationRange);
979 }
980 break;
981 }
982
983 case CodeSynthesisContext::DefaultTemplateArgumentInstantiation: {
984 TemplateDecl *Template = cast<TemplateDecl>(Val: Active->Template);
985 SmallString<128> TemplateArgsStr;
986 llvm::raw_svector_ostream OS(TemplateArgsStr);
987 Template->printName(OS, Policy: getPrintingPolicy());
988 printTemplateArgumentList(OS, Args: Active->template_arguments(),
989 Policy: getPrintingPolicy());
990 DiagFunc(Active->PointOfInstantiation,
991 PDiag(DiagID: diag::note_default_arg_instantiation_here)
992 << OS.str() << Active->InstantiationRange);
993 break;
994 }
995
996 case CodeSynthesisContext::ExplicitTemplateArgumentSubstitution: {
997 FunctionTemplateDecl *FnTmpl = cast<FunctionTemplateDecl>(Val: Active->Entity);
998 DiagFunc(Active->PointOfInstantiation,
999 PDiag(DiagID: diag::note_explicit_template_arg_substitution_here)
1000 << FnTmpl
1001 << getTemplateArgumentBindingsText(
1002 Params: FnTmpl->getTemplateParameters(), Args: Active->TemplateArgs,
1003 NumArgs: Active->NumTemplateArgs)
1004 << Active->InstantiationRange);
1005 break;
1006 }
1007
1008 case CodeSynthesisContext::DeducedTemplateArgumentSubstitution: {
1009 if (FunctionTemplateDecl *FnTmpl =
1010 dyn_cast<FunctionTemplateDecl>(Val: Active->Entity)) {
1011 DiagFunc(
1012 Active->PointOfInstantiation,
1013 PDiag(DiagID: diag::note_function_template_deduction_instantiation_here)
1014 << FnTmpl
1015 << getTemplateArgumentBindingsText(
1016 Params: FnTmpl->getTemplateParameters(), Args: Active->TemplateArgs,
1017 NumArgs: Active->NumTemplateArgs)
1018 << Active->InstantiationRange);
1019 } else {
1020 bool IsVar = isa<VarTemplateDecl>(Val: Active->Entity) ||
1021 isa<VarTemplateSpecializationDecl>(Val: Active->Entity);
1022 bool IsTemplate = false;
1023 TemplateParameterList *Params;
1024 if (auto *D = dyn_cast<TemplateDecl>(Val: Active->Entity)) {
1025 IsTemplate = true;
1026 Params = D->getTemplateParameters();
1027 } else if (auto *D = dyn_cast<ClassTemplatePartialSpecializationDecl>(
1028 Val: Active->Entity)) {
1029 Params = D->getTemplateParameters();
1030 } else if (auto *D = dyn_cast<VarTemplatePartialSpecializationDecl>(
1031 Val: Active->Entity)) {
1032 Params = D->getTemplateParameters();
1033 } else {
1034 llvm_unreachable("unexpected template kind");
1035 }
1036
1037 DiagFunc(Active->PointOfInstantiation,
1038 PDiag(DiagID: diag::note_deduced_template_arg_substitution_here)
1039 << IsVar << IsTemplate << cast<NamedDecl>(Val: Active->Entity)
1040 << getTemplateArgumentBindingsText(Params,
1041 Args: Active->TemplateArgs,
1042 NumArgs: Active->NumTemplateArgs)
1043 << Active->InstantiationRange);
1044 }
1045 break;
1046 }
1047
1048 case CodeSynthesisContext::DefaultFunctionArgumentInstantiation: {
1049 ParmVarDecl *Param = cast<ParmVarDecl>(Val: Active->Entity);
1050 FunctionDecl *FD = cast<FunctionDecl>(Val: Param->getDeclContext());
1051
1052 SmallString<128> TemplateArgsStr;
1053 llvm::raw_svector_ostream OS(TemplateArgsStr);
1054 FD->printName(OS, Policy: getPrintingPolicy());
1055 printTemplateArgumentList(OS, Args: Active->template_arguments(),
1056 Policy: getPrintingPolicy());
1057 DiagFunc(Active->PointOfInstantiation,
1058 PDiag(DiagID: diag::note_default_function_arg_instantiation_here)
1059 << OS.str() << Active->InstantiationRange);
1060 break;
1061 }
1062
1063 case CodeSynthesisContext::PriorTemplateArgumentSubstitution: {
1064 NamedDecl *Parm = cast<NamedDecl>(Val: Active->Entity);
1065 std::string Name;
1066 if (!Parm->getName().empty())
1067 Name = std::string(" '") + Parm->getName().str() + "'";
1068
1069 TemplateParameterList *TemplateParams = nullptr;
1070 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Val: Active->Template))
1071 TemplateParams = Template->getTemplateParameters();
1072 else
1073 TemplateParams =
1074 cast<ClassTemplatePartialSpecializationDecl>(Val: Active->Template)
1075 ->getTemplateParameters();
1076 DiagFunc(Active->PointOfInstantiation,
1077 PDiag(DiagID: diag::note_prior_template_arg_substitution)
1078 << isa<TemplateTemplateParmDecl>(Val: Parm) << Name
1079 << getTemplateArgumentBindingsText(Params: TemplateParams,
1080 Args: Active->TemplateArgs,
1081 NumArgs: Active->NumTemplateArgs)
1082 << Active->InstantiationRange);
1083 break;
1084 }
1085
1086 case CodeSynthesisContext::DefaultTemplateArgumentChecking: {
1087 TemplateParameterList *TemplateParams = nullptr;
1088 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Val: Active->Template))
1089 TemplateParams = Template->getTemplateParameters();
1090 else
1091 TemplateParams =
1092 cast<ClassTemplatePartialSpecializationDecl>(Val: Active->Template)
1093 ->getTemplateParameters();
1094
1095 DiagFunc(Active->PointOfInstantiation,
1096 PDiag(DiagID: diag::note_template_default_arg_checking)
1097 << getTemplateArgumentBindingsText(Params: TemplateParams,
1098 Args: Active->TemplateArgs,
1099 NumArgs: Active->NumTemplateArgs)
1100 << Active->InstantiationRange);
1101 break;
1102 }
1103
1104 case CodeSynthesisContext::ExceptionSpecEvaluation:
1105 DiagFunc(Active->PointOfInstantiation,
1106 PDiag(DiagID: diag::note_evaluating_exception_spec_here)
1107 << cast<FunctionDecl>(Val: Active->Entity));
1108 break;
1109
1110 case CodeSynthesisContext::ExceptionSpecInstantiation:
1111 DiagFunc(Active->PointOfInstantiation,
1112 PDiag(DiagID: diag::note_template_exception_spec_instantiation_here)
1113 << cast<FunctionDecl>(Val: Active->Entity)
1114 << Active->InstantiationRange);
1115 break;
1116
1117 case CodeSynthesisContext::RequirementInstantiation:
1118 DiagFunc(Active->PointOfInstantiation,
1119 PDiag(DiagID: diag::note_template_requirement_instantiation_here)
1120 << Active->InstantiationRange);
1121 break;
1122 case CodeSynthesisContext::RequirementParameterInstantiation:
1123 DiagFunc(Active->PointOfInstantiation,
1124 PDiag(DiagID: diag::note_template_requirement_params_instantiation_here)
1125 << Active->InstantiationRange);
1126 break;
1127
1128 case CodeSynthesisContext::NestedRequirementConstraintsCheck:
1129 DiagFunc(Active->PointOfInstantiation,
1130 PDiag(DiagID: diag::note_nested_requirement_here)
1131 << Active->InstantiationRange);
1132 break;
1133
1134 case CodeSynthesisContext::DeclaringSpecialMember:
1135 DiagFunc(Active->PointOfInstantiation,
1136 PDiag(DiagID: diag::note_in_declaration_of_implicit_special_member)
1137 << cast<CXXRecordDecl>(Val: Active->Entity)
1138 << Active->SpecialMember);
1139 break;
1140
1141 case CodeSynthesisContext::DeclaringImplicitEqualityComparison:
1142 DiagFunc(
1143 Active->Entity->getLocation(),
1144 PDiag(DiagID: diag::note_in_declaration_of_implicit_equality_comparison));
1145 break;
1146
1147 case CodeSynthesisContext::DefiningSynthesizedFunction: {
1148 // FIXME: For synthesized functions that are not defaulted,
1149 // produce a note.
1150 auto *FD = dyn_cast<FunctionDecl>(Val: Active->Entity);
1151 // Note: if FD is nullptr currently setting DFK to DefaultedFunctionKind()
1152 // will ensure that DFK.isComparison() is false. This is important because
1153 // we will uncondtionally dereference FD in the else if.
1154 FunctionDecl::DefaultedFunctionKind DFK =
1155 FD ? FD->getDefaultedFunctionKind()
1156 : FunctionDecl::DefaultedFunctionKind();
1157 if (DFK.isSpecialMember()) {
1158 auto *MD = cast<CXXMethodDecl>(Val: FD);
1159 DiagFunc(Active->PointOfInstantiation,
1160 PDiag(DiagID: diag::note_member_synthesized_at)
1161 << MD->isExplicitlyDefaulted() << DFK.asSpecialMember()
1162 << Context.getCanonicalTagType(TD: MD->getParent()));
1163 } else if (DFK.isComparison()) {
1164 QualType RecordType = FD->getParamDecl(i: 0)
1165 ->getType()
1166 .getNonReferenceType()
1167 .getUnqualifiedType();
1168 DiagFunc(Active->PointOfInstantiation,
1169 PDiag(DiagID: diag::note_comparison_synthesized_at)
1170 << (int)DFK.asComparison() << RecordType);
1171 }
1172 break;
1173 }
1174
1175 case CodeSynthesisContext::RewritingOperatorAsSpaceship:
1176 DiagFunc(Active->Entity->getLocation(),
1177 PDiag(DiagID: diag::note_rewriting_operator_as_spaceship));
1178 break;
1179
1180 case CodeSynthesisContext::InitializingStructuredBinding:
1181 DiagFunc(Active->PointOfInstantiation,
1182 PDiag(DiagID: diag::note_in_binding_decl_init)
1183 << cast<BindingDecl>(Val: Active->Entity));
1184 break;
1185
1186 case CodeSynthesisContext::MarkingClassDllexported:
1187 DiagFunc(Active->PointOfInstantiation,
1188 PDiag(DiagID: diag::note_due_to_dllexported_class)
1189 << cast<CXXRecordDecl>(Val: Active->Entity)
1190 << !getLangOpts().CPlusPlus11);
1191 break;
1192
1193 case CodeSynthesisContext::BuildingBuiltinDumpStructCall:
1194 DiagFunc(Active->PointOfInstantiation,
1195 PDiag(DiagID: diag::note_building_builtin_dump_struct_call)
1196 << convertCallArgsToString(
1197 S&: *this, Args: llvm::ArrayRef(Active->CallArgs,
1198 Active->NumCallArgs)));
1199 break;
1200
1201 case CodeSynthesisContext::Memoization:
1202 break;
1203
1204 case CodeSynthesisContext::LambdaExpressionSubstitution:
1205 DiagFunc(Active->PointOfInstantiation,
1206 PDiag(DiagID: diag::note_lambda_substitution_here));
1207 break;
1208 case CodeSynthesisContext::ConstraintsCheck: {
1209 unsigned DiagID = 0;
1210 if (!Active->Entity) {
1211 DiagFunc(Active->PointOfInstantiation,
1212 PDiag(DiagID: diag::note_nested_requirement_here)
1213 << Active->InstantiationRange);
1214 break;
1215 }
1216 if (isa<ConceptDecl>(Val: Active->Entity))
1217 DiagID = diag::note_concept_specialization_here;
1218 else if (isa<TemplateDecl>(Val: Active->Entity))
1219 DiagID = diag::note_checking_constraints_for_template_id_here;
1220 else if (isa<VarTemplatePartialSpecializationDecl>(Val: Active->Entity))
1221 DiagID = diag::note_checking_constraints_for_var_spec_id_here;
1222 else if (isa<ClassTemplatePartialSpecializationDecl>(Val: Active->Entity))
1223 DiagID = diag::note_checking_constraints_for_class_spec_id_here;
1224 else {
1225 assert(isa<FunctionDecl>(Active->Entity));
1226 DiagID = diag::note_checking_constraints_for_function_here;
1227 }
1228 SmallString<128> TemplateArgsStr;
1229 llvm::raw_svector_ostream OS(TemplateArgsStr);
1230 cast<NamedDecl>(Val: Active->Entity)->printName(OS, Policy: getPrintingPolicy());
1231 if (!isa<FunctionDecl>(Val: Active->Entity)) {
1232 printTemplateArgumentList(OS, Args: Active->template_arguments(),
1233 Policy: getPrintingPolicy());
1234 }
1235 DiagFunc(Active->PointOfInstantiation,
1236 PDiag(DiagID) << OS.str() << Active->InstantiationRange);
1237 break;
1238 }
1239 case CodeSynthesisContext::ConstraintSubstitution:
1240 DiagFunc(Active->PointOfInstantiation,
1241 PDiag(DiagID: diag::note_constraint_substitution_here)
1242 << Active->InstantiationRange);
1243 break;
1244 case CodeSynthesisContext::ParameterMappingSubstitution:
1245 DiagFunc(Active->PointOfInstantiation,
1246 PDiag(DiagID: diag::note_parameter_mapping_substitution_here)
1247 << Active->InstantiationRange);
1248 break;
1249 case CodeSynthesisContext::BuildingDeductionGuides:
1250 DiagFunc(Active->PointOfInstantiation,
1251 PDiag(DiagID: diag::note_building_deduction_guide_here));
1252 break;
1253 case CodeSynthesisContext::TypeAliasTemplateInstantiation:
1254 // Workaround for a workaround: don't produce a note if we are merely
1255 // instantiating some other template which contains this alias template.
1256 // This would be redundant either with the error itself, or some other
1257 // context note attached to it.
1258 if (Active->NumTemplateArgs == 0)
1259 break;
1260 DiagFunc(Active->PointOfInstantiation,
1261 PDiag(DiagID: diag::note_template_type_alias_instantiation_here)
1262 << cast<TypeAliasTemplateDecl>(Val: Active->Entity)
1263 << Active->InstantiationRange);
1264 break;
1265 case CodeSynthesisContext::PartialOrderingTTP:
1266 DiagFunc(Active->PointOfInstantiation,
1267 PDiag(DiagID: diag::note_template_arg_template_params_mismatch));
1268 if (SourceLocation ParamLoc = Active->Entity->getLocation();
1269 ParamLoc.isValid())
1270 DiagFunc(ParamLoc, PDiag(DiagID: diag::note_template_prev_declaration)
1271 << /*isTemplateTemplateParam=*/true
1272 << Active->InstantiationRange);
1273 break;
1274 case CodeSynthesisContext::SYCLKernelLaunchLookup: {
1275 const auto *SKEPAttr =
1276 Active->Entity->getAttr<SYCLKernelEntryPointAttr>();
1277 assert(SKEPAttr && "Missing sycl_kernel_entry_point attribute");
1278 assert(!SKEPAttr->isInvalidAttr() &&
1279 "sycl_kernel_entry_point attribute is invalid");
1280 DiagFunc(SKEPAttr->getLocation(), PDiag(DiagID: diag::note_sycl_runtime_defect));
1281 DiagFunc(SKEPAttr->getLocation(),
1282 PDiag(DiagID: diag::note_sycl_kernel_launch_lookup_here)
1283 << SKEPAttr->getKernelName());
1284 break;
1285 }
1286 case CodeSynthesisContext::SYCLKernelLaunchOverloadResolution: {
1287 const auto *SKEPAttr =
1288 Active->Entity->getAttr<SYCLKernelEntryPointAttr>();
1289 assert(SKEPAttr && "Missing sycl_kernel_entry_point attribute");
1290 assert(!SKEPAttr->isInvalidAttr() &&
1291 "sycl_kernel_entry_point attribute is invalid");
1292 DiagFunc(SKEPAttr->getLocation(), PDiag(DiagID: diag::note_sycl_runtime_defect));
1293 DiagFunc(SKEPAttr->getLocation(),
1294 PDiag(DiagID: diag::note_sycl_kernel_launch_overload_resolution_here)
1295 << SKEPAttr->getKernelName()
1296 << convertCallArgsValueCategoryAndTypeToString(
1297 S&: *this, Args: llvm::ArrayRef(Active->CallArgs,
1298 Active->NumCallArgs)));
1299 break;
1300 }
1301 case CodeSynthesisContext::ExpansionStmtInstantiation:
1302 Diags.Report(Loc: Active->PointOfInstantiation,
1303 DiagID: diag::note_expansion_stmt_instantiation_here);
1304 }
1305 }
1306}
1307
1308//===----------------------------------------------------------------------===/
1309// Template Instantiation for Types
1310//===----------------------------------------------------------------------===/
1311namespace {
1312
1313 class TemplateInstantiator : public TreeTransform<TemplateInstantiator> {
1314 const MultiLevelTemplateArgumentList &TemplateArgs;
1315 SourceLocation Loc;
1316 DeclarationName Entity;
1317 // Whether to evaluate the C++20 constraints or simply substitute into them.
1318 bool EvaluateConstraints = true;
1319 bool EvaluateLambdaConstraint = false;
1320 // Whether Substitution was Incomplete, that is, we tried to substitute in
1321 // any user provided template arguments which were null.
1322 bool IsIncomplete = false;
1323 // Whether an incomplete substituion should be treated as an error.
1324 bool BailOutOnIncomplete;
1325
1326 std::optional<llvm::FoldingSetNodeID> TemplateArgsHashValue;
1327 llvm::DenseMap<llvm::FoldingSetNodeID, TemplateArgumentLoc>
1328 *CurrentCachedTemplateArgs = nullptr;
1329
1330 bool instantiateMissingDeclsToScopeForConcepts(Decl *D);
1331
1332 public:
1333 typedef TreeTransform<TemplateInstantiator> inherited;
1334
1335 TemplateInstantiator(Sema &SemaRef,
1336 const MultiLevelTemplateArgumentList &TemplateArgs,
1337 SourceLocation Loc, DeclarationName Entity,
1338 bool BailOutOnIncomplete = false)
1339 : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc),
1340 Entity(Entity), BailOutOnIncomplete(BailOutOnIncomplete) {
1341 assert((!SemaRef.CodeSynthesisContexts.empty() ||
1342 SemaRef.isSFINAEContext()) &&
1343 "Cannot perform an instantiation without some context on the "
1344 "instantiation stack");
1345 }
1346
1347 void setEvaluateConstraints(bool B) {
1348 EvaluateConstraints = B;
1349 }
1350 bool getEvaluateConstraints() {
1351 return EvaluateConstraints;
1352 }
1353
1354 inline static struct ForParameterMappingSubstitution_t {
1355 } ForParameterMappingSubstitution;
1356
1357 inline static struct ForConstraintSubstitution_t {
1358 } ForConstraintSubstitution;
1359
1360 TemplateInstantiator(
1361 ForParameterMappingSubstitution_t, Sema &SemaRef, SourceLocation Loc,
1362 const MultiLevelTemplateArgumentList &TemplateArgs,
1363 llvm::DenseMap<llvm::FoldingSetNodeID, TemplateArgumentLoc> *Cache)
1364 : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc),
1365 EvaluateLambdaConstraint(true), BailOutOnIncomplete(false),
1366 CurrentCachedTemplateArgs(Cache) {
1367 if (!Cache)
1368 return;
1369 auto &V = TemplateArgsHashValue.emplace();
1370 for (auto &Level : TemplateArgs)
1371 for (auto &Arg : Level.Args)
1372 Arg.Profile(ID&: V, Context: SemaRef.Context);
1373 }
1374
1375 TemplateInstantiator(ForConstraintSubstitution_t, Sema &SemaRef,
1376 const MultiLevelTemplateArgumentList &TemplateArgs,
1377 SourceLocation Loc, DeclarationName Entity,
1378 bool BailOutOnIncomplete = false)
1379 : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc),
1380 EvaluateLambdaConstraint(true), BailOutOnIncomplete(false) {}
1381
1382 /// Determine whether the given type \p T has already been
1383 /// transformed.
1384 ///
1385 /// For the purposes of template instantiation, a type has already been
1386 /// transformed if it is NULL or if it is not dependent.
1387 bool AlreadyTransformed(QualType T);
1388
1389 /// Returns the location of the entity being instantiated, if known.
1390 SourceLocation getBaseLocation() { return Loc; }
1391
1392 /// Returns the name of the entity being instantiated, if any.
1393 DeclarationName getBaseEntity() { return Entity; }
1394
1395 /// Returns whether any substitution so far was incomplete.
1396 bool getIsIncomplete() const { return IsIncomplete; }
1397
1398 /// Sets the "base" location and entity when that
1399 /// information is known based on another transformation.
1400 void setBase(SourceLocation Loc, DeclarationName Entity) {
1401 this->Loc = Loc;
1402 this->Entity = Entity;
1403 }
1404
1405 unsigned TransformTemplateDepth(unsigned Depth) {
1406 return TemplateArgs.getNewDepth(OldDepth: Depth);
1407 }
1408
1409 bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
1410 SourceRange PatternRange,
1411 ArrayRef<UnexpandedParameterPack> Unexpanded,
1412 bool FailOnPackProducingTemplates,
1413 bool &ShouldExpand, bool &RetainExpansion,
1414 UnsignedOrNone &NumExpansions,
1415 bool Diagnose = true) {
1416 for (UnexpandedParameterPack ParmPack : Unexpanded) {
1417 if (instantiateMissingDeclsToScopeForConcepts(
1418 D: dyn_cast<NamedDecl *>(Val&: ParmPack.first)))
1419 return true;
1420 }
1421
1422 return getSema().CheckParameterPacksForExpansion(
1423 EllipsisLoc, PatternRange, Unexpanded, TemplateArgs,
1424 FailOnPackProducingTemplates, ShouldExpand, RetainExpansion,
1425 NumExpansions, Diagnose);
1426 }
1427
1428 void ExpandingFunctionParameterPack(ParmVarDecl *Pack) {
1429 SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(D: Pack);
1430 }
1431
1432 TemplateArgument ForgetPartiallySubstitutedPack() {
1433 TemplateArgument Result;
1434 if (NamedDecl *PartialPack = SemaRef.CurrentInstantiationScope
1435 ->getPartiallySubstitutedPack()) {
1436 MultiLevelTemplateArgumentList &TemplateArgs =
1437 const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
1438 unsigned Depth, Index;
1439 std::tie(args&: Depth, args&: Index) = getDepthAndIndex(ND: PartialPack);
1440 if (TemplateArgs.hasTemplateArgument(Depth, Index)) {
1441 Result = TemplateArgs(Depth, Index);
1442 TemplateArgs.setArgument(Depth, Index, Arg: TemplateArgument());
1443 } else {
1444 IsIncomplete = true;
1445 if (BailOutOnIncomplete)
1446 return TemplateArgument();
1447 }
1448 }
1449
1450 return Result;
1451 }
1452
1453 void RememberPartiallySubstitutedPack(TemplateArgument Arg) {
1454 if (Arg.isNull())
1455 return;
1456
1457 if (NamedDecl *PartialPack = SemaRef.CurrentInstantiationScope
1458 ->getPartiallySubstitutedPack()) {
1459 MultiLevelTemplateArgumentList &TemplateArgs =
1460 const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
1461 unsigned Depth, Index;
1462 std::tie(args&: Depth, args&: Index) = getDepthAndIndex(ND: PartialPack);
1463 TemplateArgs.setArgument(Depth, Index, Arg);
1464 }
1465 }
1466
1467 MultiLevelTemplateArgumentList ForgetSubstitution() {
1468 MultiLevelTemplateArgumentList New;
1469 New.addOuterRetainedLevels(Num: this->TemplateArgs.getNumLevels());
1470
1471 MultiLevelTemplateArgumentList Old =
1472 const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
1473 const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs) =
1474 std::move(New);
1475 return Old;
1476 }
1477
1478 void RememberSubstitution(MultiLevelTemplateArgumentList Old) {
1479 const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs) =
1480 std::move(Old);
1481 }
1482
1483 TemplateArgument
1484 getTemplateArgumentPackPatternForRewrite(const TemplateArgument &TA) {
1485 if (TA.getKind() != TemplateArgument::Pack)
1486 return TA;
1487 if (SemaRef.ArgPackSubstIndex)
1488 return SemaRef.getPackSubstitutedTemplateArgument(Arg: TA);
1489 assert(TA.pack_size() == 1 && TA.pack_begin()->isPackExpansion() &&
1490 "unexpected pack arguments in template rewrite");
1491 TemplateArgument Arg = *TA.pack_begin();
1492 if (Arg.isPackExpansion())
1493 Arg = Arg.getPackExpansionPattern();
1494 return Arg;
1495 }
1496
1497 /// Transform the given declaration by instantiating a reference to
1498 /// this declaration.
1499 Decl *TransformDecl(SourceLocation Loc, Decl *D);
1500
1501 void transformAttrs(Decl *Old, Decl *New) {
1502 SemaRef.InstantiateAttrs(TemplateArgs, Pattern: Old, Inst: New);
1503 }
1504
1505 void transformedLocalDecl(Decl *Old, ArrayRef<Decl *> NewDecls) {
1506 if (Old->isParameterPack() &&
1507 (NewDecls.size() != 1 || !NewDecls.front()->isParameterPack())) {
1508 SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(D: Old);
1509 for (auto *New : NewDecls)
1510 SemaRef.CurrentInstantiationScope->InstantiatedLocalPackArg(
1511 D: Old, Inst: cast<VarDecl>(Val: New));
1512 return;
1513 }
1514
1515 assert(NewDecls.size() == 1 &&
1516 "should only have multiple expansions for a pack");
1517 Decl *New = NewDecls.front();
1518
1519 // If we've instantiated the call operator of a lambda or the call
1520 // operator template of a generic lambda, update the "instantiation of"
1521 // information.
1522 auto *NewMD = dyn_cast<CXXMethodDecl>(Val: New);
1523 if (NewMD && isLambdaCallOperator(MD: NewMD)) {
1524 auto *OldMD = dyn_cast<CXXMethodDecl>(Val: Old);
1525 if (auto *NewTD = NewMD->getDescribedFunctionTemplate())
1526 NewTD->setInstantiatedFromMemberTemplate(
1527 OldMD->getDescribedFunctionTemplate());
1528 else
1529 NewMD->setInstantiationOfMemberFunction(FD: OldMD,
1530 TSK: TSK_ImplicitInstantiation);
1531 }
1532
1533 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D: Old, Inst: New);
1534
1535 // We recreated a local declaration, but not by instantiating it. There
1536 // may be pending dependent diagnostics to produce.
1537 if (auto *DC = dyn_cast<DeclContext>(Val: Old);
1538 DC && DC->isDependentContext() && DC->isFunctionOrMethod())
1539 SemaRef.PerformDependentDiagnostics(Pattern: DC, TemplateArgs);
1540 }
1541
1542 /// Transform the definition of the given declaration by
1543 /// instantiating it.
1544 Decl *TransformDefinition(SourceLocation Loc, Decl *D);
1545
1546 /// Transform the first qualifier within a scope by instantiating the
1547 /// declaration.
1548 NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc);
1549
1550 bool TransformExceptionSpec(SourceLocation Loc,
1551 FunctionProtoType::ExceptionSpecInfo &ESI,
1552 SmallVectorImpl<QualType> &Exceptions,
1553 bool &Changed);
1554
1555 /// Rebuild the exception declaration and register the declaration
1556 /// as an instantiated local.
1557 VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
1558 TypeSourceInfo *Declarator,
1559 SourceLocation StartLoc,
1560 SourceLocation NameLoc,
1561 IdentifierInfo *Name);
1562
1563 /// Rebuild the Objective-C exception declaration and register the
1564 /// declaration as an instantiated local.
1565 VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
1566 TypeSourceInfo *TSInfo, QualType T);
1567
1568 TemplateName
1569 TransformTemplateName(NestedNameSpecifierLoc &QualifierLoc,
1570 SourceLocation TemplateKWLoc, TemplateName Name,
1571 SourceLocation NameLoc,
1572 QualType ObjectType = QualType(),
1573 NamedDecl *FirstQualifierInScope = nullptr,
1574 bool AllowInjectedClassName = false);
1575
1576 const AnnotateAttr *TransformAnnotateAttr(const AnnotateAttr *AA);
1577 const CXXAssumeAttr *TransformCXXAssumeAttr(const CXXAssumeAttr *AA);
1578 const LoopHintAttr *TransformLoopHintAttr(const LoopHintAttr *LH);
1579 const NoInlineAttr *TransformStmtNoInlineAttr(const Stmt *OrigS,
1580 const Stmt *InstS,
1581 const NoInlineAttr *A);
1582 const AlwaysInlineAttr *
1583 TransformStmtAlwaysInlineAttr(const Stmt *OrigS, const Stmt *InstS,
1584 const AlwaysInlineAttr *A);
1585 const CodeAlignAttr *TransformCodeAlignAttr(const CodeAlignAttr *CA);
1586 const OpenACCRoutineDeclAttr *
1587 TransformOpenACCRoutineDeclAttr(const OpenACCRoutineDeclAttr *A);
1588 ExprResult TransformPredefinedExpr(PredefinedExpr *E);
1589 ExprResult TransformDeclRefExpr(DeclRefExpr *E);
1590 ExprResult TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E);
1591
1592 ExprResult TransformTemplateParmRefExpr(DeclRefExpr *E,
1593 NonTypeTemplateParmDecl *D);
1594
1595 /// Rebuild a DeclRefExpr for a VarDecl reference.
1596 ExprResult RebuildVarDeclRefExpr(ValueDecl *PD, SourceLocation Loc);
1597
1598 /// Transform a reference to a function or init-capture parameter pack.
1599 ExprResult TransformFunctionParmPackRefExpr(DeclRefExpr *E, ValueDecl *PD);
1600
1601 /// Transform a FunctionParmPackExpr which was built when we couldn't
1602 /// expand a function parameter pack reference which refers to an expanded
1603 /// pack.
1604 ExprResult TransformFunctionParmPackExpr(FunctionParmPackExpr *E);
1605
1606 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
1607 FunctionProtoTypeLoc TL) {
1608 // Call the base version; it will forward to our overridden version below.
1609 return inherited::TransformFunctionProtoType(TLB, TL);
1610 }
1611
1612 QualType TransformTagType(TypeLocBuilder &TLB, TagTypeLoc TL) {
1613 auto Type = inherited::TransformTagType(TLB, TL);
1614 if (!Type.isNull())
1615 return Type;
1616 // Special case for transforming a deduction guide, we return a
1617 // transformed TemplateSpecializationType.
1618 // FIXME: Why is this hack necessary?
1619 if (const auto *ICNT = dyn_cast<InjectedClassNameType>(Val: TL.getTypePtr());
1620 ICNT && SemaRef.CodeSynthesisContexts.back().Kind ==
1621 Sema::CodeSynthesisContext::BuildingDeductionGuides) {
1622 Type = inherited::TransformType(
1623 T: ICNT->getDecl()->getCanonicalTemplateSpecializationType(
1624 Ctx: SemaRef.Context));
1625 TLB.pushTrivial(Context&: SemaRef.Context, T: Type, Loc: TL.getNameLoc());
1626 }
1627 return Type;
1628 }
1629
1630 // Override the default version to handle a rewrite-template-arg-pack case
1631 // for building a deduction guide, and to cache substitution results in
1632 // concepts checking.
1633 bool TransformTemplateArgument(const TemplateArgumentLoc &Input,
1634 TemplateArgumentLoc &Output,
1635 bool Uneval = false) {
1636 const TemplateArgument &Arg = Input.getArgument();
1637 if (auto *Cache = CurrentCachedTemplateArgs;
1638 Cache && TemplateArgsHashValue) {
1639 llvm::FoldingSetNodeID ID = *TemplateArgsHashValue;
1640 ID.AddInteger(I: SemaRef.ArgPackSubstIndex.toInternalRepresentation());
1641 // FIXME: We may have better performance if we profile Arg without
1642 // sugars.
1643 Arg.Profile(ID, Context: SemaRef.Context);
1644 // FIXME: Ideally, we should only cache and restore the TemplateArgument
1645 // and rebuild the uncached TypeLoc separately in place.
1646 // We choose to accept loss of TypeLoc fidelity in cases where TypeLocs
1647 // are less critical for performance trade-off: currently, this is only
1648 // applied to concept substitutions and their valid template arguments.
1649 if (auto Iter = Cache->find(Val: ID); Iter != Cache->end()) {
1650 Output = Iter->second;
1651 return false;
1652 }
1653 bool Ret = inherited::TransformTemplateArgument(Input, Output, Uneval);
1654 if (!Ret)
1655 Cache->insert(KV: {ID, Output});
1656 return Ret;
1657 }
1658 switch (Arg.getKind()) {
1659 case TemplateArgument::Pack: {
1660 std::vector<TemplateArgument> TArgs;
1661 assert(SemaRef.CodeSynthesisContexts.empty() ||
1662 SemaRef.CodeSynthesisContexts.back().Kind ==
1663 Sema::CodeSynthesisContext::BuildingDeductionGuides);
1664 // Literally rewrite the template argument pack, instead of unpacking
1665 // it.
1666 for (auto &pack : Arg.getPackAsArray()) {
1667 TemplateArgumentLoc Input = SemaRef.getTrivialTemplateArgumentLoc(
1668 Arg: pack, NTTPType: QualType(), Loc: SourceLocation{});
1669 TemplateArgumentLoc Output;
1670 if (TransformTemplateArgument(Input, Output, Uneval))
1671 return true; // fails
1672 TArgs.push_back(x: Output.getArgument());
1673 }
1674 Output = SemaRef.getTrivialTemplateArgumentLoc(
1675 Arg: TemplateArgument(llvm::ArrayRef(TArgs).copy(A&: SemaRef.Context)),
1676 NTTPType: QualType(), Loc: SourceLocation{});
1677 return false;
1678 }
1679 default:
1680 break;
1681 }
1682 return inherited::TransformTemplateArgument(Input, Output, Uneval);
1683 }
1684
1685 using TreeTransform::TransformTemplateSpecializationType;
1686 QualType
1687 TransformTemplateSpecializationType(TypeLocBuilder &TLB,
1688 TemplateSpecializationTypeLoc TL) {
1689 auto *T = TL.getTypePtr();
1690 if (!getSema().ArgPackSubstIndex || !T->isSugared() ||
1691 !isPackProducingBuiltinTemplateName(N: T->getTemplateName()))
1692 return TreeTransform::TransformTemplateSpecializationType(TLB, TL);
1693 // Look through sugar to get to the SubstBuiltinTemplatePackType that we
1694 // need to substitute into.
1695
1696 // `TransformType` code below will handle picking the element from a pack
1697 // with the index `ArgPackSubstIndex`.
1698 // FIXME: add ability to represent sugarred type for N-th element of a
1699 // builtin pack and produce the sugar here.
1700 QualType R = TransformType(T: T->desugar());
1701 TLB.pushTrivial(Context&: getSema().getASTContext(), T: R, Loc: TL.getBeginLoc());
1702 return R;
1703 }
1704
1705 UnsignedOrNone ComputeSizeOfPackExprWithoutSubstitution(
1706 ArrayRef<TemplateArgument> PackArgs) {
1707 // Don't do this when rewriting template parameters for CTAD:
1708 // 1) The heuristic needs the unpacked Subst* nodes to figure out the
1709 // expanded size, but this never applies since Subst* nodes are not
1710 // created in rewrite scenarios.
1711 //
1712 // 2) The heuristic substitutes into the pattern with pack expansion
1713 // suppressed, which does not meet the requirements for argument
1714 // rewriting when template arguments include a non-pack matching against
1715 // a pack, particularly when rewriting an alias CTAD.
1716 if (TemplateArgs.isRewrite())
1717 return std::nullopt;
1718
1719 return inherited::ComputeSizeOfPackExprWithoutSubstitution(PackArgs);
1720 }
1721
1722 template<typename Fn>
1723 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
1724 FunctionProtoTypeLoc TL,
1725 CXXRecordDecl *ThisContext,
1726 Qualifiers ThisTypeQuals,
1727 Fn TransformExceptionSpec);
1728
1729 ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm,
1730 int indexAdjustment,
1731 UnsignedOrNone NumExpansions,
1732 bool ExpectParameterPack);
1733
1734 using inherited::TransformTemplateTypeParmType;
1735 /// Transforms a template type parameter type by performing
1736 /// substitution of the corresponding template type argument.
1737 QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
1738 TemplateTypeParmTypeLoc TL,
1739 bool SuppressObjCLifetime);
1740
1741 QualType BuildSubstTemplateTypeParmType(
1742 TypeLocBuilder &TLB, bool SuppressObjCLifetime, bool Final,
1743 Decl *AssociatedDecl, unsigned Index, UnsignedOrNone PackIndex,
1744 TemplateArgument Arg, SourceLocation NameLoc);
1745
1746 /// Transforms an already-substituted template type parameter pack
1747 /// into either itself (if we aren't substituting into its pack expansion)
1748 /// or the appropriate substituted argument.
1749 using inherited::TransformSubstTemplateTypeParmPackType;
1750 QualType
1751 TransformSubstTemplateTypeParmPackType(TypeLocBuilder &TLB,
1752 SubstTemplateTypeParmPackTypeLoc TL,
1753 bool SuppressObjCLifetime);
1754 QualType
1755 TransformSubstBuiltinTemplatePackType(TypeLocBuilder &TLB,
1756 SubstBuiltinTemplatePackTypeLoc TL);
1757
1758 CXXRecordDecl::LambdaDependencyKind
1759 ComputeLambdaDependency(LambdaScopeInfo *LSI) {
1760 if (auto TypeAlias =
1761 TemplateInstArgsHelpers::getEnclosingTypeAliasTemplateDecl(
1762 SemaRef&: getSema());
1763 TypeAlias && TemplateInstArgsHelpers::isLambdaEnclosedByTypeAliasDecl(
1764 LambdaCallOperator: LSI->CallOperator, PrimaryTypeAliasDecl: TypeAlias.PrimaryTypeAliasDecl)) {
1765 unsigned TypeAliasDeclDepth = TypeAlias.Template->getTemplateDepth();
1766 if (TypeAliasDeclDepth >= TemplateArgs.getNumSubstitutedLevels())
1767 return CXXRecordDecl::LambdaDependencyKind::LDK_AlwaysDependent;
1768 for (const TemplateArgument &TA : TypeAlias.AssociatedTemplateArguments)
1769 if (TA.isDependent())
1770 return CXXRecordDecl::LambdaDependencyKind::LDK_AlwaysDependent;
1771 }
1772 if (auto *CD = dyn_cast_if_present<ImplicitConceptSpecializationDecl>(
1773 Val: LSI->Lambda->getLambdaContextDecl())) {
1774 if (llvm::any_of(Range: CD->getTemplateArguments(),
1775 P: [](const auto &TA) { return TA.isDependent(); }))
1776 return CXXRecordDecl::LambdaDependencyKind::LDK_AlwaysDependent;
1777 }
1778 return inherited::ComputeLambdaDependency(LSI);
1779 }
1780
1781 ExprResult TransformLambdaConstraint(Expr *AC) {
1782 if (AC && EvaluateLambdaConstraint)
1783 return TransformExpr(E: const_cast<Expr *>(AC));
1784
1785 return AC;
1786 }
1787
1788 ExprResult TransformLambdaExpr(LambdaExpr *E) {
1789 // Do not rebuild lambdas to avoid creating a new type.
1790 // Lambdas have already been processed inside their eval contexts.
1791 if (SemaRef.RebuildingImmediateInvocation)
1792 return E;
1793 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true,
1794 /*InstantiatingLambdaOrBlock=*/true);
1795 llvm::SaveAndRestore RAII(EvaluateConstraints, EvaluateLambdaConstraint);
1796
1797 return inherited::TransformLambdaExpr(E);
1798 }
1799
1800 ExprResult TransformBlockExpr(BlockExpr *E) {
1801 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true,
1802 /*InstantiatingLambdaOrBlock=*/true);
1803 return inherited::TransformBlockExpr(E);
1804 }
1805
1806 ExprResult RebuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc,
1807 LambdaScopeInfo *LSI) {
1808 CXXMethodDecl *MD = LSI->CallOperator;
1809 for (ParmVarDecl *PVD : MD->parameters()) {
1810 assert(PVD && "null in a parameter list");
1811 if (!PVD->hasDefaultArg())
1812 continue;
1813 Expr *UninstExpr = PVD->getUninstantiatedDefaultArg();
1814 // FIXME: Obtain the source location for the '=' token.
1815 SourceLocation EqualLoc = UninstExpr->getBeginLoc();
1816 if (SemaRef.SubstDefaultArgument(Loc: EqualLoc, Param: PVD, TemplateArgs)) {
1817 // If substitution fails, the default argument is set to a
1818 // RecoveryExpr that wraps the uninstantiated default argument so
1819 // that downstream diagnostics are omitted.
1820 ExprResult ErrorResult = SemaRef.CreateRecoveryExpr(
1821 Begin: UninstExpr->getBeginLoc(), End: UninstExpr->getEndLoc(), SubExprs: {UninstExpr},
1822 T: UninstExpr->getType());
1823 if (ErrorResult.isUsable())
1824 PVD->setDefaultArg(ErrorResult.get());
1825 }
1826 }
1827 return inherited::RebuildLambdaExpr(StartLoc, EndLoc, LSI);
1828 }
1829
1830 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
1831 // Currently, we instantiate the body when instantiating the lambda
1832 // expression. However, `EvaluateConstraints` is disabled during the
1833 // instantiation of the lambda expression, causing the instantiation
1834 // failure of the return type requirement in the body. If p0588r1 is fully
1835 // implemented, the body will be lazily instantiated, and this problem
1836 // will not occur. Here, `EvaluateConstraints` is temporarily set to
1837 // `true` to temporarily fix this issue.
1838 // FIXME: This temporary fix can be removed after fully implementing
1839 // p0588r1.
1840 llvm::SaveAndRestore _(EvaluateConstraints, true);
1841 return inherited::TransformLambdaBody(E, S: Body);
1842 }
1843
1844 ExprResult TransformRequiresExpr(RequiresExpr *E) {
1845 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
1846 ExprResult TransReq = inherited::TransformRequiresExpr(E);
1847 if (TransReq.isInvalid())
1848 return TransReq;
1849 assert(TransReq.get() != E &&
1850 "Do not change value of isSatisfied for the existing expression. "
1851 "Create a new expression instead.");
1852 if (E->getBody()->isDependentContext()) {
1853 Sema::SFINAETrap Trap(SemaRef);
1854 // We recreate the RequiresExpr body, but not by instantiating it.
1855 // Produce pending diagnostics for dependent access check.
1856 SemaRef.PerformDependentDiagnostics(Pattern: E->getBody(), TemplateArgs);
1857 // FIXME: Store SFINAE diagnostics in RequiresExpr for diagnosis.
1858 if (Trap.hasErrorOccurred())
1859 TransReq.getAs<RequiresExpr>()->setSatisfied(false);
1860 }
1861 return TransReq;
1862 }
1863
1864 bool TransformRequiresExprRequirements(
1865 ArrayRef<concepts::Requirement *> Reqs,
1866 SmallVectorImpl<concepts::Requirement *> &Transformed) {
1867 bool SatisfactionDetermined = false;
1868 for (concepts::Requirement *Req : Reqs) {
1869 concepts::Requirement *TransReq = nullptr;
1870 if (!SatisfactionDetermined) {
1871 if (auto *TypeReq = dyn_cast<concepts::TypeRequirement>(Val: Req))
1872 TransReq = TransformTypeRequirement(Req: TypeReq);
1873 else if (auto *ExprReq = dyn_cast<concepts::ExprRequirement>(Val: Req))
1874 TransReq = TransformExprRequirement(Req: ExprReq);
1875 else
1876 TransReq = TransformNestedRequirement(
1877 Req: cast<concepts::NestedRequirement>(Val: Req));
1878 if (!TransReq)
1879 return true;
1880 if (!TransReq->isDependent() && !TransReq->isSatisfied())
1881 // [expr.prim.req]p6
1882 // [...] The substitution and semantic constraint checking
1883 // proceeds in lexical order and stops when a condition that
1884 // determines the result of the requires-expression is
1885 // encountered. [..]
1886 SatisfactionDetermined = true;
1887 } else
1888 TransReq = Req;
1889 Transformed.push_back(Elt: TransReq);
1890 }
1891 return false;
1892 }
1893
1894 TemplateParameterList *TransformTemplateParameterList(
1895 TemplateParameterList *OrigTPL) {
1896 if (!OrigTPL || !OrigTPL->size()) return OrigTPL;
1897
1898 DeclContext *Owner = OrigTPL->getParam(Idx: 0)->getDeclContext();
1899 TemplateDeclInstantiator DeclInstantiator(getSema(),
1900 /* DeclContext *Owner */ Owner,
1901 TemplateArgs);
1902 DeclInstantiator.setEvaluateConstraints(EvaluateConstraints);
1903 return DeclInstantiator.SubstTemplateParams(List: OrigTPL);
1904 }
1905
1906 concepts::TypeRequirement *
1907 TransformTypeRequirement(concepts::TypeRequirement *Req);
1908 concepts::ExprRequirement *
1909 TransformExprRequirement(concepts::ExprRequirement *Req);
1910 concepts::NestedRequirement *
1911 TransformNestedRequirement(concepts::NestedRequirement *Req);
1912 ExprResult TransformRequiresTypeParams(
1913 SourceLocation KWLoc, SourceLocation RBraceLoc, const RequiresExpr *RE,
1914 RequiresExprBodyDecl *Body, ArrayRef<ParmVarDecl *> Params,
1915 SmallVectorImpl<QualType> &PTypes,
1916 SmallVectorImpl<ParmVarDecl *> &TransParams,
1917 Sema::ExtParameterInfoBuilder &PInfos);
1918
1919 ExprResult TransformCXXDynamicCastExpr(CXXDynamicCastExpr *E) {
1920 ExprResult Ret = inherited::TransformCXXDynamicCastExpr(E);
1921 if (Ret.isInvalid())
1922 return Ret;
1923 QualType T = Ret.get()->getType();
1924 if (const auto *PT = T->getAsCanonical<PointerType>())
1925 T = PT->getPointeeType();
1926 auto *DestDecl = T->getAsCXXRecordDecl();
1927 if (DestDecl && DestDecl->isEffectivelyFinal())
1928 getSema().MarkVTableUsed(Loc: Ret.get()->getExprLoc(), Class: DestDecl);
1929 return Ret;
1930 }
1931 };
1932}
1933
1934bool TemplateInstantiator::AlreadyTransformed(QualType T) {
1935 if (T.isNull())
1936 return true;
1937
1938 if (T->isInstantiationDependentType() || T->isVariablyModifiedType() ||
1939 T->containsUnexpandedParameterPack())
1940 return false;
1941
1942 getSema().MarkDeclarationsReferencedInType(Loc, T);
1943 return true;
1944}
1945
1946Decl *TemplateInstantiator::TransformDecl(SourceLocation Loc, Decl *D) {
1947 if (!D)
1948 return nullptr;
1949
1950 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(Val: D)) {
1951 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1952 // If the corresponding template argument is NULL or non-existent, it's
1953 // because we are performing instantiation from explicitly-specified
1954 // template arguments in a function template, but there were some
1955 // arguments left unspecified.
1956 if (!TemplateArgs.hasTemplateArgument(Depth: TTP->getDepth(),
1957 Index: TTP->getPosition())) {
1958 IsIncomplete = true;
1959 return BailOutOnIncomplete ? nullptr : D;
1960 }
1961
1962 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
1963
1964 if (TTP->isParameterPack()) {
1965 assert(Arg.getKind() == TemplateArgument::Pack &&
1966 "Missing argument pack");
1967 Arg = SemaRef.getPackSubstitutedTemplateArgument(Arg);
1968 }
1969
1970 TemplateName Template = Arg.getAsTemplate();
1971 assert(!Template.isNull() && Template.getAsTemplateDecl() &&
1972 "Wrong kind of template template argument");
1973 return Template.getAsTemplateDecl();
1974 }
1975
1976 // Fall through to find the instantiated declaration for this template
1977 // template parameter.
1978 }
1979
1980 if (instantiateMissingDeclsToScopeForConcepts(D))
1981 return nullptr;
1982
1983 if (isa<CXXExpansionStmtDecl>(Val: D)) {
1984 assert(SemaRef.CurrentInstantiationScope);
1985 return cast<Decl *>(
1986 Val&: *SemaRef.CurrentInstantiationScope->findInstantiationOf(D));
1987 }
1988
1989 return SemaRef.FindInstantiatedDecl(Loc, D: cast<NamedDecl>(Val: D), TemplateArgs);
1990}
1991
1992bool TemplateInstantiator::instantiateMissingDeclsToScopeForConcepts(Decl *D) {
1993 if (!(D && (SemaRef.inConstraintSubstitution() ||
1994 SemaRef.inParameterMappingSubstitution())))
1995 return false;
1996
1997 auto *Current = SemaRef.CurrentInstantiationScope;
1998 if (!Current || Current->getInstantiationOfIfExists(D))
1999 return false;
2000
2001 // CWG2770: Function parameters should be instantiated when they are
2002 // needed by a satisfaction check of an atomic constraint or
2003 // (recursively) by another function parameter.
2004 auto *OldParm = dyn_cast<ParmVarDecl>(Val: D);
2005 if (!OldParm)
2006 return false;
2007
2008 if (!OldParm->isParameterPack())
2009 return !TransformFunctionTypeParam(OldParm, /*indexAdjustment=*/0,
2010 /*NumExpansions=*/std::nullopt,
2011 /*ExpectParameterPack=*/false);
2012
2013 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2014
2015 // Find the parameter packs that could be expanded.
2016 TypeLoc TL = OldParm->getTypeSourceInfo()->getTypeLoc();
2017 PackExpansionTypeLoc ExpansionTL = TL.castAs<PackExpansionTypeLoc>();
2018 TypeLoc Pattern = ExpansionTL.getPatternLoc();
2019 SemaRef.collectUnexpandedParameterPacks(TL: Pattern, Unexpanded);
2020 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
2021
2022 bool ShouldExpand = false;
2023 bool RetainExpansion = false;
2024 UnsignedOrNone OrigNumExpansions =
2025 ExpansionTL.getTypePtr()->getNumExpansions();
2026 UnsignedOrNone NumExpansions = OrigNumExpansions;
2027 if (TryExpandParameterPacks(EllipsisLoc: ExpansionTL.getEllipsisLoc(),
2028 PatternRange: Pattern.getSourceRange(), Unexpanded,
2029 /*FailOnPackProducingTemplates=*/true,
2030 ShouldExpand, RetainExpansion, NumExpansions))
2031 return true;
2032
2033 assert(ShouldExpand && !RetainExpansion &&
2034 "Shouldn't preserve pack expansion when evaluating constraints");
2035 ExpandingFunctionParameterPack(Pack: OldParm);
2036 for (unsigned I = 0; I != *NumExpansions; ++I) {
2037 Sema::ArgPackSubstIndexRAII SubstIndex(getSema(), I);
2038 if (!TransformFunctionTypeParam(OldParm, /*indexAdjustment=*/0,
2039 /*NumExpansions=*/OrigNumExpansions,
2040 /*ExpectParameterPack=*/false))
2041 return true;
2042 }
2043 return false;
2044}
2045
2046Decl *TemplateInstantiator::TransformDefinition(SourceLocation Loc, Decl *D) {
2047 Decl *Inst = getSema().SubstDecl(D, Owner: getSema().CurContext, TemplateArgs);
2048 if (!Inst)
2049 return nullptr;
2050
2051 getSema().CurrentInstantiationScope->InstantiatedLocal(D, Inst);
2052 return Inst;
2053}
2054
2055bool TemplateInstantiator::TransformExceptionSpec(
2056 SourceLocation Loc, FunctionProtoType::ExceptionSpecInfo &ESI,
2057 SmallVectorImpl<QualType> &Exceptions, bool &Changed) {
2058 if (ESI.Type == EST_Uninstantiated) {
2059 ESI.instantiate();
2060 Changed = true;
2061 }
2062 return inherited::TransformExceptionSpec(Loc, ESI, Exceptions, Changed);
2063}
2064
2065NamedDecl *
2066TemplateInstantiator::TransformFirstQualifierInScope(NamedDecl *D,
2067 SourceLocation Loc) {
2068 // If the first part of the nested-name-specifier was a template type
2069 // parameter, instantiate that type parameter down to a tag type.
2070 if (TemplateTypeParmDecl *TTPD = dyn_cast_or_null<TemplateTypeParmDecl>(Val: D)) {
2071 const TemplateTypeParmType *TTP
2072 = cast<TemplateTypeParmType>(Val: getSema().Context.getTypeDeclType(Decl: TTPD));
2073
2074 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
2075 // FIXME: This needs testing w/ member access expressions.
2076 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getIndex());
2077
2078 if (TTP->isParameterPack()) {
2079 assert(Arg.getKind() == TemplateArgument::Pack &&
2080 "Missing argument pack");
2081
2082 if (!getSema().ArgPackSubstIndex)
2083 return nullptr;
2084
2085 Arg = SemaRef.getPackSubstitutedTemplateArgument(Arg);
2086 }
2087
2088 QualType T = Arg.getAsType();
2089 if (T.isNull())
2090 return cast_or_null<NamedDecl>(Val: TransformDecl(Loc, D));
2091
2092 if (const TagType *Tag = T->getAs<TagType>())
2093 return Tag->getDecl();
2094
2095 // The resulting type is not a tag; complain.
2096 getSema().Diag(Loc, DiagID: diag::err_nested_name_spec_non_tag) << T;
2097 return nullptr;
2098 }
2099 }
2100
2101 return cast_or_null<NamedDecl>(Val: TransformDecl(Loc, D));
2102}
2103
2104VarDecl *
2105TemplateInstantiator::RebuildExceptionDecl(VarDecl *ExceptionDecl,
2106 TypeSourceInfo *Declarator,
2107 SourceLocation StartLoc,
2108 SourceLocation NameLoc,
2109 IdentifierInfo *Name) {
2110 VarDecl *Var = inherited::RebuildExceptionDecl(ExceptionDecl, Declarator,
2111 StartLoc, IdLoc: NameLoc, Id: Name);
2112 if (Var)
2113 getSema().CurrentInstantiationScope->InstantiatedLocal(D: ExceptionDecl, Inst: Var);
2114 return Var;
2115}
2116
2117VarDecl *TemplateInstantiator::RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
2118 TypeSourceInfo *TSInfo,
2119 QualType T) {
2120 VarDecl *Var = inherited::RebuildObjCExceptionDecl(ExceptionDecl, TInfo: TSInfo, T);
2121 if (Var)
2122 getSema().CurrentInstantiationScope->InstantiatedLocal(D: ExceptionDecl, Inst: Var);
2123 return Var;
2124}
2125
2126TemplateName TemplateInstantiator::TransformTemplateName(
2127 NestedNameSpecifierLoc &QualifierLoc, SourceLocation TemplateKWLoc,
2128 TemplateName Name, SourceLocation NameLoc, QualType ObjectType,
2129 NamedDecl *FirstQualifierInScope, bool AllowInjectedClassName) {
2130 if (Name.getKind() == TemplateName::Template) {
2131 assert(!QualifierLoc && "Unexpected qualifier");
2132 if (auto *TTP =
2133 dyn_cast<TemplateTemplateParmDecl>(Val: Name.getAsTemplateDecl());
2134 TTP && TTP->getDepth() < TemplateArgs.getNumLevels()) {
2135 // If the corresponding template argument is NULL or non-existent, it's
2136 // because we are performing instantiation from explicitly-specified
2137 // template arguments in a function template, but there were some
2138 // arguments left unspecified.
2139 if (!TemplateArgs.hasTemplateArgument(Depth: TTP->getDepth(),
2140 Index: TTP->getPosition())) {
2141 IsIncomplete = true;
2142 return BailOutOnIncomplete ? TemplateName() : Name;
2143 }
2144
2145 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
2146
2147 if (TemplateArgs.isRewrite()) {
2148 // We're rewriting the template parameter as a reference to another
2149 // template parameter.
2150 Arg = getTemplateArgumentPackPatternForRewrite(TA: Arg);
2151 assert(Arg.getKind() == TemplateArgument::Template &&
2152 "unexpected nontype template argument kind in template rewrite");
2153 return Arg.getAsTemplate();
2154 }
2155
2156 auto [AssociatedDecl, Final] =
2157 TemplateArgs.getAssociatedDecl(Depth: TTP->getDepth());
2158 UnsignedOrNone PackIndex = std::nullopt;
2159 if (TTP->isParameterPack()) {
2160 assert(Arg.getKind() == TemplateArgument::Pack &&
2161 "Missing argument pack");
2162
2163 if (!getSema().ArgPackSubstIndex) {
2164 // We have the template argument pack to substitute, but we're not
2165 // actually expanding the enclosing pack expansion yet. So, just
2166 // keep the entire argument pack.
2167 return getSema().Context.getSubstTemplateTemplateParmPack(
2168 ArgPack: Arg, AssociatedDecl, Index: TTP->getIndex(), Final);
2169 }
2170
2171 PackIndex = SemaRef.getPackIndex(Pack: Arg);
2172 Arg = SemaRef.getPackSubstitutedTemplateArgument(Arg);
2173 }
2174
2175 TemplateName Template = Arg.getAsTemplate();
2176 assert(!Template.isNull() && "Null template template argument");
2177 return getSema().Context.getSubstTemplateTemplateParm(
2178 replacement: Template, AssociatedDecl, Index: TTP->getIndex(), PackIndex, Final);
2179 }
2180 }
2181
2182 if (SubstTemplateTemplateParmPackStorage *SubstPack
2183 = Name.getAsSubstTemplateTemplateParmPack()) {
2184 if (!getSema().ArgPackSubstIndex)
2185 return Name;
2186
2187 TemplateArgument Pack = SubstPack->getArgumentPack();
2188 TemplateName Template =
2189 SemaRef.getPackSubstitutedTemplateArgument(Arg: Pack).getAsTemplate();
2190 return getSema().Context.getSubstTemplateTemplateParm(
2191 replacement: Template, AssociatedDecl: SubstPack->getAssociatedDecl(), Index: SubstPack->getIndex(),
2192 PackIndex: SemaRef.getPackIndex(Pack), Final: SubstPack->getFinal());
2193 }
2194
2195 return inherited::TransformTemplateName(
2196 QualifierLoc, TemplateKWLoc, Name, NameLoc, ObjectType,
2197 FirstQualifierInScope, AllowInjectedClassName);
2198}
2199
2200ExprResult
2201TemplateInstantiator::TransformPredefinedExpr(PredefinedExpr *E) {
2202 if (!E->isTypeDependent())
2203 return E;
2204
2205 return getSema().BuildPredefinedExpr(Loc: E->getLocation(), IK: E->getIdentKind());
2206}
2207
2208ExprResult
2209TemplateInstantiator::TransformTemplateParmRefExpr(DeclRefExpr *E,
2210 NonTypeTemplateParmDecl *NTTP) {
2211 if (TemplateArgs.retainInnerDepths() &&
2212 NTTP->getDepth() >= TemplateArgs.getNumLevels())
2213 return E;
2214 // If the corresponding template argument is NULL or non-existent, it's
2215 // because we are performing instantiation from explicitly-specified
2216 // template arguments in a function template, but there were some
2217 // arguments left unspecified.
2218 if (!TemplateArgs.hasTemplateArgument(Depth: NTTP->getDepth(),
2219 Index: NTTP->getPosition())) {
2220 IsIncomplete = true;
2221 return BailOutOnIncomplete ? ExprError() : E;
2222 }
2223
2224 TemplateArgument Arg = TemplateArgs(NTTP->getDepth(), NTTP->getPosition());
2225
2226 if (TemplateArgs.isRewrite()) {
2227 // We're rewriting the template parameter as a reference to another
2228 // template parameter.
2229 Arg = getTemplateArgumentPackPatternForRewrite(TA: Arg);
2230 assert(Arg.getKind() == TemplateArgument::Expression &&
2231 "unexpected nontype template argument kind in template rewrite");
2232 // FIXME: This can lead to the same subexpression appearing multiple times
2233 // in a complete expression.
2234 return Arg.getAsExpr();
2235 }
2236
2237 QualType ParamType = NTTP->isExpandedParameterPack()
2238 ? NTTP->getExpansionType(I: *SemaRef.ArgPackSubstIndex)
2239 : NTTP->isParameterPack() && SemaRef.ArgPackSubstIndex
2240 ? NTTP->getType().getNonPackExpansionType()
2241 : NTTP->getType();
2242 ParamType = SemaRef.SubstType(T: ParamType, TemplateArgs, Loc: E->getLocation(),
2243 Entity: NTTP->getDeclName());
2244 assert(!ParamType.isNull() && "Shouldn't substitute to an invalid type");
2245
2246 auto [AssociatedDecl, Final] =
2247 TemplateArgs.getAssociatedDecl(Depth: NTTP->getDepth());
2248 UnsignedOrNone PackIndex = std::nullopt;
2249 if (NTTP->isParameterPack() ||
2250 // In concept parameter mapping for fold expressions, packs that aren't
2251 // expanded in place are treated as having non-pack dependency, so that
2252 // a PackExpansionType won't prevent expanding the packs outside the
2253 // TreeTransform. However, we still need to unpack the arguments during
2254 // any template argument substitution, so we also check its FoundDecl.
2255 (E->getFoundDecl() && E->getFoundDecl() != E->getDecl() &&
2256 E->getFoundDecl()->isParameterPack())) {
2257 assert(Arg.getKind() == TemplateArgument::Pack && "Missing argument pack");
2258
2259 if (!getSema().ArgPackSubstIndex) {
2260 // We have an argument pack, but we can't select a particular argument
2261 // out of it yet. Therefore, we'll build an expression to hold on to that
2262 // argument pack.
2263 QualType ExprType = ParamType.getNonLValueExprType(Context: SemaRef.Context);
2264 if (ParamType->isRecordType())
2265 ExprType.addConst();
2266 return new (SemaRef.Context) SubstNonTypeTemplateParmPackExpr(
2267 ExprType, ParamType->isReferenceType() ? VK_LValue : VK_PRValue,
2268 E->getLocation(), Arg, AssociatedDecl, NTTP->getPosition(), Final);
2269 }
2270 PackIndex = SemaRef.getPackIndex(Pack: Arg);
2271 Arg = SemaRef.getPackSubstitutedTemplateArgument(Arg);
2272 }
2273 return SemaRef.BuildSubstNonTypeTemplateParmExpr(
2274 AssociatedDecl, Index: NTTP->getPosition(), ParamType, loc: E->getLocation(), Replacement: Arg,
2275 PackIndex, Final);
2276}
2277
2278const AnnotateAttr *
2279TemplateInstantiator::TransformAnnotateAttr(const AnnotateAttr *AA) {
2280 SmallVector<Expr *> Args;
2281 for (Expr *Arg : AA->args()) {
2282 ExprResult Res = getDerived().TransformExpr(E: Arg);
2283 if (Res.isUsable())
2284 Args.push_back(Elt: Res.get());
2285 }
2286 return AnnotateAttr::CreateImplicit(Ctx&: getSema().Context, Annotation: AA->getAnnotation(),
2287 Args: Args.data(), ArgsSize: Args.size(), Range: AA->getRange());
2288}
2289
2290const CXXAssumeAttr *
2291TemplateInstantiator::TransformCXXAssumeAttr(const CXXAssumeAttr *AA) {
2292 ExprResult Res = getDerived().TransformExpr(E: AA->getAssumption());
2293 if (!Res.isUsable())
2294 return AA;
2295
2296 if (!(Res.get()->getDependence() & ExprDependence::TypeValueInstantiation)) {
2297 Res = getSema().BuildCXXAssumeExpr(Assumption: Res.get(), AttrName: AA->getAttrName(),
2298 Range: AA->getRange());
2299 if (!Res.isUsable())
2300 return AA;
2301 }
2302
2303 return CXXAssumeAttr::CreateImplicit(Ctx&: getSema().Context, Assumption: Res.get(),
2304 Range: AA->getRange());
2305}
2306
2307const LoopHintAttr *
2308TemplateInstantiator::TransformLoopHintAttr(const LoopHintAttr *LH) {
2309 ExprResult TransformedExprResult = getDerived().TransformExpr(E: LH->getValue());
2310 if (!TransformedExprResult.isUsable() ||
2311 TransformedExprResult.get() == LH->getValue())
2312 return LH;
2313 Expr *TransformedExpr = TransformedExprResult.get();
2314
2315 // Generate error if there is a problem with the value.
2316 if (getSema().CheckLoopHintExpr(E: TransformedExpr, Loc: LH->getLocation(),
2317 /*AllowZero=*/LH->getSemanticSpelling() ==
2318 LoopHintAttr::Pragma_unroll))
2319 return LH;
2320
2321 LoopHintAttr::OptionType Option = LH->getOption();
2322 LoopHintAttr::LoopHintState State = LH->getState();
2323
2324 // Since C++ does not have partial instantiation, we would expect a
2325 // transformed loop hint expression to not be value dependent. However, at
2326 // the time of writing, the use of a generic lambda inside a template
2327 // triggers a double instantiation, so we must protect against this event.
2328 // This provision may become unneeded in the future.
2329 if (Option == LoopHintAttr::UnrollCount &&
2330 !TransformedExpr->isValueDependent()) {
2331 llvm::APSInt ValueAPS =
2332 TransformedExpr->EvaluateKnownConstInt(Ctx: getSema().getASTContext());
2333 // The values of 0 and 1 block any unrolling of the loop (also see
2334 // handleLoopHintAttr in SemaStmtAttr).
2335 if (ValueAPS.isZero() || ValueAPS.isOne()) {
2336 Option = LoopHintAttr::Unroll;
2337 State = LoopHintAttr::Disable;
2338 }
2339 }
2340
2341 // Create new LoopHintValueAttr with integral expression in place of the
2342 // non-type template parameter.
2343 return LoopHintAttr::CreateImplicit(Ctx&: getSema().Context, Option, State,
2344 Value: TransformedExpr, CommonInfo: *LH);
2345}
2346const NoInlineAttr *TemplateInstantiator::TransformStmtNoInlineAttr(
2347 const Stmt *OrigS, const Stmt *InstS, const NoInlineAttr *A) {
2348 if (!A || getSema().CheckNoInlineAttr(OrigSt: OrigS, CurSt: InstS, A: *A))
2349 return nullptr;
2350
2351 return A;
2352}
2353const AlwaysInlineAttr *TemplateInstantiator::TransformStmtAlwaysInlineAttr(
2354 const Stmt *OrigS, const Stmt *InstS, const AlwaysInlineAttr *A) {
2355 if (!A || getSema().CheckAlwaysInlineAttr(OrigSt: OrigS, CurSt: InstS, A: *A))
2356 return nullptr;
2357
2358 return A;
2359}
2360
2361const CodeAlignAttr *
2362TemplateInstantiator::TransformCodeAlignAttr(const CodeAlignAttr *CA) {
2363 Expr *TransformedExpr = getDerived().TransformExpr(E: CA->getAlignment()).get();
2364 return getSema().BuildCodeAlignAttr(CI: *CA, E: TransformedExpr);
2365}
2366const OpenACCRoutineDeclAttr *
2367TemplateInstantiator::TransformOpenACCRoutineDeclAttr(
2368 const OpenACCRoutineDeclAttr *A) {
2369 llvm_unreachable("RoutineDecl should only be a declaration attribute, as it "
2370 "applies to a Function Decl (and a few places for VarDecl)");
2371}
2372
2373ExprResult TemplateInstantiator::RebuildVarDeclRefExpr(ValueDecl *PD,
2374 SourceLocation Loc) {
2375 DeclarationNameInfo NameInfo(PD->getDeclName(), Loc);
2376 return getSema().BuildDeclarationNameExpr(SS: CXXScopeSpec(), NameInfo, D: PD);
2377}
2378
2379ExprResult
2380TemplateInstantiator::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {
2381 if (getSema().ArgPackSubstIndex) {
2382 // We can expand this parameter pack now.
2383 ValueDecl *D = E->getExpansion(I: *getSema().ArgPackSubstIndex);
2384 ValueDecl *VD = cast_or_null<ValueDecl>(Val: TransformDecl(Loc: E->getExprLoc(), D));
2385 if (!VD)
2386 return ExprError();
2387 return RebuildVarDeclRefExpr(PD: VD, Loc: E->getExprLoc());
2388 }
2389
2390 QualType T = TransformType(T: E->getType());
2391 if (T.isNull())
2392 return ExprError();
2393
2394 // Transform each of the parameter expansions into the corresponding
2395 // parameters in the instantiation of the function decl.
2396 SmallVector<ValueDecl *, 8> Vars;
2397 Vars.reserve(N: E->getNumExpansions());
2398 for (FunctionParmPackExpr::iterator I = E->begin(), End = E->end();
2399 I != End; ++I) {
2400 ValueDecl *D = cast_or_null<ValueDecl>(Val: TransformDecl(Loc: E->getExprLoc(), D: *I));
2401 if (!D)
2402 return ExprError();
2403 Vars.push_back(Elt: D);
2404 }
2405
2406 auto *PackExpr =
2407 FunctionParmPackExpr::Create(Context: getSema().Context, T, ParamPack: E->getParameterPack(),
2408 NameLoc: E->getParameterPackLocation(), Params: Vars);
2409 getSema().MarkFunctionParmPackReferenced(E: PackExpr);
2410 return PackExpr;
2411}
2412
2413ExprResult
2414TemplateInstantiator::TransformFunctionParmPackRefExpr(DeclRefExpr *E,
2415 ValueDecl *PD) {
2416 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
2417 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found =
2418 getSema().CurrentInstantiationScope->getInstantiationOfIfExists(D: PD);
2419
2420 // This can happen when instantiating an expansion statement that contains
2421 // a pack (e.g. `template for (auto x : {{ts...}})`).
2422 if (!Found)
2423 return E;
2424
2425 Decl *TransformedDecl;
2426 if (DeclArgumentPack *Pack = dyn_cast<DeclArgumentPack *>(Val&: *Found)) {
2427 // If this is a reference to a function parameter pack which we can
2428 // substitute but can't yet expand, build a FunctionParmPackExpr for it.
2429 if (!getSema().ArgPackSubstIndex) {
2430 QualType T = TransformType(T: E->getType());
2431 if (T.isNull())
2432 return ExprError();
2433 auto *PackExpr = FunctionParmPackExpr::Create(Context: getSema().Context, T, ParamPack: PD,
2434 NameLoc: E->getExprLoc(), Params: *Pack);
2435 getSema().MarkFunctionParmPackReferenced(E: PackExpr);
2436 return PackExpr;
2437 }
2438
2439 TransformedDecl = (*Pack)[*getSema().ArgPackSubstIndex];
2440 } else {
2441 TransformedDecl = cast<Decl *>(Val&: *Found);
2442 }
2443
2444 // We have either an unexpanded pack or a specific expansion.
2445 return RebuildVarDeclRefExpr(PD: cast<ValueDecl>(Val: TransformedDecl),
2446 Loc: E->getExprLoc());
2447}
2448
2449ExprResult
2450TemplateInstantiator::TransformDeclRefExpr(DeclRefExpr *E) {
2451 NamedDecl *D = E->getDecl();
2452
2453 // Handle references to non-type template parameters and non-type template
2454 // parameter packs.
2455 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Val: D)) {
2456 if (NTTP->getDepth() < TemplateArgs.getNumLevels())
2457 return TransformTemplateParmRefExpr(E, NTTP);
2458
2459 // We have a non-type template parameter that isn't fully substituted;
2460 // FindInstantiatedDecl will find it in the local instantiation scope.
2461 }
2462
2463 // Handle references to function parameter packs.
2464 if (VarDecl *PD = dyn_cast<VarDecl>(Val: D))
2465 if (PD->isParameterPack()) {
2466 if (instantiateMissingDeclsToScopeForConcepts(D: PD))
2467 return ExprError();
2468
2469 return TransformFunctionParmPackRefExpr(E, PD);
2470 }
2471
2472 return inherited::TransformDeclRefExpr(E);
2473}
2474
2475ExprResult TemplateInstantiator::TransformCXXDefaultArgExpr(
2476 CXXDefaultArgExpr *E) {
2477 assert(!cast<FunctionDecl>(E->getParam()->getDeclContext())->
2478 getDescribedFunctionTemplate() &&
2479 "Default arg expressions are never formed in dependent cases.");
2480 return SemaRef.BuildCXXDefaultArgExpr(
2481 CallLoc: E->getUsedLocation(), FD: cast<FunctionDecl>(Val: E->getParam()->getDeclContext()),
2482 Param: E->getParam());
2483}
2484
2485template<typename Fn>
2486QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB,
2487 FunctionProtoTypeLoc TL,
2488 CXXRecordDecl *ThisContext,
2489 Qualifiers ThisTypeQuals,
2490 Fn TransformExceptionSpec) {
2491 // If this is a lambda or block, the transformation MUST be done in the
2492 // CurrentInstantiationScope since it introduces a mapping of
2493 // the original to the newly created transformed parameters.
2494 //
2495 // In that case, TemplateInstantiator::TransformLambdaExpr will
2496 // have already pushed a scope for this prototype, so don't create
2497 // a second one.
2498 LocalInstantiationScope *Current = getSema().CurrentInstantiationScope;
2499 std::optional<LocalInstantiationScope> Scope;
2500 if (!Current || !Current->isLambdaOrBlock())
2501 Scope.emplace(args&: SemaRef, /*CombineWithOuterScope=*/args: true);
2502
2503 return inherited::TransformFunctionProtoType(
2504 TLB, TL, ThisContext, ThisTypeQuals, TransformExceptionSpec);
2505}
2506
2507ParmVarDecl *TemplateInstantiator::TransformFunctionTypeParam(
2508 ParmVarDecl *OldParm, int indexAdjustment, UnsignedOrNone NumExpansions,
2509 bool ExpectParameterPack) {
2510 auto NewParm = SemaRef.SubstParmVarDecl(
2511 D: OldParm, TemplateArgs, indexAdjustment, NumExpansions,
2512 ExpectParameterPack, EvaluateConstraints);
2513 if (NewParm && SemaRef.getLangOpts().OpenCL)
2514 SemaRef.deduceOpenCLAddressSpace(decl: NewParm);
2515 return NewParm;
2516}
2517
2518QualType TemplateInstantiator::BuildSubstTemplateTypeParmType(
2519 TypeLocBuilder &TLB, bool SuppressObjCLifetime, bool Final,
2520 Decl *AssociatedDecl, unsigned Index, UnsignedOrNone PackIndex,
2521 TemplateArgument Arg, SourceLocation NameLoc) {
2522 QualType Replacement = Arg.getAsType();
2523
2524 // If the template parameter had ObjC lifetime qualifiers,
2525 // then any such qualifiers on the replacement type are ignored.
2526 if (SuppressObjCLifetime) {
2527 Qualifiers RQs;
2528 RQs = Replacement.getQualifiers();
2529 RQs.removeObjCLifetime();
2530 Replacement =
2531 SemaRef.Context.getQualifiedType(T: Replacement.getUnqualifiedType(), Qs: RQs);
2532 }
2533
2534 // TODO: only do this uniquing once, at the start of instantiation.
2535 QualType Result = getSema().Context.getSubstTemplateTypeParmType(
2536 Replacement, AssociatedDecl, Index, PackIndex, Final);
2537 SubstTemplateTypeParmTypeLoc NewTL =
2538 TLB.push<SubstTemplateTypeParmTypeLoc>(T: Result);
2539 NewTL.setNameLoc(NameLoc);
2540 return Result;
2541}
2542
2543QualType
2544TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB,
2545 TemplateTypeParmTypeLoc TL,
2546 bool SuppressObjCLifetime) {
2547 const TemplateTypeParmType *T = TL.getTypePtr();
2548 if (T->getDepth() < TemplateArgs.getNumLevels()) {
2549 // Replace the template type parameter with its corresponding
2550 // template argument.
2551
2552 // If the corresponding template argument is NULL or doesn't exist, it's
2553 // because we are performing instantiation from explicitly-specified
2554 // template arguments in a function template class, but there were some
2555 // arguments left unspecified.
2556 if (!TemplateArgs.hasTemplateArgument(Depth: T->getDepth(), Index: T->getIndex())) {
2557 IsIncomplete = true;
2558 if (BailOutOnIncomplete)
2559 return QualType();
2560
2561 TemplateTypeParmTypeLoc NewTL
2562 = TLB.push<TemplateTypeParmTypeLoc>(T: TL.getType());
2563 NewTL.setNameLoc(TL.getNameLoc());
2564 return TL.getType();
2565 }
2566
2567 TemplateArgument Arg = TemplateArgs(T->getDepth(), T->getIndex());
2568
2569 if (TemplateArgs.isRewrite()) {
2570 // We're rewriting the template parameter as a reference to another
2571 // template parameter.
2572 Arg = getTemplateArgumentPackPatternForRewrite(TA: Arg);
2573 assert(Arg.getKind() == TemplateArgument::Type &&
2574 "unexpected nontype template argument kind in template rewrite");
2575 QualType NewT = Arg.getAsType();
2576 TLB.pushTrivial(Context&: SemaRef.Context, T: NewT, Loc: TL.getNameLoc());
2577 return NewT;
2578 }
2579
2580 auto [AssociatedDecl, Final] =
2581 TemplateArgs.getAssociatedDecl(Depth: T->getDepth());
2582 UnsignedOrNone PackIndex = std::nullopt;
2583 if (T->isParameterPack() ||
2584 // In concept parameter mapping for fold expressions, packs that aren't
2585 // expanded in place are treated as having non-pack dependency, so that
2586 // a PackExpansionType won't prevent expanding the packs outside the
2587 // TreeTransform. However, we still need to unpack the arguments during
2588 // any template argument substitution, so we check the associated
2589 // declaration instead.
2590 (T->getDecl() && T->getDecl()->isTemplateParameterPack())) {
2591 assert(Arg.getKind() == TemplateArgument::Pack &&
2592 "Missing argument pack");
2593
2594 if (!getSema().ArgPackSubstIndex) {
2595 // We have the template argument pack, but we're not expanding the
2596 // enclosing pack expansion yet. Just save the template argument
2597 // pack for later substitution.
2598 QualType Result = getSema().Context.getSubstTemplateTypeParmPackType(
2599 AssociatedDecl, Index: T->getIndex(), Final, ArgPack: Arg);
2600 SubstTemplateTypeParmPackTypeLoc NewTL
2601 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(T: Result);
2602 NewTL.setNameLoc(TL.getNameLoc());
2603 return Result;
2604 }
2605
2606 // PackIndex starts from last element.
2607 PackIndex = SemaRef.getPackIndex(Pack: Arg);
2608 Arg = SemaRef.getPackSubstitutedTemplateArgument(Arg);
2609 }
2610
2611 assert(Arg.getKind() == TemplateArgument::Type &&
2612 "Template argument kind mismatch");
2613
2614 return BuildSubstTemplateTypeParmType(TLB, SuppressObjCLifetime, Final,
2615 AssociatedDecl, Index: T->getIndex(),
2616 PackIndex, Arg, NameLoc: TL.getNameLoc());
2617 }
2618
2619 // The template type parameter comes from an inner template (e.g.,
2620 // the template parameter list of a member template inside the
2621 // template we are instantiating). Create a new template type
2622 // parameter with the template "level" reduced by one.
2623 TemplateTypeParmDecl *NewTTPDecl = nullptr;
2624 if (TemplateTypeParmDecl *OldTTPDecl = T->getDecl())
2625 NewTTPDecl = cast_or_null<TemplateTypeParmDecl>(
2626 Val: TransformDecl(Loc: TL.getNameLoc(), D: OldTTPDecl));
2627 QualType Result = getSema().Context.getTemplateTypeParmType(
2628 Depth: T->getDepth() - (TemplateArgs.retainInnerDepths()
2629 ? 0
2630 : TemplateArgs.getNumSubstitutedLevels()),
2631 Index: T->getIndex(), ParameterPack: T->isParameterPack(), ParmDecl: NewTTPDecl);
2632 TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(T: Result);
2633 NewTL.setNameLoc(TL.getNameLoc());
2634 return Result;
2635}
2636
2637QualType TemplateInstantiator::TransformSubstTemplateTypeParmPackType(
2638 TypeLocBuilder &TLB, SubstTemplateTypeParmPackTypeLoc TL,
2639 bool SuppressObjCLifetime) {
2640 const SubstTemplateTypeParmPackType *T = TL.getTypePtr();
2641
2642 Decl *NewReplaced = TransformDecl(Loc: TL.getNameLoc(), D: T->getAssociatedDecl());
2643
2644 if (!getSema().ArgPackSubstIndex) {
2645 // We aren't expanding the parameter pack, so just return ourselves.
2646 QualType Result = TL.getType();
2647 if (NewReplaced != T->getAssociatedDecl())
2648 Result = getSema().Context.getSubstTemplateTypeParmPackType(
2649 AssociatedDecl: NewReplaced, Index: T->getIndex(), Final: T->getFinal(), ArgPack: T->getArgumentPack());
2650 SubstTemplateTypeParmPackTypeLoc NewTL =
2651 TLB.push<SubstTemplateTypeParmPackTypeLoc>(T: Result);
2652 NewTL.setNameLoc(TL.getNameLoc());
2653 return Result;
2654 }
2655
2656 TemplateArgument Pack = T->getArgumentPack();
2657 TemplateArgument Arg = SemaRef.getPackSubstitutedTemplateArgument(Arg: Pack);
2658 return BuildSubstTemplateTypeParmType(
2659 TLB, SuppressObjCLifetime, Final: T->getFinal(), AssociatedDecl: NewReplaced, Index: T->getIndex(),
2660 PackIndex: SemaRef.getPackIndex(Pack), Arg, NameLoc: TL.getNameLoc());
2661}
2662
2663QualType TemplateInstantiator::TransformSubstBuiltinTemplatePackType(
2664 TypeLocBuilder &TLB, SubstBuiltinTemplatePackTypeLoc TL) {
2665 if (!getSema().ArgPackSubstIndex)
2666 return TreeTransform::TransformSubstBuiltinTemplatePackType(TLB, TL);
2667 TemplateArgument Result = SemaRef.getPackSubstitutedTemplateArgument(
2668 Arg: TL.getTypePtr()->getArgumentPack());
2669 TLB.pushTrivial(Context&: SemaRef.getASTContext(), T: Result.getAsType(),
2670 Loc: TL.getBeginLoc());
2671 return Result.getAsType();
2672}
2673
2674static concepts::Requirement::SubstitutionDiagnostic *
2675createSubstDiag(Sema &S, TemplateDeductionInfo &Info,
2676 Sema::EntityPrinter Printer) {
2677 SmallString<128> Message;
2678 SourceLocation ErrorLoc;
2679 if (Info.hasSFINAEDiagnostic()) {
2680 PartialDiagnosticAt PDA(SourceLocation(),
2681 PartialDiagnostic::NullDiagnostic{});
2682 Info.takeSFINAEDiagnostic(PD&: PDA);
2683 PDA.second.EmitToString(Diags&: S.getDiagnostics(), Buf&: Message);
2684 ErrorLoc = PDA.first;
2685 } else {
2686 ErrorLoc = Info.getLocation();
2687 }
2688 SmallString<128> Entity;
2689 llvm::raw_svector_ostream OS(Entity);
2690 Printer(OS);
2691 const ASTContext &C = S.Context;
2692 return new (C) concepts::Requirement::SubstitutionDiagnostic{
2693 .SubstitutedEntity: C.backupStr(S: Entity), .DiagLoc: ErrorLoc, .DiagMessage: C.backupStr(S: Message)};
2694}
2695
2696concepts::Requirement::SubstitutionDiagnostic *
2697Sema::createSubstDiagAt(SourceLocation Location, EntityPrinter Printer) {
2698 SmallString<128> Entity;
2699 llvm::raw_svector_ostream OS(Entity);
2700 Printer(OS);
2701 const ASTContext &C = Context;
2702 return new (C) concepts::Requirement::SubstitutionDiagnostic{
2703 /*SubstitutedEntity=*/C.backupStr(S: Entity),
2704 /*DiagLoc=*/Location, /*DiagMessage=*/StringRef()};
2705}
2706
2707ExprResult TemplateInstantiator::TransformRequiresTypeParams(
2708 SourceLocation KWLoc, SourceLocation RBraceLoc, const RequiresExpr *RE,
2709 RequiresExprBodyDecl *Body, ArrayRef<ParmVarDecl *> Params,
2710 SmallVectorImpl<QualType> &PTypes,
2711 SmallVectorImpl<ParmVarDecl *> &TransParams,
2712 Sema::ExtParameterInfoBuilder &PInfos) {
2713
2714 TemplateDeductionInfo Info(KWLoc);
2715 Sema::InstantiatingTemplate TypeInst(SemaRef, KWLoc, RE,
2716 SourceRange{KWLoc, RBraceLoc});
2717 Sema::SFINAETrap Trap(SemaRef, Info);
2718
2719 unsigned ErrorIdx;
2720 if (getDerived().TransformFunctionTypeParams(
2721 Loc: KWLoc, Params, /*ParamTypes=*/nullptr, /*ParamInfos=*/nullptr, OutParamTypes&: PTypes,
2722 PVars: &TransParams, PInfos, LastParamTransformed: &ErrorIdx) ||
2723 Trap.hasErrorOccurred()) {
2724 SmallVector<concepts::Requirement *, 4> TransReqs;
2725 ParmVarDecl *FailedDecl = Params[ErrorIdx];
2726 // Add a 'failed' Requirement to contain the error that caused the failure
2727 // here.
2728 TransReqs.push_back(Elt: RebuildTypeRequirement(SubstDiag: createSubstDiag(
2729 S&: SemaRef, Info, Printer: [&](llvm::raw_ostream &OS) { OS << *FailedDecl; })));
2730 return getDerived().RebuildRequiresExpr(RequiresKWLoc: KWLoc, Body, LParenLoc: RE->getLParenLoc(),
2731 LocalParameters: TransParams, RParenLoc: RE->getRParenLoc(),
2732 Requirements: TransReqs, ClosingBraceLoc: RBraceLoc);
2733 }
2734
2735 return ExprResult{};
2736}
2737
2738concepts::TypeRequirement *
2739TemplateInstantiator::TransformTypeRequirement(concepts::TypeRequirement *Req) {
2740 if (!Req->isDependent() && !AlwaysRebuild())
2741 return Req;
2742 if (Req->isSubstitutionFailure()) {
2743 if (AlwaysRebuild())
2744 return RebuildTypeRequirement(
2745 SubstDiag: Req->getSubstitutionDiagnostic());
2746 return Req;
2747 }
2748
2749 TemplateDeductionInfo Info(Req->getType()->getTypeLoc().getBeginLoc());
2750 Sema::SFINAETrap Trap(SemaRef, Info);
2751 Sema::InstantiatingTemplate TypeInst(
2752 SemaRef, Req->getType()->getTypeLoc().getBeginLoc(), Req,
2753 Req->getType()->getTypeLoc().getSourceRange());
2754 if (TypeInst.isInvalid())
2755 return nullptr;
2756 TypeSourceInfo *TransType = TransformType(TSI: Req->getType());
2757 if (!TransType || Trap.hasErrorOccurred())
2758 return RebuildTypeRequirement(SubstDiag: createSubstDiag(S&: SemaRef, Info,
2759 Printer: [&] (llvm::raw_ostream& OS) {
2760 Req->getType()->getType().print(OS, Policy: SemaRef.getPrintingPolicy());
2761 }));
2762 return RebuildTypeRequirement(T: TransType);
2763}
2764
2765concepts::ExprRequirement *
2766TemplateInstantiator::TransformExprRequirement(concepts::ExprRequirement *Req) {
2767 if (!Req->isDependent() && !AlwaysRebuild())
2768 return Req;
2769
2770 llvm::PointerUnion<Expr *, concepts::Requirement::SubstitutionDiagnostic *>
2771 TransExpr;
2772 if (Req->isExprSubstitutionFailure())
2773 TransExpr = Req->getExprSubstitutionDiagnostic();
2774 else {
2775 Expr *E = Req->getExpr();
2776 TemplateDeductionInfo Info(E->getBeginLoc());
2777 Sema::SFINAETrap Trap(SemaRef, Info);
2778 Sema::InstantiatingTemplate ExprInst(SemaRef, E->getBeginLoc(), Req,
2779 E->getSourceRange());
2780 if (ExprInst.isInvalid())
2781 return nullptr;
2782 ExprResult TransExprRes = TransformExpr(E);
2783 if (!TransExprRes.isInvalid() && !Trap.hasErrorOccurred() &&
2784 TransExprRes.get()->hasPlaceholderType())
2785 TransExprRes = SemaRef.CheckPlaceholderExpr(E: TransExprRes.get());
2786 if (TransExprRes.isInvalid() || Trap.hasErrorOccurred())
2787 TransExpr = createSubstDiag(S&: SemaRef, Info, Printer: [&](llvm::raw_ostream &OS) {
2788 E->printPretty(OS, Helper: nullptr, Policy: SemaRef.getPrintingPolicy());
2789 });
2790 else
2791 TransExpr = TransExprRes.get();
2792 }
2793
2794 std::optional<concepts::ExprRequirement::ReturnTypeRequirement> TransRetReq;
2795 const auto &RetReq = Req->getReturnTypeRequirement();
2796 if (RetReq.isEmpty())
2797 TransRetReq.emplace();
2798 else if (RetReq.isSubstitutionFailure())
2799 TransRetReq.emplace(args: RetReq.getSubstitutionDiagnostic());
2800 else if (RetReq.isTypeConstraint()) {
2801 TemplateParameterList *OrigTPL =
2802 RetReq.getTypeConstraintTemplateParameterList();
2803 TemplateDeductionInfo Info(OrigTPL->getTemplateLoc());
2804 Sema::SFINAETrap Trap(SemaRef, Info);
2805 Sema::InstantiatingTemplate TPLInst(SemaRef, OrigTPL->getTemplateLoc(), Req,
2806 OrigTPL->getSourceRange());
2807 if (TPLInst.isInvalid())
2808 return nullptr;
2809 TemplateParameterList *TPL = TransformTemplateParameterList(OrigTPL);
2810 if (!TPL || Trap.hasErrorOccurred())
2811 TransRetReq.emplace(args: createSubstDiag(S&: SemaRef, Info,
2812 Printer: [&] (llvm::raw_ostream& OS) {
2813 RetReq.getTypeConstraint()->getImmediatelyDeclaredConstraint()
2814 ->printPretty(OS, Helper: nullptr, Policy: SemaRef.getPrintingPolicy());
2815 }));
2816 else {
2817 TPLInst.Clear();
2818 TransRetReq.emplace(args&: TPL);
2819 }
2820 }
2821 assert(TransRetReq && "All code paths leading here must set TransRetReq");
2822 if (Expr *E = TransExpr.dyn_cast<Expr *>())
2823 return RebuildExprRequirement(E, IsSimple: Req->isSimple(), NoexceptLoc: Req->getNoexceptLoc(),
2824 Ret: std::move(*TransRetReq));
2825 return RebuildExprRequirement(
2826 SubstDiag: cast<concepts::Requirement::SubstitutionDiagnostic *>(Val&: TransExpr),
2827 IsSimple: Req->isSimple(), NoexceptLoc: Req->getNoexceptLoc(), Ret: std::move(*TransRetReq));
2828}
2829
2830concepts::NestedRequirement *
2831TemplateInstantiator::TransformNestedRequirement(
2832 concepts::NestedRequirement *Req) {
2833
2834 ASTContext &C = SemaRef.Context;
2835
2836 ConstraintSatisfaction Satisfaction;
2837
2838 auto NestedReqWithDiag = [&C, this](Expr *E,
2839 ConstraintSatisfaction Satisfaction) {
2840 Satisfaction.IsSatisfied = false;
2841 SmallString<128> Entity;
2842 llvm::raw_svector_ostream OS(Entity);
2843 E->printPretty(OS, Helper: nullptr, Policy: SemaRef.getPrintingPolicy());
2844 return new (C) concepts::NestedRequirement(
2845 SemaRef.Context, C.backupStr(S: Entity), std::move(Satisfaction));
2846 };
2847
2848 if (Req->hasInvalidConstraint()) {
2849 if (AlwaysRebuild())
2850 return RebuildNestedRequirement(InvalidConstraintEntity: Req->getInvalidConstraintEntity(),
2851 Satisfaction: Req->getConstraintSatisfaction());
2852 return Req;
2853 }
2854
2855 Expr *Constraint = Req->getConstraintExpr();
2856
2857 if (!getEvaluateConstraints()) {
2858 ExprResult TransConstraint = TransformExpr(E: Req->getConstraintExpr());
2859 if (TransConstraint.isInvalid() || !TransConstraint.get())
2860 return nullptr;
2861 if (TransConstraint.get()->isInstantiationDependent())
2862 return new (SemaRef.Context)
2863 concepts::NestedRequirement(TransConstraint.get());
2864 ConstraintSatisfaction Satisfaction;
2865 return new (SemaRef.Context) concepts::NestedRequirement(
2866 SemaRef.Context, TransConstraint.get(), Satisfaction);
2867 }
2868
2869 bool Success;
2870 Expr *NewConstraint;
2871 {
2872 EnterExpressionEvaluationContext ContextRAII(
2873 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
2874 Sema::InstantiatingTemplate ConstrInst(
2875 SemaRef, Constraint->getBeginLoc(), Req,
2876 Sema::InstantiatingTemplate::ConstraintsCheck(),
2877 Constraint->getSourceRange());
2878
2879 if (ConstrInst.isInvalid())
2880 return nullptr;
2881
2882 Success = !SemaRef.CheckConstraintSatisfaction(
2883 Entity: Req, AssociatedConstraints: AssociatedConstraint(Constraint), TemplateArgLists: TemplateArgs,
2884 TemplateIDRange: Constraint->getSourceRange(), Satisfaction,
2885 /*TopLevelConceptId=*/nullptr, ConvertedExpr: &NewConstraint);
2886 }
2887
2888 if (!Success || Satisfaction.HasSubstitutionFailure())
2889 return NestedReqWithDiag(Constraint, Satisfaction);
2890
2891 // FIXME: const correctness
2892 // MLTAL might be dependent.
2893 if (!NewConstraint) {
2894 if (!Satisfaction.IsSatisfied)
2895 return NestedReqWithDiag(Constraint, Satisfaction);
2896
2897 NewConstraint = Constraint;
2898 }
2899 return new (C) concepts::NestedRequirement(C, NewConstraint, Satisfaction);
2900}
2901
2902TypeSourceInfo *Sema::SubstType(TypeSourceInfo *T,
2903 const MultiLevelTemplateArgumentList &Args,
2904 SourceLocation Loc, DeclarationName Entity,
2905 bool AllowDeducedTST) {
2906 if (!T->getType()->isInstantiationDependentType() &&
2907 !T->getType()->isVariablyModifiedType())
2908 return T;
2909
2910 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
2911 return AllowDeducedTST ? Instantiator.TransformTypeWithDeducedTST(TSI: T)
2912 : Instantiator.TransformType(TSI: T);
2913}
2914
2915TypeSourceInfo *Sema::SubstType(TypeLoc TL,
2916 const MultiLevelTemplateArgumentList &Args,
2917 SourceLocation Loc, DeclarationName Entity) {
2918 if (TL.getType().isNull())
2919 return nullptr;
2920
2921 if (!TL.getType()->isInstantiationDependentType() &&
2922 !TL.getType()->isVariablyModifiedType()) {
2923 // FIXME: Make a copy of the TypeLoc data here, so that we can
2924 // return a new TypeSourceInfo. Inefficient!
2925 TypeLocBuilder TLB;
2926 TLB.pushFullCopy(L: TL);
2927 return TLB.getTypeSourceInfo(Context, T: TL.getType());
2928 }
2929
2930 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
2931 TypeLocBuilder TLB;
2932 TLB.reserve(Requested: TL.getFullDataSize());
2933 QualType Result = Instantiator.TransformType(TLB, T: TL);
2934 if (Result.isNull())
2935 return nullptr;
2936
2937 return TLB.getTypeSourceInfo(Context, T: Result);
2938}
2939
2940/// Deprecated form of the above.
2941QualType Sema::SubstType(QualType T,
2942 const MultiLevelTemplateArgumentList &TemplateArgs,
2943 SourceLocation Loc, DeclarationName Entity,
2944 bool *IsIncompleteSubstitution) {
2945 // If T is not a dependent type or a variably-modified type, there
2946 // is nothing to do.
2947 if (!T->isInstantiationDependentType() && !T->isVariablyModifiedType())
2948 return T;
2949
2950 TemplateInstantiator Instantiator(
2951 *this, TemplateArgs, Loc, Entity,
2952 /*BailOutOnIncomplete=*/IsIncompleteSubstitution != nullptr);
2953 QualType QT = Instantiator.TransformType(T);
2954 if (IsIncompleteSubstitution && Instantiator.getIsIncomplete())
2955 *IsIncompleteSubstitution = true;
2956 return QT;
2957}
2958
2959static bool NeedsInstantiationAsFunctionType(TypeSourceInfo *T) {
2960 if (T->getType()->isInstantiationDependentType() ||
2961 T->getType()->isVariablyModifiedType())
2962 return true;
2963
2964 TypeLoc TL = T->getTypeLoc().IgnoreParens();
2965 if (!TL.getAs<FunctionProtoTypeLoc>())
2966 return false;
2967
2968 FunctionProtoTypeLoc FP = TL.castAs<FunctionProtoTypeLoc>();
2969 for (ParmVarDecl *P : FP.getParams()) {
2970 // This must be synthesized from a typedef.
2971 if (!P) continue;
2972
2973 // If there are any parameters, a new TypeSourceInfo that refers to the
2974 // instantiated parameters must be built.
2975 return true;
2976 }
2977
2978 return false;
2979}
2980
2981TypeSourceInfo *Sema::SubstFunctionDeclType(
2982 TypeSourceInfo *T, const MultiLevelTemplateArgumentList &Args,
2983 SourceLocation Loc, DeclarationName Entity, CXXRecordDecl *ThisContext,
2984 Qualifiers ThisTypeQuals, bool EvaluateConstraints) {
2985 if (!NeedsInstantiationAsFunctionType(T))
2986 return T;
2987
2988 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
2989 Instantiator.setEvaluateConstraints(EvaluateConstraints);
2990
2991 TypeLocBuilder TLB;
2992
2993 TypeLoc TL = T->getTypeLoc();
2994 TLB.reserve(Requested: TL.getFullDataSize());
2995
2996 QualType Result;
2997
2998 if (FunctionProtoTypeLoc Proto =
2999 TL.IgnoreParens().getAs<FunctionProtoTypeLoc>()) {
3000 // Instantiate the type, other than its exception specification. The
3001 // exception specification is instantiated in InitFunctionInstantiation
3002 // once we've built the FunctionDecl.
3003 // FIXME: Set the exception specification to EST_Uninstantiated here,
3004 // instead of rebuilding the function type again later.
3005 Result = Instantiator.TransformFunctionProtoType(
3006 TLB, TL: Proto, ThisContext, ThisTypeQuals,
3007 TransformExceptionSpec: [](FunctionProtoType::ExceptionSpecInfo &ESI,
3008 bool &Changed) { return false; });
3009 } else {
3010 Result = Instantiator.TransformType(TLB, T: TL);
3011 }
3012 // When there are errors resolving types, clang may use IntTy as a fallback,
3013 // breaking our assumption that function declarations have function types.
3014 if (Result.isNull() || !Result->isFunctionType())
3015 return nullptr;
3016
3017 return TLB.getTypeSourceInfo(Context, T: Result);
3018}
3019
3020bool Sema::SubstExceptionSpec(SourceLocation Loc,
3021 FunctionProtoType::ExceptionSpecInfo &ESI,
3022 SmallVectorImpl<QualType> &ExceptionStorage,
3023 const MultiLevelTemplateArgumentList &Args) {
3024 bool Changed = false;
3025 TemplateInstantiator Instantiator(*this, Args, Loc, DeclarationName());
3026 return Instantiator.TransformExceptionSpec(Loc, ESI, Exceptions&: ExceptionStorage,
3027 Changed);
3028}
3029
3030void Sema::SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto,
3031 const MultiLevelTemplateArgumentList &Args) {
3032 FunctionProtoType::ExceptionSpecInfo ESI =
3033 Proto->getExtProtoInfo().ExceptionSpec;
3034
3035 SmallVector<QualType, 4> ExceptionStorage;
3036 if (SubstExceptionSpec(Loc: New->getTypeSourceInfo()->getTypeLoc().getEndLoc(),
3037 ESI, ExceptionStorage, Args))
3038 // On error, recover by dropping the exception specification.
3039 ESI.Type = EST_None;
3040
3041 UpdateExceptionSpec(FD: New, ESI);
3042}
3043
3044namespace {
3045
3046 struct GetContainedInventedTypeParmVisitor :
3047 public TypeVisitor<GetContainedInventedTypeParmVisitor,
3048 TemplateTypeParmDecl *> {
3049 using TypeVisitor<GetContainedInventedTypeParmVisitor,
3050 TemplateTypeParmDecl *>::Visit;
3051
3052 TemplateTypeParmDecl *Visit(QualType T) {
3053 if (T.isNull())
3054 return nullptr;
3055 return Visit(T: T.getTypePtr());
3056 }
3057 // The deduced type itself.
3058 TemplateTypeParmDecl *VisitTemplateTypeParmType(
3059 const TemplateTypeParmType *T) {
3060 if (!T->getDecl() || !T->getDecl()->isImplicit())
3061 return nullptr;
3062 return T->getDecl();
3063 }
3064
3065 // Only these types can contain 'auto' types, and subsequently be replaced
3066 // by references to invented parameters.
3067
3068 TemplateTypeParmDecl *VisitPointerType(const PointerType *T) {
3069 return Visit(T: T->getPointeeType());
3070 }
3071
3072 TemplateTypeParmDecl *VisitBlockPointerType(const BlockPointerType *T) {
3073 return Visit(T: T->getPointeeType());
3074 }
3075
3076 TemplateTypeParmDecl *VisitReferenceType(const ReferenceType *T) {
3077 return Visit(T: T->getPointeeTypeAsWritten());
3078 }
3079
3080 TemplateTypeParmDecl *VisitMemberPointerType(const MemberPointerType *T) {
3081 return Visit(T: T->getPointeeType());
3082 }
3083
3084 TemplateTypeParmDecl *VisitArrayType(const ArrayType *T) {
3085 return Visit(T: T->getElementType());
3086 }
3087
3088 TemplateTypeParmDecl *VisitDependentSizedExtVectorType(
3089 const DependentSizedExtVectorType *T) {
3090 return Visit(T: T->getElementType());
3091 }
3092
3093 TemplateTypeParmDecl *VisitVectorType(const VectorType *T) {
3094 return Visit(T: T->getElementType());
3095 }
3096
3097 TemplateTypeParmDecl *VisitFunctionProtoType(const FunctionProtoType *T) {
3098 return VisitFunctionType(T);
3099 }
3100
3101 TemplateTypeParmDecl *VisitFunctionType(const FunctionType *T) {
3102 return Visit(T: T->getReturnType());
3103 }
3104
3105 TemplateTypeParmDecl *VisitParenType(const ParenType *T) {
3106 return Visit(T: T->getInnerType());
3107 }
3108
3109 TemplateTypeParmDecl *VisitAttributedType(const AttributedType *T) {
3110 return Visit(T: T->getModifiedType());
3111 }
3112
3113 TemplateTypeParmDecl *VisitMacroQualifiedType(const MacroQualifiedType *T) {
3114 return Visit(T: T->getUnderlyingType());
3115 }
3116
3117 TemplateTypeParmDecl *VisitAdjustedType(const AdjustedType *T) {
3118 return Visit(T: T->getOriginalType());
3119 }
3120
3121 TemplateTypeParmDecl *VisitPackExpansionType(const PackExpansionType *T) {
3122 return Visit(T: T->getPattern());
3123 }
3124 };
3125
3126} // namespace
3127
3128bool Sema::SubstTypeConstraint(
3129 TemplateTypeParmDecl *Inst, const TypeConstraint *TC,
3130 const MultiLevelTemplateArgumentList &TemplateArgs,
3131 bool EvaluateConstraints) {
3132 const ASTTemplateArgumentListInfo *TemplArgInfo =
3133 TC->getTemplateArgsAsWritten();
3134
3135 if (!EvaluateConstraints) {
3136 UnsignedOrNone Index = TC->getArgPackSubstIndex();
3137 bool ContainsUnexpandedPack =
3138 TemplArgInfo &&
3139 llvm::any_of(
3140 Range: TemplArgInfo->arguments(), P: [](const TemplateArgumentLoc &TA) {
3141 return TA.getArgument().containsUnexpandedParameterPack();
3142 });
3143 if (!Index && ContainsUnexpandedPack)
3144 Index = SemaRef.ArgPackSubstIndex;
3145 Inst->setTypeConstraint(CR: TC->getConceptReference(),
3146 ImmediatelyDeclaredConstraint: TC->getImmediatelyDeclaredConstraint(), ArgPackSubstIndex: Index);
3147 return false;
3148 }
3149
3150 TemplateArgumentListInfo InstArgs;
3151
3152 if (TemplArgInfo) {
3153 InstArgs.setLAngleLoc(TemplArgInfo->LAngleLoc);
3154 InstArgs.setRAngleLoc(TemplArgInfo->RAngleLoc);
3155 if (SubstTemplateArguments(Args: TemplArgInfo->arguments(), TemplateArgs,
3156 Outputs&: InstArgs))
3157 return true;
3158 }
3159 return AttachTypeConstraint(
3160 NS: TC->getNestedNameSpecifierLoc(), NameInfo: TC->getConceptNameInfo(),
3161 NamedConcept: TC->getNamedConcept(),
3162 /*FoundDecl=*/TC->getConceptReference()->getFoundDecl(), TemplateArgs: &InstArgs, ConstrainedParameter: Inst,
3163 EllipsisLoc: Inst->isParameterPack()
3164 ? cast<CXXFoldExpr>(Val: TC->getImmediatelyDeclaredConstraint())
3165 ->getEllipsisLoc()
3166 : SourceLocation());
3167}
3168
3169ParmVarDecl *
3170Sema::SubstParmVarDecl(ParmVarDecl *OldParm,
3171 const MultiLevelTemplateArgumentList &TemplateArgs,
3172 int indexAdjustment, UnsignedOrNone NumExpansions,
3173 bool ExpectParameterPack, bool EvaluateConstraint) {
3174 TypeSourceInfo *OldTSI = OldParm->getTypeSourceInfo();
3175 TypeSourceInfo *NewTSI = nullptr;
3176
3177 TypeLoc OldTL = OldTSI->getTypeLoc();
3178 if (PackExpansionTypeLoc ExpansionTL = OldTL.getAs<PackExpansionTypeLoc>()) {
3179
3180 // We have a function parameter pack. Substitute into the pattern of the
3181 // expansion.
3182 NewTSI = SubstType(TL: ExpansionTL.getPatternLoc(), Args: TemplateArgs,
3183 Loc: OldParm->getLocation(), Entity: OldParm->getDeclName());
3184 if (!NewTSI)
3185 return nullptr;
3186
3187 if (NewTSI->getType()->containsUnexpandedParameterPack()) {
3188 // We still have unexpanded parameter packs, which means that
3189 // our function parameter is still a function parameter pack.
3190 // Therefore, make its type a pack expansion type.
3191 NewTSI = CheckPackExpansion(Pattern: NewTSI, EllipsisLoc: ExpansionTL.getEllipsisLoc(),
3192 NumExpansions);
3193 } else if (ExpectParameterPack) {
3194 // We expected to get a parameter pack but didn't (because the type
3195 // itself is not a pack expansion type), so complain. This can occur when
3196 // the substitution goes through an alias template that "loses" the
3197 // pack expansion.
3198 Diag(Loc: OldParm->getLocation(),
3199 DiagID: diag::err_function_parameter_pack_without_parameter_packs)
3200 << NewTSI->getType();
3201 return nullptr;
3202 }
3203 } else {
3204 NewTSI = SubstType(T: OldTSI, Args: TemplateArgs, Loc: OldParm->getLocation(),
3205 Entity: OldParm->getDeclName());
3206 }
3207
3208 if (!NewTSI)
3209 return nullptr;
3210
3211 if (NewTSI->getType()->isVoidType()) {
3212 Diag(Loc: OldParm->getLocation(), DiagID: diag::err_param_with_void_type);
3213 return nullptr;
3214 }
3215
3216 // In abbreviated templates, TemplateTypeParmDecls with possible
3217 // TypeConstraints are created when the parameter list is originally parsed.
3218 // The TypeConstraints can therefore reference other functions parameters in
3219 // the abbreviated function template, which is why we must instantiate them
3220 // here, when the instantiated versions of those referenced parameters are in
3221 // scope.
3222 if (TemplateTypeParmDecl *TTP =
3223 GetContainedInventedTypeParmVisitor().Visit(T: OldTSI->getType())) {
3224 if (const TypeConstraint *TC = TTP->getTypeConstraint()) {
3225 auto *Inst = cast_or_null<TemplateTypeParmDecl>(
3226 Val: FindInstantiatedDecl(Loc: TTP->getLocation(), D: TTP, TemplateArgs));
3227 // We will first get here when instantiating the abbreviated function
3228 // template's described function, but we might also get here later.
3229 // Make sure we do not instantiate the TypeConstraint more than once.
3230 if (Inst && !Inst->getTypeConstraint()) {
3231 if (SubstTypeConstraint(Inst, TC, TemplateArgs, EvaluateConstraints: EvaluateConstraint))
3232 return nullptr;
3233 }
3234 }
3235 }
3236
3237 ParmVarDecl *NewParm = CheckParameter(
3238 DC: Context.getTranslationUnitDecl(), StartLoc: OldParm->getInnerLocStart(),
3239 NameLoc: OldParm->getLocation(), Name: OldParm->getIdentifier(), T: NewTSI->getType(),
3240 TSInfo: NewTSI, SC: OldParm->getStorageClass());
3241 if (!NewParm)
3242 return nullptr;
3243
3244 // Mark the (new) default argument as uninstantiated (if any).
3245 if (OldParm->hasUninstantiatedDefaultArg()) {
3246 Expr *Arg = OldParm->getUninstantiatedDefaultArg();
3247 NewParm->setUninstantiatedDefaultArg(Arg);
3248 } else if (OldParm->hasUnparsedDefaultArg()) {
3249 NewParm->setUnparsedDefaultArg();
3250 UnparsedDefaultArgInstantiations[OldParm].push_back(NewVal: NewParm);
3251 } else if (Expr *Arg = OldParm->getDefaultArg()) {
3252 // Default arguments cannot be substituted until the declaration context
3253 // for the associated function or lambda capture class is available.
3254 // This is necessary for cases like the following where construction of
3255 // the lambda capture class for the outer lambda is dependent on the
3256 // parameter types but where the default argument is dependent on the
3257 // outer lambda's declaration context.
3258 // template <typename T>
3259 // auto f() {
3260 // return [](T = []{ return T{}; }()) { return 0; };
3261 // }
3262 NewParm->setUninstantiatedDefaultArg(Arg);
3263 }
3264
3265 NewParm->setExplicitObjectParameterLoc(
3266 OldParm->getExplicitObjectParamThisLoc());
3267 NewParm->setHasInheritedDefaultArg(OldParm->hasInheritedDefaultArg());
3268
3269 if (OldParm->isParameterPack() && !NewParm->isParameterPack()) {
3270 // Add the new parameter to the instantiated parameter pack.
3271 CurrentInstantiationScope->InstantiatedLocalPackArg(D: OldParm, Inst: NewParm);
3272 } else {
3273 // Introduce an Old -> New mapping
3274 CurrentInstantiationScope->InstantiatedLocal(D: OldParm, Inst: NewParm);
3275 }
3276
3277 // FIXME: OldParm may come from a FunctionProtoType, in which case CurContext
3278 // can be anything, is this right ?
3279 NewParm->setDeclContext(CurContext);
3280
3281 NewParm->setScopeInfo(scopeDepth: OldParm->getFunctionScopeDepth(),
3282 parameterIndex: OldParm->getFunctionScopeIndex() + indexAdjustment);
3283
3284 InstantiateAttrs(TemplateArgs, Pattern: OldParm, Inst: NewParm);
3285
3286 NewParm->deduceParmAddressSpace(Ctxt: Context);
3287
3288 return NewParm;
3289}
3290
3291bool Sema::SubstParmTypes(
3292 SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
3293 const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
3294 const MultiLevelTemplateArgumentList &TemplateArgs,
3295 SmallVectorImpl<QualType> &ParamTypes,
3296 SmallVectorImpl<ParmVarDecl *> *OutParams,
3297 ExtParameterInfoBuilder &ParamInfos) {
3298 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
3299 DeclarationName());
3300 return Instantiator.TransformFunctionTypeParams(
3301 Loc, Params, ParamTypes: nullptr, ParamInfos: ExtParamInfos, PTypes&: ParamTypes, PVars: OutParams, PInfos&: ParamInfos);
3302}
3303
3304bool Sema::SubstDefaultArgument(
3305 SourceLocation Loc,
3306 ParmVarDecl *Param,
3307 const MultiLevelTemplateArgumentList &TemplateArgs,
3308 bool ForCallExpr) {
3309 FunctionDecl *FD = cast<FunctionDecl>(Val: Param->getDeclContext());
3310 Expr *PatternExpr = Param->getUninstantiatedDefaultArg();
3311
3312 RecursiveInstGuard AlreadyInstantiating(
3313 *this, Param, RecursiveInstGuard::Kind::DefaultArgument);
3314 if (AlreadyInstantiating) {
3315 Param->setInvalidDecl();
3316 return Diag(Loc: Param->getBeginLoc(), DiagID: diag::err_recursive_default_argument)
3317 << FD << PatternExpr->getSourceRange();
3318 }
3319
3320 EnterExpressionEvaluationContext EvalContext(
3321 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
3322 NonSFINAEContext _(*this);
3323 InstantiatingTemplate Inst(*this, Loc, Param, TemplateArgs.getInnermost());
3324 if (Inst.isInvalid())
3325 return true;
3326
3327 ExprResult Result;
3328 // C++ [dcl.fct.default]p5:
3329 // The names in the [default argument] expression are bound, and
3330 // the semantic constraints are checked, at the point where the
3331 // default argument expression appears.
3332 ContextRAII SavedContext(*this, FD);
3333 {
3334 std::optional<LocalInstantiationScope> LIS;
3335
3336 if (ForCallExpr) {
3337 // When instantiating a default argument due to use in a call expression,
3338 // an instantiation scope that includes the parameters of the callee is
3339 // required to satisfy references from the default argument. For example:
3340 // template<typename T> void f(T a, int = decltype(a)());
3341 // void g() { f(0); }
3342 LIS.emplace(args&: *this);
3343 FunctionDecl *PatternFD = FD->getTemplateInstantiationPattern(
3344 /*ForDefinition*/ false);
3345 if (addInstantiatedParametersToScope(Function: FD, PatternDecl: PatternFD, Scope&: *LIS, TemplateArgs))
3346 return true;
3347 }
3348
3349 runWithSufficientStackSpace(Loc, Fn: [&] {
3350 Result = SubstInitializer(E: PatternExpr, TemplateArgs,
3351 /*DirectInit*/ CXXDirectInit: false);
3352 });
3353 }
3354 if (Result.isInvalid())
3355 return true;
3356
3357 if (ForCallExpr) {
3358 // Check the expression as an initializer for the parameter.
3359 InitializedEntity Entity
3360 = InitializedEntity::InitializeParameter(Context, Parm: Param);
3361 InitializationKind Kind = InitializationKind::CreateCopy(
3362 InitLoc: Param->getLocation(),
3363 /*FIXME:EqualLoc*/ EqualLoc: PatternExpr->getBeginLoc());
3364 Expr *ResultE = Result.getAs<Expr>();
3365
3366 InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
3367 Result = InitSeq.Perform(S&: *this, Entity, Kind, Args: ResultE);
3368 if (Result.isInvalid())
3369 return true;
3370
3371 Result =
3372 ActOnFinishFullExpr(Expr: Result.getAs<Expr>(), CC: Param->getOuterLocStart(),
3373 /*DiscardedValue*/ false);
3374 } else {
3375 // FIXME: Obtain the source location for the '=' token.
3376 SourceLocation EqualLoc = PatternExpr->getBeginLoc();
3377 Result = ConvertParamDefaultArgument(Param, DefaultArg: Result.getAs<Expr>(), EqualLoc);
3378 }
3379 if (Result.isInvalid())
3380 return true;
3381
3382 // Remember the instantiated default argument.
3383 Param->setDefaultArg(Result.getAs<Expr>());
3384
3385 return false;
3386}
3387
3388// See TreeTransform::PreparePackForExpansion for the relevant comment.
3389// This function implements the same concept for base specifiers.
3390static bool
3391PreparePackForExpansion(Sema &S, const CXXBaseSpecifier &Base,
3392 const MultiLevelTemplateArgumentList &TemplateArgs,
3393 TypeSourceInfo *&Out, UnexpandedInfo &Info) {
3394 SourceRange BaseSourceRange = Base.getSourceRange();
3395 SourceLocation BaseEllipsisLoc = Base.getEllipsisLoc();
3396 Info.Ellipsis = Base.getEllipsisLoc();
3397 auto ComputeInfo = [&S, &TemplateArgs, BaseSourceRange, BaseEllipsisLoc](
3398 TypeSourceInfo *BaseTypeInfo,
3399 bool IsLateExpansionAttempt, UnexpandedInfo &Info) {
3400 // This is a pack expansion. See whether we should expand it now, or
3401 // wait until later.
3402 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
3403 S.collectUnexpandedParameterPacks(TL: BaseTypeInfo->getTypeLoc(), Unexpanded);
3404 if (IsLateExpansionAttempt) {
3405 // Request expansion only when there is an opportunity to expand a pack
3406 // that required a substituion first.
3407 bool SawPackTypes =
3408 llvm::any_of(Range&: Unexpanded, P: [](UnexpandedParameterPack P) {
3409 return P.first.dyn_cast<const SubstBuiltinTemplatePackType *>();
3410 });
3411 if (!SawPackTypes) {
3412 Info.Expand = false;
3413 return false;
3414 }
3415 }
3416
3417 // Determine whether the set of unexpanded parameter packs can and should be
3418 // expanded.
3419 Info.Expand = false;
3420 Info.RetainExpansion = false;
3421 Info.NumExpansions = std::nullopt;
3422 return S.CheckParameterPacksForExpansion(
3423 EllipsisLoc: BaseEllipsisLoc, PatternRange: BaseSourceRange, Unexpanded, TemplateArgs,
3424 /*FailOnPackProducingTemplates=*/false, ShouldExpand&: Info.Expand,
3425 RetainExpansion&: Info.RetainExpansion, NumExpansions&: Info.NumExpansions);
3426 };
3427
3428 if (ComputeInfo(Base.getTypeSourceInfo(), false, Info))
3429 return true;
3430
3431 if (Info.Expand) {
3432 Out = Base.getTypeSourceInfo();
3433 return false;
3434 }
3435
3436 // The resulting base specifier will (still) be a pack expansion.
3437 {
3438 Sema::ArgPackSubstIndexRAII SubstIndex(S, std::nullopt);
3439 Out = S.SubstType(T: Base.getTypeSourceInfo(), Args: TemplateArgs,
3440 Loc: BaseSourceRange.getBegin(), Entity: DeclarationName());
3441 }
3442 if (!Out->getType()->containsUnexpandedParameterPack())
3443 return false;
3444
3445 // Some packs will learn their length after substitution.
3446 // We may need to request their expansion.
3447 if (ComputeInfo(Out, /*IsLateExpansionAttempt=*/true, Info))
3448 return true;
3449 if (Info.Expand)
3450 Info.ExpandUnderForgetSubstitions = true;
3451 return false;
3452}
3453
3454bool
3455Sema::SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
3456 CXXRecordDecl *Pattern,
3457 const MultiLevelTemplateArgumentList &TemplateArgs) {
3458 bool Invalid = false;
3459 SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases;
3460 for (const auto &Base : Pattern->bases()) {
3461 if (!Base.getType()->isInstantiationDependentType()) {
3462 if (const CXXRecordDecl *RD = Base.getType()->getAsCXXRecordDecl()) {
3463 if (RD->isInvalidDecl())
3464 Instantiation->setInvalidDecl();
3465 }
3466 InstantiatedBases.push_back(Elt: new (Context) CXXBaseSpecifier(Base));
3467 continue;
3468 }
3469
3470 SourceLocation EllipsisLoc;
3471 TypeSourceInfo *BaseTypeLoc = nullptr;
3472 if (Base.isPackExpansion()) {
3473 UnexpandedInfo Info;
3474 if (PreparePackForExpansion(S&: *this, Base, TemplateArgs, Out&: BaseTypeLoc,
3475 Info)) {
3476 Invalid = true;
3477 continue;
3478 }
3479
3480 // If we should expand this pack expansion now, do so.
3481 MultiLevelTemplateArgumentList EmptyList;
3482 const MultiLevelTemplateArgumentList *ArgsForSubst = &TemplateArgs;
3483 if (Info.ExpandUnderForgetSubstitions)
3484 ArgsForSubst = &EmptyList;
3485
3486 if (Info.Expand) {
3487 for (unsigned I = 0; I != *Info.NumExpansions; ++I) {
3488 Sema::ArgPackSubstIndexRAII SubstIndex(*this, I);
3489
3490 TypeSourceInfo *Expanded =
3491 SubstType(T: BaseTypeLoc, Args: *ArgsForSubst,
3492 Loc: Base.getSourceRange().getBegin(), Entity: DeclarationName());
3493 if (!Expanded) {
3494 Invalid = true;
3495 continue;
3496 }
3497
3498 if (CXXBaseSpecifier *InstantiatedBase = CheckBaseSpecifier(
3499 Class: Instantiation, SpecifierRange: Base.getSourceRange(), Virtual: Base.isVirtual(),
3500 Access: Base.getAccessSpecifierAsWritten(), TInfo: Expanded,
3501 EllipsisLoc: SourceLocation()))
3502 InstantiatedBases.push_back(Elt: InstantiatedBase);
3503 else
3504 Invalid = true;
3505 }
3506
3507 continue;
3508 }
3509
3510 // The resulting base specifier will (still) be a pack expansion.
3511 EllipsisLoc = Base.getEllipsisLoc();
3512 Sema::ArgPackSubstIndexRAII SubstIndex(*this, std::nullopt);
3513 BaseTypeLoc =
3514 SubstType(T: BaseTypeLoc, Args: *ArgsForSubst,
3515 Loc: Base.getSourceRange().getBegin(), Entity: DeclarationName());
3516 } else {
3517 BaseTypeLoc = SubstType(T: Base.getTypeSourceInfo(),
3518 Args: TemplateArgs,
3519 Loc: Base.getSourceRange().getBegin(),
3520 Entity: DeclarationName());
3521 }
3522
3523 if (!BaseTypeLoc) {
3524 Invalid = true;
3525 continue;
3526 }
3527
3528 if (CXXBaseSpecifier *InstantiatedBase
3529 = CheckBaseSpecifier(Class: Instantiation,
3530 SpecifierRange: Base.getSourceRange(),
3531 Virtual: Base.isVirtual(),
3532 Access: Base.getAccessSpecifierAsWritten(),
3533 TInfo: BaseTypeLoc,
3534 EllipsisLoc))
3535 InstantiatedBases.push_back(Elt: InstantiatedBase);
3536 else
3537 Invalid = true;
3538 }
3539
3540 if (!Invalid && AttachBaseSpecifiers(Class: Instantiation, Bases: InstantiatedBases))
3541 Invalid = true;
3542
3543 return Invalid;
3544}
3545
3546// Defined via #include from SemaTemplateInstantiateDecl.cpp
3547namespace clang {
3548 namespace sema {
3549 Attr *instantiateTemplateAttribute(const Attr *At, ASTContext &C, Sema &S,
3550 const MultiLevelTemplateArgumentList &TemplateArgs);
3551 Attr *instantiateTemplateAttributeForDecl(
3552 const Attr *At, ASTContext &C, Sema &S,
3553 const MultiLevelTemplateArgumentList &TemplateArgs);
3554 }
3555}
3556
3557bool Sema::InstantiateClass(SourceLocation PointOfInstantiation,
3558 CXXRecordDecl *Instantiation,
3559 CXXRecordDecl *Pattern,
3560 const MultiLevelTemplateArgumentList &TemplateArgs,
3561 TemplateSpecializationKind TSK, bool Complain) {
3562#ifndef NDEBUG
3563 RecursiveInstGuard AlreadyInstantiating(*this, Instantiation,
3564 RecursiveInstGuard::Kind::Template);
3565 assert(!AlreadyInstantiating && "should have been caught by caller");
3566#endif
3567
3568 return InstantiateClassImpl(PointOfInstantiation, Instantiation, Pattern,
3569 TemplateArgs, TSK, Complain);
3570}
3571
3572bool Sema::InstantiateClassImpl(
3573 SourceLocation PointOfInstantiation, CXXRecordDecl *Instantiation,
3574 CXXRecordDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs,
3575 TemplateSpecializationKind TSK, bool Complain) {
3576
3577 CXXRecordDecl *PatternDef
3578 = cast_or_null<CXXRecordDecl>(Val: Pattern->getDefinition());
3579 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
3580 InstantiatedFromMember: Instantiation->getInstantiatedFromMemberClass(),
3581 Pattern, PatternDef, TSK, Complain))
3582 return true;
3583
3584 llvm::TimeTraceScope TimeScope("InstantiateClass", [&]() {
3585 llvm::TimeTraceMetadata M;
3586 llvm::raw_string_ostream OS(M.Detail);
3587 Instantiation->getNameForDiagnostic(OS, Policy: getPrintingPolicy(),
3588 /*Qualified=*/true);
3589 if (llvm::isTimeTraceVerbose()) {
3590 auto Loc = SourceMgr.getExpansionLoc(Loc: Instantiation->getLocation());
3591 M.File = SourceMgr.getFilename(SpellingLoc: Loc);
3592 M.Line = SourceMgr.getExpansionLineNumber(Loc);
3593 }
3594 return M;
3595 });
3596
3597 Pattern = PatternDef;
3598
3599 // Record the point of instantiation.
3600 if (MemberSpecializationInfo *MSInfo
3601 = Instantiation->getMemberSpecializationInfo()) {
3602 MSInfo->setTemplateSpecializationKind(TSK);
3603 MSInfo->setPointOfInstantiation(PointOfInstantiation);
3604 } else if (ClassTemplateSpecializationDecl *Spec
3605 = dyn_cast<ClassTemplateSpecializationDecl>(Val: Instantiation)) {
3606 Spec->setTemplateSpecializationKind(TSK);
3607 Spec->setPointOfInstantiation(PointOfInstantiation);
3608 }
3609
3610 NonSFINAEContext _(*this);
3611 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
3612 if (Inst.isInvalid())
3613 return true;
3614 PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
3615 "instantiating class definition");
3616
3617 // Enter the scope of this instantiation. We don't use
3618 // PushDeclContext because we don't have a scope.
3619 ContextRAII SavedContext(*this, Instantiation);
3620 EnterExpressionEvaluationContext EvalContext(
3621 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
3622
3623 // If this is an instantiation of a local class, merge this local
3624 // instantiation scope with the enclosing scope. Otherwise, every
3625 // instantiation of a class has its own local instantiation scope.
3626 bool MergeWithParentScope = !Instantiation->isDefinedOutsideFunctionOrMethod();
3627 LocalInstantiationScope Scope(*this, MergeWithParentScope);
3628
3629 // Some class state isn't processed immediately but delayed till class
3630 // instantiation completes. We may not be ready to handle any delayed state
3631 // already on the stack as it might correspond to a different class, so save
3632 // it now and put it back later.
3633 SavePendingParsedClassStateRAII SavedPendingParsedClassState(*this);
3634
3635 // Pull attributes from the pattern onto the instantiation.
3636 InstantiateAttrs(TemplateArgs, Pattern, Inst: Instantiation);
3637
3638 // Start the definition of this instantiation.
3639 Instantiation->startDefinition();
3640
3641 // The instantiation is visible here, even if it was first declared in an
3642 // unimported module.
3643 Instantiation->setVisibleDespiteOwningModule();
3644
3645 // FIXME: This loses the as-written tag kind for an explicit instantiation.
3646 Instantiation->setTagKind(Pattern->getTagKind());
3647
3648 // Do substitution on the base class specifiers.
3649 if (SubstBaseSpecifiers(Instantiation, Pattern, TemplateArgs))
3650 Instantiation->setInvalidDecl();
3651
3652 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
3653 Instantiator.setEvaluateConstraints(false);
3654 SmallVector<Decl*, 4> Fields;
3655 // Delay instantiation of late parsed attributes.
3656 LateInstantiatedAttrVec LateAttrs;
3657 Instantiator.enableLateAttributeInstantiation(LA: &LateAttrs);
3658
3659 bool MightHaveConstexprVirtualFunctions = false;
3660 for (auto *Member : Pattern->decls()) {
3661 // Don't instantiate members not belonging in this semantic context.
3662 // e.g. for:
3663 // @code
3664 // template <int i> class A {
3665 // class B *g;
3666 // };
3667 // @endcode
3668 // 'class B' has the template as lexical context but semantically it is
3669 // introduced in namespace scope.
3670 if (Member->getDeclContext() != Pattern)
3671 continue;
3672
3673 // BlockDecls can appear in a default-member-initializer. They must be the
3674 // child of a BlockExpr, so we only know how to instantiate them from there.
3675 // Similarly, lambda closure types are recreated when instantiating the
3676 // corresponding LambdaExpr.
3677 if (isa<BlockDecl>(Val: Member) ||
3678 (isa<CXXRecordDecl>(Val: Member) && cast<CXXRecordDecl>(Val: Member)->isLambda()))
3679 continue;
3680
3681 if (Member->isInvalidDecl()) {
3682 Instantiation->setInvalidDecl();
3683 // Drop invalid members to prevent cascading diagnostic errors.
3684 // We make an exception for VarTemplateDecl because the primary template
3685 // is required for partial specialization lookup. Keeping it is safe from
3686 // cascading errors due to the parser's type recovery.
3687 if (!isa<VarTemplateDecl>(Val: Member))
3688 continue;
3689 }
3690
3691 Decl *NewMember = Instantiator.Visit(D: Member);
3692 if (NewMember) {
3693 if (FieldDecl *Field = dyn_cast<FieldDecl>(Val: NewMember)) {
3694 Fields.push_back(Elt: Field);
3695 } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(Val: NewMember)) {
3696 // C++11 [temp.inst]p1: The implicit instantiation of a class template
3697 // specialization causes the implicit instantiation of the definitions
3698 // of unscoped member enumerations.
3699 // Record a point of instantiation for this implicit instantiation.
3700 if (TSK == TSK_ImplicitInstantiation && !Enum->isScoped() &&
3701 Enum->isCompleteDefinition()) {
3702 MemberSpecializationInfo *MSInfo =Enum->getMemberSpecializationInfo();
3703 assert(MSInfo && "no spec info for member enum specialization");
3704 MSInfo->setTemplateSpecializationKind(TSK_ImplicitInstantiation);
3705 MSInfo->setPointOfInstantiation(PointOfInstantiation);
3706 }
3707 } else if (StaticAssertDecl *SA = dyn_cast<StaticAssertDecl>(Val: NewMember)) {
3708 if (SA->isFailed()) {
3709 // A static_assert failed. Bail out; instantiating this
3710 // class is probably not meaningful.
3711 Instantiation->setInvalidDecl();
3712 break;
3713 }
3714 } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: NewMember)) {
3715 if (MD->isConstexpr() && !MD->getFriendObjectKind() &&
3716 (MD->isVirtualAsWritten() || Instantiation->getNumBases()))
3717 MightHaveConstexprVirtualFunctions = true;
3718 }
3719
3720 if (Member->isInvalidDecl())
3721 NewMember->setInvalidDecl();
3722
3723 if (NewMember->isInvalidDecl())
3724 Instantiation->setInvalidDecl();
3725 } else {
3726 // FIXME: Eventually, a NULL return will mean that one of the
3727 // instantiations was a semantic disaster, and we'll want to mark the
3728 // declaration invalid.
3729 // For now, we expect to skip some members that we can't yet handle.
3730 }
3731 }
3732
3733 // Finish checking fields.
3734 ActOnFields(S: nullptr, RecLoc: Instantiation->getLocation(), TagDecl: Instantiation, Fields,
3735 LBrac: SourceLocation(), RBrac: SourceLocation(), AttrList: ParsedAttributesView());
3736 CheckCompletedCXXClass(S: nullptr, Record: Instantiation);
3737
3738 // Default arguments are parsed, if not instantiated. We can go instantiate
3739 // default arg exprs for default constructors if necessary now. Unless we're
3740 // parsing a class, in which case wait until that's finished.
3741 if (ParsingClassDepth == 0)
3742 ActOnFinishCXXNonNestedClass();
3743
3744 // Instantiate late parsed attributes, and attach them to their decls.
3745 // See Sema::InstantiateAttrs
3746 for (LateInstantiatedAttrVec::iterator I = LateAttrs.begin(),
3747 E = LateAttrs.end(); I != E; ++I) {
3748 assert(CurrentInstantiationScope == Instantiator.getStartingScope());
3749 CurrentInstantiationScope = I->Scope;
3750
3751 // Allow 'this' within late-parsed attributes.
3752 auto *ND = cast<NamedDecl>(Val: I->NewDecl);
3753 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(Val: ND->getDeclContext());
3754 CXXThisScopeRAII ThisScope(*this, ThisContext, Qualifiers(),
3755 ND->isCXXInstanceMember());
3756
3757 Attr *NewAttr =
3758 instantiateTemplateAttribute(At: I->TmplAttr, C&: Context, S&: *this, TemplateArgs);
3759 if (NewAttr && checkInstantiatedThreadSafetyAttrs(D: I->NewDecl, A: NewAttr))
3760 I->NewDecl->addAttr(A: NewAttr);
3761 LocalInstantiationScope::deleteScopes(Scope: I->Scope,
3762 Outermost: Instantiator.getStartingScope());
3763 }
3764 Instantiator.disableLateAttributeInstantiation();
3765 LateAttrs.clear();
3766
3767 ActOnFinishDelayedMemberInitializers(Record: Instantiation);
3768
3769 // FIXME: We should do something similar for explicit instantiations so they
3770 // end up in the right module.
3771 if (TSK == TSK_ImplicitInstantiation) {
3772 Instantiation->setLocation(Pattern->getLocation());
3773 Instantiation->setLocStart(Pattern->getInnerLocStart());
3774 Instantiation->setBraceRange(Pattern->getBraceRange());
3775 }
3776
3777 if (!Instantiation->isInvalidDecl()) {
3778 // Perform any dependent diagnostics from the pattern.
3779 if (Pattern->isDependentContext())
3780 PerformDependentDiagnostics(Pattern, TemplateArgs);
3781
3782 // Instantiate any out-of-line class template partial
3783 // specializations now.
3784 for (TemplateDeclInstantiator::delayed_partial_spec_iterator
3785 P = Instantiator.delayed_partial_spec_begin(),
3786 PEnd = Instantiator.delayed_partial_spec_end();
3787 P != PEnd; ++P) {
3788 if (!Instantiator.InstantiateClassTemplatePartialSpecialization(
3789 ClassTemplate: P->first, PartialSpec: P->second)) {
3790 Instantiation->setInvalidDecl();
3791 break;
3792 }
3793 }
3794
3795 // Instantiate any out-of-line variable template partial
3796 // specializations now.
3797 for (TemplateDeclInstantiator::delayed_var_partial_spec_iterator
3798 P = Instantiator.delayed_var_partial_spec_begin(),
3799 PEnd = Instantiator.delayed_var_partial_spec_end();
3800 P != PEnd; ++P) {
3801 if (!Instantiator.InstantiateVarTemplatePartialSpecialization(
3802 VarTemplate: P->first, PartialSpec: P->second)) {
3803 Instantiation->setInvalidDecl();
3804 break;
3805 }
3806 }
3807 }
3808
3809 Instantiation->setIsHLSLBuiltinRecord(Pattern->isHLSLBuiltinRecord());
3810
3811 // Exit the scope of this instantiation.
3812 SavedContext.pop();
3813
3814 if (!Instantiation->isInvalidDecl()) {
3815 // Always emit the vtable for an explicit instantiation definition
3816 // of a polymorphic class template specialization. Otherwise, eagerly
3817 // instantiate only constexpr virtual functions in preparation for their use
3818 // in constant evaluation.
3819 if (TSK == TSK_ExplicitInstantiationDefinition)
3820 MarkVTableUsed(Loc: PointOfInstantiation, Class: Instantiation, DefinitionRequired: true);
3821 else if (MightHaveConstexprVirtualFunctions)
3822 MarkVirtualMembersReferenced(Loc: PointOfInstantiation, RD: Instantiation,
3823 /*ConstexprOnly*/ true);
3824 }
3825
3826 Consumer.HandleTagDeclDefinition(D: Instantiation);
3827
3828 return Instantiation->isInvalidDecl();
3829}
3830
3831bool Sema::InstantiateEnum(SourceLocation PointOfInstantiation,
3832 EnumDecl *Instantiation, EnumDecl *Pattern,
3833 const MultiLevelTemplateArgumentList &TemplateArgs,
3834 TemplateSpecializationKind TSK) {
3835#ifndef NDEBUG
3836 RecursiveInstGuard AlreadyInstantiating(*this, Instantiation,
3837 RecursiveInstGuard::Kind::Template);
3838 assert(!AlreadyInstantiating && "should have been caught by caller");
3839#endif
3840
3841 EnumDecl *PatternDef = Pattern->getDefinition();
3842 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
3843 InstantiatedFromMember: Instantiation->getInstantiatedFromMemberEnum(),
3844 Pattern, PatternDef, TSK,/*Complain*/true))
3845 return true;
3846 Pattern = PatternDef;
3847
3848 // Record the point of instantiation.
3849 if (MemberSpecializationInfo *MSInfo
3850 = Instantiation->getMemberSpecializationInfo()) {
3851 MSInfo->setTemplateSpecializationKind(TSK);
3852 MSInfo->setPointOfInstantiation(PointOfInstantiation);
3853 }
3854
3855 NonSFINAEContext _(*this);
3856 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
3857 if (Inst.isInvalid())
3858 return true;
3859 PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
3860 "instantiating enum definition");
3861
3862 // The instantiation is visible here, even if it was first declared in an
3863 // unimported module.
3864 Instantiation->setVisibleDespiteOwningModule();
3865
3866 // Enter the scope of this instantiation. We don't use
3867 // PushDeclContext because we don't have a scope.
3868 ContextRAII SavedContext(*this, Instantiation);
3869 EnterExpressionEvaluationContext EvalContext(
3870 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
3871
3872 LocalInstantiationScope Scope(*this, /*MergeWithParentScope*/true);
3873
3874 // Pull attributes from the pattern onto the instantiation.
3875 InstantiateAttrs(TemplateArgs, Pattern, Inst: Instantiation);
3876
3877 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
3878 Instantiator.InstantiateEnumDefinition(Enum: Instantiation, Pattern);
3879
3880 // Exit the scope of this instantiation.
3881 SavedContext.pop();
3882
3883 return Instantiation->isInvalidDecl();
3884}
3885
3886bool Sema::InstantiateInClassInitializer(
3887 SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
3888 FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs) {
3889 // If there is no initializer, we don't need to do anything.
3890 if (!Pattern->hasInClassInitializer())
3891 return false;
3892
3893 assert(Instantiation->getInClassInitStyle() ==
3894 Pattern->getInClassInitStyle() &&
3895 "pattern and instantiation disagree about init style");
3896
3897 RecursiveInstGuard AlreadyInstantiating(*this, Instantiation,
3898 RecursiveInstGuard::Kind::Template);
3899 if (AlreadyInstantiating)
3900 // Error out if we hit an instantiation cycle for this initializer.
3901 return Diag(Loc: PointOfInstantiation,
3902 DiagID: diag::err_default_member_initializer_cycle)
3903 << Instantiation;
3904
3905 // Error out if we haven't parsed the initializer of the pattern yet because
3906 // we are waiting for the closing brace of the outer class.
3907 Expr *OldInit = Pattern->getInClassInitializer();
3908 if (!OldInit) {
3909 RecordDecl *PatternRD = Pattern->getParent();
3910 RecordDecl *OutermostClass = PatternRD->getOuterLexicalRecordContext();
3911 Diag(Loc: PointOfInstantiation,
3912 DiagID: diag::err_default_member_initializer_not_yet_parsed)
3913 << OutermostClass << Pattern;
3914 Diag(Loc: Pattern->getEndLoc(),
3915 DiagID: diag::note_default_member_initializer_not_yet_parsed);
3916 return true;
3917 }
3918
3919 NonSFINAEContext _(*this);
3920 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
3921 if (Inst.isInvalid())
3922 return true;
3923 PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
3924 "instantiating default member init");
3925
3926 // Enter the scope of this instantiation. We don't use PushDeclContext because
3927 // we don't have a scope.
3928 ContextRAII SavedContext(*this, Instantiation->getParent());
3929 EnterExpressionEvaluationContext EvalContext(
3930 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated,
3931 Instantiation);
3932 ExprEvalContexts.back().DelayedDefaultInitializationContext = {
3933 PointOfInstantiation, Instantiation, CurContext};
3934
3935 LocalInstantiationScope Scope(*this, true);
3936
3937 // Instantiate the initializer.
3938 ActOnStartCXXInClassMemberInitializer();
3939 CXXThisScopeRAII ThisScope(*this, Instantiation->getParent(), Qualifiers());
3940
3941 ExprResult NewInit = SubstInitializer(E: OldInit, TemplateArgs,
3942 /*CXXDirectInit=*/false);
3943 Expr *Init = NewInit.get();
3944 assert((!Init || !isa<ParenListExpr>(Init)) && "call-style init in class");
3945 ActOnFinishCXXInClassMemberInitializer(
3946 VarDecl: Instantiation, EqualLoc: Init ? Init->getBeginLoc() : SourceLocation(), Init);
3947
3948 if (auto *L = getASTMutationListener())
3949 L->DefaultMemberInitializerInstantiated(D: Instantiation);
3950
3951 // Return true if the in-class initializer is still missing.
3952 return !Instantiation->getInClassInitializer();
3953}
3954
3955namespace {
3956 /// A partial specialization whose template arguments have matched
3957 /// a given template-id.
3958 struct PartialSpecMatchResult {
3959 ClassTemplatePartialSpecializationDecl *Partial;
3960 TemplateArgumentList *Args;
3961 };
3962}
3963
3964bool Sema::usesPartialOrExplicitSpecialization(
3965 SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec) {
3966 if (ClassTemplateSpec->getTemplateSpecializationKind() ==
3967 TSK_ExplicitSpecialization)
3968 return true;
3969
3970 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
3971 ClassTemplateDecl *CTD = ClassTemplateSpec->getSpecializedTemplate();
3972 CTD->getPartialSpecializations(PS&: PartialSpecs);
3973 for (ClassTemplatePartialSpecializationDecl *CTPSD : PartialSpecs) {
3974 // C++ [temp.spec.partial.member]p2:
3975 // If the primary member template is explicitly specialized for a given
3976 // (implicit) specialization of the enclosing class template, the partial
3977 // specializations of the member template are ignored for this
3978 // specialization of the enclosing class template. If a partial
3979 // specialization of the member template is explicitly specialized for a
3980 // given (implicit) specialization of the enclosing class template, the
3981 // primary member template and its other partial specializations are still
3982 // considered for this specialization of the enclosing class template.
3983 if (CTD->isMemberSpecialization() && !CTPSD->isMemberSpecialization())
3984 continue;
3985
3986 TemplateDeductionInfo Info(Loc);
3987 if (DeduceTemplateArguments(Partial: CTPSD,
3988 TemplateArgs: ClassTemplateSpec->getTemplateArgs().asArray(),
3989 Info) == TemplateDeductionResult::Success)
3990 return true;
3991 }
3992
3993 return false;
3994}
3995
3996/// Get the instantiation pattern to use to instantiate the definition of a
3997/// given ClassTemplateSpecializationDecl (either the pattern of the primary
3998/// template or of a partial specialization).
3999static ActionResult<CXXRecordDecl *> getPatternForClassTemplateSpecialization(
4000 Sema &S, SourceLocation PointOfInstantiation,
4001 ClassTemplateSpecializationDecl *ClassTemplateSpec,
4002 TemplateSpecializationKind TSK, bool PrimaryStrictPackMatch) {
4003 std::optional<Sema::NonSFINAEContext> NSC(S);
4004 Sema::InstantiatingTemplate Inst(S, PointOfInstantiation, ClassTemplateSpec);
4005 if (Inst.isInvalid())
4006 return {/*Invalid=*/true};
4007
4008 llvm::PointerUnion<ClassTemplateDecl *,
4009 ClassTemplatePartialSpecializationDecl *>
4010 Specialized = ClassTemplateSpec->getSpecializedTemplateOrPartial();
4011 if (!isa<ClassTemplatePartialSpecializationDecl *>(Val: Specialized)) {
4012 // Find best matching specialization.
4013 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
4014
4015 // C++ [temp.class.spec.match]p1:
4016 // When a class template is used in a context that requires an
4017 // instantiation of the class, it is necessary to determine
4018 // whether the instantiation is to be generated using the primary
4019 // template or one of the partial specializations. This is done by
4020 // matching the template arguments of the class template
4021 // specialization with the template argument lists of the partial
4022 // specializations.
4023 typedef PartialSpecMatchResult MatchResult;
4024 SmallVector<MatchResult, 4> Matched, ExtraMatched;
4025 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
4026 Template->getPartialSpecializations(PS&: PartialSpecs);
4027 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation);
4028 for (ClassTemplatePartialSpecializationDecl *Partial : PartialSpecs) {
4029 // C++ [temp.spec.partial.member]p2:
4030 // If the primary member template is explicitly specialized for a given
4031 // (implicit) specialization of the enclosing class template, the
4032 // partial specializations of the member template are ignored for this
4033 // specialization of the enclosing class template. If a partial
4034 // specialization of the member template is explicitly specialized for a
4035 // given (implicit) specialization of the enclosing class template, the
4036 // primary member template and its other partial specializations are
4037 // still considered for this specialization of the enclosing class
4038 // template.
4039 if (Template->isMemberSpecialization() &&
4040 !Partial->isMemberSpecialization())
4041 continue;
4042
4043 TemplateDeductionInfo Info(FailedCandidates.getLocation());
4044 if (TemplateDeductionResult Result = S.DeduceTemplateArguments(
4045 Partial, TemplateArgs: ClassTemplateSpec->getTemplateArgs().asArray(), Info);
4046 Result != TemplateDeductionResult::Success) {
4047 // Store the failed-deduction information for use in diagnostics, later.
4048 // TODO: Actually use the failed-deduction info?
4049 FailedCandidates.addCandidate().set(
4050 Found: DeclAccessPair::make(D: Template, AS: AS_public), Spec: Partial,
4051 Info: MakeDeductionFailureInfo(Context&: S.Context, TDK: Result, Info));
4052 (void)Result;
4053 } else {
4054 auto &List = Info.hasStrictPackMatch() ? ExtraMatched : Matched;
4055 List.push_back(Elt: MatchResult{.Partial: Partial, .Args: Info.takeCanonical()});
4056 }
4057 }
4058 if (Matched.empty() && PrimaryStrictPackMatch)
4059 Matched = std::move(ExtraMatched);
4060
4061 // If we're dealing with a member template where the template parameters
4062 // have been instantiated, this provides the original template parameters
4063 // from which the member template's parameters were instantiated.
4064
4065 if (Matched.size() >= 1) {
4066 SmallVectorImpl<MatchResult>::iterator Best = Matched.begin();
4067 if (Matched.size() == 1) {
4068 // -- If exactly one matching specialization is found, the
4069 // instantiation is generated from that specialization.
4070 // We don't need to do anything for this.
4071 } else {
4072 // -- If more than one matching specialization is found, the
4073 // partial order rules (14.5.4.2) are used to determine
4074 // whether one of the specializations is more specialized
4075 // than the others. If none of the specializations is more
4076 // specialized than all of the other matching
4077 // specializations, then the use of the class template is
4078 // ambiguous and the program is ill-formed.
4079 for (SmallVectorImpl<MatchResult>::iterator P = Best + 1,
4080 PEnd = Matched.end();
4081 P != PEnd; ++P) {
4082 if (S.getMoreSpecializedPartialSpecialization(
4083 PS1: P->Partial, PS2: Best->Partial, Loc: PointOfInstantiation) ==
4084 P->Partial)
4085 Best = P;
4086 }
4087
4088 // Determine if the best partial specialization is more specialized than
4089 // the others.
4090 bool Ambiguous = false;
4091 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
4092 PEnd = Matched.end();
4093 P != PEnd; ++P) {
4094 if (P != Best && S.getMoreSpecializedPartialSpecialization(
4095 PS1: P->Partial, PS2: Best->Partial,
4096 Loc: PointOfInstantiation) != Best->Partial) {
4097 Ambiguous = true;
4098 break;
4099 }
4100 }
4101
4102 if (Ambiguous) {
4103 // Partial ordering did not produce a clear winner. Complain.
4104 Inst.Clear();
4105 NSC.reset();
4106 S.Diag(Loc: PointOfInstantiation,
4107 DiagID: diag::err_partial_spec_ordering_ambiguous)
4108 << ClassTemplateSpec;
4109
4110 // Print the matching partial specializations.
4111 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
4112 PEnd = Matched.end();
4113 P != PEnd; ++P)
4114 S.Diag(Loc: P->Partial->getLocation(), DiagID: diag::note_partial_spec_match)
4115 << S.getTemplateArgumentBindingsText(
4116 Params: P->Partial->getTemplateParameters(), Args: *P->Args);
4117
4118 return {/*Invalid=*/true};
4119 }
4120 }
4121
4122 ClassTemplateSpec->setInstantiationOf(PartialSpec: Best->Partial, TemplateArgs: Best->Args);
4123 } else {
4124 // -- If no matches are found, the instantiation is generated
4125 // from the primary template.
4126 }
4127 }
4128
4129 CXXRecordDecl *Pattern = nullptr;
4130 Specialized = ClassTemplateSpec->getSpecializedTemplateOrPartial();
4131 if (auto *PartialSpec =
4132 Specialized.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
4133 // Instantiate using the best class template partial specialization.
4134 while (PartialSpec->getInstantiatedFromMember()) {
4135 // If we've found an explicit specialization of this class template,
4136 // stop here and use that as the pattern.
4137 if (PartialSpec->isMemberSpecialization())
4138 break;
4139
4140 PartialSpec = PartialSpec->getInstantiatedFromMember();
4141 }
4142 Pattern = PartialSpec;
4143 } else {
4144 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
4145 while (Template->getInstantiatedFromMemberTemplate()) {
4146 // If we've found an explicit specialization of this class template,
4147 // stop here and use that as the pattern.
4148 if (Template->isMemberSpecialization())
4149 break;
4150
4151 Template = Template->getInstantiatedFromMemberTemplate();
4152 }
4153 Pattern = Template->getTemplatedDecl();
4154 }
4155
4156 return Pattern;
4157}
4158
4159bool Sema::InstantiateClassTemplateSpecialization(
4160 SourceLocation PointOfInstantiation,
4161 ClassTemplateSpecializationDecl *ClassTemplateSpec,
4162 TemplateSpecializationKind TSK, bool Complain,
4163 bool PrimaryStrictPackMatch) {
4164 // Perform the actual instantiation on the canonical declaration.
4165 ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>(
4166 Val: ClassTemplateSpec->getCanonicalDecl());
4167 if (ClassTemplateSpec->isInvalidDecl())
4168 return true;
4169
4170 Sema::RecursiveInstGuard AlreadyInstantiating(
4171 *this, ClassTemplateSpec, Sema::RecursiveInstGuard::Kind::Template);
4172 if (AlreadyInstantiating)
4173 return false;
4174
4175 bool HadAvaibilityWarning =
4176 ShouldDiagnoseAvailabilityOfDecl(D: ClassTemplateSpec, Message: nullptr, ClassReceiver: nullptr)
4177 .first != AR_Available;
4178
4179 ActionResult<CXXRecordDecl *> Pattern =
4180 getPatternForClassTemplateSpecialization(S&: *this, PointOfInstantiation,
4181 ClassTemplateSpec, TSK,
4182 PrimaryStrictPackMatch);
4183
4184 if (!Pattern.isUsable())
4185 return Pattern.isInvalid();
4186
4187 // Deduction has picked the pattern this specialization will be instantiated
4188 // from, which may be a declaration an external AST source has yet to define.
4189 if (!Pattern.get()->isCompleteDefinition() &&
4190 Pattern.get()->hasExternalLexicalStorage())
4191 if (ExternalASTSource *Source = Context.getExternalSource())
4192 Source->CompleteType(Tag: Pattern.get());
4193
4194 bool Err = InstantiateClassImpl(
4195 PointOfInstantiation, Instantiation: ClassTemplateSpec, Pattern: Pattern.get(),
4196 TemplateArgs: getTemplateInstantiationArgs(ND: ClassTemplateSpec), TSK, Complain);
4197
4198 // If we haven't already warn on avaibility, consider the avaibility
4199 // attributes of the partial specialization.
4200 // Note that - because we need to have deduced the partial specialization -
4201 // We can only emit these warnings when the specialization is instantiated.
4202 if (!Err && !HadAvaibilityWarning) {
4203 assert(ClassTemplateSpec->getTemplateSpecializationKind() !=
4204 TSK_Undeclared);
4205 DiagnoseAvailabilityOfDecl(D: ClassTemplateSpec, Locs: PointOfInstantiation);
4206 }
4207 return Err;
4208}
4209
4210void
4211Sema::InstantiateClassMembers(SourceLocation PointOfInstantiation,
4212 CXXRecordDecl *Instantiation,
4213 const MultiLevelTemplateArgumentList &TemplateArgs,
4214 TemplateSpecializationKind TSK) {
4215 // FIXME: We need to notify the ASTMutationListener that we did all of these
4216 // things, in case we have an explicit instantiation definition in a PCM, a
4217 // module, or preamble, and the declaration is in an imported AST.
4218 assert(
4219 (TSK == TSK_ExplicitInstantiationDefinition ||
4220 TSK == TSK_ExplicitInstantiationDeclaration ||
4221 (TSK == TSK_ImplicitInstantiation && Instantiation->isLocalClass())) &&
4222 "Unexpected template specialization kind!");
4223 for (auto *D : Instantiation->decls()) {
4224 bool SuppressNew = false;
4225 if (auto *Function = dyn_cast<FunctionDecl>(Val: D)) {
4226 if (FunctionDecl *Pattern =
4227 Function->getInstantiatedFromMemberFunction()) {
4228
4229 if (Function->getTrailingRequiresClause()) {
4230 ConstraintSatisfaction Satisfaction;
4231 if (CheckFunctionConstraints(FD: Function, Satisfaction) ||
4232 !Satisfaction.IsSatisfied) {
4233 continue;
4234 }
4235 }
4236
4237 if (Function->hasAttr<ExcludeFromExplicitInstantiationAttr>())
4238 continue;
4239
4240 TemplateSpecializationKind PrevTSK =
4241 Function->getTemplateSpecializationKind();
4242 if (PrevTSK == TSK_ExplicitSpecialization)
4243 continue;
4244
4245 if (CheckSpecializationInstantiationRedecl(
4246 NewLoc: PointOfInstantiation, ActOnExplicitInstantiationNewTSK: TSK, PrevDecl: Function, PrevTSK,
4247 PrevPtOfInstantiation: Function->getPointOfInstantiation(), SuppressNew) ||
4248 SuppressNew)
4249 continue;
4250
4251 // C++11 [temp.explicit]p8:
4252 // An explicit instantiation definition that names a class template
4253 // specialization explicitly instantiates the class template
4254 // specialization and is only an explicit instantiation definition
4255 // of members whose definition is visible at the point of
4256 // instantiation.
4257 if (TSK == TSK_ExplicitInstantiationDefinition && !Pattern->isDefined())
4258 continue;
4259
4260 Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
4261
4262 if (Function->isDefined()) {
4263 // Let the ASTConsumer know that this function has been explicitly
4264 // instantiated now, and its linkage might have changed.
4265 Consumer.HandleTopLevelDecl(D: DeclGroupRef(Function));
4266 } else if (TSK == TSK_ExplicitInstantiationDefinition) {
4267 InstantiateFunctionDefinition(PointOfInstantiation, Function);
4268 } else if (TSK == TSK_ImplicitInstantiation) {
4269 PendingLocalImplicitInstantiations.push_back(
4270 x: std::make_pair(x&: Function, y&: PointOfInstantiation));
4271 }
4272 }
4273 } else if (auto *Var = dyn_cast<VarDecl>(Val: D)) {
4274 if (isa<VarTemplateSpecializationDecl>(Val: Var))
4275 continue;
4276
4277 if (Var->isStaticDataMember()) {
4278 if (Var->hasAttr<ExcludeFromExplicitInstantiationAttr>())
4279 continue;
4280
4281 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
4282 assert(MSInfo && "No member specialization information?");
4283 if (MSInfo->getTemplateSpecializationKind()
4284 == TSK_ExplicitSpecialization)
4285 continue;
4286
4287 if (CheckSpecializationInstantiationRedecl(NewLoc: PointOfInstantiation, ActOnExplicitInstantiationNewTSK: TSK,
4288 PrevDecl: Var,
4289 PrevTSK: MSInfo->getTemplateSpecializationKind(),
4290 PrevPtOfInstantiation: MSInfo->getPointOfInstantiation(),
4291 SuppressNew) ||
4292 SuppressNew)
4293 continue;
4294
4295 if (TSK == TSK_ExplicitInstantiationDefinition) {
4296 // C++0x [temp.explicit]p8:
4297 // An explicit instantiation definition that names a class template
4298 // specialization explicitly instantiates the class template
4299 // specialization and is only an explicit instantiation definition
4300 // of members whose definition is visible at the point of
4301 // instantiation.
4302 if (!Var->getInstantiatedFromStaticDataMember()->getDefinition())
4303 continue;
4304
4305 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
4306 InstantiateVariableDefinition(PointOfInstantiation, Var);
4307 } else {
4308 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
4309 }
4310 }
4311 } else if (auto *Record = dyn_cast<CXXRecordDecl>(Val: D)) {
4312 if (Record->hasAttr<ExcludeFromExplicitInstantiationAttr>())
4313 continue;
4314
4315 // Always skip the injected-class-name, along with any
4316 // redeclarations of nested classes, since both would cause us
4317 // to try to instantiate the members of a class twice.
4318 // Skip closure types; they'll get instantiated when we instantiate
4319 // the corresponding lambda-expression.
4320 if (Record->isInjectedClassName() || Record->getPreviousDecl() ||
4321 Record->isLambda())
4322 continue;
4323
4324 MemberSpecializationInfo *MSInfo = Record->getMemberSpecializationInfo();
4325 assert(MSInfo && "No member specialization information?");
4326
4327 if (MSInfo->getTemplateSpecializationKind()
4328 == TSK_ExplicitSpecialization)
4329 continue;
4330
4331 if (Context.getTargetInfo().getTriple().isOSWindows() &&
4332 TSK == TSK_ExplicitInstantiationDeclaration) {
4333 // On Windows, explicit instantiation decl of the outer class doesn't
4334 // affect the inner class. Typically extern template declarations are
4335 // used in combination with dll import/export annotations, but those
4336 // are not propagated from the outer class templates to inner classes.
4337 // Therefore, do not instantiate inner classes on this platform, so
4338 // that users don't end up with undefined symbols during linking.
4339 continue;
4340 }
4341
4342 if (CheckSpecializationInstantiationRedecl(NewLoc: PointOfInstantiation, ActOnExplicitInstantiationNewTSK: TSK,
4343 PrevDecl: Record,
4344 PrevTSK: MSInfo->getTemplateSpecializationKind(),
4345 PrevPtOfInstantiation: MSInfo->getPointOfInstantiation(),
4346 SuppressNew) ||
4347 SuppressNew)
4348 continue;
4349
4350 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
4351 assert(Pattern && "Missing instantiated-from-template information");
4352
4353 if (!Record->getDefinition()) {
4354 if (!Pattern->getDefinition()) {
4355 // C++0x [temp.explicit]p8:
4356 // An explicit instantiation definition that names a class template
4357 // specialization explicitly instantiates the class template
4358 // specialization and is only an explicit instantiation definition
4359 // of members whose definition is visible at the point of
4360 // instantiation.
4361 if (TSK == TSK_ExplicitInstantiationDeclaration) {
4362 MSInfo->setTemplateSpecializationKind(TSK);
4363 MSInfo->setPointOfInstantiation(PointOfInstantiation);
4364 }
4365
4366 continue;
4367 }
4368
4369 InstantiateClass(PointOfInstantiation, Instantiation: Record, Pattern,
4370 TemplateArgs,
4371 TSK);
4372 } else {
4373 if (TSK == TSK_ExplicitInstantiationDefinition &&
4374 Record->getTemplateSpecializationKind() ==
4375 TSK_ExplicitInstantiationDeclaration) {
4376 Record->setTemplateSpecializationKind(TSK);
4377 MarkVTableUsed(Loc: PointOfInstantiation, Class: Record, DefinitionRequired: true);
4378 }
4379 }
4380
4381 Pattern = cast_or_null<CXXRecordDecl>(Val: Record->getDefinition());
4382 if (Pattern)
4383 InstantiateClassMembers(PointOfInstantiation, Instantiation: Pattern, TemplateArgs,
4384 TSK);
4385 } else if (auto *Enum = dyn_cast<EnumDecl>(Val: D)) {
4386 MemberSpecializationInfo *MSInfo = Enum->getMemberSpecializationInfo();
4387 assert(MSInfo && "No member specialization information?");
4388
4389 if (MSInfo->getTemplateSpecializationKind()
4390 == TSK_ExplicitSpecialization)
4391 continue;
4392
4393 if (CheckSpecializationInstantiationRedecl(
4394 NewLoc: PointOfInstantiation, ActOnExplicitInstantiationNewTSK: TSK, PrevDecl: Enum,
4395 PrevTSK: MSInfo->getTemplateSpecializationKind(),
4396 PrevPtOfInstantiation: MSInfo->getPointOfInstantiation(), SuppressNew) ||
4397 SuppressNew)
4398 continue;
4399
4400 if (Enum->getDefinition())
4401 continue;
4402
4403 EnumDecl *Pattern = Enum->getTemplateInstantiationPattern();
4404 assert(Pattern && "Missing instantiated-from-template information");
4405
4406 if (TSK == TSK_ExplicitInstantiationDefinition) {
4407 if (!Pattern->getDefinition())
4408 continue;
4409
4410 InstantiateEnum(PointOfInstantiation, Instantiation: Enum, Pattern, TemplateArgs, TSK);
4411 } else {
4412 MSInfo->setTemplateSpecializationKind(TSK);
4413 MSInfo->setPointOfInstantiation(PointOfInstantiation);
4414 }
4415 } else if (auto *Field = dyn_cast<FieldDecl>(Val: D)) {
4416 // No need to instantiate in-class initializers during explicit
4417 // instantiation.
4418 if (Field->hasInClassInitializer() && TSK == TSK_ImplicitInstantiation) {
4419 // Handle local classes which could have substituted template params.
4420 CXXRecordDecl *ClassPattern =
4421 Instantiation->isLocalClass()
4422 ? Instantiation->getInstantiatedFromMemberClass()
4423 : Instantiation->getTemplateInstantiationPattern();
4424
4425 DeclContext::lookup_result Lookup =
4426 ClassPattern->lookup(Name: Field->getDeclName());
4427 FieldDecl *Pattern = Lookup.find_first<FieldDecl>();
4428 assert(Pattern);
4429 InstantiateInClassInitializer(PointOfInstantiation, Instantiation: Field, Pattern,
4430 TemplateArgs);
4431 }
4432 }
4433 }
4434}
4435
4436void
4437Sema::InstantiateClassTemplateSpecializationMembers(
4438 SourceLocation PointOfInstantiation,
4439 ClassTemplateSpecializationDecl *ClassTemplateSpec,
4440 TemplateSpecializationKind TSK) {
4441 // C++0x [temp.explicit]p7:
4442 // An explicit instantiation that names a class template
4443 // specialization is an explicit instantion of the same kind
4444 // (declaration or definition) of each of its members (not
4445 // including members inherited from base classes) that has not
4446 // been previously explicitly specialized in the translation unit
4447 // containing the explicit instantiation, except as described
4448 // below.
4449 InstantiateClassMembers(PointOfInstantiation, Instantiation: ClassTemplateSpec,
4450 TemplateArgs: getTemplateInstantiationArgs(ND: ClassTemplateSpec),
4451 TSK);
4452}
4453
4454StmtResult
4455Sema::SubstStmt(Stmt *S, const MultiLevelTemplateArgumentList &TemplateArgs) {
4456 if (!S)
4457 return S;
4458
4459 TemplateInstantiator Instantiator(*this, TemplateArgs,
4460 SourceLocation(),
4461 DeclarationName());
4462 return Instantiator.TransformStmt(S);
4463}
4464
4465bool Sema::SubstTemplateArgument(
4466 const TemplateArgumentLoc &Input,
4467 const MultiLevelTemplateArgumentList &TemplateArgs,
4468 TemplateArgumentLoc &Output, SourceLocation Loc,
4469 const DeclarationName &Entity) {
4470 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity);
4471 return Instantiator.TransformTemplateArgument(Input, Output);
4472}
4473
4474bool Sema::SubstTemplateArguments(
4475 ArrayRef<TemplateArgumentLoc> Args,
4476 const MultiLevelTemplateArgumentList &TemplateArgs,
4477 TemplateArgumentListInfo &Out) {
4478 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
4479 DeclarationName());
4480 return Instantiator.TransformTemplateArguments(First: Args.begin(), Last: Args.end(), Outputs&: Out);
4481}
4482
4483bool Sema::SubstTemplateArgumentsInParameterMapping(
4484 ArrayRef<TemplateArgumentLoc> Args, SourceLocation BaseLoc,
4485 const MultiLevelTemplateArgumentList &TemplateArgs,
4486 TemplateArgumentListInfo &Out) {
4487 TemplateInstantiator Instantiator(
4488 TemplateInstantiator::ForParameterMappingSubstitution, *this, BaseLoc,
4489 TemplateArgs, CurrentCachedTemplateArgs);
4490 return Instantiator.TransformTemplateArguments(First: Args.begin(), Last: Args.end(), Outputs&: Out);
4491}
4492
4493UnsignedOrNone Sema::EvaluateFoldExpandedConstraintSize(
4494 const Expr *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs) {
4495 TemplateInstantiator Instantiator(
4496 TemplateInstantiator::ForConstraintSubstitution, *this, TemplateArgs,
4497 SourceLocation(), DeclarationName());
4498
4499 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
4500 collectUnexpandedParameterPacks(E: const_cast<Expr *>(Pattern), Unexpanded);
4501 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
4502
4503 bool Expand = true;
4504 bool RetainExpansion = false;
4505 UnsignedOrNone NumExpansions(std::nullopt);
4506 if (Instantiator.TryExpandParameterPacks(
4507 EllipsisLoc: Pattern->getExprLoc(), PatternRange: Pattern->getSourceRange(), Unexpanded,
4508 /*FailOnPackProducingTemplates=*/false, ShouldExpand&: Expand, RetainExpansion,
4509 NumExpansions, /*Diagnose=*/false) ||
4510 !Expand || RetainExpansion)
4511 return std::nullopt;
4512
4513 if (NumExpansions && getLangOpts().BracketDepth < *NumExpansions)
4514 return std::nullopt;
4515 return NumExpansions;
4516}
4517
4518ExprResult
4519Sema::SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs) {
4520 if (!E)
4521 return E;
4522
4523 TemplateInstantiator Instantiator(*this, TemplateArgs,
4524 SourceLocation(),
4525 DeclarationName());
4526 return Instantiator.TransformExpr(E);
4527}
4528
4529ExprResult
4530Sema::SubstCXXIdExpr(Expr *E,
4531 const MultiLevelTemplateArgumentList &TemplateArgs) {
4532 if (!E)
4533 return E;
4534
4535 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
4536 DeclarationName());
4537 return Instantiator.TransformAddressOfOperand(E);
4538}
4539
4540ExprResult
4541Sema::SubstConstraintExpr(Expr *E,
4542 const MultiLevelTemplateArgumentList &TemplateArgs) {
4543 if (!E)
4544 return E;
4545
4546 TemplateInstantiator Instantiator(
4547 TemplateInstantiator::ForConstraintSubstitution, *this, TemplateArgs,
4548 SourceLocation(), DeclarationName());
4549 return Instantiator.TransformExpr(E);
4550}
4551
4552ExprResult Sema::SubstConstraintExprWithoutSatisfaction(
4553 Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs) {
4554 if (!E)
4555 return E;
4556
4557 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
4558 DeclarationName());
4559 Instantiator.setEvaluateConstraints(false);
4560 return Instantiator.TransformExpr(E);
4561}
4562
4563ExprResult Sema::SubstConceptTemplateArguments(
4564 const ConceptSpecializationExpr *CSE, const Expr *ConstraintExpr,
4565 const MultiLevelTemplateArgumentList &MLTAL) {
4566 assert(isSFINAEContext());
4567
4568 TemplateInstantiator Instantiator(*this, MLTAL, SourceLocation(),
4569 DeclarationName());
4570 const ASTTemplateArgumentListInfo *ArgsAsWritten =
4571 CSE->getTemplateArgsAsWritten();
4572 TemplateArgumentListInfo SubstArgs(ArgsAsWritten->getLAngleLoc(),
4573 ArgsAsWritten->getRAngleLoc());
4574
4575 if (Instantiator.TransformConceptTemplateArguments(
4576 First: ArgsAsWritten->getTemplateArgs(),
4577 Last: ArgsAsWritten->getTemplateArgs() +
4578 ArgsAsWritten->getNumTemplateArgs(),
4579 Outputs&: SubstArgs))
4580 return true;
4581
4582 llvm::SmallVector<TemplateArgument, 4> NewArgList = llvm::map_to_vector(
4583 C: SubstArgs.arguments(),
4584 F: [](const TemplateArgumentLoc &Loc) { return Loc.getArgument(); });
4585
4586 MultiLevelTemplateArgumentList MLTALForConstraint =
4587 getTemplateInstantiationArgs(
4588 ND: CSE->getConceptDecl(), DC: CSE->getConceptDecl()->getLexicalDeclContext(),
4589 /*Final=*/false,
4590 /*Innermost=*/NewArgList,
4591 /*RelativeToPrimary=*/true,
4592 /*Pattern=*/nullptr,
4593 /*ForConstraintInstantiation=*/true);
4594
4595 // Rebuild a constraint, only substituting non-dependent concept names
4596 // and nothing else.
4597 // Given C<SomeType, SomeValue, SomeConceptName, SomeDependentConceptName>.
4598 // only SomeConceptName is substituted, in the constraint expression of C.
4599 struct ConstraintExprTransformer : TreeTransform<ConstraintExprTransformer> {
4600 using Base = TreeTransform<ConstraintExprTransformer>;
4601 MultiLevelTemplateArgumentList &MLTAL;
4602
4603 ConstraintExprTransformer(Sema &SemaRef,
4604 MultiLevelTemplateArgumentList &MLTAL)
4605 : TreeTransform(SemaRef), MLTAL(MLTAL) {}
4606
4607 ExprResult TransformExpr(Expr *E) {
4608 if (!E)
4609 return E;
4610 switch (E->getStmtClass()) {
4611 case Stmt::BinaryOperatorClass:
4612 case Stmt::ConceptSpecializationExprClass:
4613 case Stmt::ParenExprClass:
4614 case Stmt::UnresolvedLookupExprClass:
4615 case Stmt::DependentTemplateIdExprClass:
4616 return Base::TransformExpr(E);
4617 default:
4618 break;
4619 }
4620 return E;
4621 }
4622
4623 // Rebuild both branches of a conjunction / disjunction
4624 // even if there is a substitution failure in one of
4625 // the branch.
4626 ExprResult TransformBinaryOperator(BinaryOperator *E) {
4627 if (!(E->getOpcode() == BinaryOperatorKind::BO_LAnd ||
4628 E->getOpcode() == BinaryOperatorKind::BO_LOr))
4629 return E;
4630
4631 ExprResult LHS = TransformExpr(E: E->getLHS());
4632 ExprResult RHS = TransformExpr(E: E->getRHS());
4633
4634 if (LHS.get() == E->getLHS() && RHS.get() == E->getRHS())
4635 return E;
4636
4637 return BinaryOperator::Create(C: SemaRef.Context, lhs: LHS.get(), rhs: RHS.get(),
4638 opc: E->getOpcode(), ResTy: SemaRef.Context.BoolTy,
4639 VK: VK_PRValue, OK: OK_Ordinary,
4640 opLoc: E->getOperatorLoc(), FPFeatures: FPOptionsOverride{});
4641 }
4642
4643 bool TransformTemplateArgument(const TemplateArgumentLoc &Input,
4644 TemplateArgumentLoc &Output,
4645 bool Uneval = false) {
4646 if (Input.getArgument().isConceptOrConceptTemplateParameter())
4647 return Base::TransformTemplateArgument(Input, Output, Uneval);
4648
4649 Output = Input;
4650 return false;
4651 }
4652
4653 ExprResult RebuildConceptSpecialization(ConceptDecl *ResolvedConcept,
4654 SourceLocation NameLoc,
4655 SourceLocation LAngleLoc,
4656 SourceLocation RAngleLoc,
4657 const TemplateArgumentLoc *Args,
4658 unsigned NumArgs) {
4659 TemplateArgumentListInfo TransArgs(LAngleLoc, RAngleLoc);
4660 if (TransformTemplateArguments(Inputs: Args, NumInputs: NumArgs, Outputs&: TransArgs))
4661 return ExprError();
4662
4663 CXXScopeSpec SS;
4664 DeclarationNameInfo NameInfo(ResolvedConcept->getDeclName(), NameLoc);
4665 return SemaRef.CheckConceptTemplateId(SS, TemplateKWLoc: SourceLocation(), ConceptNameInfo: NameInfo,
4666 FoundDecl: ResolvedConcept, NamedConcept: ResolvedConcept,
4667 TemplateArgs: &TransArgs, DoCheckConstraintSatisfaction: false);
4668 }
4669
4670 ExprResult TransformDependentTemplateIdExpr(DependentTemplateIdExpr *E) {
4671 if (!E->isConceptReference())
4672 return E;
4673
4674 TemplateTemplateParmDecl *TTP = E->getParameter();
4675 unsigned Depth = TTP->getDepth();
4676 unsigned Pos = TTP->getPosition();
4677 if (!MLTAL.hasTemplateArgument(Depth, Index: Pos))
4678 return E;
4679
4680 TemplateArgument Arg = MLTAL(Depth, Pos);
4681 if (PackIndexingTemplateStorage *PI =
4682 E->getTemplateName().getAsPackIndexingTemplate()) {
4683 UnsignedOrNone Index = PI->getSelectedIndex();
4684 if (Arg.getKind() != TemplateArgument::Pack || !Index ||
4685 *Index >= Arg.pack_size())
4686 return E;
4687 Arg = Arg.getPackAsArray()[*Index];
4688 }
4689 if (Arg.getKind() != TemplateArgument::Template)
4690 return E;
4691 ConceptDecl *ResolvedConcept = dyn_cast_if_present<ConceptDecl>(
4692 Val: Arg.getAsTemplate().getAsTemplateDecl());
4693 if (!ResolvedConcept)
4694 return E;
4695
4696 return RebuildConceptSpecialization(ResolvedConcept, NameLoc: E->getNameLoc(),
4697 LAngleLoc: E->getLAngleLoc(), RAngleLoc: E->getRAngleLoc(),
4698 Args: E->template_arguments().data(),
4699 NumArgs: E->getNumTemplateArgs());
4700 }
4701 };
4702
4703 ConstraintExprTransformer Transformer(*this, MLTALForConstraint);
4704 ExprResult Res =
4705 Transformer.TransformExpr(E: const_cast<Expr *>(ConstraintExpr));
4706 return Res;
4707}
4708
4709ExprResult Sema::SubstInitializer(Expr *Init,
4710 const MultiLevelTemplateArgumentList &TemplateArgs,
4711 bool CXXDirectInit) {
4712 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
4713 DeclarationName());
4714 return Instantiator.TransformInitializer(Init, NotCopyInit: CXXDirectInit);
4715}
4716
4717bool Sema::SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
4718 const MultiLevelTemplateArgumentList &TemplateArgs,
4719 SmallVectorImpl<Expr *> &Outputs) {
4720 if (Exprs.empty())
4721 return false;
4722
4723 TemplateInstantiator Instantiator(*this, TemplateArgs,
4724 SourceLocation(),
4725 DeclarationName());
4726 return Instantiator.TransformExprs(Inputs: Exprs.data(), NumInputs: Exprs.size(),
4727 IsCall, Outputs);
4728}
4729
4730NestedNameSpecifierLoc
4731Sema::SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
4732 const MultiLevelTemplateArgumentList &TemplateArgs) {
4733 if (!NNS)
4734 return NestedNameSpecifierLoc();
4735
4736 TemplateInstantiator Instantiator(*this, TemplateArgs, NNS.getBeginLoc(),
4737 DeclarationName());
4738 return Instantiator.TransformNestedNameSpecifierLoc(NNS);
4739}
4740
4741DeclarationNameInfo
4742Sema::SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
4743 const MultiLevelTemplateArgumentList &TemplateArgs) {
4744 TemplateInstantiator Instantiator(*this, TemplateArgs, NameInfo.getLoc(),
4745 NameInfo.getName());
4746 return Instantiator.TransformDeclarationNameInfo(NameInfo);
4747}
4748
4749TemplateName
4750Sema::SubstTemplateName(SourceLocation TemplateKWLoc,
4751 NestedNameSpecifierLoc &QualifierLoc, TemplateName Name,
4752 SourceLocation NameLoc,
4753 const MultiLevelTemplateArgumentList &TemplateArgs) {
4754 TemplateInstantiator Instantiator(*this, TemplateArgs, NameLoc,
4755 DeclarationName());
4756 return Instantiator.TransformTemplateName(QualifierLoc, TemplateKWLoc, Name,
4757 NameLoc);
4758}
4759
4760static const Decl *getCanonicalParmVarDecl(const Decl *D) {
4761 // When storing ParmVarDecls in the local instantiation scope, we always
4762 // want to use the ParmVarDecl from the canonical function declaration,
4763 // since the map is then valid for any redeclaration or definition of that
4764 // function.
4765 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(Val: D)) {
4766 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: PV->getDeclContext())) {
4767 unsigned i = PV->getFunctionScopeIndex();
4768 // This parameter might be from a freestanding function type within the
4769 // function and isn't necessarily referring to one of FD's parameters.
4770 if (i < FD->getNumParams() && FD->getParamDecl(i) == PV)
4771 return FD->getCanonicalDecl()->getParamDecl(i);
4772 }
4773 }
4774 return D;
4775}
4776
4777llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> *
4778LocalInstantiationScope::getInstantiationOfIfExists(const Decl *D) {
4779 D = getCanonicalParmVarDecl(D);
4780 for (LocalInstantiationScope *Current = this; Current;
4781 Current = Current->Outer) {
4782
4783 // Check if we found something within this scope.
4784 const Decl *CheckD = D;
4785 do {
4786 LocalDeclsMap::iterator Found = Current->LocalDecls.find(Val: CheckD);
4787 if (Found != Current->LocalDecls.end())
4788 return &Found->second;
4789
4790 // If this is a tag declaration, it's possible that we need to look for
4791 // a previous declaration.
4792 if (const TagDecl *Tag = dyn_cast<TagDecl>(Val: CheckD))
4793 CheckD = Tag->getPreviousDecl();
4794 else
4795 CheckD = nullptr;
4796 } while (CheckD);
4797
4798 // If we aren't combined with our outer scope, we're done.
4799 if (!Current->CombineWithOuterScope)
4800 break;
4801 }
4802
4803 return nullptr;
4804}
4805
4806llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> *
4807LocalInstantiationScope::findInstantiationOf(const Decl *D) {
4808 auto *Result = getInstantiationOfIfExists(D);
4809 if (Result)
4810 return Result;
4811 // If we're performing a partial substitution during template argument
4812 // deduction, we may not have values for template parameters yet.
4813 if (isa<NonTypeTemplateParmDecl>(Val: D) || isa<TemplateTypeParmDecl>(Val: D) ||
4814 isa<TemplateTemplateParmDecl>(Val: D))
4815 return nullptr;
4816
4817 // Local types referenced prior to definition may require instantiation.
4818 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: D))
4819 if (RD->isLocalClass())
4820 return nullptr;
4821
4822 // Enumeration types referenced prior to definition may appear as a result of
4823 // error recovery.
4824 if (isa<EnumDecl>(Val: D))
4825 return nullptr;
4826
4827 // Materialized typedefs/type alias for implicit deduction guides may require
4828 // instantiation.
4829 if (isa<TypedefNameDecl>(Val: D) &&
4830 isa<CXXDeductionGuideDecl>(Val: D->getDeclContext()))
4831 return nullptr;
4832
4833 // If we didn't find the decl, then we either have a sema bug, or we have a
4834 // forward reference to a label declaration. Return null to indicate that
4835 // we have an uninstantiated label.
4836 assert(isa<LabelDecl>(D) && "declaration not instantiated in this scope");
4837 return nullptr;
4838}
4839
4840void LocalInstantiationScope::InstantiatedLocal(const Decl *D, Decl *Inst) {
4841 D = getCanonicalParmVarDecl(D);
4842 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
4843 if (Stored.isNull()) {
4844#ifndef NDEBUG
4845 // It should not be present in any surrounding scope either.
4846 LocalInstantiationScope *Current = this;
4847 while (Current->CombineWithOuterScope && Current->Outer) {
4848 Current = Current->Outer;
4849 assert(!Current->LocalDecls.contains(D) &&
4850 "Instantiated local in inner and outer scopes");
4851 }
4852#endif
4853 Stored = Inst;
4854 } else if (DeclArgumentPack *Pack = dyn_cast<DeclArgumentPack *>(Val&: Stored)) {
4855 Pack->push_back(Elt: cast<ValueDecl>(Val: Inst));
4856 } else {
4857 assert(cast<Decl *>(Stored) == Inst && "Already instantiated this local");
4858 }
4859}
4860
4861void LocalInstantiationScope::InstantiatedLocalPackArg(const Decl *D,
4862 VarDecl *Inst) {
4863 D = getCanonicalParmVarDecl(D);
4864 DeclArgumentPack *Pack = cast<DeclArgumentPack *>(Val&: LocalDecls[D]);
4865 Pack->push_back(Elt: Inst);
4866}
4867
4868void LocalInstantiationScope::MakeInstantiatedLocalArgPack(const Decl *D) {
4869#ifndef NDEBUG
4870 // This should be the first time we've been told about this decl.
4871 for (LocalInstantiationScope *Current = this;
4872 Current && Current->CombineWithOuterScope; Current = Current->Outer)
4873 assert(!Current->LocalDecls.contains(D) &&
4874 "Creating local pack after instantiation of local");
4875#endif
4876
4877 D = getCanonicalParmVarDecl(D);
4878 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
4879 DeclArgumentPack *Pack = new DeclArgumentPack;
4880 Stored = Pack;
4881 ArgumentPacks.push_back(Elt: Pack);
4882}
4883
4884bool LocalInstantiationScope::isLocalPackExpansion(const Decl *D) {
4885 for (DeclArgumentPack *Pack : ArgumentPacks)
4886 if (llvm::is_contained(Range&: *Pack, Element: D))
4887 return true;
4888 return false;
4889}
4890
4891void LocalInstantiationScope::SetPartiallySubstitutedPack(NamedDecl *Pack,
4892 const TemplateArgument *ExplicitArgs,
4893 unsigned NumExplicitArgs) {
4894 assert((!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack) &&
4895 "Already have a partially-substituted pack");
4896 assert((!PartiallySubstitutedPack
4897 || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) &&
4898 "Wrong number of arguments in partially-substituted pack");
4899 PartiallySubstitutedPack = Pack;
4900 ArgsInPartiallySubstitutedPack = ExplicitArgs;
4901 NumArgsInPartiallySubstitutedPack = NumExplicitArgs;
4902}
4903
4904NamedDecl *LocalInstantiationScope::getPartiallySubstitutedPack(
4905 const TemplateArgument **ExplicitArgs,
4906 unsigned *NumExplicitArgs) const {
4907 if (ExplicitArgs)
4908 *ExplicitArgs = nullptr;
4909 if (NumExplicitArgs)
4910 *NumExplicitArgs = 0;
4911
4912 for (const LocalInstantiationScope *Current = this; Current;
4913 Current = Current->Outer) {
4914 if (Current->PartiallySubstitutedPack) {
4915 if (ExplicitArgs)
4916 *ExplicitArgs = Current->ArgsInPartiallySubstitutedPack;
4917 if (NumExplicitArgs)
4918 *NumExplicitArgs = Current->NumArgsInPartiallySubstitutedPack;
4919
4920 return Current->PartiallySubstitutedPack;
4921 }
4922
4923 if (!Current->CombineWithOuterScope)
4924 break;
4925 }
4926
4927 return nullptr;
4928}
4929