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