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