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 dyn_cast<ClassTemplatePartialSpecializationDecl *>(
261 Val: ClassTemplSpec->getSpecializedTemplateOrPartial()))
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 } else if (DFK.isPostfixOperator()) {
1172 // The declared return type of a defaulted postfix operator is the
1173 // type for which it is defaulted.
1174 DiagFunc(Active->PointOfInstantiation,
1175 PDiag(DiagID: diag::note_postfix_operator_synthesized_at)
1176 << (int)DFK.asPostfixOperator()
1177 << FD->getReturnType().getUnqualifiedType());
1178 }
1179 break;
1180 }
1181
1182 case CodeSynthesisContext::RewritingOperatorAsSpaceship:
1183 DiagFunc(Active->Entity->getLocation(),
1184 PDiag(DiagID: diag::note_rewriting_operator_as_spaceship));
1185 break;
1186
1187 case CodeSynthesisContext::InitializingStructuredBinding:
1188 DiagFunc(Active->PointOfInstantiation,
1189 PDiag(DiagID: diag::note_in_binding_decl_init)
1190 << cast<BindingDecl>(Val: Active->Entity));
1191 break;
1192
1193 case CodeSynthesisContext::MarkingClassDllexported:
1194 DiagFunc(Active->PointOfInstantiation,
1195 PDiag(DiagID: diag::note_due_to_dllexported_class)
1196 << cast<CXXRecordDecl>(Val: Active->Entity)
1197 << !getLangOpts().CPlusPlus11);
1198 break;
1199
1200 case CodeSynthesisContext::BuildingBuiltinDumpStructCall:
1201 DiagFunc(Active->PointOfInstantiation,
1202 PDiag(DiagID: diag::note_building_builtin_dump_struct_call)
1203 << convertCallArgsToString(
1204 S&: *this, Args: llvm::ArrayRef(Active->CallArgs,
1205 Active->NumCallArgs)));
1206 break;
1207
1208 case CodeSynthesisContext::Memoization:
1209 break;
1210
1211 case CodeSynthesisContext::LambdaExpressionSubstitution:
1212 DiagFunc(Active->PointOfInstantiation,
1213 PDiag(DiagID: diag::note_lambda_substitution_here));
1214 break;
1215 case CodeSynthesisContext::ConstraintsCheck: {
1216 unsigned DiagID = 0;
1217 if (!Active->Entity) {
1218 DiagFunc(Active->PointOfInstantiation,
1219 PDiag(DiagID: diag::note_nested_requirement_here)
1220 << Active->InstantiationRange);
1221 break;
1222 }
1223 if (isa<ConceptDecl>(Val: Active->Entity))
1224 DiagID = diag::note_concept_specialization_here;
1225 else if (isa<TemplateDecl>(Val: Active->Entity))
1226 DiagID = diag::note_checking_constraints_for_template_id_here;
1227 else if (isa<VarTemplatePartialSpecializationDecl>(Val: Active->Entity))
1228 DiagID = diag::note_checking_constraints_for_var_spec_id_here;
1229 else if (isa<ClassTemplatePartialSpecializationDecl>(Val: Active->Entity))
1230 DiagID = diag::note_checking_constraints_for_class_spec_id_here;
1231 else {
1232 assert(isa<FunctionDecl>(Active->Entity));
1233 DiagID = diag::note_checking_constraints_for_function_here;
1234 }
1235 SmallString<128> TemplateArgsStr;
1236 llvm::raw_svector_ostream OS(TemplateArgsStr);
1237 cast<NamedDecl>(Val: Active->Entity)->printName(OS, Policy: getPrintingPolicy());
1238 if (!isa<FunctionDecl>(Val: Active->Entity)) {
1239 printTemplateArgumentList(OS, Args: Active->template_arguments(),
1240 Policy: getPrintingPolicy());
1241 }
1242 DiagFunc(Active->PointOfInstantiation,
1243 PDiag(DiagID) << OS.str() << Active->InstantiationRange);
1244 break;
1245 }
1246 case CodeSynthesisContext::ConstraintSubstitution:
1247 DiagFunc(Active->PointOfInstantiation,
1248 PDiag(DiagID: diag::note_constraint_substitution_here)
1249 << Active->InstantiationRange);
1250 break;
1251 case CodeSynthesisContext::ParameterMappingSubstitution:
1252 DiagFunc(Active->PointOfInstantiation,
1253 PDiag(DiagID: diag::note_parameter_mapping_substitution_here)
1254 << Active->InstantiationRange);
1255 break;
1256 case CodeSynthesisContext::BuildingDeductionGuides:
1257 DiagFunc(Active->PointOfInstantiation,
1258 PDiag(DiagID: diag::note_building_deduction_guide_here));
1259 break;
1260 case CodeSynthesisContext::TypeAliasTemplateInstantiation:
1261 // Workaround for a workaround: don't produce a note if we are merely
1262 // instantiating some other template which contains this alias template.
1263 // This would be redundant either with the error itself, or some other
1264 // context note attached to it.
1265 if (Active->NumTemplateArgs == 0)
1266 break;
1267 DiagFunc(Active->PointOfInstantiation,
1268 PDiag(DiagID: diag::note_template_type_alias_instantiation_here)
1269 << cast<TypeAliasTemplateDecl>(Val: Active->Entity)
1270 << Active->InstantiationRange);
1271 break;
1272 case CodeSynthesisContext::PartialOrderingTTP:
1273 DiagFunc(Active->PointOfInstantiation,
1274 PDiag(DiagID: diag::note_template_arg_template_params_mismatch));
1275 if (SourceLocation ParamLoc = Active->Entity->getLocation();
1276 ParamLoc.isValid())
1277 DiagFunc(ParamLoc, PDiag(DiagID: diag::note_template_prev_declaration)
1278 << /*isTemplateTemplateParam=*/true
1279 << Active->InstantiationRange);
1280 break;
1281 case CodeSynthesisContext::SYCLKernelLaunchLookup: {
1282 const auto *SKEPAttr =
1283 Active->Entity->getAttr<SYCLKernelEntryPointAttr>();
1284 assert(SKEPAttr && "Missing sycl_kernel_entry_point attribute");
1285 assert(!SKEPAttr->isInvalidAttr() &&
1286 "sycl_kernel_entry_point attribute is invalid");
1287 DiagFunc(SKEPAttr->getLocation(), PDiag(DiagID: diag::note_sycl_runtime_defect));
1288 DiagFunc(SKEPAttr->getLocation(),
1289 PDiag(DiagID: diag::note_sycl_kernel_launch_lookup_here)
1290 << SKEPAttr->getKernelName());
1291 break;
1292 }
1293 case CodeSynthesisContext::SYCLKernelLaunchOverloadResolution: {
1294 const auto *SKEPAttr =
1295 Active->Entity->getAttr<SYCLKernelEntryPointAttr>();
1296 assert(SKEPAttr && "Missing sycl_kernel_entry_point attribute");
1297 assert(!SKEPAttr->isInvalidAttr() &&
1298 "sycl_kernel_entry_point attribute is invalid");
1299 DiagFunc(SKEPAttr->getLocation(), PDiag(DiagID: diag::note_sycl_runtime_defect));
1300 DiagFunc(SKEPAttr->getLocation(),
1301 PDiag(DiagID: diag::note_sycl_kernel_launch_overload_resolution_here)
1302 << SKEPAttr->getKernelName()
1303 << convertCallArgsValueCategoryAndTypeToString(
1304 S&: *this, Args: llvm::ArrayRef(Active->CallArgs,
1305 Active->NumCallArgs)));
1306 break;
1307 }
1308 case CodeSynthesisContext::ExpansionStmtInstantiation:
1309 Diags.Report(Loc: Active->PointOfInstantiation,
1310 DiagID: diag::note_expansion_stmt_instantiation_here);
1311 }
1312 }
1313}
1314
1315//===----------------------------------------------------------------------===/
1316// Template Instantiation for Types
1317//===----------------------------------------------------------------------===/
1318namespace {
1319
1320 class TemplateInstantiator : public TreeTransform<TemplateInstantiator> {
1321 const MultiLevelTemplateArgumentList &TemplateArgs;
1322 SourceLocation Loc;
1323 DeclarationName Entity;
1324 // Whether to evaluate the C++20 constraints or simply substitute into them.
1325 bool EvaluateConstraints = true;
1326 bool EvaluateLambdaConstraint = false;
1327 // Whether Substitution was Incomplete, that is, we tried to substitute in
1328 // any user provided template arguments which were null.
1329 bool IsIncomplete = false;
1330 // Whether an incomplete substituion should be treated as an error.
1331 bool BailOutOnIncomplete;
1332
1333 std::optional<llvm::FoldingSetNodeID> TemplateArgsHashValue;
1334 llvm::DenseMap<llvm::FoldingSetNodeIDRef, TemplateArgumentLoc>
1335 *CurrentCachedTemplateArgs = nullptr;
1336
1337 // While the parameters of a prototype are being substituted, the vector is
1338 // populated with the late-parsed attributes, and the scope that maps them.
1339 Sema::LateInstantiatedAttrVec *LateParmAttrs = nullptr;
1340 LocalInstantiationScope *LateParmAttrScope = nullptr;
1341
1342 bool instantiateMissingDeclsToScopeForConcepts(Decl *D);
1343
1344 public:
1345 typedef TreeTransform<TemplateInstantiator> inherited;
1346
1347 TemplateInstantiator(Sema &SemaRef,
1348 const MultiLevelTemplateArgumentList &TemplateArgs,
1349 SourceLocation Loc, DeclarationName Entity,
1350 bool BailOutOnIncomplete = false)
1351 : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc),
1352 Entity(Entity), BailOutOnIncomplete(BailOutOnIncomplete) {
1353 assert((!SemaRef.CodeSynthesisContexts.empty() ||
1354 SemaRef.isSFINAEContext()) &&
1355 "Cannot perform an instantiation without some context on the "
1356 "instantiation stack");
1357 }
1358
1359 void setEvaluateConstraints(bool B) {
1360 EvaluateConstraints = B;
1361 }
1362 bool getEvaluateConstraints() {
1363 return EvaluateConstraints;
1364 }
1365
1366 inline static struct ForParameterMappingSubstitution_t {
1367 } ForParameterMappingSubstitution;
1368
1369 inline static struct ForConstraintSubstitution_t {
1370 } ForConstraintSubstitution;
1371
1372 TemplateInstantiator(
1373 ForParameterMappingSubstitution_t, Sema &SemaRef, SourceLocation Loc,
1374 const MultiLevelTemplateArgumentList &TemplateArgs,
1375 llvm::DenseMap<llvm::FoldingSetNodeIDRef, TemplateArgumentLoc> *Cache)
1376 : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc),
1377 EvaluateLambdaConstraint(true), BailOutOnIncomplete(false),
1378 CurrentCachedTemplateArgs(Cache) {
1379 if (!Cache)
1380 return;
1381 auto &V = TemplateArgsHashValue.emplace();
1382 for (auto &Level : TemplateArgs)
1383 for (auto &Arg : Level.Args)
1384 Arg.Profile(ID&: V, Context: SemaRef.Context);
1385 }
1386
1387 TemplateInstantiator(ForConstraintSubstitution_t, Sema &SemaRef,
1388 const MultiLevelTemplateArgumentList &TemplateArgs,
1389 SourceLocation Loc, DeclarationName Entity,
1390 bool BailOutOnIncomplete = false)
1391 : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc),
1392 EvaluateLambdaConstraint(true), BailOutOnIncomplete(false) {}
1393
1394 /// Determine whether the given type \p T has already been
1395 /// transformed.
1396 ///
1397 /// For the purposes of template instantiation, a type has already been
1398 /// transformed if it is NULL or if it is not dependent.
1399 bool AlreadyTransformed(QualType T);
1400
1401 /// Returns the location of the entity being instantiated, if known.
1402 SourceLocation getBaseLocation() { return Loc; }
1403
1404 /// Returns the name of the entity being instantiated, if any.
1405 DeclarationName getBaseEntity() { return Entity; }
1406
1407 /// Returns whether any substitution so far was incomplete.
1408 bool getIsIncomplete() const { return IsIncomplete; }
1409
1410 /// Sets the "base" location and entity when that
1411 /// information is known based on another transformation.
1412 void setBase(SourceLocation Loc, DeclarationName Entity) {
1413 this->Loc = Loc;
1414 this->Entity = Entity;
1415 }
1416
1417 unsigned TransformTemplateDepth(unsigned Depth) {
1418 return TemplateArgs.getNewDepth(OldDepth: Depth);
1419 }
1420
1421 bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
1422 SourceRange PatternRange,
1423 ArrayRef<UnexpandedParameterPack> Unexpanded,
1424 bool FailOnPackProducingTemplates,
1425 bool &ShouldExpand, bool &RetainExpansion,
1426 UnsignedOrNone &NumExpansions,
1427 bool Diagnose = true) {
1428 for (UnexpandedParameterPack ParmPack : Unexpanded) {
1429 if (instantiateMissingDeclsToScopeForConcepts(
1430 D: dyn_cast<NamedDecl *>(Val&: ParmPack.first)))
1431 return true;
1432 }
1433
1434 return getSema().CheckParameterPacksForExpansion(
1435 EllipsisLoc, PatternRange, Unexpanded, TemplateArgs,
1436 FailOnPackProducingTemplates, ShouldExpand, RetainExpansion,
1437 NumExpansions, Diagnose);
1438 }
1439
1440 void ExpandingFunctionParameterPack(ParmVarDecl *Pack) {
1441 SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(D: Pack);
1442 }
1443
1444 TemplateArgument ForgetPartiallySubstitutedPack() {
1445 TemplateArgument Result;
1446 if (NamedDecl *PartialPack = SemaRef.CurrentInstantiationScope
1447 ->getPartiallySubstitutedPack()) {
1448 MultiLevelTemplateArgumentList &TemplateArgs =
1449 const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
1450 unsigned Depth, Index;
1451 std::tie(args&: Depth, args&: Index) = getDepthAndIndex(ND: PartialPack);
1452 if (TemplateArgs.hasTemplateArgument(Depth, Index)) {
1453 Result = TemplateArgs(Depth, Index);
1454 TemplateArgs.setArgument(Depth, Index, Arg: TemplateArgument());
1455 } else {
1456 IsIncomplete = true;
1457 if (BailOutOnIncomplete)
1458 return TemplateArgument();
1459 }
1460 }
1461
1462 return Result;
1463 }
1464
1465 void RememberPartiallySubstitutedPack(TemplateArgument Arg) {
1466 if (Arg.isNull())
1467 return;
1468
1469 if (NamedDecl *PartialPack = SemaRef.CurrentInstantiationScope
1470 ->getPartiallySubstitutedPack()) {
1471 MultiLevelTemplateArgumentList &TemplateArgs =
1472 const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
1473 unsigned Depth, Index;
1474 std::tie(args&: Depth, args&: Index) = getDepthAndIndex(ND: PartialPack);
1475 TemplateArgs.setArgument(Depth, Index, Arg);
1476 }
1477 }
1478
1479 MultiLevelTemplateArgumentList ForgetSubstitution() {
1480 MultiLevelTemplateArgumentList New;
1481 New.addOuterRetainedLevels(Num: this->TemplateArgs.getNumLevels());
1482
1483 MultiLevelTemplateArgumentList Old =
1484 const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
1485 const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs) =
1486 std::move(New);
1487 return Old;
1488 }
1489
1490 void RememberSubstitution(MultiLevelTemplateArgumentList Old) {
1491 const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs) =
1492 std::move(Old);
1493 }
1494
1495 TemplateArgument
1496 getTemplateArgumentPackPatternForRewrite(const TemplateArgument &TA) {
1497 if (TA.getKind() != TemplateArgument::Pack)
1498 return TA;
1499 if (SemaRef.ArgPackSubstIndex)
1500 return SemaRef.getPackSubstitutedTemplateArgument(Arg: TA);
1501 assert(TA.pack_size() == 1 && TA.pack_begin()->isPackExpansion() &&
1502 "unexpected pack arguments in template rewrite");
1503 TemplateArgument Arg = *TA.pack_begin();
1504 if (Arg.isPackExpansion())
1505 Arg = Arg.getPackExpansionPattern();
1506 return Arg;
1507 }
1508
1509 /// Transform the given declaration by instantiating a reference to
1510 /// this declaration.
1511 Decl *TransformDecl(SourceLocation Loc, Decl *D);
1512
1513 void transformAttrs(Decl *Old, Decl *New) {
1514 SemaRef.InstantiateAttrs(TemplateArgs, Pattern: Old, Inst: New);
1515 }
1516
1517 void transformedLocalDecl(Decl *Old, ArrayRef<Decl *> NewDecls) {
1518 if (Old->isParameterPack() &&
1519 (NewDecls.size() != 1 || !NewDecls.front()->isParameterPack())) {
1520 SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(D: Old);
1521 for (auto *New : NewDecls)
1522 SemaRef.CurrentInstantiationScope->InstantiatedLocalPackArg(
1523 D: Old, Inst: cast<VarDecl>(Val: New));
1524 return;
1525 }
1526
1527 assert(NewDecls.size() == 1 &&
1528 "should only have multiple expansions for a pack");
1529 Decl *New = NewDecls.front();
1530
1531 // If we've instantiated the call operator of a lambda or the call
1532 // operator template of a generic lambda, update the "instantiation of"
1533 // information.
1534 auto *NewMD = dyn_cast<CXXMethodDecl>(Val: New);
1535 if (NewMD && isLambdaCallOperator(MD: NewMD)) {
1536 auto *OldMD = dyn_cast<CXXMethodDecl>(Val: Old);
1537 if (auto *NewTD = NewMD->getDescribedFunctionTemplate())
1538 NewTD->setInstantiatedFromMemberTemplate(
1539 OldMD->getDescribedFunctionTemplate());
1540 else
1541 NewMD->setInstantiationOfMemberFunction(FD: OldMD,
1542 TSK: TSK_ImplicitInstantiation);
1543 }
1544
1545 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D: Old, Inst: New);
1546
1547 // We recreated a local declaration, but not by instantiating it. There
1548 // may be pending dependent diagnostics to produce.
1549 if (auto *DC = dyn_cast<DeclContext>(Val: Old);
1550 DC && DC->isDependentContext() && DC->isFunctionOrMethod())
1551 SemaRef.PerformDependentDiagnostics(Pattern: DC, TemplateArgs);
1552 }
1553
1554 /// Transform the definition of the given declaration by
1555 /// instantiating it.
1556 Decl *TransformDefinition(SourceLocation Loc, Decl *D);
1557
1558 /// Transform the first qualifier within a scope by instantiating the
1559 /// declaration.
1560 NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc);
1561
1562 bool TransformExceptionSpec(SourceLocation Loc,
1563 FunctionProtoType::ExceptionSpecInfo &ESI,
1564 SmallVectorImpl<QualType> &Exceptions,
1565 bool &Changed);
1566
1567 /// Rebuild the exception declaration and register the declaration
1568 /// as an instantiated local.
1569 VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
1570 TypeSourceInfo *Declarator,
1571 SourceLocation StartLoc,
1572 SourceLocation NameLoc,
1573 IdentifierInfo *Name);
1574
1575 /// Rebuild the Objective-C exception declaration and register the
1576 /// declaration as an instantiated local.
1577 VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
1578 TypeSourceInfo *TSInfo, QualType T);
1579
1580 TemplateName
1581 TransformTemplateName(NestedNameSpecifierLoc &QualifierLoc,
1582 SourceLocation TemplateKWLoc, TemplateName Name,
1583 SourceLocation NameLoc,
1584 QualType ObjectType = QualType(),
1585 NamedDecl *FirstQualifierInScope = nullptr,
1586 bool AllowInjectedClassName = false);
1587
1588 const AnnotateAttr *TransformAnnotateAttr(const AnnotateAttr *AA);
1589 const CXXAssumeAttr *TransformCXXAssumeAttr(const CXXAssumeAttr *AA);
1590 const LoopHintAttr *TransformLoopHintAttr(const LoopHintAttr *LH);
1591 const NoInlineAttr *TransformStmtNoInlineAttr(const Stmt *OrigS,
1592 const Stmt *InstS,
1593 const NoInlineAttr *A);
1594 const AlwaysInlineAttr *
1595 TransformStmtAlwaysInlineAttr(const Stmt *OrigS, const Stmt *InstS,
1596 const AlwaysInlineAttr *A);
1597 const CodeAlignAttr *TransformCodeAlignAttr(const CodeAlignAttr *CA);
1598 const OpenACCRoutineDeclAttr *
1599 TransformOpenACCRoutineDeclAttr(const OpenACCRoutineDeclAttr *A);
1600 ExprResult TransformPredefinedExpr(PredefinedExpr *E);
1601 ExprResult TransformDeclRefExpr(DeclRefExpr *E);
1602 ExprResult TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E);
1603
1604 ExprResult TransformTemplateParmRefExpr(DeclRefExpr *E,
1605 NonTypeTemplateParmDecl *D);
1606
1607 /// Rebuild a DeclRefExpr for a VarDecl reference.
1608 ExprResult RebuildVarDeclRefExpr(ValueDecl *PD, SourceLocation Loc);
1609
1610 /// Transform a reference to a function or init-capture parameter pack.
1611 ExprResult TransformFunctionParmPackRefExpr(DeclRefExpr *E, ValueDecl *PD);
1612
1613 /// Transform a FunctionParmPackExpr which was built when we couldn't
1614 /// expand a function parameter pack reference which refers to an expanded
1615 /// pack.
1616 ExprResult TransformFunctionParmPackExpr(FunctionParmPackExpr *E);
1617
1618 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
1619 FunctionProtoTypeLoc TL) {
1620 // Call the base version; it will forward to our overridden version below.
1621 return inherited::TransformFunctionProtoType(TLB, TL);
1622 }
1623
1624 QualType TransformTagType(TypeLocBuilder &TLB, TagTypeLoc TL) {
1625 auto Type = inherited::TransformTagType(TLB, TL);
1626 if (!Type.isNull())
1627 return Type;
1628 // Special case for transforming a deduction guide, we return a
1629 // transformed TemplateSpecializationType.
1630 // FIXME: Why is this hack necessary?
1631 if (const auto *ICNT = dyn_cast<InjectedClassNameType>(Val: TL.getTypePtr());
1632 ICNT && SemaRef.CodeSynthesisContexts.back().Kind ==
1633 Sema::CodeSynthesisContext::BuildingDeductionGuides) {
1634 Type = inherited::TransformType(
1635 T: ICNT->getDecl()->getCanonicalTemplateSpecializationType(
1636 Ctx: SemaRef.Context));
1637 TLB.pushTrivial(Context&: SemaRef.Context, T: Type, Loc: TL.getNameLoc());
1638 }
1639 return Type;
1640 }
1641
1642 // Override the default version to handle a rewrite-template-arg-pack case
1643 // for building a deduction guide, and to cache substitution results in
1644 // concepts checking.
1645 bool TransformTemplateArgument(const TemplateArgumentLoc &Input,
1646 TemplateArgumentLoc &Output,
1647 bool Uneval = false) {
1648 const TemplateArgument &Arg = Input.getArgument();
1649 if (auto *Cache = CurrentCachedTemplateArgs;
1650 Cache && TemplateArgsHashValue) {
1651 llvm::FoldingSetNodeID ID = *TemplateArgsHashValue;
1652 ID.AddInteger(I: SemaRef.ArgPackSubstIndex.toInternalRepresentation());
1653 // FIXME: We may have better performance if we profile Arg without
1654 // sugars.
1655 Arg.Profile(ID, Context: SemaRef.Context);
1656 // FIXME: Ideally, we should only cache and restore the TemplateArgument
1657 // and rebuild the uncached TypeLoc separately in place.
1658 // We choose to accept loss of TypeLoc fidelity in cases where TypeLocs
1659 // are less critical for performance trade-off: currently, this is only
1660 // applied to concept substitutions and their valid template arguments.
1661 if (auto Iter = Cache->find(Val: ID); Iter != Cache->end()) {
1662 Output = Iter->second;
1663 return false;
1664 }
1665 bool Ret = inherited::TransformTemplateArgument(Input, Output, Uneval);
1666 if (!Ret)
1667 Cache->try_emplace(Key: ID.Intern(Allocator&: SemaRef.BumpAlloc), Args&: Output);
1668 return Ret;
1669 }
1670 switch (Arg.getKind()) {
1671 case TemplateArgument::Pack: {
1672 std::vector<TemplateArgument> TArgs;
1673 assert(SemaRef.CodeSynthesisContexts.empty() ||
1674 SemaRef.CodeSynthesisContexts.back().Kind ==
1675 Sema::CodeSynthesisContext::BuildingDeductionGuides);
1676 // Literally rewrite the template argument pack, instead of unpacking
1677 // it.
1678 for (auto &pack : Arg.getPackAsArray()) {
1679 TemplateArgumentLoc Input = SemaRef.getTrivialTemplateArgumentLoc(
1680 Arg: pack, NTTPType: QualType(), Loc: SourceLocation{});
1681 TemplateArgumentLoc Output;
1682 if (TransformTemplateArgument(Input, Output, Uneval))
1683 return true; // fails
1684 TArgs.push_back(x: Output.getArgument());
1685 }
1686 Output = SemaRef.getTrivialTemplateArgumentLoc(
1687 Arg: TemplateArgument(llvm::ArrayRef(TArgs).copy(A&: SemaRef.Context)),
1688 NTTPType: QualType(), Loc: SourceLocation{});
1689 return false;
1690 }
1691 default:
1692 break;
1693 }
1694 return inherited::TransformTemplateArgument(Input, Output, Uneval);
1695 }
1696
1697 using TreeTransform::TransformTemplateSpecializationType;
1698 QualType
1699 TransformTemplateSpecializationType(TypeLocBuilder &TLB,
1700 TemplateSpecializationTypeLoc TL) {
1701 auto *T = TL.getTypePtr();
1702 if (!getSema().ArgPackSubstIndex || !T->isSugared() ||
1703 !isPackProducingBuiltinTemplateName(N: T->getTemplateName()))
1704 return TreeTransform::TransformTemplateSpecializationType(TLB, TL);
1705 // Look through sugar to get to the SubstBuiltinTemplatePackType that we
1706 // need to substitute into.
1707
1708 // `TransformType` code below will handle picking the element from a pack
1709 // with the index `ArgPackSubstIndex`.
1710 // FIXME: add ability to represent sugarred type for N-th element of a
1711 // builtin pack and produce the sugar here.
1712 QualType R = TransformType(T: T->desugar());
1713 TLB.pushTrivial(Context&: getSema().getASTContext(), T: R, Loc: TL.getBeginLoc());
1714 return R;
1715 }
1716
1717 UnsignedOrNone ComputeSizeOfPackExprWithoutSubstitution(
1718 ArrayRef<TemplateArgument> PackArgs) {
1719 // Don't do this when rewriting template parameters for CTAD:
1720 // 1) The heuristic needs the unpacked Subst* nodes to figure out the
1721 // expanded size, but this never applies since Subst* nodes are not
1722 // created in rewrite scenarios.
1723 //
1724 // 2) The heuristic substitutes into the pattern with pack expansion
1725 // suppressed, which does not meet the requirements for argument
1726 // rewriting when template arguments include a non-pack matching against
1727 // a pack, particularly when rewriting an alias CTAD.
1728 if (TemplateArgs.isRewrite())
1729 return std::nullopt;
1730
1731 return inherited::ComputeSizeOfPackExprWithoutSubstitution(PackArgs);
1732 }
1733
1734 template<typename Fn>
1735 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
1736 FunctionProtoTypeLoc TL,
1737 CXXRecordDecl *ThisContext,
1738 Qualifiers ThisTypeQuals,
1739 Fn TransformExceptionSpec);
1740
1741 ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm,
1742 int indexAdjustment,
1743 UnsignedOrNone NumExpansions,
1744 bool ExpectParameterPack);
1745
1746 using inherited::TransformFunctionTypeParams;
1747 bool TransformFunctionTypeParams(
1748 SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
1749 const QualType *ParamTypes,
1750 const FunctionProtoType::ExtParameterInfo *ParamInfos,
1751 SmallVectorImpl<QualType> &PTypes,
1752 SmallVectorImpl<ParmVarDecl *> *PVars,
1753 Sema::ExtParameterInfoBuilder &PInfos, unsigned *LastParamTransformed);
1754
1755 using inherited::TransformTemplateTypeParmType;
1756 /// Transforms a template type parameter type by performing
1757 /// substitution of the corresponding template type argument.
1758 QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
1759 TemplateTypeParmTypeLoc TL,
1760 bool SuppressObjCLifetime);
1761
1762 QualType BuildSubstTemplateTypeParmType(
1763 TypeLocBuilder &TLB, bool SuppressObjCLifetime, bool Final,
1764 Decl *AssociatedDecl, unsigned Index, UnsignedOrNone PackIndex,
1765 TemplateArgument Arg, SourceLocation NameLoc);
1766
1767 /// Transforms an already-substituted template type parameter pack
1768 /// into either itself (if we aren't substituting into its pack expansion)
1769 /// or the appropriate substituted argument.
1770 using inherited::TransformSubstTemplateTypeParmPackType;
1771 QualType
1772 TransformSubstTemplateTypeParmPackType(TypeLocBuilder &TLB,
1773 SubstTemplateTypeParmPackTypeLoc TL,
1774 bool SuppressObjCLifetime);
1775 QualType
1776 TransformSubstBuiltinTemplatePackType(TypeLocBuilder &TLB,
1777 SubstBuiltinTemplatePackTypeLoc TL);
1778
1779 CXXRecordDecl::LambdaDependencyKind
1780 ComputeLambdaDependency(LambdaScopeInfo *LSI) {
1781 if (auto TypeAlias =
1782 TemplateInstArgsHelpers::getEnclosingTypeAliasTemplateDecl(
1783 SemaRef&: getSema());
1784 TypeAlias && TemplateInstArgsHelpers::isLambdaEnclosedByTypeAliasDecl(
1785 LambdaCallOperator: LSI->CallOperator, PrimaryTypeAliasDecl: TypeAlias.PrimaryTypeAliasDecl)) {
1786 unsigned TypeAliasDeclDepth = TypeAlias.Template->getTemplateDepth();
1787 if (TypeAliasDeclDepth >= TemplateArgs.getNumSubstitutedLevels())
1788 return CXXRecordDecl::LambdaDependencyKind::LDK_AlwaysDependent;
1789 for (const TemplateArgument &TA : TypeAlias.AssociatedTemplateArguments)
1790 if (TA.isDependent())
1791 return CXXRecordDecl::LambdaDependencyKind::LDK_AlwaysDependent;
1792 }
1793 if (auto *CD = dyn_cast_if_present<ImplicitConceptSpecializationDecl>(
1794 Val: LSI->Lambda->getLambdaContextDecl())) {
1795 if (llvm::any_of(Range: CD->getTemplateArguments(),
1796 P: [](const auto &TA) { return TA.isDependent(); }))
1797 return CXXRecordDecl::LambdaDependencyKind::LDK_AlwaysDependent;
1798 }
1799 return inherited::ComputeLambdaDependency(LSI);
1800 }
1801
1802 ExprResult TransformLambdaConstraint(Expr *AC) {
1803 if (AC && EvaluateLambdaConstraint)
1804 return TransformExpr(E: const_cast<Expr *>(AC));
1805
1806 return AC;
1807 }
1808
1809 ExprResult TransformLambdaExpr(LambdaExpr *E) {
1810 // Do not rebuild lambdas to avoid creating a new type.
1811 // Lambdas have already been processed inside their eval contexts.
1812 if (SemaRef.RebuildingImmediateInvocation)
1813 return E;
1814 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true,
1815 /*InstantiatingLambdaOrBlock=*/true);
1816 llvm::SaveAndRestore RAII(EvaluateConstraints, EvaluateLambdaConstraint);
1817
1818 return inherited::TransformLambdaExpr(E);
1819 }
1820
1821 ExprResult TransformBlockExpr(BlockExpr *E) {
1822 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true,
1823 /*InstantiatingLambdaOrBlock=*/true);
1824 return inherited::TransformBlockExpr(E);
1825 }
1826
1827 ExprResult RebuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc,
1828 LambdaScopeInfo *LSI) {
1829 CXXMethodDecl *MD = LSI->CallOperator;
1830 for (ParmVarDecl *PVD : MD->parameters()) {
1831 assert(PVD && "null in a parameter list");
1832 if (!PVD->hasDefaultArg())
1833 continue;
1834 Expr *UninstExpr = PVD->getUninstantiatedDefaultArg();
1835 // FIXME: Obtain the source location for the '=' token.
1836 SourceLocation EqualLoc = UninstExpr->getBeginLoc();
1837 if (SemaRef.SubstDefaultArgument(Loc: EqualLoc, Param: PVD, TemplateArgs)) {
1838 // If substitution fails, the default argument is set to a
1839 // RecoveryExpr that wraps the uninstantiated default argument so
1840 // that downstream diagnostics are omitted.
1841 ExprResult ErrorResult = SemaRef.CreateRecoveryExpr(
1842 Begin: UninstExpr->getBeginLoc(), End: UninstExpr->getEndLoc(), SubExprs: {UninstExpr},
1843 T: UninstExpr->getType());
1844 if (ErrorResult.isUsable())
1845 PVD->setDefaultArg(ErrorResult.get());
1846 }
1847 }
1848 return inherited::RebuildLambdaExpr(StartLoc, EndLoc, LSI);
1849 }
1850
1851 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
1852 // Currently, we instantiate the body when instantiating the lambda
1853 // expression. However, `EvaluateConstraints` is disabled during the
1854 // instantiation of the lambda expression, causing the instantiation
1855 // failure of the return type requirement in the body. If p0588r1 is fully
1856 // implemented, the body will be lazily instantiated, and this problem
1857 // will not occur. Here, `EvaluateConstraints` is temporarily set to
1858 // `true` to temporarily fix this issue.
1859 // FIXME: This temporary fix can be removed after fully implementing
1860 // p0588r1.
1861 llvm::SaveAndRestore _(EvaluateConstraints, true);
1862 return inherited::TransformLambdaBody(E, S: Body);
1863 }
1864
1865 ExprResult TransformRequiresExpr(RequiresExpr *E) {
1866 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
1867 ExprResult TransReq = inherited::TransformRequiresExpr(E);
1868 if (TransReq.isInvalid())
1869 return TransReq;
1870 assert(TransReq.get() != E &&
1871 "Do not change value of isSatisfied for the existing expression. "
1872 "Create a new expression instead.");
1873 if (E->getBody()->isDependentContext()) {
1874 Sema::SFINAETrap Trap(SemaRef);
1875 // We recreate the RequiresExpr body, but not by instantiating it.
1876 // Produce pending diagnostics for dependent access check.
1877 SemaRef.PerformDependentDiagnostics(Pattern: E->getBody(), TemplateArgs);
1878 // FIXME: Store SFINAE diagnostics in RequiresExpr for diagnosis.
1879 if (Trap.hasErrorOccurred())
1880 TransReq.getAs<RequiresExpr>()->setSatisfied(false);
1881 }
1882 return TransReq;
1883 }
1884
1885 bool TransformRequiresExprRequirements(
1886 ArrayRef<concepts::Requirement *> Reqs,
1887 SmallVectorImpl<concepts::Requirement *> &Transformed) {
1888 bool SatisfactionDetermined = false;
1889 for (concepts::Requirement *Req : Reqs) {
1890 concepts::Requirement *TransReq = nullptr;
1891 if (!SatisfactionDetermined) {
1892 if (auto *TypeReq = dyn_cast<concepts::TypeRequirement>(Val: Req))
1893 TransReq = TransformTypeRequirement(Req: TypeReq);
1894 else if (auto *ExprReq = dyn_cast<concepts::ExprRequirement>(Val: Req))
1895 TransReq = TransformExprRequirement(Req: ExprReq);
1896 else
1897 TransReq = TransformNestedRequirement(
1898 Req: cast<concepts::NestedRequirement>(Val: Req));
1899 if (!TransReq)
1900 return true;
1901 if (!TransReq->isDependent() && !TransReq->isSatisfied())
1902 // [expr.prim.req]p6
1903 // [...] The substitution and semantic constraint checking
1904 // proceeds in lexical order and stops when a condition that
1905 // determines the result of the requires-expression is
1906 // encountered. [..]
1907 SatisfactionDetermined = true;
1908 } else
1909 TransReq = Req;
1910 Transformed.push_back(Elt: TransReq);
1911 }
1912 return false;
1913 }
1914
1915 TemplateParameterList *TransformTemplateParameterList(
1916 TemplateParameterList *OrigTPL) {
1917 if (!OrigTPL || !OrigTPL->size()) return OrigTPL;
1918
1919 DeclContext *Owner = OrigTPL->getParam(Idx: 0)->getDeclContext();
1920 TemplateDeclInstantiator DeclInstantiator(getSema(),
1921 /* DeclContext *Owner */ Owner,
1922 TemplateArgs);
1923 DeclInstantiator.setEvaluateConstraints(EvaluateConstraints);
1924 return DeclInstantiator.SubstTemplateParams(List: OrigTPL);
1925 }
1926
1927 concepts::TypeRequirement *
1928 TransformTypeRequirement(concepts::TypeRequirement *Req);
1929 concepts::ExprRequirement *
1930 TransformExprRequirement(concepts::ExprRequirement *Req);
1931 concepts::NestedRequirement *
1932 TransformNestedRequirement(concepts::NestedRequirement *Req);
1933 ExprResult TransformRequiresTypeParams(
1934 SourceLocation KWLoc, SourceLocation RBraceLoc, const RequiresExpr *RE,
1935 RequiresExprBodyDecl *Body, ArrayRef<ParmVarDecl *> Params,
1936 SmallVectorImpl<QualType> &PTypes,
1937 SmallVectorImpl<ParmVarDecl *> &TransParams,
1938 Sema::ExtParameterInfoBuilder &PInfos);
1939
1940 ExprResult TransformCXXDynamicCastExpr(CXXDynamicCastExpr *E) {
1941 ExprResult Ret = inherited::TransformCXXDynamicCastExpr(E);
1942 if (Ret.isInvalid())
1943 return Ret;
1944 QualType T = Ret.get()->getType();
1945 if (const auto *PT = T->getAsCanonical<PointerType>())
1946 T = PT->getPointeeType();
1947 auto *DestDecl = T->getAsCXXRecordDecl();
1948 if (DestDecl && DestDecl->isEffectivelyFinal())
1949 getSema().MarkVTableUsed(Loc: Ret.get()->getExprLoc(), Class: DestDecl);
1950 return Ret;
1951 }
1952 };
1953}
1954
1955bool TemplateInstantiator::AlreadyTransformed(QualType T) {
1956 if (T.isNull())
1957 return true;
1958
1959 if (T->isInstantiationDependentType() || T->isVariablyModifiedType() ||
1960 T->containsUnexpandedParameterPack())
1961 return false;
1962
1963 getSema().MarkDeclarationsReferencedInType(Loc, T);
1964 return true;
1965}
1966
1967Decl *TemplateInstantiator::TransformDecl(SourceLocation Loc, Decl *D) {
1968 if (!D)
1969 return nullptr;
1970
1971 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(Val: D)) {
1972 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1973 // If the corresponding template argument is NULL or non-existent, it's
1974 // because we are performing instantiation from explicitly-specified
1975 // template arguments in a function template, but there were some
1976 // arguments left unspecified.
1977 if (!TemplateArgs.hasTemplateArgument(Depth: TTP->getDepth(),
1978 Index: TTP->getPosition())) {
1979 IsIncomplete = true;
1980 return BailOutOnIncomplete ? nullptr : D;
1981 }
1982
1983 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
1984
1985 if (TTP->isParameterPack()) {
1986 assert(Arg.getKind() == TemplateArgument::Pack &&
1987 "Missing argument pack");
1988 Arg = SemaRef.getPackSubstitutedTemplateArgument(Arg);
1989 }
1990
1991 TemplateName Template = Arg.getAsTemplate();
1992 assert(!Template.isNull() && Template.getAsTemplateDecl() &&
1993 "Wrong kind of template template argument");
1994 return Template.getAsTemplateDecl();
1995 }
1996
1997 // Fall through to find the instantiated declaration for this template
1998 // template parameter.
1999 }
2000
2001 if (instantiateMissingDeclsToScopeForConcepts(D))
2002 return nullptr;
2003
2004 if (isa<CXXExpansionStmtDecl>(Val: D)) {
2005 assert(SemaRef.CurrentInstantiationScope);
2006 return cast<Decl *>(
2007 Val&: *SemaRef.CurrentInstantiationScope->findInstantiationOf(D));
2008 }
2009
2010 return SemaRef.FindInstantiatedDecl(Loc, D: cast<NamedDecl>(Val: D), TemplateArgs);
2011}
2012
2013bool TemplateInstantiator::instantiateMissingDeclsToScopeForConcepts(Decl *D) {
2014 if (!(D && (SemaRef.inConstraintSubstitution() ||
2015 SemaRef.inParameterMappingSubstitution())))
2016 return false;
2017
2018 auto *Current = SemaRef.CurrentInstantiationScope;
2019 if (!Current || Current->getInstantiationOfIfExists(D))
2020 return false;
2021
2022 // CWG2770: Function parameters should be instantiated when they are
2023 // needed by a satisfaction check of an atomic constraint or
2024 // (recursively) by another function parameter.
2025 auto *OldParm = dyn_cast<ParmVarDecl>(Val: D);
2026 if (!OldParm)
2027 return false;
2028
2029 if (!OldParm->isParameterPack())
2030 return !TransformFunctionTypeParam(OldParm, /*indexAdjustment=*/0,
2031 /*NumExpansions=*/std::nullopt,
2032 /*ExpectParameterPack=*/false);
2033
2034 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2035
2036 // Find the parameter packs that could be expanded.
2037 TypeLoc TL = OldParm->getTypeSourceInfo()->getTypeLoc();
2038 PackExpansionTypeLoc ExpansionTL = TL.castAs<PackExpansionTypeLoc>();
2039 TypeLoc Pattern = ExpansionTL.getPatternLoc();
2040 SemaRef.collectUnexpandedParameterPacks(TL: Pattern, Unexpanded);
2041 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
2042
2043 bool ShouldExpand = false;
2044 bool RetainExpansion = false;
2045 UnsignedOrNone OrigNumExpansions =
2046 ExpansionTL.getTypePtr()->getNumExpansions();
2047 UnsignedOrNone NumExpansions = OrigNumExpansions;
2048 if (TryExpandParameterPacks(EllipsisLoc: ExpansionTL.getEllipsisLoc(),
2049 PatternRange: Pattern.getSourceRange(), Unexpanded,
2050 /*FailOnPackProducingTemplates=*/true,
2051 ShouldExpand, RetainExpansion, NumExpansions))
2052 return true;
2053
2054 assert(ShouldExpand && !RetainExpansion &&
2055 "Shouldn't preserve pack expansion when evaluating constraints");
2056 ExpandingFunctionParameterPack(Pack: OldParm);
2057 for (unsigned I = 0; I != *NumExpansions; ++I) {
2058 Sema::ArgPackSubstIndexRAII SubstIndex(getSema(), I);
2059 if (!TransformFunctionTypeParam(OldParm, /*indexAdjustment=*/0,
2060 /*NumExpansions=*/OrigNumExpansions,
2061 /*ExpectParameterPack=*/false))
2062 return true;
2063 }
2064 return false;
2065}
2066
2067Decl *TemplateInstantiator::TransformDefinition(SourceLocation Loc, Decl *D) {
2068 Decl *Inst = getSema().SubstDecl(D, Owner: getSema().CurContext, TemplateArgs);
2069 if (!Inst)
2070 return nullptr;
2071
2072 getSema().CurrentInstantiationScope->InstantiatedLocal(D, Inst);
2073 return Inst;
2074}
2075
2076bool TemplateInstantiator::TransformExceptionSpec(
2077 SourceLocation Loc, FunctionProtoType::ExceptionSpecInfo &ESI,
2078 SmallVectorImpl<QualType> &Exceptions, bool &Changed) {
2079 if (ESI.Type == EST_Uninstantiated) {
2080 ESI.instantiate();
2081 Changed = true;
2082 }
2083 return inherited::TransformExceptionSpec(Loc, ESI, Exceptions, Changed);
2084}
2085
2086NamedDecl *
2087TemplateInstantiator::TransformFirstQualifierInScope(NamedDecl *D,
2088 SourceLocation Loc) {
2089 // If the first part of the nested-name-specifier was a template type
2090 // parameter, instantiate that type parameter down to a tag type.
2091 if (TemplateTypeParmDecl *TTPD = dyn_cast_or_null<TemplateTypeParmDecl>(Val: D)) {
2092 const TemplateTypeParmType *TTP
2093 = cast<TemplateTypeParmType>(Val: getSema().Context.getTypeDeclType(Decl: TTPD));
2094
2095 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
2096 // FIXME: This needs testing w/ member access expressions.
2097 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getIndex());
2098
2099 if (TTP->isParameterPack()) {
2100 assert(Arg.getKind() == TemplateArgument::Pack &&
2101 "Missing argument pack");
2102
2103 if (!getSema().ArgPackSubstIndex)
2104 return nullptr;
2105
2106 Arg = SemaRef.getPackSubstitutedTemplateArgument(Arg);
2107 }
2108
2109 QualType T = Arg.getAsType();
2110 if (T.isNull())
2111 return cast_or_null<NamedDecl>(Val: TransformDecl(Loc, D));
2112
2113 if (const TagType *Tag = T->getAs<TagType>())
2114 return Tag->getDecl();
2115
2116 // The resulting type is not a tag; complain.
2117 getSema().Diag(Loc, DiagID: diag::err_nested_name_spec_non_tag) << T;
2118 return nullptr;
2119 }
2120 }
2121
2122 return cast_or_null<NamedDecl>(Val: TransformDecl(Loc, D));
2123}
2124
2125VarDecl *
2126TemplateInstantiator::RebuildExceptionDecl(VarDecl *ExceptionDecl,
2127 TypeSourceInfo *Declarator,
2128 SourceLocation StartLoc,
2129 SourceLocation NameLoc,
2130 IdentifierInfo *Name) {
2131 VarDecl *Var = inherited::RebuildExceptionDecl(ExceptionDecl, Declarator,
2132 StartLoc, IdLoc: NameLoc, Id: Name);
2133 if (Var)
2134 getSema().CurrentInstantiationScope->InstantiatedLocal(D: ExceptionDecl, Inst: Var);
2135 return Var;
2136}
2137
2138VarDecl *TemplateInstantiator::RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
2139 TypeSourceInfo *TSInfo,
2140 QualType T) {
2141 VarDecl *Var = inherited::RebuildObjCExceptionDecl(ExceptionDecl, TInfo: TSInfo, T);
2142 if (Var)
2143 getSema().CurrentInstantiationScope->InstantiatedLocal(D: ExceptionDecl, Inst: Var);
2144 return Var;
2145}
2146
2147TemplateName TemplateInstantiator::TransformTemplateName(
2148 NestedNameSpecifierLoc &QualifierLoc, SourceLocation TemplateKWLoc,
2149 TemplateName Name, SourceLocation NameLoc, QualType ObjectType,
2150 NamedDecl *FirstQualifierInScope, bool AllowInjectedClassName) {
2151 if (Name.getKind() == TemplateName::Template) {
2152 assert(!QualifierLoc && "Unexpected qualifier");
2153 if (auto *TTP =
2154 dyn_cast<TemplateTemplateParmDecl>(Val: Name.getAsTemplateDecl());
2155 TTP && TTP->getDepth() < TemplateArgs.getNumLevels()) {
2156 // If the corresponding template argument is NULL or non-existent, it's
2157 // because we are performing instantiation from explicitly-specified
2158 // template arguments in a function template, but there were some
2159 // arguments left unspecified.
2160 if (!TemplateArgs.hasTemplateArgument(Depth: TTP->getDepth(),
2161 Index: TTP->getPosition())) {
2162 IsIncomplete = true;
2163 return BailOutOnIncomplete ? TemplateName() : Name;
2164 }
2165
2166 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
2167
2168 if (TemplateArgs.isRewrite()) {
2169 // We're rewriting the template parameter as a reference to another
2170 // template parameter.
2171 Arg = getTemplateArgumentPackPatternForRewrite(TA: Arg);
2172 assert(Arg.getKind() == TemplateArgument::Template &&
2173 "unexpected nontype template argument kind in template rewrite");
2174 return Arg.getAsTemplate();
2175 }
2176
2177 auto [AssociatedDecl, Final] =
2178 TemplateArgs.getAssociatedDecl(Depth: TTP->getDepth());
2179 UnsignedOrNone PackIndex = std::nullopt;
2180 if (TTP->isParameterPack()) {
2181 assert(Arg.getKind() == TemplateArgument::Pack &&
2182 "Missing argument pack");
2183
2184 if (!getSema().ArgPackSubstIndex) {
2185 // We have the template argument pack to substitute, but we're not
2186 // actually expanding the enclosing pack expansion yet. So, just
2187 // keep the entire argument pack.
2188 return getSema().Context.getSubstTemplateTemplateParmPack(
2189 ArgPack: Arg, AssociatedDecl, Index: TTP->getIndex(), Final);
2190 }
2191
2192 PackIndex = SemaRef.getPackIndex(Pack: Arg);
2193 Arg = SemaRef.getPackSubstitutedTemplateArgument(Arg);
2194 }
2195
2196 TemplateName Template = Arg.getAsTemplate();
2197 assert(!Template.isNull() && "Null template template argument");
2198 return getSema().Context.getSubstTemplateTemplateParm(
2199 replacement: Template, AssociatedDecl, Index: TTP->getIndex(), PackIndex, Final);
2200 }
2201 }
2202
2203 if (SubstTemplateTemplateParmPackStorage *SubstPack
2204 = Name.getAsSubstTemplateTemplateParmPack()) {
2205 if (!getSema().ArgPackSubstIndex)
2206 return Name;
2207
2208 TemplateArgument Pack = SubstPack->getArgumentPack();
2209 TemplateName Template =
2210 SemaRef.getPackSubstitutedTemplateArgument(Arg: Pack).getAsTemplate();
2211 return getSema().Context.getSubstTemplateTemplateParm(
2212 replacement: Template, AssociatedDecl: SubstPack->getAssociatedDecl(), Index: SubstPack->getIndex(),
2213 PackIndex: SemaRef.getPackIndex(Pack), Final: SubstPack->getFinal());
2214 }
2215
2216 return inherited::TransformTemplateName(
2217 QualifierLoc, TemplateKWLoc, Name, NameLoc, ObjectType,
2218 FirstQualifierInScope, AllowInjectedClassName);
2219}
2220
2221ExprResult
2222TemplateInstantiator::TransformPredefinedExpr(PredefinedExpr *E) {
2223 if (!E->isTypeDependent())
2224 return E;
2225
2226 return getSema().BuildPredefinedExpr(Loc: E->getLocation(), IK: E->getIdentKind());
2227}
2228
2229ExprResult
2230TemplateInstantiator::TransformTemplateParmRefExpr(DeclRefExpr *E,
2231 NonTypeTemplateParmDecl *NTTP) {
2232 if (TemplateArgs.retainInnerDepths() &&
2233 NTTP->getDepth() >= TemplateArgs.getNumLevels())
2234 return E;
2235 // If the corresponding template argument is NULL or non-existent, it's
2236 // because we are performing instantiation from explicitly-specified
2237 // template arguments in a function template, but there were some
2238 // arguments left unspecified.
2239 if (!TemplateArgs.hasTemplateArgument(Depth: NTTP->getDepth(),
2240 Index: NTTP->getPosition())) {
2241 IsIncomplete = true;
2242 return BailOutOnIncomplete ? ExprError() : E;
2243 }
2244
2245 TemplateArgument Arg = TemplateArgs(NTTP->getDepth(), NTTP->getPosition());
2246
2247 if (TemplateArgs.isRewrite()) {
2248 // We're rewriting the template parameter as a reference to another
2249 // template parameter.
2250 Arg = getTemplateArgumentPackPatternForRewrite(TA: Arg);
2251 assert(Arg.getKind() == TemplateArgument::Expression &&
2252 "unexpected nontype template argument kind in template rewrite");
2253 // FIXME: This can lead to the same subexpression appearing multiple times
2254 // in a complete expression.
2255 return Arg.getAsExpr();
2256 }
2257
2258 QualType ParamType = NTTP->isExpandedParameterPack()
2259 ? NTTP->getExpansionType(I: *SemaRef.ArgPackSubstIndex)
2260 : NTTP->isParameterPack() && SemaRef.ArgPackSubstIndex
2261 ? NTTP->getType().getNonPackExpansionType()
2262 : NTTP->getType();
2263 ParamType = SemaRef.SubstType(T: ParamType, TemplateArgs, Loc: E->getLocation(),
2264 Entity: NTTP->getDeclName());
2265 assert(!ParamType.isNull() && "Shouldn't substitute to an invalid type");
2266
2267 auto [AssociatedDecl, Final] =
2268 TemplateArgs.getAssociatedDecl(Depth: NTTP->getDepth());
2269 UnsignedOrNone PackIndex = std::nullopt;
2270 if (NTTP->isParameterPack() ||
2271 // In concept parameter mapping for fold expressions, packs that aren't
2272 // expanded in place are treated as having non-pack dependency, so that
2273 // a PackExpansionType won't prevent expanding the packs outside the
2274 // TreeTransform. However, we still need to unpack the arguments during
2275 // any template argument substitution, so we also check its FoundDecl.
2276 (E->getFoundDecl() && E->getFoundDecl() != E->getDecl() &&
2277 E->getFoundDecl()->isParameterPack())) {
2278 assert(Arg.getKind() == TemplateArgument::Pack && "Missing argument pack");
2279
2280 if (!getSema().ArgPackSubstIndex) {
2281 // We have an argument pack, but we can't select a particular argument
2282 // out of it yet. Therefore, we'll build an expression to hold on to that
2283 // argument pack.
2284 QualType ExprType = ParamType.getNonLValueExprType(Context: SemaRef.Context);
2285 if (ParamType->isRecordType())
2286 ExprType.addConst();
2287 return new (SemaRef.Context) SubstNonTypeTemplateParmPackExpr(
2288 ExprType, ParamType->isReferenceType() ? VK_LValue : VK_PRValue,
2289 E->getLocation(), Arg, AssociatedDecl, NTTP->getPosition(), Final);
2290 }
2291 PackIndex = SemaRef.getPackIndex(Pack: Arg);
2292 Arg = SemaRef.getPackSubstitutedTemplateArgument(Arg);
2293 }
2294 return SemaRef.BuildSubstNonTypeTemplateParmExpr(
2295 AssociatedDecl, Index: NTTP->getPosition(), ParamType, loc: E->getLocation(), Replacement: Arg,
2296 PackIndex, Final);
2297}
2298
2299const AnnotateAttr *
2300TemplateInstantiator::TransformAnnotateAttr(const AnnotateAttr *AA) {
2301 SmallVector<Expr *> Args;
2302 for (Expr *Arg : AA->args()) {
2303 ExprResult Res = getDerived().TransformExpr(E: Arg);
2304 if (Res.isUsable())
2305 Args.push_back(Elt: Res.get());
2306 }
2307 return AnnotateAttr::CreateImplicit(Ctx&: getSema().Context, Annotation: AA->getAnnotation(),
2308 Args: Args.data(), ArgsSize: Args.size(), Range: AA->getRange());
2309}
2310
2311const CXXAssumeAttr *
2312TemplateInstantiator::TransformCXXAssumeAttr(const CXXAssumeAttr *AA) {
2313 ExprResult Res = getDerived().TransformExpr(E: AA->getAssumption());
2314 if (!Res.isUsable())
2315 return AA;
2316
2317 if (!(Res.get()->getDependence() & ExprDependence::TypeValueInstantiation)) {
2318 Res = getSema().BuildCXXAssumeExpr(Assumption: Res.get(), AttrName: AA->getAttrName(),
2319 Range: AA->getRange());
2320 if (!Res.isUsable())
2321 return AA;
2322 }
2323
2324 return CXXAssumeAttr::CreateImplicit(Ctx&: getSema().Context, Assumption: Res.get(),
2325 Range: AA->getRange());
2326}
2327
2328const LoopHintAttr *
2329TemplateInstantiator::TransformLoopHintAttr(const LoopHintAttr *LH) {
2330 ExprResult TransformedExprResult = getDerived().TransformExpr(E: LH->getValue());
2331 if (!TransformedExprResult.isUsable() ||
2332 TransformedExprResult.get() == LH->getValue())
2333 return LH;
2334 Expr *TransformedExpr = TransformedExprResult.get();
2335
2336 // Generate error if there is a problem with the value.
2337 if (getSema().CheckLoopHintExpr(E: TransformedExpr, Loc: LH->getLocation(),
2338 /*AllowZero=*/LH->getSemanticSpelling() ==
2339 LoopHintAttr::Pragma_unroll))
2340 return LH;
2341
2342 LoopHintAttr::OptionType Option = LH->getOption();
2343 LoopHintAttr::LoopHintState State = LH->getState();
2344
2345 // Since C++ does not have partial instantiation, we would expect a
2346 // transformed loop hint expression to not be value dependent. However, at
2347 // the time of writing, the use of a generic lambda inside a template
2348 // triggers a double instantiation, so we must protect against this event.
2349 // This provision may become unneeded in the future.
2350 if (Option == LoopHintAttr::UnrollCount &&
2351 !TransformedExpr->isValueDependent()) {
2352 llvm::APSInt ValueAPS =
2353 TransformedExpr->EvaluateKnownConstInt(Ctx: getSema().getASTContext());
2354 // The values of 0 and 1 block any unrolling of the loop (also see
2355 // handleLoopHintAttr in SemaStmtAttr).
2356 if (ValueAPS.isZero() || ValueAPS.isOne()) {
2357 Option = LoopHintAttr::Unroll;
2358 State = LoopHintAttr::Disable;
2359 }
2360 }
2361
2362 // Create new LoopHintValueAttr with integral expression in place of the
2363 // non-type template parameter.
2364 return LoopHintAttr::CreateImplicit(Ctx&: getSema().Context, Option, State,
2365 Value: TransformedExpr, CommonInfo: *LH);
2366}
2367const NoInlineAttr *TemplateInstantiator::TransformStmtNoInlineAttr(
2368 const Stmt *OrigS, const Stmt *InstS, const NoInlineAttr *A) {
2369 if (!A || getSema().CheckNoInlineAttr(OrigSt: OrigS, CurSt: InstS, A: *A))
2370 return nullptr;
2371
2372 return A;
2373}
2374const AlwaysInlineAttr *TemplateInstantiator::TransformStmtAlwaysInlineAttr(
2375 const Stmt *OrigS, const Stmt *InstS, const AlwaysInlineAttr *A) {
2376 if (!A || getSema().CheckAlwaysInlineAttr(OrigSt: OrigS, CurSt: InstS, A: *A))
2377 return nullptr;
2378
2379 return A;
2380}
2381
2382const CodeAlignAttr *
2383TemplateInstantiator::TransformCodeAlignAttr(const CodeAlignAttr *CA) {
2384 Expr *TransformedExpr = getDerived().TransformExpr(E: CA->getAlignment()).get();
2385 return getSema().BuildCodeAlignAttr(CI: *CA, E: TransformedExpr);
2386}
2387const OpenACCRoutineDeclAttr *
2388TemplateInstantiator::TransformOpenACCRoutineDeclAttr(
2389 const OpenACCRoutineDeclAttr *A) {
2390 llvm_unreachable("RoutineDecl should only be a declaration attribute, as it "
2391 "applies to a Function Decl (and a few places for VarDecl)");
2392}
2393
2394ExprResult TemplateInstantiator::RebuildVarDeclRefExpr(ValueDecl *PD,
2395 SourceLocation Loc) {
2396 DeclarationNameInfo NameInfo(PD->getDeclName(), Loc);
2397 return getSema().BuildDeclarationNameExpr(SS: CXXScopeSpec(), NameInfo, D: PD);
2398}
2399
2400ExprResult
2401TemplateInstantiator::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {
2402 if (getSema().ArgPackSubstIndex) {
2403 // We can expand this parameter pack now.
2404 ValueDecl *D = E->getExpansion(I: *getSema().ArgPackSubstIndex);
2405 ValueDecl *VD = cast_or_null<ValueDecl>(Val: TransformDecl(Loc: E->getExprLoc(), D));
2406 if (!VD)
2407 return ExprError();
2408 return RebuildVarDeclRefExpr(PD: VD, Loc: E->getExprLoc());
2409 }
2410
2411 QualType T = TransformType(T: E->getType());
2412 if (T.isNull())
2413 return ExprError();
2414
2415 // Transform each of the parameter expansions into the corresponding
2416 // parameters in the instantiation of the function decl.
2417 SmallVector<ValueDecl *, 8> Vars;
2418 Vars.reserve(N: E->getNumExpansions());
2419 for (FunctionParmPackExpr::iterator I = E->begin(), End = E->end();
2420 I != End; ++I) {
2421 ValueDecl *D = cast_or_null<ValueDecl>(Val: TransformDecl(Loc: E->getExprLoc(), D: *I));
2422 if (!D)
2423 return ExprError();
2424 Vars.push_back(Elt: D);
2425 }
2426
2427 auto *PackExpr =
2428 FunctionParmPackExpr::Create(Context: getSema().Context, T, ParamPack: E->getParameterPack(),
2429 NameLoc: E->getParameterPackLocation(), Params: Vars);
2430 getSema().MarkFunctionParmPackReferenced(E: PackExpr);
2431 return PackExpr;
2432}
2433
2434ExprResult
2435TemplateInstantiator::TransformFunctionParmPackRefExpr(DeclRefExpr *E,
2436 ValueDecl *PD) {
2437 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
2438 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found =
2439 getSema().CurrentInstantiationScope->getInstantiationOfIfExists(D: PD);
2440
2441 // This can happen when instantiating an expansion statement that contains
2442 // a pack (e.g. `template for (auto x : {{ts...}})`).
2443 if (!Found)
2444 return E;
2445
2446 Decl *TransformedDecl;
2447 if (DeclArgumentPack *Pack = dyn_cast<DeclArgumentPack *>(Val&: *Found)) {
2448 // If this is a reference to a function parameter pack which we can
2449 // substitute but can't yet expand, build a FunctionParmPackExpr for it.
2450 if (!getSema().ArgPackSubstIndex) {
2451 QualType T = TransformType(T: E->getType());
2452 if (T.isNull())
2453 return ExprError();
2454 auto *PackExpr = FunctionParmPackExpr::Create(Context: getSema().Context, T, ParamPack: PD,
2455 NameLoc: E->getExprLoc(), Params: *Pack);
2456 getSema().MarkFunctionParmPackReferenced(E: PackExpr);
2457 return PackExpr;
2458 }
2459
2460 TransformedDecl = (*Pack)[*getSema().ArgPackSubstIndex];
2461 } else {
2462 TransformedDecl = cast<Decl *>(Val&: *Found);
2463 }
2464
2465 // We have either an unexpanded pack or a specific expansion.
2466 return RebuildVarDeclRefExpr(PD: cast<ValueDecl>(Val: TransformedDecl),
2467 Loc: E->getExprLoc());
2468}
2469
2470ExprResult
2471TemplateInstantiator::TransformDeclRefExpr(DeclRefExpr *E) {
2472 NamedDecl *D = E->getDecl();
2473
2474 // Handle references to non-type template parameters and non-type template
2475 // parameter packs.
2476 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Val: D)) {
2477 if (NTTP->getDepth() < TemplateArgs.getNumLevels())
2478 return TransformTemplateParmRefExpr(E, NTTP);
2479
2480 // We have a non-type template parameter that isn't fully substituted;
2481 // FindInstantiatedDecl will find it in the local instantiation scope.
2482 }
2483
2484 // Handle references to function parameter packs.
2485 if (VarDecl *PD = dyn_cast<VarDecl>(Val: D))
2486 if (PD->isParameterPack()) {
2487 if (instantiateMissingDeclsToScopeForConcepts(D: PD))
2488 return ExprError();
2489
2490 return TransformFunctionParmPackRefExpr(E, PD);
2491 }
2492
2493 return inherited::TransformDeclRefExpr(E);
2494}
2495
2496ExprResult TemplateInstantiator::TransformCXXDefaultArgExpr(
2497 CXXDefaultArgExpr *E) {
2498 assert(!cast<FunctionDecl>(E->getParam()->getDeclContext())->
2499 getDescribedFunctionTemplate() &&
2500 "Default arg expressions are never formed in dependent cases.");
2501 return SemaRef.BuildCXXDefaultArgExpr(
2502 CallLoc: E->getUsedLocation(), FD: cast<FunctionDecl>(Val: E->getParam()->getDeclContext()),
2503 Param: E->getParam());
2504}
2505
2506template<typename Fn>
2507QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB,
2508 FunctionProtoTypeLoc TL,
2509 CXXRecordDecl *ThisContext,
2510 Qualifiers ThisTypeQuals,
2511 Fn TransformExceptionSpec) {
2512 // If this is a lambda or block, the transformation MUST be done in the
2513 // CurrentInstantiationScope since it introduces a mapping of
2514 // the original to the newly created transformed parameters.
2515 //
2516 // In that case, TemplateInstantiator::TransformLambdaExpr will
2517 // have already pushed a scope for this prototype, so don't create
2518 // a second one.
2519 LocalInstantiationScope *Current = getSema().CurrentInstantiationScope;
2520 std::optional<LocalInstantiationScope> Scope;
2521 if (!Current || !Current->isLambdaOrBlock())
2522 Scope.emplace(args&: SemaRef, /*CombineWithOuterScope=*/args: true);
2523
2524 return inherited::TransformFunctionProtoType(
2525 TLB, TL, ThisContext, ThisTypeQuals, TransformExceptionSpec);
2526}
2527
2528ParmVarDecl *TemplateInstantiator::TransformFunctionTypeParam(
2529 ParmVarDecl *OldParm, int indexAdjustment, UnsignedOrNone NumExpansions,
2530 bool ExpectParameterPack) {
2531 // Defer the late-parsed attributes of a parameter of the prototype being
2532 // transformed, when in its scope. A parameter is otherwise transformed on its
2533 // own only on demand, for a constraint that names it (see
2534 // instantiateMissingDeclsToScopeForConcepts). Its attributes are then
2535 // instantiated at once, and a later parameter they name is instantiated on
2536 // demand as well.
2537 Sema::LateInstantiatedAttrVec *LateAttrs = nullptr;
2538 if (LateParmAttrs && SemaRef.CurrentInstantiationScope == LateParmAttrScope)
2539 LateAttrs = LateParmAttrs;
2540 else
2541 assert((SemaRef.inConstraintSubstitution() ||
2542 SemaRef.inParameterMappingSubstitution()) &&
2543 "parameter transformed outside its prototype");
2544 auto NewParm = SemaRef.SubstParmVarDecl(
2545 D: OldParm, TemplateArgs, indexAdjustment, NumExpansions,
2546 ExpectParameterPack, EvaluateConstraints, LateAttrs);
2547 if (NewParm && SemaRef.getLangOpts().OpenCL)
2548 SemaRef.deduceOpenCLAddressSpace(decl: NewParm);
2549 return NewParm;
2550}
2551
2552bool TemplateInstantiator::TransformFunctionTypeParams(
2553 SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
2554 const QualType *ParamTypes,
2555 const FunctionProtoType::ExtParameterInfo *ParamInfos,
2556 SmallVectorImpl<QualType> &PTypes, SmallVectorImpl<ParmVarDecl *> *PVars,
2557 Sema::ExtParameterInfoBuilder &PInfos, unsigned *LastParamTransformed) {
2558 // A late-parsed attribute on a parameter may name a parameter declared after
2559 // it, so transform all parameters then instantiate all late attributes.
2560 Sema::LateInstantiatedAttrVec LateAttrs;
2561 LocalInstantiationScope *Scope = SemaRef.CurrentInstantiationScope;
2562 llvm::SaveAndRestore SaveLateAttrs(LateParmAttrs, &LateAttrs);
2563 llvm::SaveAndRestore SaveLateScope(LateParmAttrScope, Scope);
2564 bool Failed = inherited::TransformFunctionTypeParams(
2565 Loc, Params, ParamTypes, ParamInfos, OutParamTypes&: PTypes, PVars, PInfos,
2566 LastParamTransformed);
2567 // The attributes were deferred in this scope itself, so there is nothing to
2568 // free on failure.
2569 assert(
2570 llvm::all_of(LateAttrs, [&](const Sema::LateInstantiatedAttribute &LA) {
2571 return LA.Scope == Scope;
2572 }));
2573 if (Failed)
2574 return true;
2575 SemaRef.InstantiateLateAttrs(TemplateArgs, LateAttrs, OuterMostScope: Scope);
2576 return false;
2577}
2578
2579QualType TemplateInstantiator::BuildSubstTemplateTypeParmType(
2580 TypeLocBuilder &TLB, bool SuppressObjCLifetime, bool Final,
2581 Decl *AssociatedDecl, unsigned Index, UnsignedOrNone PackIndex,
2582 TemplateArgument Arg, SourceLocation NameLoc) {
2583 QualType Replacement = Arg.getAsType();
2584
2585 // If the template parameter had ObjC lifetime qualifiers,
2586 // then any such qualifiers on the replacement type are ignored.
2587 if (SuppressObjCLifetime) {
2588 Qualifiers RQs;
2589 RQs = Replacement.getQualifiers();
2590 RQs.removeObjCLifetime();
2591 Replacement =
2592 SemaRef.Context.getQualifiedType(T: Replacement.getUnqualifiedType(), Qs: RQs);
2593 }
2594
2595 // TODO: only do this uniquing once, at the start of instantiation.
2596 QualType Result = getSema().Context.getSubstTemplateTypeParmType(
2597 Replacement, AssociatedDecl, Index, PackIndex, Final);
2598 SubstTemplateTypeParmTypeLoc NewTL =
2599 TLB.push<SubstTemplateTypeParmTypeLoc>(T: Result);
2600 NewTL.setNameLoc(NameLoc);
2601 return Result;
2602}
2603
2604QualType
2605TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB,
2606 TemplateTypeParmTypeLoc TL,
2607 bool SuppressObjCLifetime) {
2608 const TemplateTypeParmType *T = TL.getTypePtr();
2609 if (T->getDepth() < TemplateArgs.getNumLevels()) {
2610 // Replace the template type parameter with its corresponding
2611 // template argument.
2612
2613 // If the corresponding template argument is NULL or doesn't exist, it's
2614 // because we are performing instantiation from explicitly-specified
2615 // template arguments in a function template class, but there were some
2616 // arguments left unspecified.
2617 if (!TemplateArgs.hasTemplateArgument(Depth: T->getDepth(), Index: T->getIndex())) {
2618 IsIncomplete = true;
2619 if (BailOutOnIncomplete)
2620 return QualType();
2621
2622 TemplateTypeParmTypeLoc NewTL
2623 = TLB.push<TemplateTypeParmTypeLoc>(T: TL.getType());
2624 NewTL.setNameLoc(TL.getNameLoc());
2625 return TL.getType();
2626 }
2627
2628 TemplateArgument Arg = TemplateArgs(T->getDepth(), T->getIndex());
2629
2630 if (TemplateArgs.isRewrite()) {
2631 // We're rewriting the template parameter as a reference to another
2632 // template parameter.
2633 Arg = getTemplateArgumentPackPatternForRewrite(TA: Arg);
2634 assert(Arg.getKind() == TemplateArgument::Type &&
2635 "unexpected nontype template argument kind in template rewrite");
2636 QualType NewT = Arg.getAsType();
2637 TLB.pushTrivial(Context&: SemaRef.Context, T: NewT, Loc: TL.getNameLoc());
2638 return NewT;
2639 }
2640
2641 auto [AssociatedDecl, Final] =
2642 TemplateArgs.getAssociatedDecl(Depth: T->getDepth());
2643 UnsignedOrNone PackIndex = std::nullopt;
2644 if (T->isParameterPack() ||
2645 // In concept parameter mapping for fold expressions, packs that aren't
2646 // expanded in place are treated as having non-pack dependency, so that
2647 // a PackExpansionType won't prevent expanding the packs outside the
2648 // TreeTransform. However, we still need to unpack the arguments during
2649 // any template argument substitution, so we check the associated
2650 // declaration instead.
2651 (T->getDecl() && T->getDecl()->isTemplateParameterPack())) {
2652 assert(Arg.getKind() == TemplateArgument::Pack &&
2653 "Missing argument pack");
2654
2655 if (!getSema().ArgPackSubstIndex) {
2656 // We have the template argument pack, but we're not expanding the
2657 // enclosing pack expansion yet. Just save the template argument
2658 // pack for later substitution.
2659 QualType Result = getSema().Context.getSubstTemplateTypeParmPackType(
2660 AssociatedDecl, Index: T->getIndex(), Final, ArgPack: Arg);
2661 SubstTemplateTypeParmPackTypeLoc NewTL
2662 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(T: Result);
2663 NewTL.setNameLoc(TL.getNameLoc());
2664 return Result;
2665 }
2666
2667 // PackIndex starts from last element.
2668 PackIndex = SemaRef.getPackIndex(Pack: Arg);
2669 Arg = SemaRef.getPackSubstitutedTemplateArgument(Arg);
2670 }
2671
2672 assert(Arg.getKind() == TemplateArgument::Type &&
2673 "Template argument kind mismatch");
2674
2675 return BuildSubstTemplateTypeParmType(TLB, SuppressObjCLifetime, Final,
2676 AssociatedDecl, Index: T->getIndex(),
2677 PackIndex, Arg, NameLoc: TL.getNameLoc());
2678 }
2679
2680 // The template type parameter comes from an inner template (e.g.,
2681 // the template parameter list of a member template inside the
2682 // template we are instantiating). Create a new template type
2683 // parameter with the template "level" reduced by one.
2684 TemplateTypeParmDecl *NewTTPDecl = nullptr;
2685 if (TemplateTypeParmDecl *OldTTPDecl = T->getDecl())
2686 NewTTPDecl = cast_or_null<TemplateTypeParmDecl>(
2687 Val: TransformDecl(Loc: TL.getNameLoc(), D: OldTTPDecl));
2688 QualType Result = getSema().Context.getTemplateTypeParmType(
2689 Depth: T->getDepth() - (TemplateArgs.retainInnerDepths()
2690 ? 0
2691 : TemplateArgs.getNumSubstitutedLevels()),
2692 Index: T->getIndex(), ParameterPack: T->isParameterPack(), ParmDecl: NewTTPDecl);
2693 TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(T: Result);
2694 NewTL.setNameLoc(TL.getNameLoc());
2695 return Result;
2696}
2697
2698QualType TemplateInstantiator::TransformSubstTemplateTypeParmPackType(
2699 TypeLocBuilder &TLB, SubstTemplateTypeParmPackTypeLoc TL,
2700 bool SuppressObjCLifetime) {
2701 const SubstTemplateTypeParmPackType *T = TL.getTypePtr();
2702
2703 Decl *NewReplaced = TransformDecl(Loc: TL.getNameLoc(), D: T->getAssociatedDecl());
2704
2705 if (!getSema().ArgPackSubstIndex) {
2706 // We aren't expanding the parameter pack, so just return ourselves.
2707 QualType Result = TL.getType();
2708 if (NewReplaced != T->getAssociatedDecl())
2709 Result = getSema().Context.getSubstTemplateTypeParmPackType(
2710 AssociatedDecl: NewReplaced, Index: T->getIndex(), Final: T->getFinal(), ArgPack: T->getArgumentPack());
2711 SubstTemplateTypeParmPackTypeLoc NewTL =
2712 TLB.push<SubstTemplateTypeParmPackTypeLoc>(T: Result);
2713 NewTL.setNameLoc(TL.getNameLoc());
2714 return Result;
2715 }
2716
2717 TemplateArgument Pack = T->getArgumentPack();
2718 TemplateArgument Arg = SemaRef.getPackSubstitutedTemplateArgument(Arg: Pack);
2719 return BuildSubstTemplateTypeParmType(
2720 TLB, SuppressObjCLifetime, Final: T->getFinal(), AssociatedDecl: NewReplaced, Index: T->getIndex(),
2721 PackIndex: SemaRef.getPackIndex(Pack), Arg, NameLoc: TL.getNameLoc());
2722}
2723
2724QualType TemplateInstantiator::TransformSubstBuiltinTemplatePackType(
2725 TypeLocBuilder &TLB, SubstBuiltinTemplatePackTypeLoc TL) {
2726 if (!getSema().ArgPackSubstIndex)
2727 return TreeTransform::TransformSubstBuiltinTemplatePackType(TLB, TL);
2728 TemplateArgument Result = SemaRef.getPackSubstitutedTemplateArgument(
2729 Arg: TL.getTypePtr()->getArgumentPack());
2730 TLB.pushTrivial(Context&: SemaRef.getASTContext(), T: Result.getAsType(),
2731 Loc: TL.getBeginLoc());
2732 return Result.getAsType();
2733}
2734
2735static concepts::Requirement::SubstitutionDiagnostic *
2736createSubstDiag(Sema &S, TemplateDeductionInfo &Info,
2737 Sema::EntityPrinter Printer) {
2738 SmallString<128> Message;
2739 SourceLocation ErrorLoc;
2740 if (Info.hasSFINAEDiagnostic()) {
2741 PartialDiagnosticAt PDA(SourceLocation(),
2742 PartialDiagnostic::NullDiagnostic{});
2743 Info.takeSFINAEDiagnostic(PD&: PDA);
2744 PDA.second.EmitToString(Diags&: S.getDiagnostics(), Buf&: Message);
2745 ErrorLoc = PDA.first;
2746 } else {
2747 ErrorLoc = Info.getLocation();
2748 }
2749 SmallString<128> Entity;
2750 llvm::raw_svector_ostream OS(Entity);
2751 Printer(OS);
2752 const ASTContext &C = S.Context;
2753 return new (C) concepts::Requirement::SubstitutionDiagnostic{
2754 .SubstitutedEntity: C.backupStr(S: Entity), .DiagLoc: ErrorLoc, .DiagMessage: C.backupStr(S: Message)};
2755}
2756
2757concepts::Requirement::SubstitutionDiagnostic *
2758Sema::createSubstDiagAt(SourceLocation Location, EntityPrinter Printer) {
2759 SmallString<128> Entity;
2760 llvm::raw_svector_ostream OS(Entity);
2761 Printer(OS);
2762 const ASTContext &C = Context;
2763 return new (C) concepts::Requirement::SubstitutionDiagnostic{
2764 /*SubstitutedEntity=*/C.backupStr(S: Entity),
2765 /*DiagLoc=*/Location, /*DiagMessage=*/StringRef()};
2766}
2767
2768ExprResult TemplateInstantiator::TransformRequiresTypeParams(
2769 SourceLocation KWLoc, SourceLocation RBraceLoc, const RequiresExpr *RE,
2770 RequiresExprBodyDecl *Body, ArrayRef<ParmVarDecl *> Params,
2771 SmallVectorImpl<QualType> &PTypes,
2772 SmallVectorImpl<ParmVarDecl *> &TransParams,
2773 Sema::ExtParameterInfoBuilder &PInfos) {
2774
2775 TemplateDeductionInfo Info(KWLoc);
2776 Sema::InstantiatingTemplate TypeInst(SemaRef, KWLoc, RE,
2777 SourceRange{KWLoc, RBraceLoc});
2778 Sema::SFINAETrap Trap(SemaRef, Info);
2779
2780 unsigned ErrorIdx;
2781 if (getDerived().TransformFunctionTypeParams(
2782 Loc: KWLoc, Params, /*ParamTypes=*/nullptr, /*ParamInfos=*/nullptr, PTypes,
2783 PVars: &TransParams, PInfos, LastParamTransformed: &ErrorIdx) ||
2784 Trap.hasErrorOccurred()) {
2785 SmallVector<concepts::Requirement *, 4> TransReqs;
2786 ParmVarDecl *FailedDecl = Params[ErrorIdx];
2787 // Add a 'failed' Requirement to contain the error that caused the failure
2788 // here.
2789 TransReqs.push_back(Elt: RebuildTypeRequirement(SubstDiag: createSubstDiag(
2790 S&: SemaRef, Info, Printer: [&](llvm::raw_ostream &OS) { OS << *FailedDecl; })));
2791 return getDerived().RebuildRequiresExpr(RequiresKWLoc: KWLoc, Body, LParenLoc: RE->getLParenLoc(),
2792 LocalParameters: TransParams, RParenLoc: RE->getRParenLoc(),
2793 Requirements: TransReqs, ClosingBraceLoc: RBraceLoc);
2794 }
2795
2796 return ExprResult{};
2797}
2798
2799concepts::TypeRequirement *
2800TemplateInstantiator::TransformTypeRequirement(concepts::TypeRequirement *Req) {
2801 if (!Req->isDependent() && !AlwaysRebuild())
2802 return Req;
2803 if (Req->isSubstitutionFailure()) {
2804 if (AlwaysRebuild())
2805 return RebuildTypeRequirement(
2806 SubstDiag: Req->getSubstitutionDiagnostic());
2807 return Req;
2808 }
2809
2810 TemplateDeductionInfo Info(Req->getType()->getTypeLoc().getBeginLoc());
2811 Sema::SFINAETrap Trap(SemaRef, Info);
2812 Sema::InstantiatingTemplate TypeInst(
2813 SemaRef, Req->getType()->getTypeLoc().getBeginLoc(), Req,
2814 Req->getType()->getTypeLoc().getSourceRange());
2815 if (TypeInst.isInvalid())
2816 return nullptr;
2817 TypeSourceInfo *TransType = TransformType(TSI: Req->getType());
2818 if (!TransType || Trap.hasErrorOccurred())
2819 return RebuildTypeRequirement(SubstDiag: createSubstDiag(S&: SemaRef, Info,
2820 Printer: [&] (llvm::raw_ostream& OS) {
2821 Req->getType()->getType().print(OS, Policy: SemaRef.getPrintingPolicy());
2822 }));
2823 return RebuildTypeRequirement(T: TransType);
2824}
2825
2826concepts::ExprRequirement *
2827TemplateInstantiator::TransformExprRequirement(concepts::ExprRequirement *Req) {
2828 if (!Req->isDependent() && !AlwaysRebuild())
2829 return Req;
2830
2831 llvm::PointerUnion<Expr *, concepts::Requirement::SubstitutionDiagnostic *>
2832 TransExpr;
2833 if (Req->isExprSubstitutionFailure())
2834 TransExpr = Req->getExprSubstitutionDiagnostic();
2835 else {
2836 Expr *E = Req->getExpr();
2837 TemplateDeductionInfo Info(E->getBeginLoc());
2838 Sema::SFINAETrap Trap(SemaRef, Info);
2839 Sema::InstantiatingTemplate ExprInst(SemaRef, E->getBeginLoc(), Req,
2840 E->getSourceRange());
2841 if (ExprInst.isInvalid())
2842 return nullptr;
2843 ExprResult TransExprRes = TransformExpr(E);
2844 if (!TransExprRes.isInvalid() && !Trap.hasErrorOccurred() &&
2845 TransExprRes.get()->hasPlaceholderType())
2846 TransExprRes = SemaRef.CheckPlaceholderExpr(E: TransExprRes.get());
2847 if (TransExprRes.isInvalid() || Trap.hasErrorOccurred())
2848 TransExpr = createSubstDiag(S&: SemaRef, Info, Printer: [&](llvm::raw_ostream &OS) {
2849 E->printPretty(OS, Helper: nullptr, Policy: SemaRef.getPrintingPolicy());
2850 });
2851 else
2852 TransExpr = TransExprRes.get();
2853 }
2854
2855 std::optional<concepts::ExprRequirement::ReturnTypeRequirement> TransRetReq;
2856 const auto &RetReq = Req->getReturnTypeRequirement();
2857 if (RetReq.isEmpty())
2858 TransRetReq.emplace();
2859 else if (RetReq.isSubstitutionFailure())
2860 TransRetReq.emplace(args: RetReq.getSubstitutionDiagnostic());
2861 else if (RetReq.isTypeConstraint()) {
2862 TemplateParameterList *OrigTPL =
2863 RetReq.getTypeConstraintTemplateParameterList();
2864 TemplateDeductionInfo Info(OrigTPL->getTemplateLoc());
2865 Sema::SFINAETrap Trap(SemaRef, Info);
2866 Sema::InstantiatingTemplate TPLInst(SemaRef, OrigTPL->getTemplateLoc(), Req,
2867 OrigTPL->getSourceRange());
2868 if (TPLInst.isInvalid())
2869 return nullptr;
2870 TemplateParameterList *TPL = TransformTemplateParameterList(OrigTPL);
2871 if (!TPL || Trap.hasErrorOccurred())
2872 TransRetReq.emplace(args: createSubstDiag(S&: SemaRef, Info,
2873 Printer: [&] (llvm::raw_ostream& OS) {
2874 RetReq.getTypeConstraint()->getImmediatelyDeclaredConstraint()
2875 ->printPretty(OS, Helper: nullptr, Policy: SemaRef.getPrintingPolicy());
2876 }));
2877 else {
2878 TPLInst.Clear();
2879 TransRetReq.emplace(args&: TPL);
2880 }
2881 }
2882 assert(TransRetReq && "All code paths leading here must set TransRetReq");
2883 if (Expr *E = dyn_cast<Expr *>(Val&: TransExpr))
2884 return RebuildExprRequirement(E, IsSimple: Req->isSimple(), NoexceptLoc: Req->getNoexceptLoc(),
2885 Ret: std::move(*TransRetReq));
2886 return RebuildExprRequirement(
2887 SubstDiag: cast<concepts::Requirement::SubstitutionDiagnostic *>(Val&: TransExpr),
2888 IsSimple: Req->isSimple(), NoexceptLoc: Req->getNoexceptLoc(), Ret: std::move(*TransRetReq));
2889}
2890
2891concepts::NestedRequirement *
2892TemplateInstantiator::TransformNestedRequirement(
2893 concepts::NestedRequirement *Req) {
2894
2895 ASTContext &C = SemaRef.Context;
2896
2897 ConstraintSatisfaction Satisfaction;
2898
2899 auto NestedReqWithDiag = [&C, this](Expr *E,
2900 ConstraintSatisfaction Satisfaction) {
2901 Satisfaction.IsSatisfied = false;
2902 SmallString<128> Entity;
2903 llvm::raw_svector_ostream OS(Entity);
2904 E->printPretty(OS, Helper: nullptr, Policy: SemaRef.getPrintingPolicy());
2905 return new (C) concepts::NestedRequirement(
2906 SemaRef.Context, C.backupStr(S: Entity), std::move(Satisfaction));
2907 };
2908
2909 if (Req->hasInvalidConstraint()) {
2910 if (AlwaysRebuild())
2911 return RebuildNestedRequirement(InvalidConstraintEntity: Req->getInvalidConstraintEntity(),
2912 Satisfaction: Req->getConstraintSatisfaction());
2913 return Req;
2914 }
2915
2916 Expr *Constraint = Req->getConstraintExpr();
2917
2918 if (!getEvaluateConstraints()) {
2919 ExprResult TransConstraint = TransformExpr(E: Req->getConstraintExpr());
2920 if (TransConstraint.isInvalid() || !TransConstraint.get())
2921 return nullptr;
2922 if (TransConstraint.get()->isInstantiationDependent())
2923 return new (SemaRef.Context)
2924 concepts::NestedRequirement(TransConstraint.get());
2925 ConstraintSatisfaction Satisfaction;
2926 return new (SemaRef.Context) concepts::NestedRequirement(
2927 SemaRef.Context, TransConstraint.get(), Satisfaction);
2928 }
2929
2930 bool Success;
2931 Expr *NewConstraint;
2932 {
2933 EnterExpressionEvaluationContext ContextRAII(
2934 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
2935 Sema::InstantiatingTemplate ConstrInst(
2936 SemaRef, Constraint->getBeginLoc(), Req,
2937 Sema::InstantiatingTemplate::ConstraintsCheck(),
2938 Constraint->getSourceRange());
2939
2940 if (ConstrInst.isInvalid())
2941 return nullptr;
2942
2943 Success = !SemaRef.CheckConstraintSatisfaction(
2944 Entity: Req, AssociatedConstraints: AssociatedConstraint(Constraint), TemplateArgLists: TemplateArgs,
2945 TemplateIDRange: Constraint->getSourceRange(), Satisfaction,
2946 /*TopLevelConceptId=*/nullptr, ConvertedExpr: &NewConstraint);
2947 }
2948
2949 if (!Success || Satisfaction.HasSubstitutionFailure())
2950 return NestedReqWithDiag(Constraint, Satisfaction);
2951
2952 // FIXME: const correctness
2953 // MLTAL might be dependent.
2954 if (!NewConstraint) {
2955 if (!Satisfaction.IsSatisfied)
2956 return NestedReqWithDiag(Constraint, Satisfaction);
2957
2958 NewConstraint = Constraint;
2959 }
2960 return new (C) concepts::NestedRequirement(C, NewConstraint, Satisfaction);
2961}
2962
2963TypeSourceInfo *Sema::SubstType(TypeSourceInfo *T,
2964 const MultiLevelTemplateArgumentList &Args,
2965 SourceLocation Loc, DeclarationName Entity,
2966 bool AllowDeducedTST) {
2967 if (!T->getType()->isInstantiationDependentType() &&
2968 !T->getType()->isVariablyModifiedType())
2969 return T;
2970
2971 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
2972 return AllowDeducedTST ? Instantiator.TransformTypeWithDeducedTST(TSI: T)
2973 : Instantiator.TransformType(TSI: T);
2974}
2975
2976TypeSourceInfo *Sema::SubstType(TypeLoc TL,
2977 const MultiLevelTemplateArgumentList &Args,
2978 SourceLocation Loc, DeclarationName Entity) {
2979 if (TL.getType().isNull())
2980 return nullptr;
2981
2982 if (!TL.getType()->isInstantiationDependentType() &&
2983 !TL.getType()->isVariablyModifiedType()) {
2984 // FIXME: Make a copy of the TypeLoc data here, so that we can
2985 // return a new TypeSourceInfo. Inefficient!
2986 TypeLocBuilder TLB;
2987 TLB.pushFullCopy(L: TL);
2988 return TLB.getTypeSourceInfo(Context, T: TL.getType());
2989 }
2990
2991 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
2992 TypeLocBuilder TLB;
2993 TLB.reserve(Requested: TL.getFullDataSize());
2994 QualType Result = Instantiator.TransformType(TLB, T: TL);
2995 if (Result.isNull())
2996 return nullptr;
2997
2998 return TLB.getTypeSourceInfo(Context, T: Result);
2999}
3000
3001/// Deprecated form of the above.
3002QualType Sema::SubstType(QualType T,
3003 const MultiLevelTemplateArgumentList &TemplateArgs,
3004 SourceLocation Loc, DeclarationName Entity,
3005 bool *IsIncompleteSubstitution) {
3006 // If T is not a dependent type or a variably-modified type, there
3007 // is nothing to do.
3008 if (!T->isInstantiationDependentType() && !T->isVariablyModifiedType())
3009 return T;
3010
3011 TemplateInstantiator Instantiator(
3012 *this, TemplateArgs, Loc, Entity,
3013 /*BailOutOnIncomplete=*/IsIncompleteSubstitution != nullptr);
3014 QualType QT = Instantiator.TransformType(T);
3015 if (IsIncompleteSubstitution && Instantiator.getIsIncomplete())
3016 *IsIncompleteSubstitution = true;
3017 return QT;
3018}
3019
3020static bool NeedsInstantiationAsFunctionType(TypeSourceInfo *T) {
3021 if (T->getType()->isInstantiationDependentType() ||
3022 T->getType()->isVariablyModifiedType())
3023 return true;
3024
3025 TypeLoc TL = T->getTypeLoc().IgnoreParens();
3026 if (!TL.getAs<FunctionProtoTypeLoc>())
3027 return false;
3028
3029 FunctionProtoTypeLoc FP = TL.castAs<FunctionProtoTypeLoc>();
3030 for (ParmVarDecl *P : FP.getParams()) {
3031 // This must be synthesized from a typedef.
3032 if (!P) continue;
3033
3034 // If there are any parameters, a new TypeSourceInfo that refers to the
3035 // instantiated parameters must be built.
3036 return true;
3037 }
3038
3039 return false;
3040}
3041
3042TypeSourceInfo *Sema::SubstFunctionDeclType(
3043 TypeSourceInfo *T, const MultiLevelTemplateArgumentList &Args,
3044 SourceLocation Loc, DeclarationName Entity, CXXRecordDecl *ThisContext,
3045 Qualifiers ThisTypeQuals, bool EvaluateConstraints) {
3046 if (!NeedsInstantiationAsFunctionType(T))
3047 return T;
3048
3049 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
3050 Instantiator.setEvaluateConstraints(EvaluateConstraints);
3051
3052 TypeLocBuilder TLB;
3053
3054 TypeLoc TL = T->getTypeLoc();
3055 TLB.reserve(Requested: TL.getFullDataSize());
3056
3057 QualType Result;
3058
3059 if (FunctionProtoTypeLoc Proto =
3060 TL.IgnoreParens().getAs<FunctionProtoTypeLoc>()) {
3061 // Instantiate the type, other than its exception specification. The
3062 // exception specification is instantiated in InitFunctionInstantiation
3063 // once we've built the FunctionDecl.
3064 // FIXME: Set the exception specification to EST_Uninstantiated here,
3065 // instead of rebuilding the function type again later.
3066 Result = Instantiator.TransformFunctionProtoType(
3067 TLB, TL: Proto, ThisContext, ThisTypeQuals,
3068 TransformExceptionSpec: [](FunctionProtoType::ExceptionSpecInfo &ESI,
3069 bool &Changed) { return false; });
3070 } else {
3071 Result = Instantiator.TransformType(TLB, T: TL);
3072 }
3073 // When there are errors resolving types, clang may use IntTy as a fallback,
3074 // breaking our assumption that function declarations have function types.
3075 if (Result.isNull() || !Result->isFunctionType())
3076 return nullptr;
3077
3078 return TLB.getTypeSourceInfo(Context, T: Result);
3079}
3080
3081bool Sema::SubstExceptionSpec(SourceLocation Loc,
3082 FunctionProtoType::ExceptionSpecInfo &ESI,
3083 SmallVectorImpl<QualType> &ExceptionStorage,
3084 const MultiLevelTemplateArgumentList &Args) {
3085 bool Changed = false;
3086 TemplateInstantiator Instantiator(*this, Args, Loc, DeclarationName());
3087 return Instantiator.TransformExceptionSpec(Loc, ESI, Exceptions&: ExceptionStorage,
3088 Changed);
3089}
3090
3091void Sema::SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto,
3092 const MultiLevelTemplateArgumentList &Args) {
3093 FunctionProtoType::ExceptionSpecInfo ESI =
3094 Proto->getExtProtoInfo().ExceptionSpec;
3095
3096 SmallVector<QualType, 4> ExceptionStorage;
3097 if (SubstExceptionSpec(Loc: New->getTypeSourceInfo()->getTypeLoc().getEndLoc(),
3098 ESI, ExceptionStorage, Args))
3099 // On error, recover by dropping the exception specification.
3100 ESI.Type = EST_None;
3101
3102 UpdateExceptionSpec(FD: New, ESI);
3103}
3104
3105namespace {
3106
3107 struct GetContainedInventedTypeParmVisitor :
3108 public TypeVisitor<GetContainedInventedTypeParmVisitor,
3109 TemplateTypeParmDecl *> {
3110 using TypeVisitor<GetContainedInventedTypeParmVisitor,
3111 TemplateTypeParmDecl *>::Visit;
3112
3113 TemplateTypeParmDecl *Visit(QualType T) {
3114 if (T.isNull())
3115 return nullptr;
3116 return Visit(T: T.getTypePtr());
3117 }
3118 // The deduced type itself.
3119 TemplateTypeParmDecl *VisitTemplateTypeParmType(
3120 const TemplateTypeParmType *T) {
3121 if (!T->getDecl() || !T->getDecl()->isImplicit())
3122 return nullptr;
3123 return T->getDecl();
3124 }
3125
3126 // Only these types can contain 'auto' types, and subsequently be replaced
3127 // by references to invented parameters.
3128
3129 TemplateTypeParmDecl *VisitPointerType(const PointerType *T) {
3130 return Visit(T: T->getPointeeType());
3131 }
3132
3133 TemplateTypeParmDecl *VisitBlockPointerType(const BlockPointerType *T) {
3134 return Visit(T: T->getPointeeType());
3135 }
3136
3137 TemplateTypeParmDecl *VisitReferenceType(const ReferenceType *T) {
3138 return Visit(T: T->getPointeeTypeAsWritten());
3139 }
3140
3141 TemplateTypeParmDecl *VisitMemberPointerType(const MemberPointerType *T) {
3142 return Visit(T: T->getPointeeType());
3143 }
3144
3145 TemplateTypeParmDecl *VisitArrayType(const ArrayType *T) {
3146 return Visit(T: T->getElementType());
3147 }
3148
3149 TemplateTypeParmDecl *VisitDependentSizedExtVectorType(
3150 const DependentSizedExtVectorType *T) {
3151 return Visit(T: T->getElementType());
3152 }
3153
3154 TemplateTypeParmDecl *VisitVectorType(const VectorType *T) {
3155 return Visit(T: T->getElementType());
3156 }
3157
3158 TemplateTypeParmDecl *VisitFunctionProtoType(const FunctionProtoType *T) {
3159 return VisitFunctionType(T);
3160 }
3161
3162 TemplateTypeParmDecl *VisitFunctionType(const FunctionType *T) {
3163 return Visit(T: T->getReturnType());
3164 }
3165
3166 TemplateTypeParmDecl *VisitParenType(const ParenType *T) {
3167 return Visit(T: T->getInnerType());
3168 }
3169
3170 TemplateTypeParmDecl *VisitAttributedType(const AttributedType *T) {
3171 return Visit(T: T->getModifiedType());
3172 }
3173
3174 TemplateTypeParmDecl *VisitMacroQualifiedType(const MacroQualifiedType *T) {
3175 return Visit(T: T->getUnderlyingType());
3176 }
3177
3178 TemplateTypeParmDecl *VisitAdjustedType(const AdjustedType *T) {
3179 return Visit(T: T->getOriginalType());
3180 }
3181
3182 TemplateTypeParmDecl *VisitPackExpansionType(const PackExpansionType *T) {
3183 return Visit(T: T->getPattern());
3184 }
3185 };
3186
3187} // namespace
3188
3189bool Sema::SubstTypeConstraint(
3190 TemplateTypeParmDecl *Inst, const TypeConstraint *TC,
3191 const MultiLevelTemplateArgumentList &TemplateArgs,
3192 bool EvaluateConstraints) {
3193 const ASTTemplateArgumentListInfo *TemplArgInfo =
3194 TC->getTemplateArgsAsWritten();
3195
3196 if (!EvaluateConstraints) {
3197 UnsignedOrNone Index = TC->getArgPackSubstIndex();
3198 bool ContainsUnexpandedPack =
3199 TemplArgInfo &&
3200 llvm::any_of(
3201 Range: TemplArgInfo->arguments(), P: [](const TemplateArgumentLoc &TA) {
3202 return TA.getArgument().containsUnexpandedParameterPack();
3203 });
3204 if (!Index && ContainsUnexpandedPack)
3205 Index = SemaRef.ArgPackSubstIndex;
3206 Inst->setTypeConstraint(CR: TC->getConceptReference(),
3207 ImmediatelyDeclaredConstraint: TC->getImmediatelyDeclaredConstraint(), ArgPackSubstIndex: Index);
3208 return false;
3209 }
3210
3211 TemplateArgumentListInfo InstArgs;
3212
3213 if (TemplArgInfo) {
3214 InstArgs.setLAngleLoc(TemplArgInfo->LAngleLoc);
3215 InstArgs.setRAngleLoc(TemplArgInfo->RAngleLoc);
3216 // Constraints on lambda arguments can depend on the substituted parameters.
3217 TemplateInstantiator Instantiator(
3218 TemplateInstantiator::ForConstraintSubstitution, *this, TemplateArgs,
3219 TC->getConceptNameLoc(), DeclarationName());
3220 if (Instantiator.TransformTemplateArguments(
3221 First: TemplArgInfo->arguments().begin(), Last: TemplArgInfo->arguments().end(),
3222 Outputs&: InstArgs))
3223 return true;
3224 }
3225 return AttachTypeConstraint(
3226 NS: TC->getNestedNameSpecifierLoc(), NameInfo: TC->getConceptNameInfo(),
3227 NamedConcept: TC->getNamedConcept(),
3228 /*FoundDecl=*/TC->getConceptReference()->getFoundDecl(), TemplateArgs: &InstArgs, ConstrainedParameter: Inst,
3229 EllipsisLoc: Inst->isParameterPack()
3230 ? cast<CXXFoldExpr>(Val: TC->getImmediatelyDeclaredConstraint())
3231 ->getEllipsisLoc()
3232 : SourceLocation());
3233}
3234
3235ParmVarDecl *Sema::SubstParmVarDecl(
3236 ParmVarDecl *OldParm, const MultiLevelTemplateArgumentList &TemplateArgs,
3237 int indexAdjustment, UnsignedOrNone NumExpansions, bool ExpectParameterPack,
3238 bool EvaluateConstraint, LateInstantiatedAttrVec *LateAttrs) {
3239 TypeSourceInfo *OldTSI = OldParm->getTypeSourceInfo();
3240 TypeSourceInfo *NewTSI = nullptr;
3241
3242 TypeLoc OldTL = OldTSI->getTypeLoc();
3243 if (PackExpansionTypeLoc ExpansionTL = OldTL.getAs<PackExpansionTypeLoc>()) {
3244
3245 // We have a function parameter pack. Substitute into the pattern of the
3246 // expansion.
3247 NewTSI = SubstType(TL: ExpansionTL.getPatternLoc(), Args: TemplateArgs,
3248 Loc: OldParm->getLocation(), Entity: OldParm->getDeclName());
3249 if (!NewTSI)
3250 return nullptr;
3251
3252 if (NewTSI->getType()->containsUnexpandedParameterPack()) {
3253 // We still have unexpanded parameter packs, which means that
3254 // our function parameter is still a function parameter pack.
3255 // Therefore, make its type a pack expansion type.
3256 NewTSI = CheckPackExpansion(Pattern: NewTSI, EllipsisLoc: ExpansionTL.getEllipsisLoc(),
3257 NumExpansions);
3258 } else if (ExpectParameterPack) {
3259 // We expected to get a parameter pack but didn't (because the type
3260 // itself is not a pack expansion type), so complain. This can occur when
3261 // the substitution goes through an alias template that "loses" the
3262 // pack expansion.
3263 Diag(Loc: OldParm->getLocation(),
3264 DiagID: diag::err_function_parameter_pack_without_parameter_packs)
3265 << NewTSI->getType();
3266 return nullptr;
3267 }
3268 } else {
3269 NewTSI = SubstType(T: OldTSI, Args: TemplateArgs, Loc: OldParm->getLocation(),
3270 Entity: OldParm->getDeclName());
3271 }
3272
3273 if (!NewTSI)
3274 return nullptr;
3275
3276 if (NewTSI->getType()->isVoidType()) {
3277 Diag(Loc: OldParm->getLocation(), DiagID: diag::err_param_with_void_type);
3278 return nullptr;
3279 }
3280
3281 // In abbreviated templates, TemplateTypeParmDecls with possible
3282 // TypeConstraints are created when the parameter list is originally parsed.
3283 // The TypeConstraints can therefore reference other functions parameters in
3284 // the abbreviated function template, which is why we must instantiate them
3285 // here, when the instantiated versions of those referenced parameters are in
3286 // scope.
3287 if (TemplateTypeParmDecl *TTP =
3288 GetContainedInventedTypeParmVisitor().Visit(T: OldTSI->getType())) {
3289 if (const TypeConstraint *TC = TTP->getTypeConstraint()) {
3290 auto *Inst = cast_or_null<TemplateTypeParmDecl>(
3291 Val: FindInstantiatedDecl(Loc: TTP->getLocation(), D: TTP, TemplateArgs));
3292 // We will first get here when instantiating the abbreviated function
3293 // template's described function, but we might also get here later.
3294 // Make sure we do not instantiate the TypeConstraint more than once.
3295 if (Inst && !Inst->getTypeConstraint()) {
3296 if (SubstTypeConstraint(Inst, TC, TemplateArgs, EvaluateConstraints: EvaluateConstraint))
3297 return nullptr;
3298 }
3299 }
3300 }
3301
3302 ParmVarDecl *NewParm = CheckParameter(
3303 DC: Context.getTranslationUnitDecl(), StartLoc: OldParm->getInnerLocStart(),
3304 NameLoc: OldParm->getLocation(), Name: OldParm->getIdentifier(), T: NewTSI->getType(),
3305 TSInfo: NewTSI, SC: OldParm->getStorageClass());
3306 if (!NewParm)
3307 return nullptr;
3308
3309 // Mark the (new) default argument as uninstantiated (if any).
3310 if (OldParm->hasUninstantiatedDefaultArg()) {
3311 Expr *Arg = OldParm->getUninstantiatedDefaultArg();
3312 NewParm->setUninstantiatedDefaultArg(Arg);
3313 } else if (OldParm->hasUnparsedDefaultArg()) {
3314 NewParm->setUnparsedDefaultArg();
3315 UnparsedDefaultArgInstantiations[OldParm].push_back(NewVal: NewParm);
3316 } else if (Expr *Arg = OldParm->getDefaultArg()) {
3317 // Default arguments cannot be substituted until the declaration context
3318 // for the associated function or lambda capture class is available.
3319 // This is necessary for cases like the following where construction of
3320 // the lambda capture class for the outer lambda is dependent on the
3321 // parameter types but where the default argument is dependent on the
3322 // outer lambda's declaration context.
3323 // template <typename T>
3324 // auto f() {
3325 // return [](T = []{ return T{}; }()) { return 0; };
3326 // }
3327 NewParm->setUninstantiatedDefaultArg(Arg);
3328 }
3329
3330 NewParm->setExplicitObjectParameterLoc(
3331 OldParm->getExplicitObjectParamThisLoc());
3332 NewParm->setHasInheritedDefaultArg(OldParm->hasInheritedDefaultArg());
3333
3334 if (OldParm->isParameterPack() && !NewParm->isParameterPack()) {
3335 // Add the new parameter to the instantiated parameter pack.
3336 CurrentInstantiationScope->InstantiatedLocalPackArg(D: OldParm, Inst: NewParm);
3337 } else {
3338 // Introduce an Old -> New mapping
3339 CurrentInstantiationScope->InstantiatedLocal(D: OldParm, Inst: NewParm);
3340 }
3341
3342 // A parameter that is not a function's own, such as one of a function
3343 // pointer's pointee, belongs to no function (see ActOnParamDeclarator); keep
3344 // it in the translation unit, where CheckParameter created it.
3345 // FIXME: For other parameters from a FunctionProtoType, CurContext can be
3346 // anything; is this right?
3347 if (!OldParm->getDeclContext()->isTranslationUnit())
3348 NewParm->setDeclContext(CurContext);
3349
3350 NewParm->setScopeInfo(scopeDepth: OldParm->getFunctionScopeDepth(),
3351 parameterIndex: OldParm->getFunctionScopeIndex() + indexAdjustment);
3352
3353 InstantiateAttrs(TemplateArgs, Pattern: OldParm, Inst: NewParm, LateAttrs,
3354 OuterMostScope: CurrentInstantiationScope);
3355
3356 NewParm->deduceParmAddressSpace(Ctxt: Context);
3357
3358 return NewParm;
3359}
3360
3361bool Sema::SubstParmTypes(
3362 SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
3363 const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
3364 const MultiLevelTemplateArgumentList &TemplateArgs,
3365 SmallVectorImpl<QualType> &ParamTypes,
3366 SmallVectorImpl<ParmVarDecl *> *OutParams,
3367 ExtParameterInfoBuilder &ParamInfos, const QualType *OldParamTypes,
3368 bool EvaluateConstraints) {
3369 // If there is a parameter with no ParmVarDecl to substitute, its type needs
3370 // to come from OldParamTypes instead.
3371 assert((OldParamTypes || !llvm::is_contained(Params, nullptr)) &&
3372 "a parameter with no ParmVarDecl needs OldParamTypes to be passed");
3373 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
3374 DeclarationName());
3375 Instantiator.setEvaluateConstraints(EvaluateConstraints);
3376 return Instantiator.TransformFunctionTypeParams(Loc, Params, ParamTypes: OldParamTypes,
3377 ParamInfos: ExtParamInfos, PTypes&: ParamTypes,
3378 PVars: OutParams, PInfos&: ParamInfos);
3379}
3380
3381bool Sema::SubstDefaultArgument(
3382 SourceLocation Loc,
3383 ParmVarDecl *Param,
3384 const MultiLevelTemplateArgumentList &TemplateArgs,
3385 bool ForCallExpr) {
3386 FunctionDecl *FD = cast<FunctionDecl>(Val: Param->getDeclContext());
3387 Expr *PatternExpr = Param->getUninstantiatedDefaultArg();
3388
3389 RecursiveInstGuard AlreadyInstantiating(
3390 *this, Param, RecursiveInstGuard::Kind::DefaultArgument);
3391 if (AlreadyInstantiating) {
3392 Param->setInvalidDecl();
3393 return Diag(Loc: Param->getBeginLoc(), DiagID: diag::err_recursive_default_argument)
3394 << FD << PatternExpr->getSourceRange();
3395 }
3396
3397 EnterExpressionEvaluationContext EvalContext(
3398 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
3399 NonSFINAEContext _(*this);
3400 InstantiatingTemplate Inst(*this, Loc, Param, TemplateArgs.getInnermost());
3401 if (Inst.isInvalid())
3402 return true;
3403
3404 ExprResult Result;
3405 // C++ [dcl.fct.default]p5:
3406 // The names in the [default argument] expression are bound, and
3407 // the semantic constraints are checked, at the point where the
3408 // default argument expression appears.
3409 ContextRAII SavedContext(*this, FD);
3410 {
3411 std::optional<LocalInstantiationScope> LIS;
3412
3413 if (ForCallExpr) {
3414 // When instantiating a default argument due to use in a call expression,
3415 // an instantiation scope that includes the parameters of the callee is
3416 // required to satisfy references from the default argument. For example:
3417 // template<typename T> void f(T a, int = decltype(a)());
3418 // void g() { f(0); }
3419 LIS.emplace(args&: *this);
3420 FunctionDecl *PatternFD = FD->getTemplateInstantiationPattern(
3421 /*ForDefinition*/ false);
3422 if (addInstantiatedParametersToScope(Function: FD, PatternDecl: PatternFD, Scope&: *LIS, TemplateArgs))
3423 return true;
3424 }
3425
3426 runWithSufficientStackSpace(Loc, Fn: [&] {
3427 Result = SubstInitializer(E: PatternExpr, TemplateArgs,
3428 /*DirectInit*/ CXXDirectInit: false);
3429 });
3430 }
3431 if (Result.isInvalid())
3432 return true;
3433
3434 if (ForCallExpr) {
3435 // Check the expression as an initializer for the parameter.
3436 InitializedEntity Entity
3437 = InitializedEntity::InitializeParameter(Context, Parm: Param);
3438 InitializationKind Kind = InitializationKind::CreateCopy(
3439 InitLoc: Param->getLocation(),
3440 /*FIXME:EqualLoc*/ EqualLoc: PatternExpr->getBeginLoc());
3441 Expr *ResultE = Result.getAs<Expr>();
3442
3443 InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
3444 Result = InitSeq.Perform(S&: *this, Entity, Kind, Args: ResultE);
3445 if (Result.isInvalid())
3446 return true;
3447
3448 Result =
3449 ActOnFinishFullExpr(Expr: Result.getAs<Expr>(), CC: Param->getOuterLocStart(),
3450 /*DiscardedValue*/ false);
3451 } else {
3452 // FIXME: Obtain the source location for the '=' token.
3453 SourceLocation EqualLoc = PatternExpr->getBeginLoc();
3454 Result = ConvertParamDefaultArgument(Param, DefaultArg: Result.getAs<Expr>(), EqualLoc);
3455 }
3456 if (Result.isInvalid())
3457 return true;
3458
3459 // Remember the instantiated default argument.
3460 Param->setDefaultArg(Result.getAs<Expr>());
3461
3462 return false;
3463}
3464
3465// See TreeTransform::PreparePackForExpansion for the relevant comment.
3466// This function implements the same concept for base specifiers.
3467static bool
3468PreparePackForExpansion(Sema &S, const CXXBaseSpecifier &Base,
3469 const MultiLevelTemplateArgumentList &TemplateArgs,
3470 TypeSourceInfo *&Out, UnexpandedInfo &Info) {
3471 SourceRange BaseSourceRange = Base.getSourceRange();
3472 SourceLocation BaseEllipsisLoc = Base.getEllipsisLoc();
3473 Info.Ellipsis = Base.getEllipsisLoc();
3474 auto ComputeInfo = [&S, &TemplateArgs, BaseSourceRange, BaseEllipsisLoc](
3475 TypeSourceInfo *BaseTypeInfo,
3476 bool IsLateExpansionAttempt, UnexpandedInfo &Info) {
3477 // This is a pack expansion. See whether we should expand it now, or
3478 // wait until later.
3479 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
3480 S.collectUnexpandedParameterPacks(TL: BaseTypeInfo->getTypeLoc(), Unexpanded);
3481 if (IsLateExpansionAttempt) {
3482 // Request expansion only when there is an opportunity to expand a pack
3483 // that required a substituion first.
3484 bool SawPackTypes =
3485 llvm::any_of(Range&: Unexpanded, P: [](UnexpandedParameterPack P) {
3486 return isa<const SubstBuiltinTemplatePackType *>(Val: P.first);
3487 });
3488 if (!SawPackTypes) {
3489 Info.Expand = false;
3490 return false;
3491 }
3492 }
3493
3494 // Determine whether the set of unexpanded parameter packs can and should be
3495 // expanded.
3496 Info.Expand = false;
3497 Info.RetainExpansion = false;
3498 Info.NumExpansions = std::nullopt;
3499 return S.CheckParameterPacksForExpansion(
3500 EllipsisLoc: BaseEllipsisLoc, PatternRange: BaseSourceRange, Unexpanded, TemplateArgs,
3501 /*FailOnPackProducingTemplates=*/false, ShouldExpand&: Info.Expand,
3502 RetainExpansion&: Info.RetainExpansion, NumExpansions&: Info.NumExpansions);
3503 };
3504
3505 if (ComputeInfo(Base.getTypeSourceInfo(), false, Info))
3506 return true;
3507
3508 if (Info.Expand) {
3509 Out = Base.getTypeSourceInfo();
3510 return false;
3511 }
3512
3513 // The resulting base specifier will (still) be a pack expansion.
3514 {
3515 Sema::ArgPackSubstIndexRAII SubstIndex(S, std::nullopt);
3516 Out = S.SubstType(T: Base.getTypeSourceInfo(), Args: TemplateArgs,
3517 Loc: BaseSourceRange.getBegin(), Entity: DeclarationName());
3518 }
3519 if (!Out->getType()->containsUnexpandedParameterPack())
3520 return false;
3521
3522 // Some packs will learn their length after substitution.
3523 // We may need to request their expansion.
3524 if (ComputeInfo(Out, /*IsLateExpansionAttempt=*/true, Info))
3525 return true;
3526 if (Info.Expand)
3527 Info.ExpandUnderForgetSubstitions = true;
3528 return false;
3529}
3530
3531bool
3532Sema::SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
3533 CXXRecordDecl *Pattern,
3534 const MultiLevelTemplateArgumentList &TemplateArgs) {
3535 bool Invalid = false;
3536 SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases;
3537 for (const auto &Base : Pattern->bases()) {
3538 if (!Base.getType()->isInstantiationDependentType()) {
3539 if (const CXXRecordDecl *RD = Base.getType()->getAsCXXRecordDecl()) {
3540 if (RD->isInvalidDecl())
3541 Instantiation->setInvalidDecl();
3542 }
3543 InstantiatedBases.push_back(Elt: new (Context) CXXBaseSpecifier(Base));
3544 continue;
3545 }
3546
3547 SourceLocation EllipsisLoc;
3548 TypeSourceInfo *BaseTypeLoc = nullptr;
3549 if (Base.isPackExpansion()) {
3550 UnexpandedInfo Info;
3551 if (PreparePackForExpansion(S&: *this, Base, TemplateArgs, Out&: BaseTypeLoc,
3552 Info)) {
3553 Invalid = true;
3554 continue;
3555 }
3556
3557 // If we should expand this pack expansion now, do so.
3558 MultiLevelTemplateArgumentList EmptyList;
3559 const MultiLevelTemplateArgumentList *ArgsForSubst = &TemplateArgs;
3560 if (Info.ExpandUnderForgetSubstitions)
3561 ArgsForSubst = &EmptyList;
3562
3563 if (Info.Expand) {
3564 for (unsigned I = 0; I != *Info.NumExpansions; ++I) {
3565 Sema::ArgPackSubstIndexRAII SubstIndex(*this, I);
3566
3567 TypeSourceInfo *Expanded =
3568 SubstType(T: BaseTypeLoc, Args: *ArgsForSubst,
3569 Loc: Base.getSourceRange().getBegin(), Entity: DeclarationName());
3570 if (!Expanded) {
3571 Invalid = true;
3572 continue;
3573 }
3574
3575 if (CXXBaseSpecifier *InstantiatedBase = CheckBaseSpecifier(
3576 Class: Instantiation, SpecifierRange: Base.getSourceRange(), Virtual: Base.isVirtual(),
3577 Access: Base.getAccessSpecifierAsWritten(), TInfo: Expanded,
3578 EllipsisLoc: SourceLocation()))
3579 InstantiatedBases.push_back(Elt: InstantiatedBase);
3580 else
3581 Invalid = true;
3582 }
3583
3584 continue;
3585 }
3586
3587 // The resulting base specifier will (still) be a pack expansion.
3588 EllipsisLoc = Base.getEllipsisLoc();
3589 Sema::ArgPackSubstIndexRAII SubstIndex(*this, std::nullopt);
3590 BaseTypeLoc =
3591 SubstType(T: BaseTypeLoc, Args: *ArgsForSubst,
3592 Loc: Base.getSourceRange().getBegin(), Entity: DeclarationName());
3593 } else {
3594 BaseTypeLoc = SubstType(T: Base.getTypeSourceInfo(),
3595 Args: TemplateArgs,
3596 Loc: Base.getSourceRange().getBegin(),
3597 Entity: DeclarationName());
3598 }
3599
3600 if (!BaseTypeLoc) {
3601 Invalid = true;
3602 continue;
3603 }
3604
3605 if (CXXBaseSpecifier *InstantiatedBase
3606 = CheckBaseSpecifier(Class: Instantiation,
3607 SpecifierRange: Base.getSourceRange(),
3608 Virtual: Base.isVirtual(),
3609 Access: Base.getAccessSpecifierAsWritten(),
3610 TInfo: BaseTypeLoc,
3611 EllipsisLoc))
3612 InstantiatedBases.push_back(Elt: InstantiatedBase);
3613 else
3614 Invalid = true;
3615 }
3616
3617 if (!Invalid && AttachBaseSpecifiers(Class: Instantiation, Bases: InstantiatedBases))
3618 Invalid = true;
3619
3620 return Invalid;
3621}
3622
3623// Defined via #include from SemaTemplateInstantiateDecl.cpp
3624namespace clang {
3625 namespace sema {
3626 Attr *instantiateTemplateAttribute(const Attr *At, ASTContext &C, Sema &S,
3627 const MultiLevelTemplateArgumentList &TemplateArgs);
3628 Attr *instantiateTemplateAttributeForDecl(
3629 const Attr *At, ASTContext &C, Sema &S,
3630 const MultiLevelTemplateArgumentList &TemplateArgs);
3631 }
3632}
3633
3634bool Sema::InstantiateClass(SourceLocation PointOfInstantiation,
3635 CXXRecordDecl *Instantiation,
3636 CXXRecordDecl *Pattern,
3637 const MultiLevelTemplateArgumentList &TemplateArgs,
3638 TemplateSpecializationKind TSK, bool Complain) {
3639#ifndef NDEBUG
3640 RecursiveInstGuard AlreadyInstantiating(*this, Instantiation,
3641 RecursiveInstGuard::Kind::Template);
3642 assert(!AlreadyInstantiating && "should have been caught by caller");
3643#endif
3644
3645 return InstantiateClassImpl(PointOfInstantiation, Instantiation, Pattern,
3646 TemplateArgs, TSK, Complain);
3647}
3648
3649bool Sema::InstantiateClassImpl(
3650 SourceLocation PointOfInstantiation, CXXRecordDecl *Instantiation,
3651 CXXRecordDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs,
3652 TemplateSpecializationKind TSK, bool Complain) {
3653
3654 CXXRecordDecl *PatternDef
3655 = cast_or_null<CXXRecordDecl>(Val: Pattern->getDefinition());
3656 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
3657 InstantiatedFromMember: Instantiation->getInstantiatedFromMemberClass(),
3658 Pattern, PatternDef, TSK, Complain))
3659 return true;
3660
3661 llvm::TimeTraceScope TimeScope("InstantiateClass", [&]() {
3662 llvm::TimeTraceMetadata M;
3663 llvm::raw_string_ostream OS(M.Detail);
3664 Instantiation->getNameForDiagnostic(OS, Policy: getPrintingPolicy(),
3665 /*Qualified=*/true);
3666 if (llvm::isTimeTraceVerbose()) {
3667 auto Loc = SourceMgr.getExpansionLoc(Loc: Instantiation->getLocation());
3668 M.File = SourceMgr.getFilename(SpellingLoc: Loc);
3669 M.Line = SourceMgr.getExpansionLineNumber(Loc);
3670 }
3671 return M;
3672 });
3673
3674 Pattern = PatternDef;
3675
3676 // Record the point of instantiation.
3677 if (MemberSpecializationInfo *MSInfo
3678 = Instantiation->getMemberSpecializationInfo()) {
3679 MSInfo->setTemplateSpecializationKind(TSK);
3680 MSInfo->setPointOfInstantiation(PointOfInstantiation);
3681 } else if (ClassTemplateSpecializationDecl *Spec
3682 = dyn_cast<ClassTemplateSpecializationDecl>(Val: Instantiation)) {
3683 Spec->setTemplateSpecializationKind(TSK);
3684 Spec->setPointOfInstantiation(PointOfInstantiation);
3685 }
3686
3687 NonSFINAEContext _(*this);
3688 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
3689 if (Inst.isInvalid())
3690 return true;
3691 PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
3692 "instantiating class definition");
3693
3694 // Enter the scope of this instantiation. We don't use
3695 // PushDeclContext because we don't have a scope.
3696 ContextRAII SavedContext(*this, Instantiation);
3697 EnterExpressionEvaluationContext EvalContext(
3698 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
3699
3700 // If this is an instantiation of a local class, merge this local
3701 // instantiation scope with the enclosing scope. Otherwise, every
3702 // instantiation of a class has its own local instantiation scope.
3703 bool MergeWithParentScope = !Instantiation->isDefinedOutsideFunctionOrMethod();
3704 LocalInstantiationScope Scope(*this, MergeWithParentScope);
3705
3706 // Some class state isn't processed immediately but delayed till class
3707 // instantiation completes. We may not be ready to handle any delayed state
3708 // already on the stack as it might correspond to a different class, so save
3709 // it now and put it back later.
3710 SavePendingParsedClassStateRAII SavedPendingParsedClassState(*this);
3711
3712 // Pull attributes from the pattern onto the instantiation.
3713 InstantiateAttrs(TemplateArgs, Pattern, Inst: Instantiation);
3714
3715 // Start the definition of this instantiation.
3716 Instantiation->startDefinition();
3717
3718 // The instantiation is visible here, even if it was first declared in an
3719 // unimported module.
3720 Instantiation->setVisibleDespiteOwningModule();
3721
3722 // FIXME: This loses the as-written tag kind for an explicit instantiation.
3723 Instantiation->setTagKind(Pattern->getTagKind());
3724
3725 // Do substitution on the base class specifiers.
3726 if (SubstBaseSpecifiers(Instantiation, Pattern, TemplateArgs))
3727 Instantiation->setInvalidDecl();
3728
3729 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
3730 Instantiator.setEvaluateConstraints(false);
3731 SmallVector<Decl*, 4> Fields;
3732 // Delay instantiation of late parsed attributes.
3733 LateInstantiatedAttrVec LateAttrs;
3734 Instantiator.enableLateAttributeInstantiation(LA: &LateAttrs);
3735
3736 bool MightHaveConstexprVirtualFunctions = false;
3737 for (auto *Member : Pattern->decls()) {
3738 // Don't instantiate members not belonging in this semantic context.
3739 // e.g. for:
3740 // @code
3741 // template <int i> class A {
3742 // class B *g;
3743 // };
3744 // @endcode
3745 // 'class B' has the template as lexical context but semantically it is
3746 // introduced in namespace scope.
3747 if (Member->getDeclContext() != Pattern)
3748 continue;
3749
3750 // BlockDecls can appear in a default-member-initializer. They must be the
3751 // child of a BlockExpr, so we only know how to instantiate them from there.
3752 // Similarly, lambda closure types are recreated when instantiating the
3753 // corresponding LambdaExpr.
3754 if (isa<BlockDecl>(Val: Member) ||
3755 (isa<CXXRecordDecl>(Val: Member) && cast<CXXRecordDecl>(Val: Member)->isLambda()))
3756 continue;
3757
3758 if (Member->isInvalidDecl()) {
3759 Instantiation->setInvalidDecl();
3760 // Drop invalid members to prevent cascading diagnostic errors.
3761 // We make an exception for VarTemplateDecl because the primary template
3762 // is required for partial specialization lookup. Keeping it is safe from
3763 // cascading errors due to the parser's type recovery.
3764 if (!isa<VarTemplateDecl>(Val: Member))
3765 continue;
3766 }
3767
3768 Decl *NewMember = Instantiator.Visit(D: Member);
3769 if (NewMember) {
3770 if (FieldDecl *Field = dyn_cast<FieldDecl>(Val: NewMember)) {
3771 Fields.push_back(Elt: Field);
3772 } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(Val: NewMember)) {
3773 // C++11 [temp.inst]p1: The implicit instantiation of a class template
3774 // specialization causes the implicit instantiation of the definitions
3775 // of unscoped member enumerations.
3776 // Record a point of instantiation for this implicit instantiation.
3777 if (TSK == TSK_ImplicitInstantiation && !Enum->isScoped() &&
3778 Enum->isCompleteDefinition()) {
3779 MemberSpecializationInfo *MSInfo =Enum->getMemberSpecializationInfo();
3780 assert(MSInfo && "no spec info for member enum specialization");
3781 MSInfo->setTemplateSpecializationKind(TSK_ImplicitInstantiation);
3782 MSInfo->setPointOfInstantiation(PointOfInstantiation);
3783 }
3784 } else if (StaticAssertDecl *SA = dyn_cast<StaticAssertDecl>(Val: NewMember)) {
3785 if (SA->isFailed()) {
3786 // A static_assert failed. Bail out; instantiating this
3787 // class is probably not meaningful.
3788 Instantiation->setInvalidDecl();
3789 break;
3790 }
3791 } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: NewMember)) {
3792 if (MD->isConstexpr() && !MD->getFriendObjectKind() &&
3793 (MD->isVirtualAsWritten() || Instantiation->getNumBases()))
3794 MightHaveConstexprVirtualFunctions = true;
3795 }
3796
3797 if (Member->isInvalidDecl())
3798 NewMember->setInvalidDecl();
3799
3800 if (NewMember->isInvalidDecl())
3801 Instantiation->setInvalidDecl();
3802 } else {
3803 // FIXME: Eventually, a NULL return will mean that one of the
3804 // instantiations was a semantic disaster, and we'll want to mark the
3805 // declaration invalid.
3806 // For now, we expect to skip some members that we can't yet handle.
3807 }
3808 }
3809
3810 // Finish checking fields.
3811 ActOnFields(S: nullptr, RecLoc: Instantiation->getLocation(), TagDecl: Instantiation, Fields,
3812 LBrac: SourceLocation(), RBrac: SourceLocation(), AttrList: ParsedAttributesView());
3813 CheckCompletedCXXClass(S: nullptr, Record: Instantiation);
3814
3815 // Default arguments are parsed, if not instantiated. We can go instantiate
3816 // default arg exprs for default constructors if necessary now. Unless we're
3817 // parsing a class, in which case wait until that's finished.
3818 if (ParsingClassDepth == 0)
3819 ActOnFinishCXXNonNestedClass();
3820
3821 // Instantiate late parsed attributes, and attach them to their decls.
3822 InstantiateLateAttrs(TemplateArgs, LateAttrs,
3823 OuterMostScope: Instantiator.getStartingScope());
3824 Instantiator.disableLateAttributeInstantiation();
3825
3826 ActOnFinishDelayedMemberInitializers(Record: Instantiation);
3827
3828 // FIXME: We should do something similar for explicit instantiations so they
3829 // end up in the right module.
3830 if (TSK == TSK_ImplicitInstantiation) {
3831 Instantiation->setLocation(Pattern->getLocation());
3832 Instantiation->setLocStart(Pattern->getInnerLocStart());
3833 Instantiation->setBraceRange(Pattern->getBraceRange());
3834 }
3835
3836 if (!Instantiation->isInvalidDecl()) {
3837 // Perform any dependent diagnostics from the pattern.
3838 if (Pattern->isDependentContext())
3839 PerformDependentDiagnostics(Pattern, TemplateArgs);
3840
3841 // Instantiate any out-of-line class template partial
3842 // specializations now.
3843 for (TemplateDeclInstantiator::delayed_partial_spec_iterator
3844 P = Instantiator.delayed_partial_spec_begin(),
3845 PEnd = Instantiator.delayed_partial_spec_end();
3846 P != PEnd; ++P) {
3847 if (!Instantiator.InstantiateClassTemplatePartialSpecialization(
3848 ClassTemplate: P->first, PartialSpec: P->second)) {
3849 Instantiation->setInvalidDecl();
3850 break;
3851 }
3852 }
3853
3854 // Instantiate any out-of-line variable template partial
3855 // specializations now.
3856 for (TemplateDeclInstantiator::delayed_var_partial_spec_iterator
3857 P = Instantiator.delayed_var_partial_spec_begin(),
3858 PEnd = Instantiator.delayed_var_partial_spec_end();
3859 P != PEnd; ++P) {
3860 if (!Instantiator.InstantiateVarTemplatePartialSpecialization(
3861 VarTemplate: P->first, PartialSpec: P->second)) {
3862 Instantiation->setInvalidDecl();
3863 break;
3864 }
3865 }
3866 }
3867
3868 Instantiation->setIsHLSLBuiltinRecord(Pattern->isHLSLBuiltinRecord());
3869
3870 // Exit the scope of this instantiation.
3871 SavedContext.pop();
3872
3873 if (!Instantiation->isInvalidDecl()) {
3874 // Always emit the vtable for an explicit instantiation definition
3875 // of a polymorphic class template specialization. Otherwise, eagerly
3876 // instantiate only constexpr virtual functions in preparation for their use
3877 // in constant evaluation.
3878 if (TSK == TSK_ExplicitInstantiationDefinition)
3879 MarkVTableUsed(Loc: PointOfInstantiation, Class: Instantiation, DefinitionRequired: true);
3880 else if (MightHaveConstexprVirtualFunctions)
3881 MarkVirtualMembersReferenced(Loc: PointOfInstantiation, RD: Instantiation,
3882 /*ConstexprOnly*/ true);
3883 }
3884
3885 Consumer.HandleTagDeclDefinition(D: Instantiation);
3886
3887 return Instantiation->isInvalidDecl();
3888}
3889
3890bool Sema::InstantiateEnum(SourceLocation PointOfInstantiation,
3891 EnumDecl *Instantiation, EnumDecl *Pattern,
3892 const MultiLevelTemplateArgumentList &TemplateArgs,
3893 TemplateSpecializationKind TSK) {
3894#ifndef NDEBUG
3895 RecursiveInstGuard AlreadyInstantiating(*this, Instantiation,
3896 RecursiveInstGuard::Kind::Template);
3897 assert(!AlreadyInstantiating && "should have been caught by caller");
3898#endif
3899
3900 EnumDecl *PatternDef = Pattern->getDefinition();
3901 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
3902 InstantiatedFromMember: Instantiation->getInstantiatedFromMemberEnum(),
3903 Pattern, PatternDef, TSK,/*Complain*/true))
3904 return true;
3905 Pattern = PatternDef;
3906
3907 // Record the point of instantiation.
3908 if (MemberSpecializationInfo *MSInfo
3909 = Instantiation->getMemberSpecializationInfo()) {
3910 MSInfo->setTemplateSpecializationKind(TSK);
3911 MSInfo->setPointOfInstantiation(PointOfInstantiation);
3912 }
3913
3914 NonSFINAEContext _(*this);
3915 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
3916 if (Inst.isInvalid())
3917 return true;
3918 PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
3919 "instantiating enum definition");
3920
3921 // The instantiation is visible here, even if it was first declared in an
3922 // unimported module.
3923 Instantiation->setVisibleDespiteOwningModule();
3924
3925 // Enter the scope of this instantiation. We don't use
3926 // PushDeclContext because we don't have a scope.
3927 ContextRAII SavedContext(*this, Instantiation);
3928 EnterExpressionEvaluationContext EvalContext(
3929 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
3930
3931 LocalInstantiationScope Scope(*this, /*MergeWithParentScope*/true);
3932
3933 // Pull attributes from the pattern onto the instantiation.
3934 InstantiateAttrs(TemplateArgs, Pattern, Inst: Instantiation);
3935
3936 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
3937 Instantiator.InstantiateEnumDefinition(Enum: Instantiation, Pattern);
3938
3939 // Exit the scope of this instantiation.
3940 SavedContext.pop();
3941
3942 return Instantiation->isInvalidDecl();
3943}
3944
3945bool Sema::InstantiateInClassInitializer(
3946 SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
3947 FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs) {
3948 // If there is no initializer, we don't need to do anything.
3949 if (!Pattern->hasInClassInitializer())
3950 return false;
3951
3952 assert(Instantiation->getInClassInitStyle() ==
3953 Pattern->getInClassInitStyle() &&
3954 "pattern and instantiation disagree about init style");
3955
3956 RecursiveInstGuard AlreadyInstantiating(*this, Instantiation,
3957 RecursiveInstGuard::Kind::Template);
3958 if (AlreadyInstantiating)
3959 // Error out if we hit an instantiation cycle for this initializer.
3960 return Diag(Loc: PointOfInstantiation,
3961 DiagID: diag::err_default_member_initializer_cycle)
3962 << Instantiation;
3963
3964 // Error out if we haven't parsed the initializer of the pattern yet because
3965 // we are waiting for the closing brace of the outer class.
3966 Expr *OldInit = Pattern->getInClassInitializer();
3967 if (!OldInit) {
3968 RecordDecl *PatternRD = Pattern->getParent();
3969 RecordDecl *OutermostClass = PatternRD->getOuterLexicalRecordContext();
3970 Diag(Loc: PointOfInstantiation,
3971 DiagID: diag::err_default_member_initializer_not_yet_parsed)
3972 << OutermostClass << Pattern;
3973 Diag(Loc: Pattern->getEndLoc(),
3974 DiagID: diag::note_default_member_initializer_not_yet_parsed);
3975 return true;
3976 }
3977
3978 NonSFINAEContext _(*this);
3979 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
3980 if (Inst.isInvalid())
3981 return true;
3982 PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
3983 "instantiating default member init");
3984
3985 // Enter the scope of this instantiation. We don't use PushDeclContext because
3986 // we don't have a scope.
3987 ContextRAII SavedContext(*this, Instantiation->getParent());
3988 EnterExpressionEvaluationContext EvalContext(
3989 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated,
3990 Instantiation);
3991 ExprEvalContexts.back().DelayedDefaultInitializationContext = {
3992 PointOfInstantiation, Instantiation, CurContext};
3993
3994 LocalInstantiationScope Scope(*this, true);
3995
3996 // Instantiate the initializer.
3997 ActOnStartCXXInClassMemberInitializer();
3998 CXXThisScopeRAII ThisScope(*this, Instantiation->getParent(), Qualifiers());
3999
4000 ExprResult NewInit = SubstInitializer(E: OldInit, TemplateArgs,
4001 /*CXXDirectInit=*/false);
4002 Expr *Init = NewInit.get();
4003 assert((!Init || !isa<ParenListExpr>(Init)) && "call-style init in class");
4004 ActOnFinishCXXInClassMemberInitializer(
4005 VarDecl: Instantiation, EqualLoc: Init ? Init->getBeginLoc() : SourceLocation(), Init);
4006
4007 if (auto *L = getASTMutationListener())
4008 L->DefaultMemberInitializerInstantiated(D: Instantiation);
4009
4010 // Return true if the in-class initializer is still missing.
4011 return !Instantiation->getInClassInitializer();
4012}
4013
4014namespace {
4015 /// A partial specialization whose template arguments have matched
4016 /// a given template-id.
4017 struct PartialSpecMatchResult {
4018 ClassTemplatePartialSpecializationDecl *Partial;
4019 TemplateArgumentList *Args;
4020 };
4021}
4022
4023bool Sema::usesPartialOrExplicitSpecialization(
4024 SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec) {
4025 if (ClassTemplateSpec->getTemplateSpecializationKind() ==
4026 TSK_ExplicitSpecialization)
4027 return true;
4028
4029 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
4030 ClassTemplateDecl *CTD = ClassTemplateSpec->getSpecializedTemplate();
4031 CTD->getPartialSpecializations(PS&: PartialSpecs);
4032 for (ClassTemplatePartialSpecializationDecl *CTPSD : PartialSpecs) {
4033 // C++ [temp.spec.partial.member]p2:
4034 // If the primary member template is explicitly specialized for a given
4035 // (implicit) specialization of the enclosing class template, the partial
4036 // specializations of the member template are ignored for this
4037 // specialization of the enclosing class template. If a partial
4038 // specialization of the member template is explicitly specialized for a
4039 // given (implicit) specialization of the enclosing class template, the
4040 // primary member template and its other partial specializations are still
4041 // considered for this specialization of the enclosing class template.
4042 if (CTD->isMemberSpecialization() && !CTPSD->isMemberSpecialization())
4043 continue;
4044
4045 TemplateDeductionInfo Info(Loc);
4046 if (DeduceTemplateArguments(Partial: CTPSD,
4047 TemplateArgs: ClassTemplateSpec->getTemplateArgs().asArray(),
4048 Info) == TemplateDeductionResult::Success)
4049 return true;
4050 }
4051
4052 return false;
4053}
4054
4055/// Get the instantiation pattern to use to instantiate the definition of a
4056/// given ClassTemplateSpecializationDecl (either the pattern of the primary
4057/// template or of a partial specialization).
4058static ActionResult<CXXRecordDecl *> getPatternForClassTemplateSpecialization(
4059 Sema &S, SourceLocation PointOfInstantiation,
4060 ClassTemplateSpecializationDecl *ClassTemplateSpec,
4061 TemplateSpecializationKind TSK, bool PrimaryStrictPackMatch) {
4062 std::optional<Sema::NonSFINAEContext> NSC(S);
4063 Sema::InstantiatingTemplate Inst(S, PointOfInstantiation, ClassTemplateSpec);
4064 if (Inst.isInvalid())
4065 return {/*Invalid=*/true};
4066
4067 llvm::PointerUnion<ClassTemplateDecl *,
4068 ClassTemplatePartialSpecializationDecl *>
4069 Specialized = ClassTemplateSpec->getSpecializedTemplateOrPartial();
4070 if (!isa<ClassTemplatePartialSpecializationDecl *>(Val: Specialized)) {
4071 // Find best matching specialization.
4072 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
4073
4074 // C++ [temp.class.spec.match]p1:
4075 // When a class template is used in a context that requires an
4076 // instantiation of the class, it is necessary to determine
4077 // whether the instantiation is to be generated using the primary
4078 // template or one of the partial specializations. This is done by
4079 // matching the template arguments of the class template
4080 // specialization with the template argument lists of the partial
4081 // specializations.
4082 typedef PartialSpecMatchResult MatchResult;
4083 SmallVector<MatchResult, 4> Matched, ExtraMatched;
4084 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
4085 Template->getPartialSpecializations(PS&: PartialSpecs);
4086 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation);
4087 for (ClassTemplatePartialSpecializationDecl *Partial : PartialSpecs) {
4088 // C++ [temp.spec.partial.member]p2:
4089 // If the primary member template is explicitly specialized for a given
4090 // (implicit) specialization of the enclosing class template, the
4091 // partial specializations of the member template are ignored for this
4092 // specialization of the enclosing class template. If a partial
4093 // specialization of the member template is explicitly specialized for a
4094 // given (implicit) specialization of the enclosing class template, the
4095 // primary member template and its other partial specializations are
4096 // still considered for this specialization of the enclosing class
4097 // template.
4098 if (Template->isMemberSpecialization() &&
4099 !Partial->isMemberSpecialization())
4100 continue;
4101
4102 TemplateDeductionInfo Info(FailedCandidates.getLocation());
4103 if (TemplateDeductionResult Result = S.DeduceTemplateArguments(
4104 Partial, TemplateArgs: ClassTemplateSpec->getTemplateArgs().asArray(), Info);
4105 Result != TemplateDeductionResult::Success) {
4106 // Store the failed-deduction information for use in diagnostics, later.
4107 // TODO: Actually use the failed-deduction info?
4108 FailedCandidates.addCandidate().set(
4109 Found: DeclAccessPair::make(D: Template, AS: AS_public), Spec: Partial,
4110 Info: MakeDeductionFailureInfo(Context&: S.Context, TDK: Result, Info));
4111 (void)Result;
4112 } else {
4113 auto &List = Info.hasStrictPackMatch() ? ExtraMatched : Matched;
4114 List.push_back(Elt: MatchResult{.Partial: Partial, .Args: Info.takeCanonical()});
4115 }
4116 }
4117 if (Matched.empty() && PrimaryStrictPackMatch)
4118 Matched = std::move(ExtraMatched);
4119
4120 // If we're dealing with a member template where the template parameters
4121 // have been instantiated, this provides the original template parameters
4122 // from which the member template's parameters were instantiated.
4123
4124 if (Matched.size() >= 1) {
4125 SmallVectorImpl<MatchResult>::iterator Best = Matched.begin();
4126 if (Matched.size() == 1) {
4127 // -- If exactly one matching specialization is found, the
4128 // instantiation is generated from that specialization.
4129 // We don't need to do anything for this.
4130 } else {
4131 // -- If more than one matching specialization is found, the
4132 // partial order rules (14.5.4.2) are used to determine
4133 // whether one of the specializations is more specialized
4134 // than the others. If none of the specializations is more
4135 // specialized than all of the other matching
4136 // specializations, then the use of the class template is
4137 // ambiguous and the program is ill-formed.
4138 for (SmallVectorImpl<MatchResult>::iterator P = Best + 1,
4139 PEnd = Matched.end();
4140 P != PEnd; ++P) {
4141 if (S.getMoreSpecializedPartialSpecialization(
4142 PS1: P->Partial, PS2: Best->Partial, Loc: PointOfInstantiation) ==
4143 P->Partial)
4144 Best = P;
4145 }
4146
4147 // Determine if the best partial specialization is more specialized than
4148 // the others.
4149 bool Ambiguous = false;
4150 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
4151 PEnd = Matched.end();
4152 P != PEnd; ++P) {
4153 if (P != Best && S.getMoreSpecializedPartialSpecialization(
4154 PS1: P->Partial, PS2: Best->Partial,
4155 Loc: PointOfInstantiation) != Best->Partial) {
4156 Ambiguous = true;
4157 break;
4158 }
4159 }
4160
4161 if (Ambiguous) {
4162 // Partial ordering did not produce a clear winner. Complain.
4163 Inst.Clear();
4164 NSC.reset();
4165 S.Diag(Loc: PointOfInstantiation,
4166 DiagID: diag::err_partial_spec_ordering_ambiguous)
4167 << ClassTemplateSpec;
4168
4169 // Print the matching partial specializations.
4170 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
4171 PEnd = Matched.end();
4172 P != PEnd; ++P)
4173 S.Diag(Loc: P->Partial->getLocation(), DiagID: diag::note_partial_spec_match)
4174 << S.getTemplateArgumentBindingsText(
4175 Params: P->Partial->getTemplateParameters(), Args: *P->Args);
4176
4177 return {/*Invalid=*/true};
4178 }
4179 }
4180
4181 ClassTemplateSpec->setInstantiationOf(PartialSpec: Best->Partial, TemplateArgs: Best->Args);
4182 } else {
4183 // -- If no matches are found, the instantiation is generated
4184 // from the primary template.
4185 }
4186 }
4187
4188 CXXRecordDecl *Pattern = nullptr;
4189 Specialized = ClassTemplateSpec->getSpecializedTemplateOrPartial();
4190 if (auto *PartialSpec =
4191 dyn_cast<ClassTemplatePartialSpecializationDecl *>(Val&: Specialized)) {
4192 // Instantiate using the best class template partial specialization.
4193 while (PartialSpec->getInstantiatedFromMember()) {
4194 // If we've found an explicit specialization of this class template,
4195 // stop here and use that as the pattern.
4196 if (PartialSpec->isMemberSpecialization())
4197 break;
4198
4199 PartialSpec = PartialSpec->getInstantiatedFromMember();
4200 }
4201 Pattern = PartialSpec;
4202 } else {
4203 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
4204 while (Template->getInstantiatedFromMemberTemplate()) {
4205 // If we've found an explicit specialization of this class template,
4206 // stop here and use that as the pattern.
4207 if (Template->isMemberSpecialization())
4208 break;
4209
4210 Template = Template->getInstantiatedFromMemberTemplate();
4211 }
4212 Pattern = Template->getTemplatedDecl();
4213 }
4214
4215 return Pattern;
4216}
4217
4218bool Sema::InstantiateClassTemplateSpecialization(
4219 SourceLocation PointOfInstantiation,
4220 ClassTemplateSpecializationDecl *ClassTemplateSpec,
4221 TemplateSpecializationKind TSK, bool Complain,
4222 bool PrimaryStrictPackMatch) {
4223 // Perform the actual instantiation on the canonical declaration.
4224 ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>(
4225 Val: ClassTemplateSpec->getCanonicalDecl());
4226 if (ClassTemplateSpec->isInvalidDecl())
4227 return true;
4228
4229 Sema::RecursiveInstGuard AlreadyInstantiating(
4230 *this, ClassTemplateSpec, Sema::RecursiveInstGuard::Kind::Template);
4231 if (AlreadyInstantiating)
4232 return false;
4233
4234 bool HadAvaibilityWarning =
4235 ShouldDiagnoseAvailabilityOfDecl(D: ClassTemplateSpec, Message: nullptr, ClassReceiver: nullptr)
4236 .first != AR_Available;
4237
4238 ActionResult<CXXRecordDecl *> Pattern =
4239 getPatternForClassTemplateSpecialization(S&: *this, PointOfInstantiation,
4240 ClassTemplateSpec, TSK,
4241 PrimaryStrictPackMatch);
4242
4243 if (!Pattern.isUsable())
4244 return Pattern.isInvalid();
4245
4246 // Deduction has picked the pattern this specialization will be instantiated
4247 // from, which may be a declaration an external AST source has yet to define.
4248 if (!Pattern.get()->isCompleteDefinition() &&
4249 Pattern.get()->hasExternalLexicalStorage())
4250 if (ExternalASTSource *Source = Context.getExternalSource())
4251 Source->CompleteType(Tag: Pattern.get());
4252
4253 bool Err = InstantiateClassImpl(
4254 PointOfInstantiation, Instantiation: ClassTemplateSpec, Pattern: Pattern.get(),
4255 TemplateArgs: getTemplateInstantiationArgs(ND: ClassTemplateSpec), TSK, Complain);
4256
4257 // If we haven't already warn on avaibility, consider the avaibility
4258 // attributes of the partial specialization.
4259 // Note that - because we need to have deduced the partial specialization -
4260 // We can only emit these warnings when the specialization is instantiated.
4261 if (!Err && !HadAvaibilityWarning) {
4262 assert(ClassTemplateSpec->getTemplateSpecializationKind() !=
4263 TSK_Undeclared);
4264 DiagnoseAvailabilityOfDecl(D: ClassTemplateSpec, Locs: PointOfInstantiation);
4265 }
4266 return Err;
4267}
4268
4269void
4270Sema::InstantiateClassMembers(SourceLocation PointOfInstantiation,
4271 CXXRecordDecl *Instantiation,
4272 const MultiLevelTemplateArgumentList &TemplateArgs,
4273 TemplateSpecializationKind TSK) {
4274 // FIXME: We need to notify the ASTMutationListener that we did all of these
4275 // things, in case we have an explicit instantiation definition in a PCM, a
4276 // module, or preamble, and the declaration is in an imported AST.
4277 assert(
4278 (TSK == TSK_ExplicitInstantiationDefinition ||
4279 TSK == TSK_ExplicitInstantiationDeclaration ||
4280 (TSK == TSK_ImplicitInstantiation && Instantiation->isLocalClass())) &&
4281 "Unexpected template specialization kind!");
4282 for (auto *D : Instantiation->decls()) {
4283 bool SuppressNew = false;
4284 if (auto *Function = dyn_cast<FunctionDecl>(Val: D)) {
4285 if (FunctionDecl *Pattern =
4286 Function->getInstantiatedFromMemberFunction()) {
4287
4288 if (Function->getTrailingRequiresClause()) {
4289 ConstraintSatisfaction Satisfaction;
4290 if (CheckFunctionConstraints(FD: Function, Satisfaction) ||
4291 !Satisfaction.IsSatisfied) {
4292 continue;
4293 }
4294 }
4295
4296 if (Function->hasAttr<ExcludeFromExplicitInstantiationAttr>())
4297 continue;
4298
4299 TemplateSpecializationKind PrevTSK =
4300 Function->getTemplateSpecializationKind();
4301 if (PrevTSK == TSK_ExplicitSpecialization)
4302 continue;
4303
4304 if (CheckSpecializationInstantiationRedecl(
4305 NewLoc: PointOfInstantiation, ActOnExplicitInstantiationNewTSK: TSK, PrevDecl: Function, PrevTSK,
4306 PrevPtOfInstantiation: Function->getPointOfInstantiation(), SuppressNew) ||
4307 SuppressNew)
4308 continue;
4309
4310 // C++11 [temp.explicit]p8:
4311 // An explicit instantiation definition that names a class template
4312 // specialization explicitly instantiates the class template
4313 // specialization and is only an explicit instantiation definition
4314 // of members whose definition is visible at the point of
4315 // instantiation.
4316 if (TSK == TSK_ExplicitInstantiationDefinition && !Pattern->isDefined())
4317 continue;
4318
4319 Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
4320
4321 if (Function->isDefined()) {
4322 // Let the ASTConsumer know that this function has been explicitly
4323 // instantiated now, and its linkage might have changed.
4324 Consumer.HandleTopLevelDecl(D: DeclGroupRef(Function));
4325 } else if (TSK == TSK_ExplicitInstantiationDefinition) {
4326 InstantiateFunctionDefinition(PointOfInstantiation, Function);
4327 } else if (TSK == TSK_ImplicitInstantiation) {
4328 PendingLocalImplicitInstantiations.push_back(
4329 x: std::make_pair(x&: Function, y&: PointOfInstantiation));
4330 }
4331 }
4332 } else if (auto *Var = dyn_cast<VarDecl>(Val: D)) {
4333 if (isa<VarTemplateSpecializationDecl>(Val: Var))
4334 continue;
4335
4336 if (Var->isStaticDataMember()) {
4337 if (Var->hasAttr<ExcludeFromExplicitInstantiationAttr>())
4338 continue;
4339
4340 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
4341 assert(MSInfo && "No member specialization information?");
4342 if (MSInfo->getTemplateSpecializationKind()
4343 == TSK_ExplicitSpecialization)
4344 continue;
4345
4346 if (CheckSpecializationInstantiationRedecl(NewLoc: PointOfInstantiation, ActOnExplicitInstantiationNewTSK: TSK,
4347 PrevDecl: Var,
4348 PrevTSK: MSInfo->getTemplateSpecializationKind(),
4349 PrevPtOfInstantiation: MSInfo->getPointOfInstantiation(),
4350 SuppressNew) ||
4351 SuppressNew)
4352 continue;
4353
4354 if (TSK == TSK_ExplicitInstantiationDefinition) {
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 (!Var->getInstantiatedFromStaticDataMember()->getDefinition())
4362 continue;
4363
4364 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
4365 InstantiateVariableDefinition(PointOfInstantiation, Var);
4366 } else {
4367 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
4368 }
4369 }
4370 } else if (auto *Record = dyn_cast<CXXRecordDecl>(Val: D)) {
4371 if (Record->hasAttr<ExcludeFromExplicitInstantiationAttr>())
4372 continue;
4373
4374 // Always skip the injected-class-name, along with any
4375 // redeclarations of nested classes, since both would cause us
4376 // to try to instantiate the members of a class twice.
4377 // Skip closure types; they'll get instantiated when we instantiate
4378 // the corresponding lambda-expression.
4379 if (Record->isInjectedClassName() || Record->getPreviousDecl() ||
4380 Record->isLambda())
4381 continue;
4382
4383 MemberSpecializationInfo *MSInfo = Record->getMemberSpecializationInfo();
4384 assert(MSInfo && "No member specialization information?");
4385
4386 if (MSInfo->getTemplateSpecializationKind()
4387 == TSK_ExplicitSpecialization)
4388 continue;
4389
4390 if (Context.getTargetInfo().getTriple().isOSWindows() &&
4391 TSK == TSK_ExplicitInstantiationDeclaration) {
4392 // On Windows, explicit instantiation decl of the outer class doesn't
4393 // affect the inner class. Typically extern template declarations are
4394 // used in combination with dll import/export annotations, but those
4395 // are not propagated from the outer class templates to inner classes.
4396 // Therefore, do not instantiate inner classes on this platform, so
4397 // that users don't end up with undefined symbols during linking.
4398 continue;
4399 }
4400
4401 if (CheckSpecializationInstantiationRedecl(NewLoc: PointOfInstantiation, ActOnExplicitInstantiationNewTSK: TSK,
4402 PrevDecl: Record,
4403 PrevTSK: MSInfo->getTemplateSpecializationKind(),
4404 PrevPtOfInstantiation: MSInfo->getPointOfInstantiation(),
4405 SuppressNew) ||
4406 SuppressNew)
4407 continue;
4408
4409 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
4410 assert(Pattern && "Missing instantiated-from-template information");
4411
4412 if (!Record->getDefinition()) {
4413 if (!Pattern->getDefinition()) {
4414 // C++0x [temp.explicit]p8:
4415 // An explicit instantiation definition that names a class template
4416 // specialization explicitly instantiates the class template
4417 // specialization and is only an explicit instantiation definition
4418 // of members whose definition is visible at the point of
4419 // instantiation.
4420 if (TSK == TSK_ExplicitInstantiationDeclaration) {
4421 MSInfo->setTemplateSpecializationKind(TSK);
4422 MSInfo->setPointOfInstantiation(PointOfInstantiation);
4423 }
4424
4425 continue;
4426 }
4427
4428 InstantiateClass(PointOfInstantiation, Instantiation: Record, Pattern,
4429 TemplateArgs,
4430 TSK);
4431 } else {
4432 if (TSK == TSK_ExplicitInstantiationDefinition &&
4433 Record->getTemplateSpecializationKind() ==
4434 TSK_ExplicitInstantiationDeclaration) {
4435 Record->setTemplateSpecializationKind(TSK);
4436 MarkVTableUsed(Loc: PointOfInstantiation, Class: Record, DefinitionRequired: true);
4437 }
4438 }
4439
4440 Pattern = cast_or_null<CXXRecordDecl>(Val: Record->getDefinition());
4441 if (Pattern)
4442 InstantiateClassMembers(PointOfInstantiation, Instantiation: Pattern, TemplateArgs,
4443 TSK);
4444 } else if (auto *Enum = dyn_cast<EnumDecl>(Val: D)) {
4445 MemberSpecializationInfo *MSInfo = Enum->getMemberSpecializationInfo();
4446 assert(MSInfo && "No member specialization information?");
4447
4448 if (MSInfo->getTemplateSpecializationKind()
4449 == TSK_ExplicitSpecialization)
4450 continue;
4451
4452 if (CheckSpecializationInstantiationRedecl(
4453 NewLoc: PointOfInstantiation, ActOnExplicitInstantiationNewTSK: TSK, PrevDecl: Enum,
4454 PrevTSK: MSInfo->getTemplateSpecializationKind(),
4455 PrevPtOfInstantiation: MSInfo->getPointOfInstantiation(), SuppressNew) ||
4456 SuppressNew)
4457 continue;
4458
4459 if (Enum->getDefinition())
4460 continue;
4461
4462 EnumDecl *Pattern = Enum->getTemplateInstantiationPattern();
4463 assert(Pattern && "Missing instantiated-from-template information");
4464
4465 if (TSK == TSK_ExplicitInstantiationDefinition) {
4466 if (!Pattern->getDefinition())
4467 continue;
4468
4469 InstantiateEnum(PointOfInstantiation, Instantiation: Enum, Pattern, TemplateArgs, TSK);
4470 } else {
4471 MSInfo->setTemplateSpecializationKind(TSK);
4472 MSInfo->setPointOfInstantiation(PointOfInstantiation);
4473 }
4474 } else if (auto *Field = dyn_cast<FieldDecl>(Val: D)) {
4475 // No need to instantiate in-class initializers during explicit
4476 // instantiation.
4477 if (Field->hasInClassInitializer() && TSK == TSK_ImplicitInstantiation) {
4478 // Handle local classes which could have substituted template params.
4479 CXXRecordDecl *ClassPattern =
4480 Instantiation->isLocalClass()
4481 ? Instantiation->getInstantiatedFromMemberClass()
4482 : Instantiation->getTemplateInstantiationPattern();
4483
4484 DeclContext::lookup_result Lookup =
4485 ClassPattern->lookup(Name: Field->getDeclName());
4486 FieldDecl *Pattern = Lookup.find_first<FieldDecl>();
4487 assert(Pattern);
4488 InstantiateInClassInitializer(PointOfInstantiation, Instantiation: Field, Pattern,
4489 TemplateArgs);
4490 }
4491 }
4492 }
4493}
4494
4495void
4496Sema::InstantiateClassTemplateSpecializationMembers(
4497 SourceLocation PointOfInstantiation,
4498 ClassTemplateSpecializationDecl *ClassTemplateSpec,
4499 TemplateSpecializationKind TSK) {
4500 // C++0x [temp.explicit]p7:
4501 // An explicit instantiation that names a class template
4502 // specialization is an explicit instantion of the same kind
4503 // (declaration or definition) of each of its members (not
4504 // including members inherited from base classes) that has not
4505 // been previously explicitly specialized in the translation unit
4506 // containing the explicit instantiation, except as described
4507 // below.
4508 InstantiateClassMembers(PointOfInstantiation, Instantiation: ClassTemplateSpec,
4509 TemplateArgs: getTemplateInstantiationArgs(ND: ClassTemplateSpec),
4510 TSK);
4511}
4512
4513StmtResult
4514Sema::SubstStmt(Stmt *S, const MultiLevelTemplateArgumentList &TemplateArgs) {
4515 if (!S)
4516 return S;
4517
4518 TemplateInstantiator Instantiator(*this, TemplateArgs,
4519 SourceLocation(),
4520 DeclarationName());
4521 return Instantiator.TransformStmt(S);
4522}
4523
4524bool Sema::SubstTemplateArgument(
4525 const TemplateArgumentLoc &Input,
4526 const MultiLevelTemplateArgumentList &TemplateArgs,
4527 TemplateArgumentLoc &Output, SourceLocation Loc,
4528 const DeclarationName &Entity) {
4529 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity);
4530 return Instantiator.TransformTemplateArgument(Input, Output);
4531}
4532
4533bool Sema::SubstTemplateArguments(
4534 ArrayRef<TemplateArgumentLoc> Args,
4535 const MultiLevelTemplateArgumentList &TemplateArgs,
4536 TemplateArgumentListInfo &Out) {
4537 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
4538 DeclarationName());
4539 return Instantiator.TransformTemplateArguments(First: Args.begin(), Last: Args.end(), Outputs&: Out);
4540}
4541
4542bool Sema::SubstTemplateArgumentsInParameterMapping(
4543 ArrayRef<TemplateArgumentLoc> Args, SourceLocation BaseLoc,
4544 const MultiLevelTemplateArgumentList &TemplateArgs,
4545 TemplateArgumentListInfo &Out) {
4546 TemplateInstantiator Instantiator(
4547 TemplateInstantiator::ForParameterMappingSubstitution, *this, BaseLoc,
4548 TemplateArgs, CurrentCachedTemplateArgs);
4549 return Instantiator.TransformTemplateArguments(First: Args.begin(), Last: Args.end(), Outputs&: Out);
4550}
4551
4552UnsignedOrNone Sema::EvaluateFoldExpandedConstraintSize(
4553 const Expr *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs) {
4554 TemplateInstantiator Instantiator(
4555 TemplateInstantiator::ForConstraintSubstitution, *this, TemplateArgs,
4556 SourceLocation(), DeclarationName());
4557
4558 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
4559 collectUnexpandedParameterPacks(E: const_cast<Expr *>(Pattern), Unexpanded);
4560 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
4561
4562 bool Expand = true;
4563 bool RetainExpansion = false;
4564 UnsignedOrNone NumExpansions(std::nullopt);
4565 if (Instantiator.TryExpandParameterPacks(
4566 EllipsisLoc: Pattern->getExprLoc(), PatternRange: Pattern->getSourceRange(), Unexpanded,
4567 /*FailOnPackProducingTemplates=*/false, ShouldExpand&: Expand, RetainExpansion,
4568 NumExpansions, /*Diagnose=*/false) ||
4569 !Expand || RetainExpansion)
4570 return std::nullopt;
4571
4572 if (NumExpansions && getLangOpts().BracketDepth < *NumExpansions)
4573 return std::nullopt;
4574 return NumExpansions;
4575}
4576
4577ExprResult
4578Sema::SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs) {
4579 if (!E)
4580 return E;
4581
4582 TemplateInstantiator Instantiator(*this, TemplateArgs,
4583 SourceLocation(),
4584 DeclarationName());
4585 return Instantiator.TransformExpr(E);
4586}
4587
4588ExprResult
4589Sema::SubstCXXIdExpr(Expr *E,
4590 const MultiLevelTemplateArgumentList &TemplateArgs) {
4591 if (!E)
4592 return E;
4593
4594 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
4595 DeclarationName());
4596 return Instantiator.TransformAddressOfOperand(E);
4597}
4598
4599ExprResult
4600Sema::SubstConstraintExpr(Expr *E,
4601 const MultiLevelTemplateArgumentList &TemplateArgs) {
4602 if (!E)
4603 return E;
4604
4605 TemplateInstantiator Instantiator(
4606 TemplateInstantiator::ForConstraintSubstitution, *this, TemplateArgs,
4607 SourceLocation(), DeclarationName());
4608 return Instantiator.TransformExpr(E);
4609}
4610
4611ExprResult Sema::SubstConstraintExprWithoutSatisfaction(
4612 Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs) {
4613 if (!E)
4614 return E;
4615
4616 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
4617 DeclarationName());
4618 Instantiator.setEvaluateConstraints(false);
4619 return Instantiator.TransformExpr(E);
4620}
4621
4622ExprResult Sema::SubstConceptTemplateArguments(
4623 const ConceptSpecializationExpr *CSE, const Expr *ConstraintExpr,
4624 const MultiLevelTemplateArgumentList &MLTAL) {
4625 assert(isSFINAEContext());
4626
4627 TemplateInstantiator Instantiator(*this, MLTAL, SourceLocation(),
4628 DeclarationName());
4629 const ASTTemplateArgumentListInfo *ArgsAsWritten =
4630 CSE->getTemplateArgsAsWritten();
4631 TemplateArgumentListInfo SubstArgs(ArgsAsWritten->getLAngleLoc(),
4632 ArgsAsWritten->getRAngleLoc());
4633
4634 if (Instantiator.TransformConceptTemplateArguments(
4635 First: ArgsAsWritten->getTemplateArgs(),
4636 Last: ArgsAsWritten->getTemplateArgs() +
4637 ArgsAsWritten->getNumTemplateArgs(),
4638 Outputs&: SubstArgs))
4639 return true;
4640
4641 llvm::SmallVector<TemplateArgument, 4> NewArgList = llvm::map_to_vector(
4642 C: SubstArgs.arguments(),
4643 F: [](const TemplateArgumentLoc &Loc) { return Loc.getArgument(); });
4644
4645 MultiLevelTemplateArgumentList MLTALForConstraint =
4646 getTemplateInstantiationArgs(
4647 ND: CSE->getConceptDecl(), DC: CSE->getConceptDecl()->getLexicalDeclContext(),
4648 /*Final=*/false,
4649 /*Innermost=*/NewArgList,
4650 /*RelativeToPrimary=*/true,
4651 /*Pattern=*/nullptr,
4652 /*ForConstraintInstantiation=*/true);
4653
4654 // Rebuild a constraint, only substituting non-dependent concept names
4655 // and nothing else.
4656 // Given C<SomeType, SomeValue, SomeConceptName, SomeDependentConceptName>.
4657 // only SomeConceptName is substituted, in the constraint expression of C.
4658 struct ConstraintExprTransformer : TreeTransform<ConstraintExprTransformer> {
4659 using Base = TreeTransform<ConstraintExprTransformer>;
4660 MultiLevelTemplateArgumentList &MLTAL;
4661
4662 ConstraintExprTransformer(Sema &SemaRef,
4663 MultiLevelTemplateArgumentList &MLTAL)
4664 : TreeTransform(SemaRef), MLTAL(MLTAL) {}
4665
4666 ExprResult TransformExpr(Expr *E) {
4667 if (!E)
4668 return E;
4669 switch (E->getStmtClass()) {
4670 case Stmt::BinaryOperatorClass:
4671 case Stmt::ConceptSpecializationExprClass:
4672 case Stmt::ParenExprClass:
4673 case Stmt::UnresolvedLookupExprClass:
4674 case Stmt::DependentTemplateIdExprClass:
4675 return Base::TransformExpr(E);
4676 default:
4677 break;
4678 }
4679 return E;
4680 }
4681
4682 // Rebuild both branches of a conjunction / disjunction
4683 // even if there is a substitution failure in one of
4684 // the branch.
4685 ExprResult TransformBinaryOperator(BinaryOperator *E) {
4686 if (!(E->getOpcode() == BinaryOperatorKind::BO_LAnd ||
4687 E->getOpcode() == BinaryOperatorKind::BO_LOr))
4688 return E;
4689
4690 ExprResult LHS = TransformExpr(E: E->getLHS());
4691 ExprResult RHS = TransformExpr(E: E->getRHS());
4692
4693 if (LHS.get() == E->getLHS() && RHS.get() == E->getRHS())
4694 return E;
4695
4696 return BinaryOperator::Create(C: SemaRef.Context, lhs: LHS.get(), rhs: RHS.get(),
4697 opc: E->getOpcode(), ResTy: SemaRef.Context.BoolTy,
4698 VK: VK_PRValue, OK: OK_Ordinary,
4699 opLoc: E->getOperatorLoc(), FPFeatures: FPOptionsOverride{});
4700 }
4701
4702 bool TransformTemplateArgument(const TemplateArgumentLoc &Input,
4703 TemplateArgumentLoc &Output,
4704 bool Uneval = false) {
4705 if (Input.getArgument().isConceptOrConceptTemplateParameter())
4706 return Base::TransformTemplateArgument(Input, Output, Uneval);
4707
4708 Output = Input;
4709 return false;
4710 }
4711
4712 ExprResult RebuildConceptSpecialization(ConceptDecl *ResolvedConcept,
4713 SourceLocation NameLoc,
4714 SourceLocation LAngleLoc,
4715 SourceLocation RAngleLoc,
4716 const TemplateArgumentLoc *Args,
4717 unsigned NumArgs) {
4718 TemplateArgumentListInfo TransArgs(LAngleLoc, RAngleLoc);
4719 if (TransformTemplateArguments(Inputs: Args, NumInputs: NumArgs, Outputs&: TransArgs))
4720 return ExprError();
4721
4722 CXXScopeSpec SS;
4723 DeclarationNameInfo NameInfo(ResolvedConcept->getDeclName(), NameLoc);
4724 return SemaRef.CheckConceptTemplateId(SS, TemplateKWLoc: SourceLocation(), ConceptNameInfo: NameInfo,
4725 FoundDecl: ResolvedConcept, NamedConcept: ResolvedConcept,
4726 TemplateArgs: &TransArgs, DoCheckConstraintSatisfaction: false);
4727 }
4728
4729 ExprResult TransformDependentTemplateIdExpr(DependentTemplateIdExpr *E) {
4730 if (!E->isConceptReference())
4731 return E;
4732
4733 TemplateTemplateParmDecl *TTP = E->getParameter();
4734 unsigned Depth = TTP->getDepth();
4735 unsigned Pos = TTP->getPosition();
4736 if (!MLTAL.hasTemplateArgument(Depth, Index: Pos))
4737 return E;
4738
4739 TemplateArgument Arg = MLTAL(Depth, Pos);
4740 if (PackIndexingTemplateStorage *PI =
4741 E->getTemplateName().getAsPackIndexingTemplate()) {
4742 UnsignedOrNone Index = PI->getSelectedIndex();
4743 if (Arg.getKind() != TemplateArgument::Pack || !Index ||
4744 *Index >= Arg.pack_size())
4745 return E;
4746 Arg = Arg.getPackAsArray()[*Index];
4747 }
4748 if (Arg.getKind() != TemplateArgument::Template)
4749 return E;
4750 ConceptDecl *ResolvedConcept = dyn_cast_if_present<ConceptDecl>(
4751 Val: Arg.getAsTemplate().getAsTemplateDecl());
4752 if (!ResolvedConcept)
4753 return E;
4754
4755 return RebuildConceptSpecialization(ResolvedConcept, NameLoc: E->getNameLoc(),
4756 LAngleLoc: E->getLAngleLoc(), RAngleLoc: E->getRAngleLoc(),
4757 Args: E->template_arguments().data(),
4758 NumArgs: E->getNumTemplateArgs());
4759 }
4760 };
4761
4762 ConstraintExprTransformer Transformer(*this, MLTALForConstraint);
4763 ExprResult Res =
4764 Transformer.TransformExpr(E: const_cast<Expr *>(ConstraintExpr));
4765 return Res;
4766}
4767
4768ExprResult Sema::SubstInitializer(Expr *Init,
4769 const MultiLevelTemplateArgumentList &TemplateArgs,
4770 bool CXXDirectInit) {
4771 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
4772 DeclarationName());
4773 return Instantiator.TransformInitializer(Init, NotCopyInit: CXXDirectInit);
4774}
4775
4776bool Sema::SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
4777 const MultiLevelTemplateArgumentList &TemplateArgs,
4778 SmallVectorImpl<Expr *> &Outputs) {
4779 if (Exprs.empty())
4780 return false;
4781
4782 TemplateInstantiator Instantiator(*this, TemplateArgs,
4783 SourceLocation(),
4784 DeclarationName());
4785 return Instantiator.TransformExprs(Inputs: Exprs.data(), NumInputs: Exprs.size(),
4786 IsCall, Outputs);
4787}
4788
4789NestedNameSpecifierLoc
4790Sema::SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
4791 const MultiLevelTemplateArgumentList &TemplateArgs) {
4792 if (!NNS)
4793 return NestedNameSpecifierLoc();
4794
4795 TemplateInstantiator Instantiator(*this, TemplateArgs, NNS.getBeginLoc(),
4796 DeclarationName());
4797 return Instantiator.TransformNestedNameSpecifierLoc(NNS);
4798}
4799
4800DeclarationNameInfo
4801Sema::SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
4802 const MultiLevelTemplateArgumentList &TemplateArgs) {
4803 TemplateInstantiator Instantiator(*this, TemplateArgs, NameInfo.getLoc(),
4804 NameInfo.getName());
4805 return Instantiator.TransformDeclarationNameInfo(NameInfo);
4806}
4807
4808TemplateName
4809Sema::SubstTemplateName(SourceLocation TemplateKWLoc,
4810 NestedNameSpecifierLoc &QualifierLoc, TemplateName Name,
4811 SourceLocation NameLoc,
4812 const MultiLevelTemplateArgumentList &TemplateArgs) {
4813 TemplateInstantiator Instantiator(*this, TemplateArgs, NameLoc,
4814 DeclarationName());
4815 return Instantiator.TransformTemplateName(QualifierLoc, TemplateKWLoc, Name,
4816 NameLoc);
4817}
4818
4819static const Decl *getCanonicalParmVarDecl(const Decl *D) {
4820 // When storing ParmVarDecls in the local instantiation scope, we always
4821 // want to use the ParmVarDecl from the canonical function declaration,
4822 // since the map is then valid for any redeclaration or definition of that
4823 // function.
4824 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(Val: D)) {
4825 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: PV->getDeclContext())) {
4826 unsigned i = PV->getFunctionScopeIndex();
4827 // This parameter might be from a freestanding function type within the
4828 // function and isn't necessarily referring to one of FD's parameters.
4829 if (i < FD->getNumParams() && FD->getParamDecl(i) == PV)
4830 return FD->getCanonicalDecl()->getParamDecl(i);
4831 }
4832 }
4833 return D;
4834}
4835
4836llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> *
4837LocalInstantiationScope::getInstantiationOfIfExists(const Decl *D) {
4838 D = getCanonicalParmVarDecl(D);
4839 for (LocalInstantiationScope *Current = this; Current;
4840 Current = Current->Outer) {
4841
4842 // Check if we found something within this scope.
4843 const Decl *CheckD = D;
4844 do {
4845 LocalDeclsMap::iterator Found = Current->LocalDecls.find(Val: CheckD);
4846 if (Found != Current->LocalDecls.end())
4847 return &Found->second;
4848
4849 // If this is a tag declaration, it's possible that we need to look for
4850 // a previous declaration.
4851 if (const TagDecl *Tag = dyn_cast<TagDecl>(Val: CheckD))
4852 CheckD = Tag->getPreviousDecl();
4853 else
4854 CheckD = nullptr;
4855 } while (CheckD);
4856
4857 // If we aren't combined with our outer scope, we're done.
4858 if (!Current->CombineWithOuterScope)
4859 break;
4860 }
4861
4862 return nullptr;
4863}
4864
4865llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> *
4866LocalInstantiationScope::findInstantiationOf(const Decl *D) {
4867 auto *Result = getInstantiationOfIfExists(D);
4868 if (Result)
4869 return Result;
4870 // If we're performing a partial substitution during template argument
4871 // deduction, we may not have values for template parameters yet.
4872 if (isa<NonTypeTemplateParmDecl>(Val: D) || isa<TemplateTypeParmDecl>(Val: D) ||
4873 isa<TemplateTemplateParmDecl>(Val: D))
4874 return nullptr;
4875
4876 // Local types referenced prior to definition may require instantiation.
4877 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: D))
4878 if (RD->isLocalClass())
4879 return nullptr;
4880
4881 // Enumeration types referenced prior to definition may appear as a result of
4882 // error recovery.
4883 if (isa<EnumDecl>(Val: D))
4884 return nullptr;
4885
4886 // Materialized typedefs/type alias for implicit deduction guides may require
4887 // instantiation.
4888 if (isa<TypedefNameDecl>(Val: D) &&
4889 isa<CXXDeductionGuideDecl>(Val: D->getDeclContext()))
4890 return nullptr;
4891
4892 // If we didn't find the decl, then we either have a sema bug, or we have a
4893 // forward reference to a label declaration. Return null to indicate that
4894 // we have an uninstantiated label.
4895 assert(isa<LabelDecl>(D) && "declaration not instantiated in this scope");
4896 return nullptr;
4897}
4898
4899void LocalInstantiationScope::InstantiatedLocal(const Decl *D, Decl *Inst) {
4900 D = getCanonicalParmVarDecl(D);
4901 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
4902 if (Stored.isNull()) {
4903#ifndef NDEBUG
4904 // It should not be present in any surrounding scope either.
4905 LocalInstantiationScope *Current = this;
4906 while (Current->CombineWithOuterScope && Current->Outer) {
4907 Current = Current->Outer;
4908 assert(!Current->LocalDecls.contains(D) &&
4909 "Instantiated local in inner and outer scopes");
4910 }
4911#endif
4912 Stored = Inst;
4913 } else if (DeclArgumentPack *Pack = dyn_cast<DeclArgumentPack *>(Val&: Stored)) {
4914 Pack->push_back(Elt: cast<ValueDecl>(Val: Inst));
4915 } else {
4916 assert(cast<Decl *>(Stored) == Inst && "Already instantiated this local");
4917 }
4918}
4919
4920void LocalInstantiationScope::InstantiatedLocalPackArg(const Decl *D,
4921 VarDecl *Inst) {
4922 D = getCanonicalParmVarDecl(D);
4923 DeclArgumentPack *Pack = cast<DeclArgumentPack *>(Val&: LocalDecls[D]);
4924 Pack->push_back(Elt: Inst);
4925}
4926
4927void LocalInstantiationScope::MakeInstantiatedLocalArgPack(const Decl *D) {
4928#ifndef NDEBUG
4929 // This should be the first time we've been told about this decl.
4930 for (LocalInstantiationScope *Current = this;
4931 Current && Current->CombineWithOuterScope; Current = Current->Outer)
4932 assert(!Current->LocalDecls.contains(D) &&
4933 "Creating local pack after instantiation of local");
4934#endif
4935
4936 D = getCanonicalParmVarDecl(D);
4937 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
4938 DeclArgumentPack *Pack = new DeclArgumentPack;
4939 Stored = Pack;
4940 ArgumentPacks.push_back(Elt: Pack);
4941}
4942
4943bool LocalInstantiationScope::isLocalPackExpansion(const Decl *D) {
4944 for (DeclArgumentPack *Pack : ArgumentPacks)
4945 if (llvm::is_contained(Range&: *Pack, Element: D))
4946 return true;
4947 return false;
4948}
4949
4950void LocalInstantiationScope::SetPartiallySubstitutedPack(NamedDecl *Pack,
4951 const TemplateArgument *ExplicitArgs,
4952 unsigned NumExplicitArgs) {
4953 assert((!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack) &&
4954 "Already have a partially-substituted pack");
4955 assert((!PartiallySubstitutedPack
4956 || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) &&
4957 "Wrong number of arguments in partially-substituted pack");
4958 PartiallySubstitutedPack = Pack;
4959 ArgsInPartiallySubstitutedPack = ExplicitArgs;
4960 NumArgsInPartiallySubstitutedPack = NumExplicitArgs;
4961}
4962
4963NamedDecl *LocalInstantiationScope::getPartiallySubstitutedPack(
4964 const TemplateArgument **ExplicitArgs,
4965 unsigned *NumExplicitArgs) const {
4966 if (ExplicitArgs)
4967 *ExplicitArgs = nullptr;
4968 if (NumExplicitArgs)
4969 *NumExplicitArgs = 0;
4970
4971 for (const LocalInstantiationScope *Current = this; Current;
4972 Current = Current->Outer) {
4973 if (Current->PartiallySubstitutedPack) {
4974 if (ExplicitArgs)
4975 *ExplicitArgs = Current->ArgsInPartiallySubstitutedPack;
4976 if (NumExplicitArgs)
4977 *NumExplicitArgs = Current->NumArgsInPartiallySubstitutedPack;
4978
4979 return Current->PartiallySubstitutedPack;
4980 }
4981
4982 if (!Current->CombineWithOuterScope)
4983 break;
4984 }
4985
4986 return nullptr;
4987}
4988