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