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