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