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 << SYCL().GetSYCLKernelInfoClassSpecializationType(
1291 SKEPAttr->getKernelName()));
1292 break;
1293 }
1295 const auto *SKEPAttr =
1296 Active->Entity->getAttr<SYCLKernelEntryPointAttr>();
1297 assert(SKEPAttr && "Missing sycl_kernel_entry_point attribute");
1298 assert(!SKEPAttr->isInvalidAttr() &&
1299 "sycl_kernel_entry_point attribute is invalid");
1300 DiagFunc(SKEPAttr->getLocation(), PDiag(diag::note_sycl_runtime_defect));
1301 DiagFunc(SKEPAttr->getLocation(),
1302 PDiag(diag::note_sycl_kernel_launch_overload_resolution_here)
1303 << SYCL().GetSYCLKernelInfoClassSpecializationType(
1304 SKEPAttr->getKernelName())
1306 *this, llvm::ArrayRef(Active->CallArgs,
1307 Active->NumCallArgs)));
1308 break;
1309 }
1311 Diags.Report(Active->PointOfInstantiation,
1312 diag::note_expansion_stmt_instantiation_here);
1313 }
1314 }
1315}
1316
1317//===----------------------------------------------------------------------===/
1318// Template Instantiation for Types
1319//===----------------------------------------------------------------------===/
1320namespace {
1321
1322 class TemplateInstantiator : public TreeTransform<TemplateInstantiator> {
1323 const MultiLevelTemplateArgumentList &TemplateArgs;
1324 SourceLocation Loc;
1325 DeclarationName Entity;
1326 // Whether to evaluate the C++20 constraints or simply substitute into them.
1327 bool EvaluateConstraints = true;
1328 bool EvaluateLambdaConstraint = false;
1329 // Whether Substitution was Incomplete, that is, we tried to substitute in
1330 // any user provided template arguments which were null.
1331 bool IsIncomplete = false;
1332 // Whether an incomplete substituion should be treated as an error.
1333 bool BailOutOnIncomplete;
1334
1335 std::optional<llvm::FoldingSetNodeID> TemplateArgsHashValue;
1336 llvm::DenseMap<llvm::FoldingSetNodeIDRef, TemplateArgumentLoc>
1337 *CurrentCachedTemplateArgs = nullptr;
1338
1339 // While the parameters of a prototype are being substituted, the vector is
1340 // populated with the late-parsed attributes, and the scope that maps them.
1341 Sema::LateInstantiatedAttrVec *LateParmAttrs = nullptr;
1342 LocalInstantiationScope *LateParmAttrScope = nullptr;
1343 // If set, the function whose type is substituted, and the late-parsed
1344 // attributes of its parameters, deferred until it is declared with scopes
1345 // that extend the one the substitution started in.
1346 const FunctionDecl *FunctionOfParmAttrs = nullptr;
1347 Sema::LateInstantiatedAttrVec *FunctionParmAttrs = nullptr;
1348 LocalInstantiationScope *FunctionParmAttrScope = nullptr;
1349
1350 bool instantiateMissingDeclsToScopeForConcepts(Decl *D);
1351
1352 public:
1353 typedef TreeTransform<TemplateInstantiator> inherited;
1354
1355 TemplateInstantiator(Sema &SemaRef,
1356 const MultiLevelTemplateArgumentList &TemplateArgs,
1357 SourceLocation Loc, DeclarationName Entity,
1358 bool BailOutOnIncomplete = false)
1359 : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc),
1360 Entity(Entity), BailOutOnIncomplete(BailOutOnIncomplete) {
1361 assert((!SemaRef.CodeSynthesisContexts.empty() ||
1362 SemaRef.isSFINAEContext()) &&
1363 "Cannot perform an instantiation without some context on the "
1364 "instantiation stack");
1365 }
1366
1367 void deferFunctionParmAttrs(const FunctionDecl *Fn,
1369 FunctionOfParmAttrs = Fn;
1370 FunctionParmAttrs = Attrs;
1371 FunctionParmAttrScope = SemaRef.CurrentInstantiationScope;
1372 }
1373
1374 void setEvaluateConstraints(bool B) {
1375 EvaluateConstraints = B;
1376 }
1377 bool getEvaluateConstraints() {
1378 return EvaluateConstraints;
1379 }
1380
1381 inline static struct ForParameterMappingSubstitution_t {
1382 } ForParameterMappingSubstitution;
1383
1384 inline static struct ForConstraintSubstitution_t {
1385 } ForConstraintSubstitution;
1386
1387 TemplateInstantiator(
1388 ForParameterMappingSubstitution_t, Sema &SemaRef, SourceLocation Loc,
1389 const MultiLevelTemplateArgumentList &TemplateArgs,
1390 llvm::DenseMap<llvm::FoldingSetNodeIDRef, TemplateArgumentLoc> *Cache)
1391 : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc),
1392 EvaluateLambdaConstraint(true), BailOutOnIncomplete(false),
1393 CurrentCachedTemplateArgs(Cache) {
1394 if (!Cache)
1395 return;
1396 auto &V = TemplateArgsHashValue.emplace();
1397 for (auto &Level : TemplateArgs)
1398 for (auto &Arg : Level.Args)
1399 Arg.Profile(V, SemaRef.Context);
1400 }
1401
1402 TemplateInstantiator(ForConstraintSubstitution_t, Sema &SemaRef,
1403 const MultiLevelTemplateArgumentList &TemplateArgs,
1404 SourceLocation Loc, DeclarationName Entity,
1405 bool BailOutOnIncomplete = false)
1406 : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc),
1407 EvaluateLambdaConstraint(true), BailOutOnIncomplete(false) {}
1408
1409 /// Determine whether the given type \p T has already been
1410 /// transformed.
1411 ///
1412 /// For the purposes of template instantiation, a type has already been
1413 /// transformed if it is NULL or if it is not dependent.
1414 bool AlreadyTransformed(QualType T);
1415
1416 /// Returns the location of the entity being instantiated, if known.
1417 SourceLocation getBaseLocation() { return Loc; }
1418
1419 /// Returns the name of the entity being instantiated, if any.
1420 DeclarationName getBaseEntity() { return Entity; }
1421
1422 /// Returns whether any substitution so far was incomplete.
1423 bool getIsIncomplete() const { return IsIncomplete; }
1424
1425 /// Sets the "base" location and entity when that
1426 /// information is known based on another transformation.
1427 void setBase(SourceLocation Loc, DeclarationName Entity) {
1428 this->Loc = Loc;
1429 this->Entity = Entity;
1430 }
1431
1432 unsigned TransformTemplateDepth(unsigned Depth) {
1433 return TemplateArgs.getNewDepth(Depth);
1434 }
1435
1436 bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
1437 SourceRange PatternRange,
1438 ArrayRef<UnexpandedParameterPack> Unexpanded,
1439 bool FailOnPackProducingTemplates,
1440 bool &ShouldExpand, bool &RetainExpansion,
1441 UnsignedOrNone &NumExpansions,
1442 bool Diagnose = true) {
1443 for (UnexpandedParameterPack ParmPack : Unexpanded) {
1444 if (instantiateMissingDeclsToScopeForConcepts(
1445 dyn_cast<NamedDecl *>(ParmPack.first)))
1446 return true;
1447 }
1448
1449 return getSema().CheckParameterPacksForExpansion(
1450 EllipsisLoc, PatternRange, Unexpanded, TemplateArgs,
1451 FailOnPackProducingTemplates, ShouldExpand, RetainExpansion,
1452 NumExpansions, Diagnose);
1453 }
1454
1455 void ExpandingFunctionParameterPack(ParmVarDecl *Pack) {
1457 }
1458
1459 TemplateArgument ForgetPartiallySubstitutedPack() {
1460 TemplateArgument Result;
1461 if (NamedDecl *PartialPack = SemaRef.CurrentInstantiationScope
1463 MultiLevelTemplateArgumentList &TemplateArgs =
1464 const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
1465 unsigned Depth, Index;
1466 std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
1467 if (TemplateArgs.hasTemplateArgument(Depth, Index)) {
1468 Result = TemplateArgs(Depth, Index);
1469 TemplateArgs.setArgument(Depth, Index, TemplateArgument());
1470 } else {
1471 IsIncomplete = true;
1472 if (BailOutOnIncomplete)
1473 return TemplateArgument();
1474 }
1475 }
1476
1477 return Result;
1478 }
1479
1480 void RememberPartiallySubstitutedPack(TemplateArgument Arg) {
1481 if (Arg.isNull())
1482 return;
1483
1484 if (NamedDecl *PartialPack = SemaRef.CurrentInstantiationScope
1486 MultiLevelTemplateArgumentList &TemplateArgs =
1487 const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
1488 unsigned Depth, Index;
1489 std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
1490 TemplateArgs.setArgument(Depth, Index, Arg);
1491 }
1492 }
1493
1494 MultiLevelTemplateArgumentList ForgetSubstitution() {
1495 MultiLevelTemplateArgumentList New;
1496 New.addOuterRetainedLevels(this->TemplateArgs.getNumLevels());
1497
1498 MultiLevelTemplateArgumentList Old =
1499 const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
1500 const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs) =
1501 std::move(New);
1502 return Old;
1503 }
1504
1505 void RememberSubstitution(MultiLevelTemplateArgumentList Old) {
1506 const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs) =
1507 std::move(Old);
1508 }
1509
1510 TemplateArgument
1511 getTemplateArgumentPackPatternForRewrite(const TemplateArgument &TA) {
1512 if (TA.getKind() != TemplateArgument::Pack)
1513 return TA;
1514 if (SemaRef.ArgPackSubstIndex)
1515 return SemaRef.getPackSubstitutedTemplateArgument(TA);
1516 assert(TA.pack_size() == 1 && TA.pack_begin()->isPackExpansion() &&
1517 "unexpected pack arguments in template rewrite");
1518 TemplateArgument Arg = *TA.pack_begin();
1519 if (Arg.isPackExpansion())
1520 Arg = Arg.getPackExpansionPattern();
1521 return Arg;
1522 }
1523
1524 /// Transform the given declaration by instantiating a reference to
1525 /// this declaration.
1526 Decl *TransformDecl(SourceLocation Loc, Decl *D);
1527
1528 void transformAttrs(Decl *Old, Decl *New) {
1529 SemaRef.InstantiateAttrs(TemplateArgs, Old, New);
1530 }
1531
1532 void transformedLocalDecl(Decl *Old, ArrayRef<Decl *> NewDecls) {
1533 if (Old->isParameterPack() &&
1534 (NewDecls.size() != 1 || !NewDecls.front()->isParameterPack())) {
1536 for (auto *New : NewDecls)
1538 Old, cast<VarDecl>(New));
1539 return;
1540 }
1541
1542 assert(NewDecls.size() == 1 &&
1543 "should only have multiple expansions for a pack");
1544 Decl *New = NewDecls.front();
1545
1546 // If we've instantiated the call operator of a lambda or the call
1547 // operator template of a generic lambda, update the "instantiation of"
1548 // information.
1549 auto *NewMD = dyn_cast<CXXMethodDecl>(New);
1550 if (NewMD && isLambdaCallOperator(NewMD)) {
1551 auto *OldMD = dyn_cast<CXXMethodDecl>(Old);
1552 if (auto *NewTD = NewMD->getDescribedFunctionTemplate())
1553 NewTD->setInstantiatedFromMemberTemplate(
1554 OldMD->getDescribedFunctionTemplate());
1555 else
1556 NewMD->setInstantiationOfMemberFunction(OldMD,
1558 }
1559
1561
1562 // We recreated a local declaration, but not by instantiating it. There
1563 // may be pending dependent diagnostics to produce.
1564 if (auto *DC = dyn_cast<DeclContext>(Old);
1565 DC && DC->isDependentContext() && DC->isFunctionOrMethod())
1566 SemaRef.PerformDependentDiagnostics(DC, TemplateArgs);
1567 }
1568
1569 /// Transform the definition of the given declaration by
1570 /// instantiating it.
1571 Decl *TransformDefinition(SourceLocation Loc, Decl *D);
1572
1573 /// Transform the first qualifier within a scope by instantiating the
1574 /// declaration.
1575 NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc);
1576
1577 bool TransformExceptionSpec(SourceLocation Loc,
1578 FunctionProtoType::ExceptionSpecInfo &ESI,
1579 SmallVectorImpl<QualType> &Exceptions,
1580 bool &Changed);
1581
1582 /// Rebuild the exception declaration and register the declaration
1583 /// as an instantiated local.
1584 VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
1585 TypeSourceInfo *Declarator,
1586 SourceLocation StartLoc,
1587 SourceLocation NameLoc,
1588 IdentifierInfo *Name);
1589
1590 /// Rebuild the Objective-C exception declaration and register the
1591 /// declaration as an instantiated local.
1592 VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
1593 TypeSourceInfo *TSInfo, QualType T);
1594
1596 TransformTemplateName(NestedNameSpecifierLoc &QualifierLoc,
1597 SourceLocation TemplateKWLoc, TemplateName Name,
1598 SourceLocation NameLoc,
1599 QualType ObjectType = QualType(),
1600 NamedDecl *FirstQualifierInScope = nullptr,
1601 bool AllowInjectedClassName = false);
1602
1603 const AnnotateAttr *TransformAnnotateAttr(const AnnotateAttr *AA);
1604 const CXXAssumeAttr *TransformCXXAssumeAttr(const CXXAssumeAttr *AA);
1605 const LoopHintAttr *TransformLoopHintAttr(const LoopHintAttr *LH);
1606 const NoInlineAttr *TransformStmtNoInlineAttr(const Stmt *OrigS,
1607 const Stmt *InstS,
1608 const NoInlineAttr *A);
1609 const AlwaysInlineAttr *
1610 TransformStmtAlwaysInlineAttr(const Stmt *OrigS, const Stmt *InstS,
1611 const AlwaysInlineAttr *A);
1612 const CodeAlignAttr *TransformCodeAlignAttr(const CodeAlignAttr *CA);
1613 const OpenACCRoutineDeclAttr *
1614 TransformOpenACCRoutineDeclAttr(const OpenACCRoutineDeclAttr *A);
1615 ExprResult TransformPredefinedExpr(PredefinedExpr *E);
1616 ExprResult TransformDeclRefExpr(DeclRefExpr *E);
1617 ExprResult TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E);
1618
1619 ExprResult TransformTemplateParmRefExpr(DeclRefExpr *E,
1620 NonTypeTemplateParmDecl *D);
1621
1622 /// Rebuild a DeclRefExpr for a VarDecl reference.
1623 ExprResult RebuildVarDeclRefExpr(ValueDecl *PD, SourceLocation Loc);
1624
1625 /// Transform a reference to a function or init-capture parameter pack.
1626 ExprResult TransformFunctionParmPackRefExpr(DeclRefExpr *E, ValueDecl *PD);
1627
1628 /// Transform a FunctionParmPackExpr which was built when we couldn't
1629 /// expand a function parameter pack reference which refers to an expanded
1630 /// pack.
1631 ExprResult TransformFunctionParmPackExpr(FunctionParmPackExpr *E);
1632
1633 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
1634 FunctionProtoTypeLoc TL) {
1635 // Call the base version; it will forward to our overridden version below.
1636 return inherited::TransformFunctionProtoType(TLB, TL);
1637 }
1638
1639 QualType TransformTagType(TypeLocBuilder &TLB, TagTypeLoc TL) {
1640 auto Type = inherited::TransformTagType(TLB, TL);
1641 if (!Type.isNull())
1642 return Type;
1643 // Special case for transforming a deduction guide, we return a
1644 // transformed TemplateSpecializationType.
1645 // FIXME: Why is this hack necessary?
1646 if (const auto *ICNT = dyn_cast<InjectedClassNameType>(TL.getTypePtr());
1647 ICNT && SemaRef.CodeSynthesisContexts.back().Kind ==
1649 Type = inherited::TransformType(
1650 ICNT->getDecl()->getCanonicalTemplateSpecializationType(
1651 SemaRef.Context));
1652 TLB.pushTrivial(SemaRef.Context, Type, TL.getNameLoc());
1653 }
1654 return Type;
1655 }
1656
1657 // Override the default version to handle a rewrite-template-arg-pack case
1658 // for building a deduction guide, and to cache substitution results in
1659 // concepts checking.
1660 bool TransformTemplateArgument(const TemplateArgumentLoc &Input,
1661 TemplateArgumentLoc &Output,
1662 bool Uneval = false) {
1663 const TemplateArgument &Arg = Input.getArgument();
1664 if (auto *Cache = CurrentCachedTemplateArgs;
1665 Cache && TemplateArgsHashValue) {
1666 llvm::FoldingSetNodeID ID = *TemplateArgsHashValue;
1667 ID.AddInteger(SemaRef.ArgPackSubstIndex.toInternalRepresentation());
1668 // FIXME: We may have better performance if we profile Arg without
1669 // sugars.
1670 Arg.Profile(ID, SemaRef.Context);
1671 // FIXME: Ideally, we should only cache and restore the TemplateArgument
1672 // and rebuild the uncached TypeLoc separately in place.
1673 // We choose to accept loss of TypeLoc fidelity in cases where TypeLocs
1674 // are less critical for performance trade-off: currently, this is only
1675 // applied to concept substitutions and their valid template arguments.
1676 if (auto Iter = Cache->find(ID); Iter != Cache->end()) {
1677 Output = Iter->second;
1678 return false;
1679 }
1680 bool Ret = inherited::TransformTemplateArgument(Input, Output, Uneval);
1681 if (!Ret)
1682 Cache->try_emplace(ID.Intern(SemaRef.BumpAlloc), Output);
1683 return Ret;
1684 }
1685 switch (Arg.getKind()) {
1687 std::vector<TemplateArgument> TArgs;
1688 assert(SemaRef.CodeSynthesisContexts.empty() ||
1689 SemaRef.CodeSynthesisContexts.back().Kind ==
1691 // Literally rewrite the template argument pack, instead of unpacking
1692 // it.
1693 for (auto &pack : Arg.getPackAsArray()) {
1694 TemplateArgumentLoc Input = SemaRef.getTrivialTemplateArgumentLoc(
1695 pack, QualType(), SourceLocation{});
1696 TemplateArgumentLoc Output;
1697 if (TransformTemplateArgument(Input, Output, Uneval))
1698 return true; // fails
1699 TArgs.push_back(Output.getArgument());
1700 }
1701 Output = SemaRef.getTrivialTemplateArgumentLoc(
1702 TemplateArgument(llvm::ArrayRef(TArgs).copy(SemaRef.Context)),
1703 QualType(), SourceLocation{});
1704 return false;
1705 }
1706 default:
1707 break;
1708 }
1709 return inherited::TransformTemplateArgument(Input, Output, Uneval);
1710 }
1711
1713 QualType
1714 TransformTemplateSpecializationType(TypeLocBuilder &TLB,
1715 TemplateSpecializationTypeLoc TL) {
1716 auto *T = TL.getTypePtr();
1717 if (!getSema().ArgPackSubstIndex || !T->isSugared() ||
1718 !isPackProducingBuiltinTemplateName(T->getTemplateName()))
1720 // Look through sugar to get to the SubstBuiltinTemplatePackType that we
1721 // need to substitute into.
1722
1723 // `TransformType` code below will handle picking the element from a pack
1724 // with the index `ArgPackSubstIndex`.
1725 // FIXME: add ability to represent sugarred type for N-th element of a
1726 // builtin pack and produce the sugar here.
1727 QualType R = TransformType(T->desugar());
1728 TLB.pushTrivial(getSema().getASTContext(), R, TL.getBeginLoc());
1729 return R;
1730 }
1731
1732 UnsignedOrNone ComputeSizeOfPackExprWithoutSubstitution(
1733 ArrayRef<TemplateArgument> PackArgs) {
1734 // Don't do this when rewriting template parameters for CTAD:
1735 // 1) The heuristic needs the unpacked Subst* nodes to figure out the
1736 // expanded size, but this never applies since Subst* nodes are not
1737 // created in rewrite scenarios.
1738 //
1739 // 2) The heuristic substitutes into the pattern with pack expansion
1740 // suppressed, which does not meet the requirements for argument
1741 // rewriting when template arguments include a non-pack matching against
1742 // a pack, particularly when rewriting an alias CTAD.
1743 if (TemplateArgs.isRewrite())
1744 return std::nullopt;
1745
1746 return inherited::ComputeSizeOfPackExprWithoutSubstitution(PackArgs);
1747 }
1748
1749 template<typename Fn>
1750 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
1751 FunctionProtoTypeLoc TL,
1752 CXXRecordDecl *ThisContext,
1753 Qualifiers ThisTypeQuals,
1754 Fn TransformExceptionSpec);
1755
1756 ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm,
1757 int indexAdjustment,
1758 UnsignedOrNone NumExpansions,
1759 bool ExpectParameterPack);
1760
1761 using inherited::TransformFunctionTypeParams;
1762 bool TransformFunctionTypeParams(
1763 SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
1764 const QualType *ParamTypes,
1765 const FunctionProtoType::ExtParameterInfo *ParamInfos,
1766 SmallVectorImpl<QualType> &PTypes,
1767 SmallVectorImpl<ParmVarDecl *> *PVars,
1768 Sema::ExtParameterInfoBuilder &PInfos, unsigned *LastParamTransformed);
1769
1770 using inherited::TransformTemplateTypeParmType;
1771 /// Transforms a template type parameter type by performing
1772 /// substitution of the corresponding template type argument.
1773 QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
1774 TemplateTypeParmTypeLoc TL,
1775 bool SuppressObjCLifetime);
1776
1777 QualType BuildSubstTemplateTypeParmType(
1778 TypeLocBuilder &TLB, bool SuppressObjCLifetime, bool Final,
1779 Decl *AssociatedDecl, unsigned Index, UnsignedOrNone PackIndex,
1780 TemplateArgument Arg, SourceLocation NameLoc);
1781
1782 /// Transforms an already-substituted template type parameter pack
1783 /// into either itself (if we aren't substituting into its pack expansion)
1784 /// or the appropriate substituted argument.
1785 using inherited::TransformSubstTemplateTypeParmPackType;
1786 QualType
1787 TransformSubstTemplateTypeParmPackType(TypeLocBuilder &TLB,
1788 SubstTemplateTypeParmPackTypeLoc TL,
1789 bool SuppressObjCLifetime);
1790 QualType
1791 TransformSubstBuiltinTemplatePackType(TypeLocBuilder &TLB,
1792 SubstBuiltinTemplatePackTypeLoc TL);
1793
1795 ComputeLambdaDependency(LambdaScopeInfo *LSI) {
1796 if (auto TypeAlias =
1797 TemplateInstArgsHelpers::getEnclosingTypeAliasTemplateDecl(
1798 getSema());
1799 TypeAlias && TemplateInstArgsHelpers::isLambdaEnclosedByTypeAliasDecl(
1800 LSI->CallOperator, TypeAlias.PrimaryTypeAliasDecl)) {
1801 unsigned TypeAliasDeclDepth = TypeAlias.Template->getTemplateDepth();
1802 if (TypeAliasDeclDepth >= TemplateArgs.getNumSubstitutedLevels())
1803 return CXXRecordDecl::LambdaDependencyKind::LDK_AlwaysDependent;
1804 for (const TemplateArgument &TA : TypeAlias.AssociatedTemplateArguments)
1805 if (TA.isDependent())
1806 return CXXRecordDecl::LambdaDependencyKind::LDK_AlwaysDependent;
1807 }
1808 if (auto *CD = dyn_cast_if_present<ImplicitConceptSpecializationDecl>(
1809 LSI->Lambda->getLambdaContextDecl())) {
1810 if (llvm::any_of(CD->getTemplateArguments(),
1811 [](const auto &TA) { return TA.isDependent(); }))
1812 return CXXRecordDecl::LambdaDependencyKind::LDK_AlwaysDependent;
1813 }
1814 return inherited::ComputeLambdaDependency(LSI);
1815 }
1816
1817 ExprResult TransformLambdaConstraint(Expr *AC) {
1818 if (AC && EvaluateLambdaConstraint)
1819 return TransformExpr(const_cast<Expr *>(AC));
1820
1821 return AC;
1822 }
1823
1824 ExprResult TransformLambdaExpr(LambdaExpr *E) {
1825 // Do not rebuild lambdas to avoid creating a new type.
1826 // Lambdas have already been processed inside their eval contexts.
1828 return E;
1829 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true,
1830 /*InstantiatingLambdaOrBlock=*/true);
1831 llvm::SaveAndRestore RAII(EvaluateConstraints, EvaluateLambdaConstraint);
1832
1833 return inherited::TransformLambdaExpr(E);
1834 }
1835
1836 ExprResult TransformBlockExpr(BlockExpr *E) {
1837 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true,
1838 /*InstantiatingLambdaOrBlock=*/true);
1839 return inherited::TransformBlockExpr(E);
1840 }
1841
1842 ExprResult RebuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc,
1843 LambdaScopeInfo *LSI) {
1844 CXXMethodDecl *MD = LSI->CallOperator;
1845 for (ParmVarDecl *PVD : MD->parameters()) {
1846 assert(PVD && "null in a parameter list");
1847 if (!PVD->hasDefaultArg())
1848 continue;
1849 Expr *UninstExpr = PVD->getUninstantiatedDefaultArg();
1850 // FIXME: Obtain the source location for the '=' token.
1851 SourceLocation EqualLoc = UninstExpr->getBeginLoc();
1852 if (SemaRef.SubstDefaultArgument(EqualLoc, PVD, TemplateArgs)) {
1853 // If substitution fails, the default argument is set to a
1854 // RecoveryExpr that wraps the uninstantiated default argument so
1855 // that downstream diagnostics are omitted.
1856 ExprResult ErrorResult = SemaRef.CreateRecoveryExpr(
1857 UninstExpr->getBeginLoc(), UninstExpr->getEndLoc(), {UninstExpr},
1858 UninstExpr->getType());
1859 if (ErrorResult.isUsable())
1860 PVD->setDefaultArg(ErrorResult.get());
1861 }
1862 }
1863 return inherited::RebuildLambdaExpr(StartLoc, EndLoc, LSI);
1864 }
1865
1866 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
1867 // Currently, we instantiate the body when instantiating the lambda
1868 // expression. However, `EvaluateConstraints` is disabled during the
1869 // instantiation of the lambda expression, causing the instantiation
1870 // failure of the return type requirement in the body. If p0588r1 is fully
1871 // implemented, the body will be lazily instantiated, and this problem
1872 // will not occur. Here, `EvaluateConstraints` is temporarily set to
1873 // `true` to temporarily fix this issue.
1874 // FIXME: This temporary fix can be removed after fully implementing
1875 // p0588r1.
1876 llvm::SaveAndRestore _(EvaluateConstraints, true);
1877 return inherited::TransformLambdaBody(E, Body);
1878 }
1879
1880 ExprResult TransformRequiresExpr(RequiresExpr *E) {
1881 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
1882 ExprResult TransReq = inherited::TransformRequiresExpr(E);
1883 if (TransReq.isInvalid())
1884 return TransReq;
1885 assert(TransReq.get() != E &&
1886 "Do not change value of isSatisfied for the existing expression. "
1887 "Create a new expression instead.");
1888 if (E->getBody()->isDependentContext()) {
1889 Sema::SFINAETrap Trap(SemaRef);
1890 // We recreate the RequiresExpr body, but not by instantiating it.
1891 // Produce pending diagnostics for dependent access check.
1892 SemaRef.PerformDependentDiagnostics(E->getBody(), TemplateArgs);
1893 // FIXME: Store SFINAE diagnostics in RequiresExpr for diagnosis.
1894 if (Trap.hasErrorOccurred())
1895 TransReq.getAs<RequiresExpr>()->setSatisfied(false);
1896 }
1897 return TransReq;
1898 }
1899
1900 bool TransformRequiresExprRequirements(
1901 ArrayRef<concepts::Requirement *> Reqs,
1902 SmallVectorImpl<concepts::Requirement *> &Transformed) {
1903 bool SatisfactionDetermined = false;
1904 for (concepts::Requirement *Req : Reqs) {
1905 concepts::Requirement *TransReq = nullptr;
1906 if (!SatisfactionDetermined) {
1907 if (auto *TypeReq = dyn_cast<concepts::TypeRequirement>(Req))
1908 TransReq = TransformTypeRequirement(TypeReq);
1909 else if (auto *ExprReq = dyn_cast<concepts::ExprRequirement>(Req))
1910 TransReq = TransformExprRequirement(ExprReq);
1911 else
1912 TransReq = TransformNestedRequirement(
1914 if (!TransReq)
1915 return true;
1916 if (!TransReq->isDependent() && !TransReq->isSatisfied())
1917 // [expr.prim.req]p6
1918 // [...] The substitution and semantic constraint checking
1919 // proceeds in lexical order and stops when a condition that
1920 // determines the result of the requires-expression is
1921 // encountered. [..]
1922 SatisfactionDetermined = true;
1923 } else
1924 TransReq = Req;
1925 Transformed.push_back(TransReq);
1926 }
1927 return false;
1928 }
1929
1930 TemplateParameterList *TransformTemplateParameterList(
1931 TemplateParameterList *OrigTPL) {
1932 if (!OrigTPL || !OrigTPL->size()) return OrigTPL;
1933
1934 DeclContext *Owner = OrigTPL->getParam(0)->getDeclContext();
1935 TemplateDeclInstantiator DeclInstantiator(getSema(),
1936 /* DeclContext *Owner */ Owner,
1937 TemplateArgs);
1938 DeclInstantiator.setEvaluateConstraints(EvaluateConstraints);
1939 return DeclInstantiator.SubstTemplateParams(OrigTPL);
1940 }
1941
1942 concepts::TypeRequirement *
1943 TransformTypeRequirement(concepts::TypeRequirement *Req);
1944 concepts::ExprRequirement *
1945 TransformExprRequirement(concepts::ExprRequirement *Req);
1946 concepts::NestedRequirement *
1947 TransformNestedRequirement(concepts::NestedRequirement *Req);
1948 ExprResult TransformRequiresTypeParams(
1949 SourceLocation KWLoc, SourceLocation RBraceLoc, const RequiresExpr *RE,
1950 RequiresExprBodyDecl *Body, ArrayRef<ParmVarDecl *> Params,
1951 SmallVectorImpl<QualType> &PTypes,
1952 SmallVectorImpl<ParmVarDecl *> &TransParams,
1953 Sema::ExtParameterInfoBuilder &PInfos);
1954
1955 ExprResult TransformCXXDynamicCastExpr(CXXDynamicCastExpr *E) {
1956 ExprResult Ret = inherited::TransformCXXDynamicCastExpr(E);
1957 if (Ret.isInvalid())
1958 return Ret;
1959 QualType T = Ret.get()->getType();
1960 if (const auto *PT = T->getAsCanonical<PointerType>())
1961 T = PT->getPointeeType();
1962 auto *DestDecl = T->getAsCXXRecordDecl();
1963 if (DestDecl && DestDecl->isEffectivelyFinal())
1964 getSema().MarkVTableUsed(Ret.get()->getExprLoc(), DestDecl);
1965 return Ret;
1966 }
1967 };
1968}
1969
1970bool TemplateInstantiator::AlreadyTransformed(QualType T) {
1971 if (T.isNull())
1972 return true;
1973
1976 return false;
1977
1978 getSema().MarkDeclarationsReferencedInType(Loc, T);
1979 return true;
1980}
1981
1982Decl *TemplateInstantiator::TransformDecl(SourceLocation Loc, Decl *D) {
1983 if (!D)
1984 return nullptr;
1985
1986 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(D)) {
1987 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1988 // If the corresponding template argument is NULL or non-existent, it's
1989 // because we are performing instantiation from explicitly-specified
1990 // template arguments in a function template, but there were some
1991 // arguments left unspecified.
1992 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
1993 TTP->getPosition())) {
1994 IsIncomplete = true;
1995 return BailOutOnIncomplete ? nullptr : D;
1996 }
1997
1998 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
1999
2000 if (TTP->isParameterPack()) {
2001 assert(Arg.getKind() == TemplateArgument::Pack &&
2002 "Missing argument pack");
2003 Arg = SemaRef.getPackSubstitutedTemplateArgument(Arg);
2004 }
2005
2007 assert(!Template.isNull() && Template.getAsTemplateDecl() &&
2008 "Wrong kind of template template argument");
2009 return Template.getAsTemplateDecl();
2010 }
2011
2012 // Fall through to find the instantiated declaration for this template
2013 // template parameter.
2014 }
2015
2016 if (instantiateMissingDeclsToScopeForConcepts(D))
2017 return nullptr;
2018
2020 assert(SemaRef.CurrentInstantiationScope);
2021 return cast<Decl *>(
2022 *SemaRef.CurrentInstantiationScope->findInstantiationOf(D));
2023 }
2024
2025 return SemaRef.FindInstantiatedDecl(Loc, cast<NamedDecl>(D), TemplateArgs);
2026}
2027
2028bool TemplateInstantiator::instantiateMissingDeclsToScopeForConcepts(Decl *D) {
2029 if (!(D && (SemaRef.inConstraintSubstitution() ||
2030 SemaRef.inParameterMappingSubstitution())))
2031 return false;
2032
2033 auto *Current = SemaRef.CurrentInstantiationScope;
2034 if (!Current || Current->getInstantiationOfIfExists(D))
2035 return false;
2036
2037 // CWG2770: Function parameters should be instantiated when they are
2038 // needed by a satisfaction check of an atomic constraint or
2039 // (recursively) by another function parameter.
2040 auto *OldParm = dyn_cast<ParmVarDecl>(D);
2041 if (!OldParm)
2042 return false;
2043
2044 if (!OldParm->isParameterPack())
2045 return !TransformFunctionTypeParam(OldParm, /*indexAdjustment=*/0,
2046 /*NumExpansions=*/std::nullopt,
2047 /*ExpectParameterPack=*/false);
2048
2049 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2050
2051 // Find the parameter packs that could be expanded.
2052 TypeLoc TL = OldParm->getTypeSourceInfo()->getTypeLoc();
2053 PackExpansionTypeLoc ExpansionTL = TL.castAs<PackExpansionTypeLoc>();
2054 TypeLoc Pattern = ExpansionTL.getPatternLoc();
2055 SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
2056 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
2057
2058 bool ShouldExpand = false;
2059 bool RetainExpansion = false;
2060 UnsignedOrNone OrigNumExpansions =
2061 ExpansionTL.getTypePtr()->getNumExpansions();
2062 UnsignedOrNone NumExpansions = OrigNumExpansions;
2063 if (TryExpandParameterPacks(ExpansionTL.getEllipsisLoc(),
2064 Pattern.getSourceRange(), Unexpanded,
2065 /*FailOnPackProducingTemplates=*/true,
2066 ShouldExpand, RetainExpansion, NumExpansions))
2067 return true;
2068
2069 assert(ShouldExpand && !RetainExpansion &&
2070 "Shouldn't preserve pack expansion when evaluating constraints");
2071 ExpandingFunctionParameterPack(OldParm);
2072 for (unsigned I = 0; I != *NumExpansions; ++I) {
2073 Sema::ArgPackSubstIndexRAII SubstIndex(getSema(), I);
2074 if (!TransformFunctionTypeParam(OldParm, /*indexAdjustment=*/0,
2075 /*NumExpansions=*/OrigNumExpansions,
2076 /*ExpectParameterPack=*/false))
2077 return true;
2078 }
2079 return false;
2080}
2081
2082Decl *TemplateInstantiator::TransformDefinition(SourceLocation Loc, Decl *D) {
2083 Decl *Inst = getSema().SubstDecl(D, getSema().CurContext, TemplateArgs);
2084 if (!Inst)
2085 return nullptr;
2086
2087 getSema().CurrentInstantiationScope->InstantiatedLocal(D, Inst);
2088 return Inst;
2089}
2090
2091bool TemplateInstantiator::TransformExceptionSpec(
2092 SourceLocation Loc, FunctionProtoType::ExceptionSpecInfo &ESI,
2093 SmallVectorImpl<QualType> &Exceptions, bool &Changed) {
2094 if (ESI.Type == EST_Uninstantiated) {
2095 ESI.instantiate();
2096 Changed = true;
2097 }
2098 return inherited::TransformExceptionSpec(Loc, ESI, Exceptions, Changed);
2099}
2100
2101NamedDecl *
2102TemplateInstantiator::TransformFirstQualifierInScope(NamedDecl *D,
2103 SourceLocation Loc) {
2104 // If the first part of the nested-name-specifier was a template type
2105 // parameter, instantiate that type parameter down to a tag type.
2106 if (TemplateTypeParmDecl *TTPD = dyn_cast_or_null<TemplateTypeParmDecl>(D)) {
2107 const TemplateTypeParmType *TTP
2108 = cast<TemplateTypeParmType>(getSema().Context.getTypeDeclType(TTPD));
2109
2110 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
2111 // FIXME: This needs testing w/ member access expressions.
2112 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getIndex());
2113
2114 if (TTP->isParameterPack()) {
2115 assert(Arg.getKind() == TemplateArgument::Pack &&
2116 "Missing argument pack");
2117
2118 if (!getSema().ArgPackSubstIndex)
2119 return nullptr;
2120
2121 Arg = SemaRef.getPackSubstitutedTemplateArgument(Arg);
2122 }
2123
2124 QualType T = Arg.getAsType();
2125 if (T.isNull())
2126 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
2127
2128 if (const TagType *Tag = T->getAs<TagType>())
2129 return Tag->getDecl();
2130
2131 // The resulting type is not a tag; complain.
2132 getSema().Diag(Loc, diag::err_nested_name_spec_non_tag) << T;
2133 return nullptr;
2134 }
2135 }
2136
2137 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
2138}
2139
2140VarDecl *
2141TemplateInstantiator::RebuildExceptionDecl(VarDecl *ExceptionDecl,
2142 TypeSourceInfo *Declarator,
2143 SourceLocation StartLoc,
2144 SourceLocation NameLoc,
2145 IdentifierInfo *Name) {
2146 VarDecl *Var = inherited::RebuildExceptionDecl(ExceptionDecl, Declarator,
2147 StartLoc, NameLoc, Name);
2148 if (Var)
2149 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
2150 return Var;
2151}
2152
2153VarDecl *TemplateInstantiator::RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
2154 TypeSourceInfo *TSInfo,
2155 QualType T) {
2156 VarDecl *Var = inherited::RebuildObjCExceptionDecl(ExceptionDecl, TSInfo, T);
2157 if (Var)
2158 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
2159 return Var;
2160}
2161
2162TemplateName TemplateInstantiator::TransformTemplateName(
2163 NestedNameSpecifierLoc &QualifierLoc, SourceLocation TemplateKWLoc,
2164 TemplateName Name, SourceLocation NameLoc, QualType ObjectType,
2165 NamedDecl *FirstQualifierInScope, bool AllowInjectedClassName) {
2166 if (Name.getKind() == TemplateName::Template) {
2167 assert(!QualifierLoc && "Unexpected qualifier");
2168 if (auto *TTP =
2169 dyn_cast<TemplateTemplateParmDecl>(Name.getAsTemplateDecl());
2170 TTP && TTP->getDepth() < TemplateArgs.getNumLevels()) {
2171 // If the corresponding template argument is NULL or non-existent, it's
2172 // because we are performing instantiation from explicitly-specified
2173 // template arguments in a function template, but there were some
2174 // arguments left unspecified.
2175 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
2176 TTP->getPosition())) {
2177 IsIncomplete = true;
2178 return BailOutOnIncomplete ? TemplateName() : Name;
2179 }
2180
2181 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
2182
2183 if (TemplateArgs.isRewrite()) {
2184 // We're rewriting the template parameter as a reference to another
2185 // template parameter.
2186 Arg = getTemplateArgumentPackPatternForRewrite(Arg);
2187 assert(Arg.getKind() == TemplateArgument::Template &&
2188 "unexpected nontype template argument kind in template rewrite");
2189 return Arg.getAsTemplate();
2190 }
2191
2192 auto [AssociatedDecl, Final] =
2193 TemplateArgs.getAssociatedDecl(TTP->getDepth());
2194 UnsignedOrNone PackIndex = std::nullopt;
2195 if (TTP->isParameterPack()) {
2196 assert(Arg.getKind() == TemplateArgument::Pack &&
2197 "Missing argument pack");
2198
2199 if (!getSema().ArgPackSubstIndex) {
2200 // We have the template argument pack to substitute, but we're not
2201 // actually expanding the enclosing pack expansion yet. So, just
2202 // keep the entire argument pack.
2203 return getSema().Context.getSubstTemplateTemplateParmPack(
2204 Arg, AssociatedDecl, TTP->getIndex(), Final);
2205 }
2206
2207 PackIndex = SemaRef.getPackIndex(Arg);
2208 Arg = SemaRef.getPackSubstitutedTemplateArgument(Arg);
2209 }
2210
2212 assert(!Template.isNull() && "Null template template argument");
2213 return getSema().Context.getSubstTemplateTemplateParm(
2214 Template, AssociatedDecl, TTP->getIndex(), PackIndex, Final);
2215 }
2216 }
2217
2218 if (SubstTemplateTemplateParmPackStorage *SubstPack
2220 if (!getSema().ArgPackSubstIndex)
2221 return Name;
2222
2223 TemplateArgument Pack = SubstPack->getArgumentPack();
2225 SemaRef.getPackSubstitutedTemplateArgument(Pack).getAsTemplate();
2226 return getSema().Context.getSubstTemplateTemplateParm(
2227 Template, SubstPack->getAssociatedDecl(), SubstPack->getIndex(),
2228 SemaRef.getPackIndex(Pack), SubstPack->getFinal());
2229 }
2230
2231 return inherited::TransformTemplateName(
2232 QualifierLoc, TemplateKWLoc, Name, NameLoc, ObjectType,
2233 FirstQualifierInScope, AllowInjectedClassName);
2234}
2235
2237TemplateInstantiator::TransformPredefinedExpr(PredefinedExpr *E) {
2238 if (!E->isTypeDependent())
2239 return E;
2240
2241 return getSema().BuildPredefinedExpr(E->getLocation(), E->getIdentKind());
2242}
2243
2245TemplateInstantiator::TransformTemplateParmRefExpr(DeclRefExpr *E,
2246 NonTypeTemplateParmDecl *NTTP) {
2247 if (TemplateArgs.retainInnerDepths() &&
2248 NTTP->getDepth() >= TemplateArgs.getNumLevels())
2249 return E;
2250 // If the corresponding template argument is NULL or non-existent, it's
2251 // because we are performing instantiation from explicitly-specified
2252 // template arguments in a function template, but there were some
2253 // arguments left unspecified.
2254 if (!TemplateArgs.hasTemplateArgument(NTTP->getDepth(),
2255 NTTP->getPosition())) {
2256 IsIncomplete = true;
2257 return BailOutOnIncomplete ? ExprError() : E;
2258 }
2259
2260 TemplateArgument Arg = TemplateArgs(NTTP->getDepth(), NTTP->getPosition());
2261
2262 if (TemplateArgs.isRewrite()) {
2263 // We're rewriting the template parameter as a reference to another
2264 // template parameter.
2265 Arg = getTemplateArgumentPackPatternForRewrite(Arg);
2266 assert(Arg.getKind() == TemplateArgument::Expression &&
2267 "unexpected nontype template argument kind in template rewrite");
2268 // FIXME: This can lead to the same subexpression appearing multiple times
2269 // in a complete expression.
2270 return Arg.getAsExpr();
2271 }
2272
2273 QualType ParamType = NTTP->isExpandedParameterPack()
2274 ? NTTP->getExpansionType(*SemaRef.ArgPackSubstIndex)
2275 : NTTP->isParameterPack() && SemaRef.ArgPackSubstIndex
2277 : NTTP->getType();
2278 ParamType = SemaRef.SubstType(ParamType, TemplateArgs, E->getLocation(),
2279 NTTP->getDeclName());
2280 assert(!ParamType.isNull() && "Shouldn't substitute to an invalid type");
2281
2282 auto [AssociatedDecl, Final] =
2283 TemplateArgs.getAssociatedDecl(NTTP->getDepth());
2284 UnsignedOrNone PackIndex = std::nullopt;
2285 if (NTTP->isParameterPack() ||
2286 // In concept parameter mapping for fold expressions, packs that aren't
2287 // expanded in place are treated as having non-pack dependency, so that
2288 // a PackExpansionType won't prevent expanding the packs outside the
2289 // TreeTransform. However, we still need to unpack the arguments during
2290 // any template argument substitution, so we also check its FoundDecl.
2291 (E->getFoundDecl() && E->getFoundDecl() != E->getDecl() &&
2292 E->getFoundDecl()->isParameterPack())) {
2293 assert(Arg.getKind() == TemplateArgument::Pack && "Missing argument pack");
2294
2295 if (!getSema().ArgPackSubstIndex) {
2296 // We have an argument pack, but we can't select a particular argument
2297 // out of it yet. Therefore, we'll build an expression to hold on to that
2298 // argument pack.
2299 QualType ExprType = ParamType.getNonLValueExprType(SemaRef.Context);
2300 if (ParamType->isRecordType())
2301 ExprType.addConst();
2302 return new (SemaRef.Context) SubstNonTypeTemplateParmPackExpr(
2303 ExprType, ParamType->isReferenceType() ? VK_LValue : VK_PRValue,
2304 E->getLocation(), Arg, AssociatedDecl, NTTP->getPosition(), Final);
2305 }
2306 PackIndex = SemaRef.getPackIndex(Arg);
2307 Arg = SemaRef.getPackSubstitutedTemplateArgument(Arg);
2308 }
2309 return SemaRef.BuildSubstNonTypeTemplateParmExpr(
2310 AssociatedDecl, NTTP->getPosition(), ParamType, E->getLocation(), Arg,
2311 PackIndex, Final);
2312}
2313
2314const AnnotateAttr *
2315TemplateInstantiator::TransformAnnotateAttr(const AnnotateAttr *AA) {
2316 SmallVector<Expr *> Args;
2317 for (Expr *Arg : AA->args()) {
2318 ExprResult Res = getDerived().TransformExpr(Arg);
2319 if (Res.isUsable())
2320 Args.push_back(Res.get());
2321 }
2322 return AnnotateAttr::CreateImplicit(getSema().Context, AA->getAnnotation(),
2323 Args.data(), Args.size(), AA->getRange());
2324}
2325
2326const CXXAssumeAttr *
2327TemplateInstantiator::TransformCXXAssumeAttr(const CXXAssumeAttr *AA) {
2328 ExprResult Res = getDerived().TransformExpr(AA->getAssumption());
2329 if (!Res.isUsable())
2330 return AA;
2331
2332 if (!(Res.get()->getDependence() & ExprDependence::TypeValueInstantiation)) {
2333 Res = getSema().BuildCXXAssumeExpr(Res.get(), AA->getAttrName(),
2334 AA->getRange());
2335 if (!Res.isUsable())
2336 return AA;
2337 }
2338
2339 return CXXAssumeAttr::CreateImplicit(getSema().Context, Res.get(),
2340 AA->getRange());
2341}
2342
2343const LoopHintAttr *
2344TemplateInstantiator::TransformLoopHintAttr(const LoopHintAttr *LH) {
2345 ExprResult TransformedExprResult = getDerived().TransformExpr(LH->getValue());
2346 if (!TransformedExprResult.isUsable() ||
2347 TransformedExprResult.get() == LH->getValue())
2348 return LH;
2349 Expr *TransformedExpr = TransformedExprResult.get();
2350
2351 // Generate error if there is a problem with the value.
2352 if (getSema().CheckLoopHintExpr(TransformedExpr, LH->getLocation(),
2353 /*AllowZero=*/LH->getSemanticSpelling() ==
2354 LoopHintAttr::Pragma_unroll))
2355 return LH;
2356
2357 LoopHintAttr::OptionType Option = LH->getOption();
2358 LoopHintAttr::LoopHintState State = LH->getState();
2359
2360 // Since C++ does not have partial instantiation, we would expect a
2361 // transformed loop hint expression to not be value dependent. However, at
2362 // the time of writing, the use of a generic lambda inside a template
2363 // triggers a double instantiation, so we must protect against this event.
2364 // This provision may become unneeded in the future.
2365 if (Option == LoopHintAttr::UnrollCount &&
2366 !TransformedExpr->isValueDependent()) {
2367 llvm::APSInt ValueAPS =
2368 TransformedExpr->EvaluateKnownConstInt(getSema().getASTContext());
2369 // The values of 0 and 1 block any unrolling of the loop (also see
2370 // handleLoopHintAttr in SemaStmtAttr).
2371 if (ValueAPS.isZero() || ValueAPS.isOne()) {
2372 Option = LoopHintAttr::Unroll;
2373 State = LoopHintAttr::Disable;
2374 }
2375 }
2376
2377 // Create new LoopHintValueAttr with integral expression in place of the
2378 // non-type template parameter.
2379 return LoopHintAttr::CreateImplicit(getSema().Context, Option, State,
2380 TransformedExpr, *LH);
2381}
2382const NoInlineAttr *TemplateInstantiator::TransformStmtNoInlineAttr(
2383 const Stmt *OrigS, const Stmt *InstS, const NoInlineAttr *A) {
2384 if (!A || getSema().CheckNoInlineAttr(OrigS, InstS, *A))
2385 return nullptr;
2386
2387 return A;
2388}
2389const AlwaysInlineAttr *TemplateInstantiator::TransformStmtAlwaysInlineAttr(
2390 const Stmt *OrigS, const Stmt *InstS, const AlwaysInlineAttr *A) {
2391 if (!A || getSema().CheckAlwaysInlineAttr(OrigS, InstS, *A))
2392 return nullptr;
2393
2394 return A;
2395}
2396
2397const CodeAlignAttr *
2398TemplateInstantiator::TransformCodeAlignAttr(const CodeAlignAttr *CA) {
2399 Expr *TransformedExpr = getDerived().TransformExpr(CA->getAlignment()).get();
2400 return getSema().BuildCodeAlignAttr(*CA, TransformedExpr);
2401}
2402const OpenACCRoutineDeclAttr *
2403TemplateInstantiator::TransformOpenACCRoutineDeclAttr(
2404 const OpenACCRoutineDeclAttr *A) {
2405 llvm_unreachable("RoutineDecl should only be a declaration attribute, as it "
2406 "applies to a Function Decl (and a few places for VarDecl)");
2407}
2408
2409ExprResult TemplateInstantiator::RebuildVarDeclRefExpr(ValueDecl *PD,
2410 SourceLocation Loc) {
2411 DeclarationNameInfo NameInfo(PD->getDeclName(), Loc);
2412 return getSema().BuildDeclarationNameExpr(CXXScopeSpec(), NameInfo, PD);
2413}
2414
2416TemplateInstantiator::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {
2417 if (getSema().ArgPackSubstIndex) {
2418 // We can expand this parameter pack now.
2419 ValueDecl *D = E->getExpansion(*getSema().ArgPackSubstIndex);
2420 ValueDecl *VD = cast_or_null<ValueDecl>(TransformDecl(E->getExprLoc(), D));
2421 if (!VD)
2422 return ExprError();
2423 return RebuildVarDeclRefExpr(VD, E->getExprLoc());
2424 }
2425
2426 QualType T = TransformType(E->getType());
2427 if (T.isNull())
2428 return ExprError();
2429
2430 // Transform each of the parameter expansions into the corresponding
2431 // parameters in the instantiation of the function decl.
2432 SmallVector<ValueDecl *, 8> Vars;
2433 Vars.reserve(E->getNumExpansions());
2434 for (FunctionParmPackExpr::iterator I = E->begin(), End = E->end();
2435 I != End; ++I) {
2436 ValueDecl *D = cast_or_null<ValueDecl>(TransformDecl(E->getExprLoc(), *I));
2437 if (!D)
2438 return ExprError();
2439 Vars.push_back(D);
2440 }
2441
2442 auto *PackExpr =
2444 E->getParameterPackLocation(), Vars);
2445 getSema().MarkFunctionParmPackReferenced(PackExpr);
2446 return PackExpr;
2447}
2448
2450TemplateInstantiator::TransformFunctionParmPackRefExpr(DeclRefExpr *E,
2451 ValueDecl *PD) {
2452 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
2453 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found =
2454 getSema().CurrentInstantiationScope->getInstantiationOfIfExists(PD);
2455
2456 // This can happen when instantiating an expansion statement that contains
2457 // a pack (e.g. `template for (auto x : {{ts...}})`).
2458 if (!Found)
2459 return E;
2460
2461 Decl *TransformedDecl;
2462 if (DeclArgumentPack *Pack = dyn_cast<DeclArgumentPack *>(*Found)) {
2463 // If this is a reference to a function parameter pack which we can
2464 // substitute but can't yet expand, build a FunctionParmPackExpr for it.
2465 if (!getSema().ArgPackSubstIndex) {
2466 QualType T = TransformType(E->getType());
2467 if (T.isNull())
2468 return ExprError();
2469 auto *PackExpr = FunctionParmPackExpr::Create(getSema().Context, T, PD,
2470 E->getExprLoc(), *Pack);
2471 getSema().MarkFunctionParmPackReferenced(PackExpr);
2472 return PackExpr;
2473 }
2474
2475 TransformedDecl = (*Pack)[*getSema().ArgPackSubstIndex];
2476 } else {
2477 TransformedDecl = cast<Decl *>(*Found);
2478 }
2479
2480 // We have either an unexpanded pack or a specific expansion.
2481 return RebuildVarDeclRefExpr(cast<ValueDecl>(TransformedDecl),
2482 E->getExprLoc());
2483}
2484
2486TemplateInstantiator::TransformDeclRefExpr(DeclRefExpr *E) {
2487 NamedDecl *D = E->getDecl();
2488
2489 // Handle references to non-type template parameters and non-type template
2490 // parameter packs.
2491 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) {
2492 if (NTTP->getDepth() < TemplateArgs.getNumLevels())
2493 return TransformTemplateParmRefExpr(E, NTTP);
2494
2495 // We have a non-type template parameter that isn't fully substituted;
2496 // FindInstantiatedDecl will find it in the local instantiation scope.
2497 }
2498
2499 // Handle references to function parameter packs.
2500 if (VarDecl *PD = dyn_cast<VarDecl>(D))
2501 if (PD->isParameterPack()) {
2502 if (instantiateMissingDeclsToScopeForConcepts(PD))
2503 return ExprError();
2504
2505 return TransformFunctionParmPackRefExpr(E, PD);
2506 }
2507
2508 return inherited::TransformDeclRefExpr(E);
2509}
2510
2511ExprResult TemplateInstantiator::TransformCXXDefaultArgExpr(
2512 CXXDefaultArgExpr *E) {
2513 assert(!cast<FunctionDecl>(E->getParam()->getDeclContext())->
2514 getDescribedFunctionTemplate() &&
2515 "Default arg expressions are never formed in dependent cases.");
2516 return SemaRef.BuildCXXDefaultArgExpr(
2518 E->getParam());
2519}
2520
2521template<typename Fn>
2522QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB,
2523 FunctionProtoTypeLoc TL,
2524 CXXRecordDecl *ThisContext,
2525 Qualifiers ThisTypeQuals,
2526 Fn TransformExceptionSpec) {
2527 // If this is a lambda or block, the transformation MUST be done in the
2528 // CurrentInstantiationScope since it introduces a mapping of
2529 // the original to the newly created transformed parameters.
2530 //
2531 // In that case, TemplateInstantiator::TransformLambdaExpr will
2532 // have already pushed a scope for this prototype, so don't create
2533 // a second one.
2534 LocalInstantiationScope *Current = getSema().CurrentInstantiationScope;
2535 std::optional<LocalInstantiationScope> Scope;
2536 if (!Current || !Current->isLambdaOrBlock())
2537 Scope.emplace(SemaRef, /*CombineWithOuterScope=*/true);
2538
2539 return inherited::TransformFunctionProtoType(
2540 TLB, TL, ThisContext, ThisTypeQuals, TransformExceptionSpec);
2541}
2542
2543ParmVarDecl *TemplateInstantiator::TransformFunctionTypeParam(
2544 ParmVarDecl *OldParm, int indexAdjustment, UnsignedOrNone NumExpansions,
2545 bool ExpectParameterPack) {
2546 // Defer the late-parsed attributes of a parameter of the prototype being
2547 // transformed, when in its scope. A parameter is otherwise transformed on its
2548 // own only on demand, for a constraint that names it (see
2549 // instantiateMissingDeclsToScopeForConcepts). Its attributes are then
2550 // instantiated at once, and a later parameter they name is instantiated on
2551 // demand as well.
2552 Sema::LateInstantiatedAttrVec *LateAttrs = nullptr;
2553 if (LateParmAttrs && SemaRef.CurrentInstantiationScope == LateParmAttrScope)
2554 LateAttrs = LateParmAttrs;
2555 else
2556 assert((SemaRef.inConstraintSubstitution() ||
2557 SemaRef.inParameterMappingSubstitution()) &&
2558 "parameter transformed outside its prototype");
2559 auto NewParm = SemaRef.SubstParmVarDecl(
2560 OldParm, TemplateArgs, indexAdjustment, NumExpansions,
2561 ExpectParameterPack, EvaluateConstraints, LateAttrs);
2562 if (NewParm && SemaRef.getLangOpts().OpenCL)
2563 SemaRef.deduceOpenCLAddressSpace(NewParm);
2564 return NewParm;
2565}
2566
2567bool TemplateInstantiator::TransformFunctionTypeParams(
2568 SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
2569 const QualType *ParamTypes,
2570 const FunctionProtoType::ExtParameterInfo *ParamInfos,
2571 SmallVectorImpl<QualType> &PTypes, SmallVectorImpl<ParmVarDecl *> *PVars,
2572 Sema::ExtParameterInfoBuilder &PInfos, unsigned *LastParamTransformed) {
2573 // A late-parsed attribute on a parameter may name a parameter declared after
2574 // it, so transform all parameters then instantiate all late attributes.
2576 LocalInstantiationScope *Scope = SemaRef.CurrentInstantiationScope;
2577 llvm::SaveAndRestore SaveLateAttrs(LateParmAttrs, &LateAttrs);
2578 llvm::SaveAndRestore SaveLateScope(LateParmAttrScope, Scope);
2579 bool Failed = inherited::TransformFunctionTypeParams(
2580 Loc, Params, ParamTypes, ParamInfos, PTypes, PVars, PInfos,
2581 LastParamTransformed);
2582 // The attributes were deferred in this scope itself, so there is nothing to
2583 // free on failure.
2584 assert(
2585 llvm::all_of(LateAttrs, [&](const Sema::LateInstantiatedAttribute &LA) {
2586 return LA.Scope == Scope;
2587 }));
2588 if (Failed)
2589 return true;
2590 // The parser parses the late-parsed attributes of a function's parameters in
2591 // the function's scope, once it is declared; see
2592 // Parser::ParseFunctionDeclarator. Defer them likewise, if asked to.
2593 const auto *It = llvm::find_if(Params, [](ParmVarDecl *P) { return P; });
2594 if (FunctionParmAttrs && It != Params.end() &&
2595 (*It)->getDeclContext() == FunctionOfParmAttrs) {
2596 // The prototype's scope ends with its substitution, so keep a copy.
2597 for (const Sema::LateInstantiatedAttribute &LA : LateAttrs)
2598 FunctionParmAttrs->push_back(Sema::LateInstantiatedAttribute(
2599 LA.TmplAttr, LA.Scope->cloneScopes(FunctionParmAttrScope),
2600 LA.NewDecl));
2601 return false;
2602 }
2603 SemaRef.InstantiateLateAttrs(TemplateArgs, LateAttrs, Scope);
2604 return false;
2605}
2606
2607QualType TemplateInstantiator::BuildSubstTemplateTypeParmType(
2608 TypeLocBuilder &TLB, bool SuppressObjCLifetime, bool Final,
2609 Decl *AssociatedDecl, unsigned Index, UnsignedOrNone PackIndex,
2610 TemplateArgument Arg, SourceLocation NameLoc) {
2611 QualType Replacement = Arg.getAsType();
2612
2613 // If the template parameter had ObjC lifetime qualifiers,
2614 // then any such qualifiers on the replacement type are ignored.
2615 if (SuppressObjCLifetime) {
2616 Qualifiers RQs;
2617 RQs = Replacement.getQualifiers();
2618 RQs.removeObjCLifetime();
2619 Replacement =
2620 SemaRef.Context.getQualifiedType(Replacement.getUnqualifiedType(), RQs);
2621 }
2622
2623 // TODO: only do this uniquing once, at the start of instantiation.
2624 QualType Result = getSema().Context.getSubstTemplateTypeParmType(
2625 Replacement, AssociatedDecl, Index, PackIndex, Final);
2626 SubstTemplateTypeParmTypeLoc NewTL =
2627 TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
2628 NewTL.setNameLoc(NameLoc);
2629 return Result;
2630}
2631
2632QualType
2633TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB,
2634 TemplateTypeParmTypeLoc TL,
2635 bool SuppressObjCLifetime) {
2636 const TemplateTypeParmType *T = TL.getTypePtr();
2637 if (T->getDepth() < TemplateArgs.getNumLevels()) {
2638 // Replace the template type parameter with its corresponding
2639 // template argument.
2640
2641 // If the corresponding template argument is NULL or doesn't exist, it's
2642 // because we are performing instantiation from explicitly-specified
2643 // template arguments in a function template class, but there were some
2644 // arguments left unspecified.
2645 if (!TemplateArgs.hasTemplateArgument(T->getDepth(), T->getIndex())) {
2646 IsIncomplete = true;
2647 if (BailOutOnIncomplete)
2648 return QualType();
2649
2650 TemplateTypeParmTypeLoc NewTL
2651 = TLB.push<TemplateTypeParmTypeLoc>(TL.getType());
2652 NewTL.setNameLoc(TL.getNameLoc());
2653 return TL.getType();
2654 }
2655
2656 TemplateArgument Arg = TemplateArgs(T->getDepth(), T->getIndex());
2657
2658 if (TemplateArgs.isRewrite()) {
2659 // We're rewriting the template parameter as a reference to another
2660 // template parameter.
2661 Arg = getTemplateArgumentPackPatternForRewrite(Arg);
2662 assert(Arg.getKind() == TemplateArgument::Type &&
2663 "unexpected nontype template argument kind in template rewrite");
2664 QualType NewT = Arg.getAsType();
2665 TLB.pushTrivial(SemaRef.Context, NewT, TL.getNameLoc());
2666 return NewT;
2667 }
2668
2669 auto [AssociatedDecl, Final] =
2670 TemplateArgs.getAssociatedDecl(T->getDepth());
2671 UnsignedOrNone PackIndex = std::nullopt;
2672 if (T->isParameterPack() ||
2673 // In concept parameter mapping for fold expressions, packs that aren't
2674 // expanded in place are treated as having non-pack dependency, so that
2675 // a PackExpansionType won't prevent expanding the packs outside the
2676 // TreeTransform. However, we still need to unpack the arguments during
2677 // any template argument substitution, so we check the associated
2678 // declaration instead.
2679 (T->getDecl() && T->getDecl()->isTemplateParameterPack())) {
2680 assert(Arg.getKind() == TemplateArgument::Pack &&
2681 "Missing argument pack");
2682
2683 if (!getSema().ArgPackSubstIndex) {
2684 // We have the template argument pack, but we're not expanding the
2685 // enclosing pack expansion yet. Just save the template argument
2686 // pack for later substitution.
2687 QualType Result = getSema().Context.getSubstTemplateTypeParmPackType(
2688 AssociatedDecl, T->getIndex(), Final, Arg);
2689 SubstTemplateTypeParmPackTypeLoc NewTL
2690 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(Result);
2691 NewTL.setNameLoc(TL.getNameLoc());
2692 return Result;
2693 }
2694
2695 // PackIndex starts from last element.
2696 PackIndex = SemaRef.getPackIndex(Arg);
2697 Arg = SemaRef.getPackSubstitutedTemplateArgument(Arg);
2698 }
2699
2700 assert(Arg.getKind() == TemplateArgument::Type &&
2701 "Template argument kind mismatch");
2702
2703 return BuildSubstTemplateTypeParmType(TLB, SuppressObjCLifetime, Final,
2704 AssociatedDecl, T->getIndex(),
2705 PackIndex, Arg, TL.getNameLoc());
2706 }
2707
2708 // The template type parameter comes from an inner template (e.g.,
2709 // the template parameter list of a member template inside the
2710 // template we are instantiating). Create a new template type
2711 // parameter with the template "level" reduced by one.
2712 TemplateTypeParmDecl *NewTTPDecl = nullptr;
2713 if (TemplateTypeParmDecl *OldTTPDecl = T->getDecl())
2714 NewTTPDecl = cast_or_null<TemplateTypeParmDecl>(
2715 TransformDecl(TL.getNameLoc(), OldTTPDecl));
2716 QualType Result = getSema().Context.getTemplateTypeParmType(
2717 T->getDepth() - (TemplateArgs.retainInnerDepths()
2718 ? 0
2719 : TemplateArgs.getNumSubstitutedLevels()),
2720 T->getIndex(), T->isParameterPack(), NewTTPDecl);
2721 TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result);
2722 NewTL.setNameLoc(TL.getNameLoc());
2723 return Result;
2724}
2725
2726QualType TemplateInstantiator::TransformSubstTemplateTypeParmPackType(
2727 TypeLocBuilder &TLB, SubstTemplateTypeParmPackTypeLoc TL,
2728 bool SuppressObjCLifetime) {
2729 const SubstTemplateTypeParmPackType *T = TL.getTypePtr();
2730
2731 Decl *NewReplaced = TransformDecl(TL.getNameLoc(), T->getAssociatedDecl());
2732
2733 if (!getSema().ArgPackSubstIndex) {
2734 // We aren't expanding the parameter pack, so just return ourselves.
2735 QualType Result = TL.getType();
2736 if (NewReplaced != T->getAssociatedDecl())
2737 Result = getSema().Context.getSubstTemplateTypeParmPackType(
2738 NewReplaced, T->getIndex(), T->getFinal(), T->getArgumentPack());
2739 SubstTemplateTypeParmPackTypeLoc NewTL =
2740 TLB.push<SubstTemplateTypeParmPackTypeLoc>(Result);
2741 NewTL.setNameLoc(TL.getNameLoc());
2742 return Result;
2743 }
2744
2745 TemplateArgument Pack = T->getArgumentPack();
2746 TemplateArgument Arg = SemaRef.getPackSubstitutedTemplateArgument(Pack);
2747 return BuildSubstTemplateTypeParmType(
2748 TLB, SuppressObjCLifetime, T->getFinal(), NewReplaced, T->getIndex(),
2749 SemaRef.getPackIndex(Pack), Arg, TL.getNameLoc());
2750}
2751
2752QualType TemplateInstantiator::TransformSubstBuiltinTemplatePackType(
2753 TypeLocBuilder &TLB, SubstBuiltinTemplatePackTypeLoc TL) {
2754 if (!getSema().ArgPackSubstIndex)
2755 return TreeTransform::TransformSubstBuiltinTemplatePackType(TLB, TL);
2756 TemplateArgument Result = SemaRef.getPackSubstitutedTemplateArgument(
2757 TL.getTypePtr()->getArgumentPack());
2758 TLB.pushTrivial(SemaRef.getASTContext(), Result.getAsType(),
2759 TL.getBeginLoc());
2760 return Result.getAsType();
2761}
2762
2763static concepts::Requirement::SubstitutionDiagnostic *
2765 Sema::EntityPrinter Printer) {
2766 SmallString<128> Message;
2767 SourceLocation ErrorLoc;
2768 if (Info.hasSFINAEDiagnostic()) {
2771 Info.takeSFINAEDiagnostic(PDA);
2772 PDA.second.EmitToString(S.getDiagnostics(), Message);
2773 ErrorLoc = PDA.first;
2774 } else {
2775 ErrorLoc = Info.getLocation();
2776 }
2777 SmallString<128> Entity;
2778 llvm::raw_svector_ostream OS(Entity);
2779 Printer(OS);
2780 const ASTContext &C = S.Context;
2782 C.backupStr(Entity), ErrorLoc, C.backupStr(Message)};
2783}
2784
2785concepts::Requirement::SubstitutionDiagnostic *
2787 SmallString<128> Entity;
2788 llvm::raw_svector_ostream OS(Entity);
2789 Printer(OS);
2790 const ASTContext &C = Context;
2792 /*SubstitutedEntity=*/C.backupStr(Entity),
2793 /*DiagLoc=*/Location, /*DiagMessage=*/StringRef()};
2794}
2795
2796ExprResult TemplateInstantiator::TransformRequiresTypeParams(
2797 SourceLocation KWLoc, SourceLocation RBraceLoc, const RequiresExpr *RE,
2800 SmallVectorImpl<ParmVarDecl *> &TransParams,
2802
2803 TemplateDeductionInfo Info(KWLoc);
2804 Sema::InstantiatingTemplate TypeInst(SemaRef, KWLoc, RE,
2805 SourceRange{KWLoc, RBraceLoc});
2806 Sema::SFINAETrap Trap(SemaRef, Info);
2807
2808 unsigned ErrorIdx;
2809 if (getDerived().TransformFunctionTypeParams(
2810 KWLoc, Params, /*ParamTypes=*/nullptr, /*ParamInfos=*/nullptr, PTypes,
2811 &TransParams, PInfos, &ErrorIdx) ||
2812 Trap.hasErrorOccurred()) {
2814 ParmVarDecl *FailedDecl = Params[ErrorIdx];
2815 // Add a 'failed' Requirement to contain the error that caused the failure
2816 // here.
2817 TransReqs.push_back(RebuildTypeRequirement(createSubstDiag(
2818 SemaRef, Info, [&](llvm::raw_ostream &OS) { OS << *FailedDecl; })));
2819 return getDerived().RebuildRequiresExpr(KWLoc, Body, RE->getLParenLoc(),
2820 TransParams, RE->getRParenLoc(),
2821 TransReqs, RBraceLoc);
2822 }
2823
2824 return ExprResult{};
2825}
2826
2827concepts::TypeRequirement *
2828TemplateInstantiator::TransformTypeRequirement(concepts::TypeRequirement *Req) {
2829 if (!Req->isDependent() && !AlwaysRebuild())
2830 return Req;
2831 if (Req->isSubstitutionFailure()) {
2832 if (AlwaysRebuild())
2833 return RebuildTypeRequirement(
2835 return Req;
2836 }
2837
2838 TemplateDeductionInfo Info(Req->getType()->getTypeLoc().getBeginLoc());
2839 Sema::SFINAETrap Trap(SemaRef, Info);
2840 Sema::InstantiatingTemplate TypeInst(
2841 SemaRef, Req->getType()->getTypeLoc().getBeginLoc(), Req,
2842 Req->getType()->getTypeLoc().getSourceRange());
2843 if (TypeInst.isInvalid())
2844 return nullptr;
2845 TypeSourceInfo *TransType = TransformType(Req->getType());
2846 if (!TransType || Trap.hasErrorOccurred())
2847 return RebuildTypeRequirement(createSubstDiag(SemaRef, Info,
2848 [&] (llvm::raw_ostream& OS) {
2849 Req->getType()->getType().print(OS, SemaRef.getPrintingPolicy());
2850 }));
2851 return RebuildTypeRequirement(TransType);
2852}
2853
2854concepts::ExprRequirement *
2855TemplateInstantiator::TransformExprRequirement(concepts::ExprRequirement *Req) {
2856 if (!Req->isDependent() && !AlwaysRebuild())
2857 return Req;
2858
2859 llvm::PointerUnion<Expr *, concepts::Requirement::SubstitutionDiagnostic *>
2860 TransExpr;
2861 if (Req->isExprSubstitutionFailure())
2862 TransExpr = Req->getExprSubstitutionDiagnostic();
2863 else {
2864 Expr *E = Req->getExpr();
2865 TemplateDeductionInfo Info(E->getBeginLoc());
2866 Sema::SFINAETrap Trap(SemaRef, Info);
2867 Sema::InstantiatingTemplate ExprInst(SemaRef, E->getBeginLoc(), Req,
2868 E->getSourceRange());
2869 if (ExprInst.isInvalid())
2870 return nullptr;
2871 ExprResult TransExprRes = TransformExpr(E);
2872 if (!TransExprRes.isInvalid() && !Trap.hasErrorOccurred() &&
2873 TransExprRes.get()->hasPlaceholderType())
2874 TransExprRes = SemaRef.CheckPlaceholderExpr(TransExprRes.get());
2875 if (TransExprRes.isInvalid() || Trap.hasErrorOccurred())
2876 TransExpr = createSubstDiag(SemaRef, Info, [&](llvm::raw_ostream &OS) {
2877 E->printPretty(OS, nullptr, SemaRef.getPrintingPolicy());
2878 });
2879 else
2880 TransExpr = TransExprRes.get();
2881 }
2882
2883 std::optional<concepts::ExprRequirement::ReturnTypeRequirement> TransRetReq;
2884 const auto &RetReq = Req->getReturnTypeRequirement();
2885 if (RetReq.isEmpty())
2886 TransRetReq.emplace();
2887 else if (RetReq.isSubstitutionFailure())
2888 TransRetReq.emplace(RetReq.getSubstitutionDiagnostic());
2889 else if (RetReq.isTypeConstraint()) {
2890 TemplateParameterList *OrigTPL =
2891 RetReq.getTypeConstraintTemplateParameterList();
2892 TemplateDeductionInfo Info(OrigTPL->getTemplateLoc());
2893 Sema::SFINAETrap Trap(SemaRef, Info);
2894 Sema::InstantiatingTemplate TPLInst(SemaRef, OrigTPL->getTemplateLoc(), Req,
2895 OrigTPL->getSourceRange());
2896 if (TPLInst.isInvalid())
2897 return nullptr;
2898 TemplateParameterList *TPL = TransformTemplateParameterList(OrigTPL);
2899 if (!TPL || Trap.hasErrorOccurred())
2900 TransRetReq.emplace(createSubstDiag(SemaRef, Info,
2901 [&] (llvm::raw_ostream& OS) {
2902 RetReq.getTypeConstraint()->getImmediatelyDeclaredConstraint()
2903 ->printPretty(OS, nullptr, SemaRef.getPrintingPolicy());
2904 }));
2905 else {
2906 TPLInst.Clear();
2907 TransRetReq.emplace(TPL);
2908 }
2909 }
2910 assert(TransRetReq && "All code paths leading here must set TransRetReq");
2911 if (Expr *E = dyn_cast<Expr *>(TransExpr))
2912 return RebuildExprRequirement(E, Req->isSimple(), Req->getNoexceptLoc(),
2913 std::move(*TransRetReq));
2914 return RebuildExprRequirement(
2916 Req->isSimple(), Req->getNoexceptLoc(), std::move(*TransRetReq));
2917}
2918
2919concepts::NestedRequirement *
2920TemplateInstantiator::TransformNestedRequirement(
2921 concepts::NestedRequirement *Req) {
2922
2923 ASTContext &C = SemaRef.Context;
2924
2925 ConstraintSatisfaction Satisfaction;
2926
2927 auto NestedReqWithDiag = [&C, this](Expr *E,
2928 ConstraintSatisfaction Satisfaction) {
2929 Satisfaction.IsSatisfied = false;
2930 SmallString<128> Entity;
2931 llvm::raw_svector_ostream OS(Entity);
2932 E->printPretty(OS, nullptr, SemaRef.getPrintingPolicy());
2933 return new (C) concepts::NestedRequirement(
2934 SemaRef.Context, C.backupStr(Entity), std::move(Satisfaction));
2935 };
2936
2937 if (Req->hasInvalidConstraint()) {
2938 if (AlwaysRebuild())
2939 return RebuildNestedRequirement(Req->getInvalidConstraintEntity(),
2941 return Req;
2942 }
2943
2944 Expr *Constraint = Req->getConstraintExpr();
2945
2946 if (!getEvaluateConstraints()) {
2947 ExprResult TransConstraint = TransformExpr(Req->getConstraintExpr());
2948 if (TransConstraint.isInvalid() || !TransConstraint.get())
2949 return nullptr;
2950 if (TransConstraint.get()->isInstantiationDependent())
2951 return new (SemaRef.Context)
2952 concepts::NestedRequirement(TransConstraint.get());
2953 ConstraintSatisfaction Satisfaction;
2954 return new (SemaRef.Context) concepts::NestedRequirement(
2955 SemaRef.Context, TransConstraint.get(), Satisfaction);
2956 }
2957
2958 bool Success;
2959 Expr *NewConstraint;
2960 {
2961 EnterExpressionEvaluationContext ContextRAII(
2963 Sema::InstantiatingTemplate ConstrInst(
2964 SemaRef, Constraint->getBeginLoc(), Req,
2965 Sema::InstantiatingTemplate::ConstraintsCheck(),
2966 Constraint->getSourceRange());
2967
2968 if (ConstrInst.isInvalid())
2969 return nullptr;
2970
2971 Success = !SemaRef.CheckConstraintSatisfaction(
2972 Req, AssociatedConstraint(Constraint), TemplateArgs,
2973 Constraint->getSourceRange(), Satisfaction,
2974 /*TopLevelConceptId=*/nullptr, &NewConstraint);
2975 }
2976
2977 if (!Success || Satisfaction.HasSubstitutionFailure())
2978 return NestedReqWithDiag(Constraint, Satisfaction);
2979
2980 // FIXME: const correctness
2981 // MLTAL might be dependent.
2982 if (!NewConstraint) {
2983 if (!Satisfaction.IsSatisfied)
2984 return NestedReqWithDiag(Constraint, Satisfaction);
2985
2986 NewConstraint = Constraint;
2987 }
2988 return new (C) concepts::NestedRequirement(C, NewConstraint, Satisfaction);
2989}
2990
2993 SourceLocation Loc, DeclarationName Entity,
2994 bool AllowDeducedTST) {
2995 if (!T->getType()->isInstantiationDependentType() &&
2996 !T->getType()->isVariablyModifiedType())
2997 return T;
2998
2999 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
3000 return AllowDeducedTST ? Instantiator.TransformTypeWithDeducedTST(T)
3001 : Instantiator.TransformType(T);
3002}
3003
3006 SourceLocation Loc, DeclarationName Entity) {
3007 if (TL.getType().isNull())
3008 return nullptr;
3009
3012 // FIXME: Make a copy of the TypeLoc data here, so that we can
3013 // return a new TypeSourceInfo. Inefficient!
3014 TypeLocBuilder TLB;
3015 TLB.pushFullCopy(TL);
3016 return TLB.getTypeSourceInfo(Context, TL.getType());
3017 }
3018
3019 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
3020 TypeLocBuilder TLB;
3021 TLB.reserve(TL.getFullDataSize());
3022 QualType Result = Instantiator.TransformType(TLB, TL);
3023 if (Result.isNull())
3024 return nullptr;
3025
3026 return TLB.getTypeSourceInfo(Context, Result);
3027}
3028
3029/// Deprecated form of the above.
3031 const MultiLevelTemplateArgumentList &TemplateArgs,
3032 SourceLocation Loc, DeclarationName Entity,
3033 bool *IsIncompleteSubstitution) {
3034 // If T is not a dependent type or a variably-modified type, there
3035 // is nothing to do.
3036 if (!T->isInstantiationDependentType() && !T->isVariablyModifiedType())
3037 return T;
3038
3039 TemplateInstantiator Instantiator(
3040 *this, TemplateArgs, Loc, Entity,
3041 /*BailOutOnIncomplete=*/IsIncompleteSubstitution != nullptr);
3042 QualType QT = Instantiator.TransformType(T);
3043 if (IsIncompleteSubstitution && Instantiator.getIsIncomplete())
3044 *IsIncompleteSubstitution = true;
3045 return QT;
3046}
3047
3049 if (T->getType()->isInstantiationDependentType() ||
3050 T->getType()->isVariablyModifiedType())
3051 return true;
3052
3053 TypeLoc TL = T->getTypeLoc().IgnoreParens();
3054 if (!TL.getAs<FunctionProtoTypeLoc>())
3055 return false;
3056
3058 for (ParmVarDecl *P : FP.getParams()) {
3059 // This must be synthesized from a typedef.
3060 if (!P) continue;
3061
3062 // If there are any parameters, a new TypeSourceInfo that refers to the
3063 // instantiated parameters must be built.
3064 return true;
3065 }
3066
3067 return false;
3068}
3069
3072 SourceLocation Loc, DeclarationName Entity, CXXRecordDecl *ThisContext,
3073 Qualifiers ThisTypeQuals, bool EvaluateConstraints, const FunctionDecl *Fn,
3074 LateInstantiatedAttrVec *ParamAttrs) {
3076 return T;
3077
3078 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
3079 Instantiator.setEvaluateConstraints(EvaluateConstraints);
3080 Instantiator.deferFunctionParmAttrs(Fn, ParamAttrs);
3081
3082 TypeLocBuilder TLB;
3083
3084 TypeLoc TL = T->getTypeLoc();
3085 TLB.reserve(TL.getFullDataSize());
3086
3088
3089 if (FunctionProtoTypeLoc Proto =
3091 // Instantiate the type, other than its exception specification. The
3092 // exception specification is instantiated in InitFunctionInstantiation
3093 // once we've built the FunctionDecl.
3094 // FIXME: Set the exception specification to EST_Uninstantiated here,
3095 // instead of rebuilding the function type again later.
3096 Result = Instantiator.TransformFunctionProtoType(
3097 TLB, Proto, ThisContext, ThisTypeQuals,
3099 bool &Changed) { return false; });
3100 } else {
3101 Result = Instantiator.TransformType(TLB, TL);
3102 }
3103 // When there are errors resolving types, clang may use IntTy as a fallback,
3104 // breaking our assumption that function declarations have function types.
3105 if (Result.isNull() || !Result->isFunctionType())
3106 return nullptr;
3107
3108 return TLB.getTypeSourceInfo(Context, Result);
3109}
3110
3113 SmallVectorImpl<QualType> &ExceptionStorage,
3114 const MultiLevelTemplateArgumentList &Args) {
3115 bool Changed = false;
3116 TemplateInstantiator Instantiator(*this, Args, Loc, DeclarationName());
3117 return Instantiator.TransformExceptionSpec(Loc, ESI, ExceptionStorage,
3118 Changed);
3119}
3120
3122 const MultiLevelTemplateArgumentList &Args) {
3125
3126 SmallVector<QualType, 4> ExceptionStorage;
3127 if (SubstExceptionSpec(New->getTypeSourceInfo()->getTypeLoc().getEndLoc(),
3128 ESI, ExceptionStorage, Args))
3129 // On error, recover by dropping the exception specification.
3130 ESI.Type = EST_None;
3131
3133}
3134
3135namespace {
3136
3137 struct GetContainedInventedTypeParmVisitor :
3138 public TypeVisitor<GetContainedInventedTypeParmVisitor,
3139 TemplateTypeParmDecl *> {
3140 using TypeVisitor<GetContainedInventedTypeParmVisitor,
3141 TemplateTypeParmDecl *>::Visit;
3142
3143 TemplateTypeParmDecl *Visit(QualType T) {
3144 if (T.isNull())
3145 return nullptr;
3146 return Visit(T.getTypePtr());
3147 }
3148 // The deduced type itself.
3149 TemplateTypeParmDecl *VisitTemplateTypeParmType(
3150 const TemplateTypeParmType *T) {
3151 if (!T->getDecl() || !T->getDecl()->isImplicit())
3152 return nullptr;
3153 return T->getDecl();
3154 }
3155
3156 // Only these types can contain 'auto' types, and subsequently be replaced
3157 // by references to invented parameters.
3158
3159 TemplateTypeParmDecl *VisitPointerType(const PointerType *T) {
3160 return Visit(T->getPointeeType());
3161 }
3162
3163 TemplateTypeParmDecl *VisitBlockPointerType(const BlockPointerType *T) {
3164 return Visit(T->getPointeeType());
3165 }
3166
3167 TemplateTypeParmDecl *VisitReferenceType(const ReferenceType *T) {
3168 return Visit(T->getPointeeTypeAsWritten());
3169 }
3170
3171 TemplateTypeParmDecl *VisitMemberPointerType(const MemberPointerType *T) {
3172 return Visit(T->getPointeeType());
3173 }
3174
3175 TemplateTypeParmDecl *VisitArrayType(const ArrayType *T) {
3176 return Visit(T->getElementType());
3177 }
3178
3179 TemplateTypeParmDecl *VisitDependentSizedExtVectorType(
3180 const DependentSizedExtVectorType *T) {
3181 return Visit(T->getElementType());
3182 }
3183
3184 TemplateTypeParmDecl *VisitVectorType(const VectorType *T) {
3185 return Visit(T->getElementType());
3186 }
3187
3188 TemplateTypeParmDecl *VisitFunctionProtoType(const FunctionProtoType *T) {
3189 return VisitFunctionType(T);
3190 }
3191
3192 TemplateTypeParmDecl *VisitFunctionType(const FunctionType *T) {
3193 return Visit(T->getReturnType());
3194 }
3195
3196 TemplateTypeParmDecl *VisitParenType(const ParenType *T) {
3197 return Visit(T->getInnerType());
3198 }
3199
3200 TemplateTypeParmDecl *VisitAttributedType(const AttributedType *T) {
3201 return Visit(T->getModifiedType());
3202 }
3203
3204 TemplateTypeParmDecl *VisitMacroQualifiedType(const MacroQualifiedType *T) {
3205 return Visit(T->getUnderlyingType());
3206 }
3207
3208 TemplateTypeParmDecl *VisitAdjustedType(const AdjustedType *T) {
3209 return Visit(T->getOriginalType());
3210 }
3211
3212 TemplateTypeParmDecl *VisitPackExpansionType(const PackExpansionType *T) {
3213 return Visit(T->getPattern());
3214 }
3215 };
3216
3217} // namespace
3218
3220 TemplateTypeParmDecl *Inst, const TypeConstraint *TC,
3221 const MultiLevelTemplateArgumentList &TemplateArgs,
3222 bool EvaluateConstraints) {
3223 const ASTTemplateArgumentListInfo *TemplArgInfo =
3225
3226 if (!EvaluateConstraints) {
3228 bool ContainsUnexpandedPack =
3229 TemplArgInfo &&
3230 llvm::any_of(
3231 TemplArgInfo->arguments(), [](const TemplateArgumentLoc &TA) {
3232 return TA.getArgument().containsUnexpandedParameterPack();
3233 });
3234 if (!Index && ContainsUnexpandedPack)
3235 Index = SemaRef.ArgPackSubstIndex;
3238 return false;
3239 }
3240
3241 TemplateArgumentListInfo InstArgs;
3242
3243 if (TemplArgInfo) {
3244 InstArgs.setLAngleLoc(TemplArgInfo->LAngleLoc);
3245 InstArgs.setRAngleLoc(TemplArgInfo->RAngleLoc);
3246 // Constraints on lambda arguments can depend on the substituted parameters.
3247 TemplateInstantiator Instantiator(
3248 TemplateInstantiator::ForConstraintSubstitution, *this, TemplateArgs,
3250 if (Instantiator.TransformTemplateArguments(
3251 TemplArgInfo->arguments().begin(), TemplArgInfo->arguments().end(),
3252 InstArgs))
3253 return true;
3254 }
3255 return AttachTypeConstraint(
3257 TC->getNamedConcept(),
3258 /*FoundDecl=*/TC->getConceptReference()->getFoundDecl(), &InstArgs, Inst,
3259 Inst->isParameterPack()
3261 ->getEllipsisLoc()
3262 : SourceLocation());
3263}
3264
3266 ParmVarDecl *OldParm, const MultiLevelTemplateArgumentList &TemplateArgs,
3267 int indexAdjustment, UnsignedOrNone NumExpansions, bool ExpectParameterPack,
3268 bool EvaluateConstraint, LateInstantiatedAttrVec *LateAttrs) {
3269 TypeSourceInfo *OldTSI = OldParm->getTypeSourceInfo();
3270 TypeSourceInfo *NewTSI = nullptr;
3271
3272 TypeLoc OldTL = OldTSI->getTypeLoc();
3273 if (PackExpansionTypeLoc ExpansionTL = OldTL.getAs<PackExpansionTypeLoc>()) {
3274
3275 // We have a function parameter pack. Substitute into the pattern of the
3276 // expansion.
3277 NewTSI = SubstType(ExpansionTL.getPatternLoc(), TemplateArgs,
3278 OldParm->getLocation(), OldParm->getDeclName());
3279 if (!NewTSI)
3280 return nullptr;
3281
3282 if (NewTSI->getType()->containsUnexpandedParameterPack()) {
3283 // We still have unexpanded parameter packs, which means that
3284 // our function parameter is still a function parameter pack.
3285 // Therefore, make its type a pack expansion type.
3286 NewTSI = CheckPackExpansion(NewTSI, ExpansionTL.getEllipsisLoc(),
3287 NumExpansions);
3288 } else if (ExpectParameterPack) {
3289 // We expected to get a parameter pack but didn't (because the type
3290 // itself is not a pack expansion type), so complain. This can occur when
3291 // the substitution goes through an alias template that "loses" the
3292 // pack expansion.
3293 Diag(OldParm->getLocation(),
3294 diag::err_function_parameter_pack_without_parameter_packs)
3295 << NewTSI->getType();
3296 return nullptr;
3297 }
3298 } else {
3299 NewTSI = SubstType(OldTSI, TemplateArgs, OldParm->getLocation(),
3300 OldParm->getDeclName());
3301 }
3302
3303 if (!NewTSI)
3304 return nullptr;
3305
3306 if (NewTSI->getType()->isVoidType()) {
3307 Diag(OldParm->getLocation(), diag::err_param_with_void_type);
3308 return nullptr;
3309 }
3310
3311 // In abbreviated templates, TemplateTypeParmDecls with possible
3312 // TypeConstraints are created when the parameter list is originally parsed.
3313 // The TypeConstraints can therefore reference other functions parameters in
3314 // the abbreviated function template, which is why we must instantiate them
3315 // here, when the instantiated versions of those referenced parameters are in
3316 // scope.
3317 if (TemplateTypeParmDecl *TTP =
3318 GetContainedInventedTypeParmVisitor().Visit(OldTSI->getType())) {
3319 if (const TypeConstraint *TC = TTP->getTypeConstraint()) {
3320 auto *Inst = cast_or_null<TemplateTypeParmDecl>(
3321 FindInstantiatedDecl(TTP->getLocation(), TTP, TemplateArgs));
3322 // We will first get here when instantiating the abbreviated function
3323 // template's described function, but we might also get here later.
3324 // Make sure we do not instantiate the TypeConstraint more than once.
3325 if (Inst && !Inst->getTypeConstraint()) {
3326 if (SubstTypeConstraint(Inst, TC, TemplateArgs, EvaluateConstraint))
3327 return nullptr;
3328 }
3329 }
3330 }
3331
3332 ParmVarDecl *NewParm = CheckParameter(
3333 Context.getTranslationUnitDecl(), OldParm->getInnerLocStart(),
3334 OldParm->getLocation(), OldParm->getIdentifier(), NewTSI->getType(),
3335 NewTSI, OldParm->getStorageClass());
3336 if (!NewParm)
3337 return nullptr;
3338
3339 // Mark the (new) default argument as uninstantiated (if any).
3340 if (OldParm->hasUninstantiatedDefaultArg()) {
3341 Expr *Arg = OldParm->getUninstantiatedDefaultArg();
3342 NewParm->setUninstantiatedDefaultArg(Arg);
3343 } else if (OldParm->hasUnparsedDefaultArg()) {
3344 NewParm->setUnparsedDefaultArg();
3345 UnparsedDefaultArgInstantiations[OldParm].push_back(NewParm);
3346 } else if (Expr *Arg = OldParm->getDefaultArg()) {
3347 // Default arguments cannot be substituted until the declaration context
3348 // for the associated function or lambda capture class is available.
3349 // This is necessary for cases like the following where construction of
3350 // the lambda capture class for the outer lambda is dependent on the
3351 // parameter types but where the default argument is dependent on the
3352 // outer lambda's declaration context.
3353 // template <typename T>
3354 // auto f() {
3355 // return [](T = []{ return T{}; }()) { return 0; };
3356 // }
3357 NewParm->setUninstantiatedDefaultArg(Arg);
3358 }
3359
3363
3364 if (OldParm->isParameterPack() && !NewParm->isParameterPack()) {
3365 // Add the new parameter to the instantiated parameter pack.
3366 CurrentInstantiationScope->InstantiatedLocalPackArg(OldParm, NewParm);
3367 } else {
3368 // Introduce an Old -> New mapping
3369 CurrentInstantiationScope->InstantiatedLocal(OldParm, NewParm);
3370 }
3371
3372 // A parameter that is not a function's own, such as one of a function
3373 // pointer's pointee, belongs to no function (see ActOnParamDeclarator); keep
3374 // it in the translation unit, where CheckParameter created it.
3375 // FIXME: For other parameters from a FunctionProtoType, CurContext can be
3376 // anything; is this right?
3377 if (!OldParm->getDeclContext()->isTranslationUnit())
3378 NewParm->setDeclContext(CurContext);
3379
3380 NewParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
3381 OldParm->getFunctionScopeIndex() + indexAdjustment);
3382
3383 InstantiateAttrs(TemplateArgs, OldParm, NewParm, LateAttrs,
3385
3387
3388 return NewParm;
3389}
3390
3393 const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
3394 const MultiLevelTemplateArgumentList &TemplateArgs,
3395 SmallVectorImpl<QualType> &ParamTypes,
3397 ExtParameterInfoBuilder &ParamInfos, const QualType *OldParamTypes,
3398 bool EvaluateConstraints, const FunctionDecl *Fn,
3399 LateInstantiatedAttrVec *ParamAttrs) {
3400 // If there is a parameter with no ParmVarDecl to substitute, its type needs
3401 // to come from OldParamTypes instead.
3402 assert((OldParamTypes || !llvm::is_contained(Params, nullptr)) &&
3403 "a parameter with no ParmVarDecl needs OldParamTypes to be passed");
3404 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
3405 DeclarationName());
3406 Instantiator.setEvaluateConstraints(EvaluateConstraints);
3407 Instantiator.deferFunctionParmAttrs(Fn, ParamAttrs);
3408 return Instantiator.TransformFunctionTypeParams(Loc, Params, OldParamTypes,
3409 ExtParamInfos, ParamTypes,
3410 OutParams, ParamInfos);
3411}
3412
3414 SourceLocation Loc,
3415 ParmVarDecl *Param,
3416 const MultiLevelTemplateArgumentList &TemplateArgs,
3417 bool ForCallExpr) {
3418 FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());
3419 Expr *PatternExpr = Param->getUninstantiatedDefaultArg();
3420
3421 RecursiveInstGuard AlreadyInstantiating(
3423 if (AlreadyInstantiating) {
3424 Param->setInvalidDecl();
3425 return Diag(Param->getBeginLoc(), diag::err_recursive_default_argument)
3426 << FD << PatternExpr->getSourceRange();
3427 }
3428
3431 NonSFINAEContext _(*this);
3432 InstantiatingTemplate Inst(*this, Loc, Param, TemplateArgs.getInnermost());
3433 if (Inst.isInvalid())
3434 return true;
3435
3437 // C++ [dcl.fct.default]p5:
3438 // The names in the [default argument] expression are bound, and
3439 // the semantic constraints are checked, at the point where the
3440 // default argument expression appears.
3441 ContextRAII SavedContext(*this, FD);
3442 {
3443 std::optional<LocalInstantiationScope> LIS;
3444
3445 if (ForCallExpr) {
3446 // When instantiating a default argument due to use in a call expression,
3447 // an instantiation scope that includes the parameters of the callee is
3448 // required to satisfy references from the default argument. For example:
3449 // template<typename T> void f(T a, int = decltype(a)());
3450 // void g() { f(0); }
3451 LIS.emplace(*this);
3453 /*ForDefinition*/ false);
3454 if (addInstantiatedParametersToScope(FD, PatternFD, *LIS, TemplateArgs))
3455 return true;
3456 }
3457
3459 Result = SubstInitializer(PatternExpr, TemplateArgs,
3460 /*DirectInit*/ false);
3461 });
3462 }
3463 if (Result.isInvalid())
3464 return true;
3465
3466 if (ForCallExpr) {
3467 // Check the expression as an initializer for the parameter.
3468 InitializedEntity Entity
3471 Param->getLocation(),
3472 /*FIXME:EqualLoc*/ PatternExpr->getBeginLoc());
3473 Expr *ResultE = Result.getAs<Expr>();
3474
3475 InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
3476 Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
3477 if (Result.isInvalid())
3478 return true;
3479
3480 Result =
3481 ActOnFinishFullExpr(Result.getAs<Expr>(), Param->getOuterLocStart(),
3482 /*DiscardedValue*/ false);
3483 } else {
3484 // FIXME: Obtain the source location for the '=' token.
3485 SourceLocation EqualLoc = PatternExpr->getBeginLoc();
3486 Result = ConvertParamDefaultArgument(Param, Result.getAs<Expr>(), EqualLoc);
3487 }
3488 if (Result.isInvalid())
3489 return true;
3490
3491 // Remember the instantiated default argument.
3492 Param->setDefaultArg(Result.getAs<Expr>());
3493
3494 return false;
3495}
3496
3497// See TreeTransform::PreparePackForExpansion for the relevant comment.
3498// This function implements the same concept for base specifiers.
3499static bool
3501 const MultiLevelTemplateArgumentList &TemplateArgs,
3502 TypeSourceInfo *&Out, UnexpandedInfo &Info) {
3503 SourceRange BaseSourceRange = Base.getSourceRange();
3504 SourceLocation BaseEllipsisLoc = Base.getEllipsisLoc();
3505 Info.Ellipsis = Base.getEllipsisLoc();
3506 auto ComputeInfo = [&S, &TemplateArgs, BaseSourceRange, BaseEllipsisLoc](
3507 TypeSourceInfo *BaseTypeInfo,
3508 bool IsLateExpansionAttempt, UnexpandedInfo &Info) {
3509 // This is a pack expansion. See whether we should expand it now, or
3510 // wait until later.
3512 S.collectUnexpandedParameterPacks(BaseTypeInfo->getTypeLoc(), Unexpanded);
3513 if (IsLateExpansionAttempt) {
3514 // Request expansion only when there is an opportunity to expand a pack
3515 // that required a substituion first.
3516 bool SawPackTypes =
3517 llvm::any_of(Unexpanded, [](UnexpandedParameterPack P) {
3519 });
3520 if (!SawPackTypes) {
3521 Info.Expand = false;
3522 return false;
3523 }
3524 }
3525
3526 // Determine whether the set of unexpanded parameter packs can and should be
3527 // expanded.
3528 Info.Expand = false;
3529 Info.RetainExpansion = false;
3530 Info.NumExpansions = std::nullopt;
3532 BaseEllipsisLoc, BaseSourceRange, Unexpanded, TemplateArgs,
3533 /*FailOnPackProducingTemplates=*/false, Info.Expand,
3534 Info.RetainExpansion, Info.NumExpansions);
3535 };
3536
3537 if (ComputeInfo(Base.getTypeSourceInfo(), false, Info))
3538 return true;
3539
3540 if (Info.Expand) {
3541 Out = Base.getTypeSourceInfo();
3542 return false;
3543 }
3544
3545 // The resulting base specifier will (still) be a pack expansion.
3546 {
3547 Sema::ArgPackSubstIndexRAII SubstIndex(S, std::nullopt);
3548 Out = S.SubstType(Base.getTypeSourceInfo(), TemplateArgs,
3549 BaseSourceRange.getBegin(), DeclarationName());
3550 }
3551 if (!Out->getType()->containsUnexpandedParameterPack())
3552 return false;
3553
3554 // Some packs will learn their length after substitution.
3555 // We may need to request their expansion.
3556 if (ComputeInfo(Out, /*IsLateExpansionAttempt=*/true, Info))
3557 return true;
3558 if (Info.Expand)
3559 Info.ExpandUnderForgetSubstitions = true;
3560 return false;
3561}
3562
3563bool
3565 CXXRecordDecl *Pattern,
3566 const MultiLevelTemplateArgumentList &TemplateArgs) {
3567 bool Invalid = false;
3568 SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases;
3569 for (const auto &Base : Pattern->bases()) {
3570 if (!Base.getType()->isInstantiationDependentType()) {
3571 if (const CXXRecordDecl *RD = Base.getType()->getAsCXXRecordDecl()) {
3572 if (RD->isInvalidDecl())
3573 Instantiation->setInvalidDecl();
3574 }
3575 InstantiatedBases.push_back(new (Context) CXXBaseSpecifier(Base));
3576 continue;
3577 }
3578
3579 SourceLocation EllipsisLoc;
3580 TypeSourceInfo *BaseTypeLoc = nullptr;
3581 if (Base.isPackExpansion()) {
3582 UnexpandedInfo Info;
3583 if (PreparePackForExpansion(*this, Base, TemplateArgs, BaseTypeLoc,
3584 Info)) {
3585 Invalid = true;
3586 continue;
3587 }
3588
3589 // If we should expand this pack expansion now, do so.
3591 const MultiLevelTemplateArgumentList *ArgsForSubst = &TemplateArgs;
3593 ArgsForSubst = &EmptyList;
3594
3595 if (Info.Expand) {
3596 for (unsigned I = 0; I != *Info.NumExpansions; ++I) {
3597 Sema::ArgPackSubstIndexRAII SubstIndex(*this, I);
3598
3599 TypeSourceInfo *Expanded =
3600 SubstType(BaseTypeLoc, *ArgsForSubst,
3601 Base.getSourceRange().getBegin(), DeclarationName());
3602 if (!Expanded) {
3603 Invalid = true;
3604 continue;
3605 }
3606
3607 if (CXXBaseSpecifier *InstantiatedBase = CheckBaseSpecifier(
3608 Instantiation, Base.getSourceRange(), Base.isVirtual(),
3609 Base.getAccessSpecifierAsWritten(), Expanded,
3610 SourceLocation()))
3611 InstantiatedBases.push_back(InstantiatedBase);
3612 else
3613 Invalid = true;
3614 }
3615
3616 continue;
3617 }
3618
3619 // The resulting base specifier will (still) be a pack expansion.
3620 EllipsisLoc = Base.getEllipsisLoc();
3621 Sema::ArgPackSubstIndexRAII SubstIndex(*this, std::nullopt);
3622 BaseTypeLoc =
3623 SubstType(BaseTypeLoc, *ArgsForSubst,
3624 Base.getSourceRange().getBegin(), DeclarationName());
3625 } else {
3626 BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
3627 TemplateArgs,
3628 Base.getSourceRange().getBegin(),
3629 DeclarationName());
3630 }
3631
3632 if (!BaseTypeLoc) {
3633 Invalid = true;
3634 continue;
3635 }
3636
3637 if (CXXBaseSpecifier *InstantiatedBase
3638 = CheckBaseSpecifier(Instantiation,
3639 Base.getSourceRange(),
3640 Base.isVirtual(),
3641 Base.getAccessSpecifierAsWritten(),
3642 BaseTypeLoc,
3643 EllipsisLoc))
3644 InstantiatedBases.push_back(InstantiatedBase);
3645 else
3646 Invalid = true;
3647 }
3648
3649 if (!Invalid && AttachBaseSpecifiers(Instantiation, InstantiatedBases))
3650 Invalid = true;
3651
3652 return Invalid;
3653}
3654
3655// Defined via #include from SemaTemplateInstantiateDecl.cpp
3656namespace clang {
3657 namespace sema {
3659 const MultiLevelTemplateArgumentList &TemplateArgs);
3661 const Attr *At, ASTContext &C, Sema &S,
3662 const MultiLevelTemplateArgumentList &TemplateArgs);
3663 }
3664}
3665
3666bool Sema::InstantiateClass(SourceLocation PointOfInstantiation,
3667 CXXRecordDecl *Instantiation,
3668 CXXRecordDecl *Pattern,
3669 const MultiLevelTemplateArgumentList &TemplateArgs,
3670 TemplateSpecializationKind TSK, bool Complain) {
3671#ifndef NDEBUG
3672 RecursiveInstGuard AlreadyInstantiating(*this, Instantiation,
3674 assert(!AlreadyInstantiating && "should have been caught by caller");
3675#endif
3676
3677 return InstantiateClassImpl(PointOfInstantiation, Instantiation, Pattern,
3678 TemplateArgs, TSK, Complain);
3679}
3680
3681bool Sema::InstantiateClassImpl(
3682 SourceLocation PointOfInstantiation, CXXRecordDecl *Instantiation,
3683 CXXRecordDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs,
3684 TemplateSpecializationKind TSK, bool Complain) {
3685
3686 CXXRecordDecl *PatternDef
3687 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
3688 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
3689 Instantiation->getInstantiatedFromMemberClass(),
3690 Pattern, PatternDef, TSK, Complain))
3691 return true;
3692
3693 llvm::TimeTraceScope TimeScope("InstantiateClass", [&]() {
3694 llvm::TimeTraceMetadata M;
3695 llvm::raw_string_ostream OS(M.Detail);
3696 Instantiation->getNameForDiagnostic(OS, getPrintingPolicy(),
3697 /*Qualified=*/true);
3698 if (llvm::isTimeTraceVerbose()) {
3699 auto Loc = SourceMgr.getExpansionLoc(Instantiation->getLocation());
3700 M.File = SourceMgr.getFilename(Loc);
3701 M.Line = SourceMgr.getExpansionLineNumber(Loc);
3702 }
3703 return M;
3704 });
3705
3706 Pattern = PatternDef;
3707
3708 // Record the point of instantiation.
3709 if (MemberSpecializationInfo *MSInfo
3710 = Instantiation->getMemberSpecializationInfo()) {
3711 MSInfo->setTemplateSpecializationKind(TSK);
3712 MSInfo->setPointOfInstantiation(PointOfInstantiation);
3713 } else if (ClassTemplateSpecializationDecl *Spec
3714 = dyn_cast<ClassTemplateSpecializationDecl>(Instantiation)) {
3715 Spec->setTemplateSpecializationKind(TSK);
3716 Spec->setPointOfInstantiation(PointOfInstantiation);
3717 }
3718
3719 NonSFINAEContext _(*this);
3720 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
3721 if (Inst.isInvalid())
3722 return true;
3723 PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
3724 "instantiating class definition");
3725
3726 // Enter the scope of this instantiation. We don't use
3727 // PushDeclContext because we don't have a scope.
3728 ContextRAII SavedContext(*this, Instantiation);
3729 EnterExpressionEvaluationContext EvalContext(
3730 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
3731
3732 // If this is an instantiation of a local class, merge this local
3733 // instantiation scope with the enclosing scope. Otherwise, every
3734 // instantiation of a class has its own local instantiation scope.
3735 bool MergeWithParentScope = !Instantiation->isDefinedOutsideFunctionOrMethod();
3736 LocalInstantiationScope Scope(*this, MergeWithParentScope);
3737
3738 // Some class state isn't processed immediately but delayed till class
3739 // instantiation completes. We may not be ready to handle any delayed state
3740 // already on the stack as it might correspond to a different class, so save
3741 // it now and put it back later.
3742 SavePendingParsedClassStateRAII SavedPendingParsedClassState(*this);
3743
3744 // Pull attributes from the pattern onto the instantiation.
3745 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
3746
3747 // Start the definition of this instantiation.
3748 Instantiation->startDefinition();
3749
3750 // The instantiation is visible here, even if it was first declared in an
3751 // unimported module.
3752 Instantiation->setVisibleDespiteOwningModule();
3753
3754 // FIXME: This loses the as-written tag kind for an explicit instantiation.
3755 Instantiation->setTagKind(Pattern->getTagKind());
3756
3757 // Do substitution on the base class specifiers.
3758 if (SubstBaseSpecifiers(Instantiation, Pattern, TemplateArgs))
3759 Instantiation->setInvalidDecl();
3760
3761 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
3762 Instantiator.setEvaluateConstraints(false);
3763 SmallVector<Decl*, 4> Fields;
3764 // Delay instantiation of late parsed attributes.
3765 LateInstantiatedAttrVec LateAttrs;
3766 Instantiator.enableLateAttributeInstantiation(&LateAttrs);
3767
3768 bool MightHaveConstexprVirtualFunctions = false;
3769 for (auto *Member : Pattern->decls()) {
3770 // Don't instantiate members not belonging in this semantic context.
3771 // e.g. for:
3772 // @code
3773 // template <int i> class A {
3774 // class B *g;
3775 // };
3776 // @endcode
3777 // 'class B' has the template as lexical context but semantically it is
3778 // introduced in namespace scope.
3779 if (Member->getDeclContext() != Pattern)
3780 continue;
3781
3782 // BlockDecls can appear in a default-member-initializer. They must be the
3783 // child of a BlockExpr, so we only know how to instantiate them from there.
3784 // Similarly, lambda closure types are recreated when instantiating the
3785 // corresponding LambdaExpr.
3786 if (isa<BlockDecl>(Member) ||
3788 continue;
3789
3790 if (Member->isInvalidDecl()) {
3791 Instantiation->setInvalidDecl();
3792 // Drop invalid members to prevent cascading diagnostic errors.
3793 // We make an exception for VarTemplateDecl because the primary template
3794 // is required for partial specialization lookup. Keeping it is safe from
3795 // cascading errors due to the parser's type recovery.
3797 continue;
3798 }
3799
3800 Decl *NewMember = Instantiator.Visit(Member);
3801 if (NewMember) {
3802 if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember)) {
3803 Fields.push_back(Field);
3804 } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(NewMember)) {
3805 // C++11 [temp.inst]p1: The implicit instantiation of a class template
3806 // specialization causes the implicit instantiation of the definitions
3807 // of unscoped member enumerations.
3808 // Record a point of instantiation for this implicit instantiation.
3809 if (TSK == TSK_ImplicitInstantiation && !Enum->isScoped() &&
3810 Enum->isCompleteDefinition()) {
3811 MemberSpecializationInfo *MSInfo =Enum->getMemberSpecializationInfo();
3812 assert(MSInfo && "no spec info for member enum specialization");
3814 MSInfo->setPointOfInstantiation(PointOfInstantiation);
3815 }
3816 } else if (StaticAssertDecl *SA = dyn_cast<StaticAssertDecl>(NewMember)) {
3817 if (SA->isFailed()) {
3818 // A static_assert failed. Bail out; instantiating this
3819 // class is probably not meaningful.
3820 Instantiation->setInvalidDecl();
3821 break;
3822 }
3823 } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewMember)) {
3824 if (MD->isConstexpr() && !MD->getFriendObjectKind() &&
3825 (MD->isVirtualAsWritten() || Instantiation->getNumBases()))
3826 MightHaveConstexprVirtualFunctions = true;
3827 }
3828
3829 if (Member->isInvalidDecl())
3830 NewMember->setInvalidDecl();
3831
3832 if (NewMember->isInvalidDecl())
3833 Instantiation->setInvalidDecl();
3834 } else {
3835 // FIXME: Eventually, a NULL return will mean that one of the
3836 // instantiations was a semantic disaster, and we'll want to mark the
3837 // declaration invalid.
3838 // For now, we expect to skip some members that we can't yet handle.
3839 }
3840 }
3841
3842 // Finish checking fields.
3843 ActOnFields(nullptr, Instantiation->getLocation(), Instantiation, Fields,
3844 SourceLocation(), SourceLocation(), ParsedAttributesView());
3845 CheckCompletedCXXClass(nullptr, Instantiation);
3846
3847 // Default arguments are parsed, if not instantiated. We can go instantiate
3848 // default arg exprs for default constructors if necessary now. Unless we're
3849 // parsing a class, in which case wait until that's finished.
3850 if (ParsingClassDepth == 0)
3851 ActOnFinishCXXNonNestedClass();
3852
3853 // Instantiate late parsed attributes, and attach them to their decls.
3854 InstantiateLateAttrs(TemplateArgs, LateAttrs,
3855 Instantiator.getStartingScope());
3856 Instantiator.disableLateAttributeInstantiation();
3857
3858 ActOnFinishDelayedMemberInitializers(Instantiation);
3859
3860 // FIXME: We should do something similar for explicit instantiations so they
3861 // end up in the right module.
3862 if (TSK == TSK_ImplicitInstantiation) {
3863 Instantiation->setLocation(Pattern->getLocation());
3864 Instantiation->setLocStart(Pattern->getInnerLocStart());
3865 Instantiation->setBraceRange(Pattern->getBraceRange());
3866 }
3867
3868 if (!Instantiation->isInvalidDecl()) {
3869 // Perform any dependent diagnostics from the pattern.
3870 if (Pattern->isDependentContext())
3871 PerformDependentDiagnostics(Pattern, TemplateArgs);
3872
3873 // Instantiate any out-of-line class template partial
3874 // specializations now.
3876 P = Instantiator.delayed_partial_spec_begin(),
3877 PEnd = Instantiator.delayed_partial_spec_end();
3878 P != PEnd; ++P) {
3879 if (!Instantiator.InstantiateClassTemplatePartialSpecialization(
3880 P->first, P->second)) {
3881 Instantiation->setInvalidDecl();
3882 break;
3883 }
3884 }
3885
3886 // Instantiate any out-of-line variable template partial
3887 // specializations now.
3889 P = Instantiator.delayed_var_partial_spec_begin(),
3890 PEnd = Instantiator.delayed_var_partial_spec_end();
3891 P != PEnd; ++P) {
3892 if (!Instantiator.InstantiateVarTemplatePartialSpecialization(
3893 P->first, P->second)) {
3894 Instantiation->setInvalidDecl();
3895 break;
3896 }
3897 }
3898 }
3899
3900 Instantiation->setIsHLSLBuiltinRecord(Pattern->isHLSLBuiltinRecord());
3901
3902 // Exit the scope of this instantiation.
3903 SavedContext.pop();
3904
3905 if (!Instantiation->isInvalidDecl()) {
3906 // Always emit the vtable for an explicit instantiation definition
3907 // of a polymorphic class template specialization. Otherwise, eagerly
3908 // instantiate only constexpr virtual functions in preparation for their use
3909 // in constant evaluation.
3911 MarkVTableUsed(PointOfInstantiation, Instantiation, true);
3912 else if (MightHaveConstexprVirtualFunctions)
3913 MarkVirtualMembersReferenced(PointOfInstantiation, Instantiation,
3914 /*ConstexprOnly*/ true);
3915 }
3916
3917 Consumer.HandleTagDeclDefinition(Instantiation);
3918
3919 return Instantiation->isInvalidDecl();
3920}
3921
3922bool Sema::InstantiateEnum(SourceLocation PointOfInstantiation,
3923 EnumDecl *Instantiation, EnumDecl *Pattern,
3924 const MultiLevelTemplateArgumentList &TemplateArgs,
3926#ifndef NDEBUG
3927 RecursiveInstGuard AlreadyInstantiating(*this, Instantiation,
3929 assert(!AlreadyInstantiating && "should have been caught by caller");
3930#endif
3931
3932 EnumDecl *PatternDef = Pattern->getDefinition();
3933 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
3934 Instantiation->getInstantiatedFromMemberEnum(),
3935 Pattern, PatternDef, TSK,/*Complain*/true))
3936 return true;
3937 Pattern = PatternDef;
3938
3939 // Record the point of instantiation.
3940 if (MemberSpecializationInfo *MSInfo
3941 = Instantiation->getMemberSpecializationInfo()) {
3942 MSInfo->setTemplateSpecializationKind(TSK);
3943 MSInfo->setPointOfInstantiation(PointOfInstantiation);
3944 }
3945
3946 NonSFINAEContext _(*this);
3947 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
3948 if (Inst.isInvalid())
3949 return true;
3950 PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
3951 "instantiating enum definition");
3952
3953 // The instantiation is visible here, even if it was first declared in an
3954 // unimported module.
3955 Instantiation->setVisibleDespiteOwningModule();
3956
3957 // Enter the scope of this instantiation. We don't use
3958 // PushDeclContext because we don't have a scope.
3959 ContextRAII SavedContext(*this, Instantiation);
3962
3963 LocalInstantiationScope Scope(*this, /*MergeWithParentScope*/true);
3964
3965 // Pull attributes from the pattern onto the instantiation.
3966 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
3967
3968 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
3969 Instantiator.InstantiateEnumDefinition(Instantiation, Pattern);
3970
3971 // Exit the scope of this instantiation.
3972 SavedContext.pop();
3973
3974 return Instantiation->isInvalidDecl();
3975}
3976
3978 SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
3979 FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs) {
3980 // If there is no initializer, we don't need to do anything.
3981 if (!Pattern->hasInClassInitializer())
3982 return false;
3983
3984 assert(Instantiation->getInClassInitStyle() ==
3985 Pattern->getInClassInitStyle() &&
3986 "pattern and instantiation disagree about init style");
3987
3988 RecursiveInstGuard AlreadyInstantiating(*this, Instantiation,
3990 if (AlreadyInstantiating)
3991 // Error out if we hit an instantiation cycle for this initializer.
3992 return Diag(PointOfInstantiation,
3993 diag::err_default_member_initializer_cycle)
3994 << Instantiation;
3995
3996 // Error out if we haven't parsed the initializer of the pattern yet because
3997 // we are waiting for the closing brace of the outer class.
3998 Expr *OldInit = Pattern->getInClassInitializer();
3999 if (!OldInit) {
4000 RecordDecl *PatternRD = Pattern->getParent();
4001 RecordDecl *OutermostClass = PatternRD->getOuterLexicalRecordContext();
4002 Diag(PointOfInstantiation,
4003 diag::err_default_member_initializer_not_yet_parsed)
4004 << OutermostClass << Pattern;
4005 Diag(Pattern->getEndLoc(),
4006 diag::note_default_member_initializer_not_yet_parsed);
4007 return true;
4008 }
4009
4010 NonSFINAEContext _(*this);
4011 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
4012 if (Inst.isInvalid())
4013 return true;
4014 PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
4015 "instantiating default member init");
4016
4017 // Enter the scope of this instantiation. We don't use PushDeclContext because
4018 // we don't have a scope.
4019 ContextRAII SavedContext(*this, Instantiation->getParent());
4022 Instantiation);
4023 ExprEvalContexts.back().DelayedDefaultInitializationContext = {
4024 PointOfInstantiation, Instantiation, CurContext};
4025
4026 LocalInstantiationScope Scope(*this, true);
4027
4028 // Instantiate the initializer.
4030 CXXThisScopeRAII ThisScope(*this, Instantiation->getParent(), Qualifiers());
4031
4032 ExprResult NewInit = SubstInitializer(OldInit, TemplateArgs,
4033 /*CXXDirectInit=*/false);
4034 Expr *Init = NewInit.get();
4035 assert((!Init || !isa<ParenListExpr>(Init)) && "call-style init in class");
4037 Instantiation, Init ? Init->getBeginLoc() : SourceLocation(), Init);
4038
4039 if (auto *L = getASTMutationListener())
4040 L->DefaultMemberInitializerInstantiated(Instantiation);
4041
4042 // Return true if the in-class initializer is still missing.
4043 return !Instantiation->getInClassInitializer();
4044}
4045
4046namespace {
4047 /// A partial specialization whose template arguments have matched
4048 /// a given template-id.
4049 struct PartialSpecMatchResult {
4052 };
4053}
4054
4056 SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec) {
4057 if (ClassTemplateSpec->getTemplateSpecializationKind() ==
4059 return true;
4060
4062 ClassTemplateDecl *CTD = ClassTemplateSpec->getSpecializedTemplate();
4063 CTD->getPartialSpecializations(PartialSpecs);
4064 for (ClassTemplatePartialSpecializationDecl *CTPSD : PartialSpecs) {
4065 // C++ [temp.spec.partial.member]p2:
4066 // If the primary member template is explicitly specialized for a given
4067 // (implicit) specialization of the enclosing class template, the partial
4068 // specializations of the member template are ignored for this
4069 // specialization of the enclosing class template. If a partial
4070 // specialization of the member template is explicitly specialized for a
4071 // given (implicit) specialization of the enclosing class template, the
4072 // primary member template and its other partial specializations are still
4073 // considered for this specialization of the enclosing class template.
4074 if (CTD->isMemberSpecialization() && !CTPSD->isMemberSpecialization())
4075 continue;
4076
4077 TemplateDeductionInfo Info(Loc);
4078 if (DeduceTemplateArguments(CTPSD,
4079 ClassTemplateSpec->getTemplateArgs().asArray(),
4081 return true;
4082 }
4083
4084 return false;
4085}
4086
4087/// Get the instantiation pattern to use to instantiate the definition of a
4088/// given ClassTemplateSpecializationDecl (either the pattern of the primary
4089/// template or of a partial specialization).
4091 Sema &S, SourceLocation PointOfInstantiation,
4092 ClassTemplateSpecializationDecl *ClassTemplateSpec,
4093 TemplateSpecializationKind TSK, bool PrimaryStrictPackMatch) {
4094 std::optional<Sema::NonSFINAEContext> NSC(S);
4095 Sema::InstantiatingTemplate Inst(S, PointOfInstantiation, ClassTemplateSpec);
4096 if (Inst.isInvalid())
4097 return {/*Invalid=*/true};
4098
4099 llvm::PointerUnion<ClassTemplateDecl *,
4101 Specialized = ClassTemplateSpec->getSpecializedTemplateOrPartial();
4103 // Find best matching specialization.
4104 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
4105
4106 // C++ [temp.class.spec.match]p1:
4107 // When a class template is used in a context that requires an
4108 // instantiation of the class, it is necessary to determine
4109 // whether the instantiation is to be generated using the primary
4110 // template or one of the partial specializations. This is done by
4111 // matching the template arguments of the class template
4112 // specialization with the template argument lists of the partial
4113 // specializations.
4114 typedef PartialSpecMatchResult MatchResult;
4115 SmallVector<MatchResult, 4> Matched, ExtraMatched;
4117 Template->getPartialSpecializations(PartialSpecs);
4118 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation);
4119 for (ClassTemplatePartialSpecializationDecl *Partial : PartialSpecs) {
4120 // C++ [temp.spec.partial.member]p2:
4121 // If the primary member template is explicitly specialized for a given
4122 // (implicit) specialization of the enclosing class template, the
4123 // partial specializations of the member template are ignored for this
4124 // specialization of the enclosing class template. If a partial
4125 // specialization of the member template is explicitly specialized for a
4126 // given (implicit) specialization of the enclosing class template, the
4127 // primary member template and its other partial specializations are
4128 // still considered for this specialization of the enclosing class
4129 // template.
4130 if (Template->isMemberSpecialization() &&
4131 !Partial->isMemberSpecialization())
4132 continue;
4133
4134 TemplateDeductionInfo Info(FailedCandidates.getLocation());
4136 Partial, ClassTemplateSpec->getTemplateArgs().asArray(), Info);
4138 // Store the failed-deduction information for use in diagnostics, later.
4139 // TODO: Actually use the failed-deduction info?
4140 FailedCandidates.addCandidate().set(
4143 (void)Result;
4144 } else {
4145 auto &List = Info.hasStrictPackMatch() ? ExtraMatched : Matched;
4146 List.push_back(MatchResult{Partial, Info.takeCanonical()});
4147 }
4148 }
4149 if (Matched.empty() && PrimaryStrictPackMatch)
4150 Matched = std::move(ExtraMatched);
4151
4152 // If we're dealing with a member template where the template parameters
4153 // have been instantiated, this provides the original template parameters
4154 // from which the member template's parameters were instantiated.
4155
4156 if (Matched.size() >= 1) {
4157 SmallVectorImpl<MatchResult>::iterator Best = Matched.begin();
4158 if (Matched.size() == 1) {
4159 // -- If exactly one matching specialization is found, the
4160 // instantiation is generated from that specialization.
4161 // We don't need to do anything for this.
4162 } else {
4163 // -- If more than one matching specialization is found, the
4164 // partial order rules (14.5.4.2) are used to determine
4165 // whether one of the specializations is more specialized
4166 // than the others. If none of the specializations is more
4167 // specialized than all of the other matching
4168 // specializations, then the use of the class template is
4169 // ambiguous and the program is ill-formed.
4171 PEnd = Matched.end();
4172 P != PEnd; ++P) {
4174 P->Partial, Best->Partial, PointOfInstantiation) ==
4175 P->Partial)
4176 Best = P;
4177 }
4178
4179 // Determine if the best partial specialization is more specialized than
4180 // the others.
4181 bool Ambiguous = false;
4182 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
4183 PEnd = Matched.end();
4184 P != PEnd; ++P) {
4185 if (P != Best && S.getMoreSpecializedPartialSpecialization(
4186 P->Partial, Best->Partial,
4187 PointOfInstantiation) != Best->Partial) {
4188 Ambiguous = true;
4189 break;
4190 }
4191 }
4192
4193 if (Ambiguous) {
4194 // Partial ordering did not produce a clear winner. Complain.
4195 Inst.Clear();
4196 NSC.reset();
4197 S.Diag(PointOfInstantiation,
4198 diag::err_partial_spec_ordering_ambiguous)
4199 << ClassTemplateSpec;
4200
4201 // Print the matching partial specializations.
4202 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
4203 PEnd = Matched.end();
4204 P != PEnd; ++P)
4205 S.Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
4207 P->Partial->getTemplateParameters(), *P->Args);
4208
4209 return {/*Invalid=*/true};
4210 }
4211 }
4212
4213 ClassTemplateSpec->setInstantiationOf(Best->Partial, Best->Args);
4214 } else {
4215 // -- If no matches are found, the instantiation is generated
4216 // from the primary template.
4217 }
4218 }
4219
4220 CXXRecordDecl *Pattern = nullptr;
4221 Specialized = ClassTemplateSpec->getSpecializedTemplateOrPartial();
4222 if (auto *PartialSpec =
4223 dyn_cast<ClassTemplatePartialSpecializationDecl *>(Specialized)) {
4224 // Instantiate using the best class template partial specialization.
4225 while (PartialSpec->getInstantiatedFromMember()) {
4226 // If we've found an explicit specialization of this class template,
4227 // stop here and use that as the pattern.
4228 if (PartialSpec->isMemberSpecialization())
4229 break;
4230
4231 PartialSpec = PartialSpec->getInstantiatedFromMember();
4232 }
4233 Pattern = PartialSpec;
4234 } else {
4235 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
4236 while (Template->getInstantiatedFromMemberTemplate()) {
4237 // If we've found an explicit specialization of this class template,
4238 // stop here and use that as the pattern.
4239 if (Template->isMemberSpecialization())
4240 break;
4241
4242 Template = Template->getInstantiatedFromMemberTemplate();
4243 }
4244 Pattern = Template->getTemplatedDecl();
4245 }
4246
4247 return Pattern;
4248}
4249
4251 SourceLocation PointOfInstantiation,
4252 ClassTemplateSpecializationDecl *ClassTemplateSpec,
4253 TemplateSpecializationKind TSK, bool Complain,
4254 bool PrimaryStrictPackMatch) {
4255 // Perform the actual instantiation on the canonical declaration.
4256 ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>(
4257 ClassTemplateSpec->getCanonicalDecl());
4258 if (ClassTemplateSpec->isInvalidDecl())
4259 return true;
4260
4261 Sema::RecursiveInstGuard AlreadyInstantiating(
4262 *this, ClassTemplateSpec, Sema::RecursiveInstGuard::Kind::Template);
4263 if (AlreadyInstantiating)
4264 return false;
4265
4266 bool HadAvaibilityWarning =
4267 ShouldDiagnoseAvailabilityOfDecl(ClassTemplateSpec, nullptr, nullptr)
4268 .first != AR_Available;
4269
4271 getPatternForClassTemplateSpecialization(*this, PointOfInstantiation,
4272 ClassTemplateSpec, TSK,
4273 PrimaryStrictPackMatch);
4274
4275 if (!Pattern.isUsable())
4276 return Pattern.isInvalid();
4277
4278 // Deduction has picked the pattern this specialization will be instantiated
4279 // from, which may be a declaration an external AST source has yet to define.
4280 if (!Pattern.get()->isCompleteDefinition() &&
4281 Pattern.get()->hasExternalLexicalStorage())
4282 if (ExternalASTSource *Source = Context.getExternalSource())
4283 Source->CompleteType(Pattern.get());
4284
4285 bool Err = InstantiateClassImpl(
4286 PointOfInstantiation, ClassTemplateSpec, Pattern.get(),
4287 getTemplateInstantiationArgs(ClassTemplateSpec), TSK, Complain);
4288
4289 // If we haven't already warn on avaibility, consider the avaibility
4290 // attributes of the partial specialization.
4291 // Note that - because we need to have deduced the partial specialization -
4292 // We can only emit these warnings when the specialization is instantiated.
4293 if (!Err && !HadAvaibilityWarning) {
4294 assert(ClassTemplateSpec->getTemplateSpecializationKind() !=
4296 DiagnoseAvailabilityOfDecl(ClassTemplateSpec, PointOfInstantiation);
4297 }
4298 return Err;
4299}
4300
4301void
4303 CXXRecordDecl *Instantiation,
4304 const MultiLevelTemplateArgumentList &TemplateArgs,
4306 // FIXME: We need to notify the ASTMutationListener that we did all of these
4307 // things, in case we have an explicit instantiation definition in a PCM, a
4308 // module, or preamble, and the declaration is in an imported AST.
4309 assert(
4312 (TSK == TSK_ImplicitInstantiation && Instantiation->isLocalClass())) &&
4313 "Unexpected template specialization kind!");
4314 for (auto *D : Instantiation->decls()) {
4315 bool SuppressNew = false;
4316 if (auto *Function = dyn_cast<FunctionDecl>(D)) {
4317 if (FunctionDecl *Pattern =
4318 Function->getInstantiatedFromMemberFunction()) {
4319
4320 if (Function->getTrailingRequiresClause()) {
4321 ConstraintSatisfaction Satisfaction;
4322 if (CheckFunctionConstraints(Function, Satisfaction) ||
4323 !Satisfaction.IsSatisfied) {
4324 continue;
4325 }
4326 }
4327
4328 if (Function->hasAttr<ExcludeFromExplicitInstantiationAttr>())
4329 continue;
4330
4332 Function->getTemplateSpecializationKind();
4333 if (PrevTSK == TSK_ExplicitSpecialization)
4334 continue;
4335
4337 PointOfInstantiation, TSK, Function, PrevTSK,
4338 Function->getPointOfInstantiation(), SuppressNew) ||
4339 SuppressNew)
4340 continue;
4341
4342 // C++11 [temp.explicit]p8:
4343 // An explicit instantiation definition that names a class template
4344 // specialization explicitly instantiates the class template
4345 // specialization and is only an explicit instantiation definition
4346 // of members whose definition is visible at the point of
4347 // instantiation.
4348 if (TSK == TSK_ExplicitInstantiationDefinition && !Pattern->isDefined())
4349 continue;
4350
4351 Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
4352
4353 if (Function->isDefined()) {
4354 // Let the ASTConsumer know that this function has been explicitly
4355 // instantiated now, and its linkage might have changed.
4356 Consumer.HandleTopLevelDecl(DeclGroupRef(Function));
4357 } else if (TSK == TSK_ExplicitInstantiationDefinition) {
4358 InstantiateFunctionDefinition(PointOfInstantiation, Function);
4359 } else if (TSK == TSK_ImplicitInstantiation) {
4361 std::make_pair(Function, PointOfInstantiation));
4362 }
4363 }
4364 } else if (auto *Var = dyn_cast<VarDecl>(D)) {
4366 continue;
4367
4368 if (Var->isStaticDataMember()) {
4369 if (Var->hasAttr<ExcludeFromExplicitInstantiationAttr>())
4370 continue;
4371
4373 assert(MSInfo && "No member specialization information?");
4374 if (MSInfo->getTemplateSpecializationKind()
4376 continue;
4377
4378 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
4379 Var,
4381 MSInfo->getPointOfInstantiation(),
4382 SuppressNew) ||
4383 SuppressNew)
4384 continue;
4385
4387 // C++0x [temp.explicit]p8:
4388 // An explicit instantiation definition that names a class template
4389 // specialization explicitly instantiates the class template
4390 // specialization and is only an explicit instantiation definition
4391 // of members whose definition is visible at the point of
4392 // instantiation.
4394 continue;
4395
4396 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
4397 InstantiateVariableDefinition(PointOfInstantiation, Var);
4398 } else {
4399 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
4400 }
4401 }
4402 } else if (auto *Record = dyn_cast<CXXRecordDecl>(D)) {
4403 if (Record->hasAttr<ExcludeFromExplicitInstantiationAttr>())
4404 continue;
4405
4406 // Always skip the injected-class-name, along with any
4407 // redeclarations of nested classes, since both would cause us
4408 // to try to instantiate the members of a class twice.
4409 // Skip closure types; they'll get instantiated when we instantiate
4410 // the corresponding lambda-expression.
4411 if (Record->isInjectedClassName() || Record->getPreviousDecl() ||
4412 Record->isLambda())
4413 continue;
4414
4415 MemberSpecializationInfo *MSInfo = Record->getMemberSpecializationInfo();
4416 assert(MSInfo && "No member specialization information?");
4417
4418 if (MSInfo->getTemplateSpecializationKind()
4420 continue;
4421
4422 if (Context.getTargetInfo().getTriple().isOSWindows() &&
4424 // On Windows, explicit instantiation decl of the outer class doesn't
4425 // affect the inner class. Typically extern template declarations are
4426 // used in combination with dll import/export annotations, but those
4427 // are not propagated from the outer class templates to inner classes.
4428 // Therefore, do not instantiate inner classes on this platform, so
4429 // that users don't end up with undefined symbols during linking.
4430 continue;
4431 }
4432
4433 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
4434 Record,
4436 MSInfo->getPointOfInstantiation(),
4437 SuppressNew) ||
4438 SuppressNew)
4439 continue;
4440
4441 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
4442 assert(Pattern && "Missing instantiated-from-template information");
4443
4444 if (!Record->getDefinition()) {
4445 if (!Pattern->getDefinition()) {
4446 // C++0x [temp.explicit]p8:
4447 // An explicit instantiation definition that names a class template
4448 // specialization explicitly instantiates the class template
4449 // specialization and is only an explicit instantiation definition
4450 // of members whose definition is visible at the point of
4451 // instantiation.
4453 MSInfo->setTemplateSpecializationKind(TSK);
4454 MSInfo->setPointOfInstantiation(PointOfInstantiation);
4455 }
4456
4457 continue;
4458 }
4459
4460 InstantiateClass(PointOfInstantiation, Record, Pattern,
4461 TemplateArgs,
4462 TSK);
4463 } else {
4465 Record->getTemplateSpecializationKind() ==
4467 Record->setTemplateSpecializationKind(TSK);
4468 MarkVTableUsed(PointOfInstantiation, Record, true);
4469 }
4470 }
4471
4472 Pattern = cast_or_null<CXXRecordDecl>(Record->getDefinition());
4473 if (Pattern)
4474 InstantiateClassMembers(PointOfInstantiation, Pattern, TemplateArgs,
4475 TSK);
4476 } else if (auto *Enum = dyn_cast<EnumDecl>(D)) {
4477 MemberSpecializationInfo *MSInfo = Enum->getMemberSpecializationInfo();
4478 assert(MSInfo && "No member specialization information?");
4479
4480 if (MSInfo->getTemplateSpecializationKind()
4482 continue;
4483
4485 PointOfInstantiation, TSK, Enum,
4487 MSInfo->getPointOfInstantiation(), SuppressNew) ||
4488 SuppressNew)
4489 continue;
4490
4491 if (Enum->getDefinition())
4492 continue;
4493
4494 EnumDecl *Pattern = Enum->getTemplateInstantiationPattern();
4495 assert(Pattern && "Missing instantiated-from-template information");
4496
4498 if (!Pattern->getDefinition())
4499 continue;
4500
4501 InstantiateEnum(PointOfInstantiation, Enum, Pattern, TemplateArgs, TSK);
4502 } else {
4503 MSInfo->setTemplateSpecializationKind(TSK);
4504 MSInfo->setPointOfInstantiation(PointOfInstantiation);
4505 }
4506 } else if (auto *Field = dyn_cast<FieldDecl>(D)) {
4507 // No need to instantiate in-class initializers during explicit
4508 // instantiation.
4509 if (Field->hasInClassInitializer() && TSK == TSK_ImplicitInstantiation) {
4510 // Handle local classes which could have substituted template params.
4511 CXXRecordDecl *ClassPattern =
4512 Instantiation->isLocalClass()
4513 ? Instantiation->getInstantiatedFromMemberClass()
4514 : Instantiation->getTemplateInstantiationPattern();
4515
4517 ClassPattern->lookup(Field->getDeclName());
4518 FieldDecl *Pattern = Lookup.find_first<FieldDecl>();
4519 assert(Pattern);
4520 InstantiateInClassInitializer(PointOfInstantiation, Field, Pattern,
4521 TemplateArgs);
4522 }
4523 }
4524 }
4525}
4526
4527void
4529 SourceLocation PointOfInstantiation,
4530 ClassTemplateSpecializationDecl *ClassTemplateSpec,
4532 // C++0x [temp.explicit]p7:
4533 // An explicit instantiation that names a class template
4534 // specialization is an explicit instantion of the same kind
4535 // (declaration or definition) of each of its members (not
4536 // including members inherited from base classes) that has not
4537 // been previously explicitly specialized in the translation unit
4538 // containing the explicit instantiation, except as described
4539 // below.
4540 InstantiateClassMembers(PointOfInstantiation, ClassTemplateSpec,
4541 getTemplateInstantiationArgs(ClassTemplateSpec),
4542 TSK);
4543}
4544
4547 if (!S)
4548 return S;
4549
4550 TemplateInstantiator Instantiator(*this, TemplateArgs,
4552 DeclarationName());
4553 return Instantiator.TransformStmt(S);
4554}
4555
4557 const TemplateArgumentLoc &Input,
4558 const MultiLevelTemplateArgumentList &TemplateArgs,
4560 const DeclarationName &Entity) {
4561 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity);
4562 return Instantiator.TransformTemplateArgument(Input, Output);
4563}
4564
4567 const MultiLevelTemplateArgumentList &TemplateArgs,
4569 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
4570 DeclarationName());
4571 return Instantiator.TransformTemplateArguments(Args.begin(), Args.end(), Out);
4572}
4573
4576 const MultiLevelTemplateArgumentList &TemplateArgs,
4578 TemplateInstantiator Instantiator(
4579 TemplateInstantiator::ForParameterMappingSubstitution, *this, BaseLoc,
4580 TemplateArgs, CurrentCachedTemplateArgs);
4581 return Instantiator.TransformTemplateArguments(Args.begin(), Args.end(), Out);
4582}
4583
4584UnsignedOrNone Sema::EvaluateFoldExpandedConstraintSize(
4585 const Expr *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs) {
4586 TemplateInstantiator Instantiator(
4587 TemplateInstantiator::ForConstraintSubstitution, *this, TemplateArgs,
4589
4591 collectUnexpandedParameterPacks(const_cast<Expr *>(Pattern), Unexpanded);
4592 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
4593
4594 bool Expand = true;
4595 bool RetainExpansion = false;
4596 UnsignedOrNone NumExpansions(std::nullopt);
4597 if (Instantiator.TryExpandParameterPacks(
4598 Pattern->getExprLoc(), Pattern->getSourceRange(), Unexpanded,
4599 /*FailOnPackProducingTemplates=*/false, Expand, RetainExpansion,
4600 NumExpansions, /*Diagnose=*/false) ||
4601 !Expand || RetainExpansion)
4602 return std::nullopt;
4603
4604 if (NumExpansions && getLangOpts().BracketDepth < *NumExpansions)
4605 return std::nullopt;
4606 return NumExpansions;
4607}
4608
4611 if (!E)
4612 return E;
4613
4614 TemplateInstantiator Instantiator(*this, TemplateArgs,
4616 DeclarationName());
4617 return Instantiator.TransformExpr(E);
4618}
4619
4622 const MultiLevelTemplateArgumentList &TemplateArgs) {
4623 if (!E)
4624 return E;
4625
4626 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
4627 DeclarationName());
4628 return Instantiator.TransformAddressOfOperand(E);
4629}
4630
4633 const MultiLevelTemplateArgumentList &TemplateArgs) {
4634 if (!E)
4635 return E;
4636
4637 TemplateInstantiator Instantiator(
4638 TemplateInstantiator::ForConstraintSubstitution, *this, TemplateArgs,
4640 return Instantiator.TransformExpr(E);
4641}
4642
4644 Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs) {
4645 if (!E)
4646 return E;
4647
4648 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
4649 DeclarationName());
4650 Instantiator.setEvaluateConstraints(false);
4651 return Instantiator.TransformExpr(E);
4652}
4653
4655 const ConceptSpecializationExpr *CSE, const Expr *ConstraintExpr,
4656 const MultiLevelTemplateArgumentList &MLTAL) {
4657 assert(isSFINAEContext());
4658
4659 TemplateInstantiator Instantiator(*this, MLTAL, SourceLocation(),
4660 DeclarationName());
4661 const ASTTemplateArgumentListInfo *ArgsAsWritten =
4663 TemplateArgumentListInfo SubstArgs(ArgsAsWritten->getLAngleLoc(),
4664 ArgsAsWritten->getRAngleLoc());
4665
4666 if (Instantiator.TransformConceptTemplateArguments(
4667 ArgsAsWritten->getTemplateArgs(),
4668 ArgsAsWritten->getTemplateArgs() +
4669 ArgsAsWritten->getNumTemplateArgs(),
4670 SubstArgs))
4671 return true;
4672
4673 llvm::SmallVector<TemplateArgument, 4> NewArgList = llvm::map_to_vector(
4674 SubstArgs.arguments(),
4675 [](const TemplateArgumentLoc &Loc) { return Loc.getArgument(); });
4676
4677 MultiLevelTemplateArgumentList MLTALForConstraint =
4680 /*Final=*/false,
4681 /*Innermost=*/NewArgList,
4682 /*RelativeToPrimary=*/true,
4683 /*Pattern=*/nullptr,
4684 /*ForConstraintInstantiation=*/true);
4685
4686 // Rebuild a constraint, only substituting non-dependent concept names
4687 // and nothing else.
4688 // Given C<SomeType, SomeValue, SomeConceptName, SomeDependentConceptName>.
4689 // only SomeConceptName is substituted, in the constraint expression of C.
4690 struct ConstraintExprTransformer : TreeTransform<ConstraintExprTransformer> {
4693
4694 ConstraintExprTransformer(Sema &SemaRef,
4696 : TreeTransform(SemaRef), MLTAL(MLTAL) {}
4697
4698 ExprResult TransformExpr(Expr *E) {
4699 if (!E)
4700 return E;
4701 switch (E->getStmtClass()) {
4702 case Stmt::BinaryOperatorClass:
4703 case Stmt::ConceptSpecializationExprClass:
4704 case Stmt::ParenExprClass:
4705 case Stmt::UnresolvedLookupExprClass:
4706 case Stmt::DependentTemplateIdExprClass:
4707 return Base::TransformExpr(E);
4708 default:
4709 break;
4710 }
4711 return E;
4712 }
4713
4714 // Rebuild both branches of a conjunction / disjunction
4715 // even if there is a substitution failure in one of
4716 // the branch.
4717 ExprResult TransformBinaryOperator(BinaryOperator *E) {
4718 if (!(E->getOpcode() == BinaryOperatorKind::BO_LAnd ||
4719 E->getOpcode() == BinaryOperatorKind::BO_LOr))
4720 return E;
4721
4722 ExprResult LHS = TransformExpr(E->getLHS());
4723 ExprResult RHS = TransformExpr(E->getRHS());
4724
4725 if (LHS.get() == E->getLHS() && RHS.get() == E->getRHS())
4726 return E;
4727
4728 return BinaryOperator::Create(SemaRef.Context, LHS.get(), RHS.get(),
4729 E->getOpcode(), SemaRef.Context.BoolTy,
4732 }
4733
4734 bool TransformTemplateArgument(const TemplateArgumentLoc &Input,
4735 TemplateArgumentLoc &Output,
4736 bool Uneval = false) {
4737 if (Input.getArgument().isConceptOrConceptTemplateParameter())
4738 return Base::TransformTemplateArgument(Input, Output, Uneval);
4739
4740 Output = Input;
4741 return false;
4742 }
4743
4744 ExprResult RebuildConceptSpecialization(ConceptDecl *ResolvedConcept,
4745 SourceLocation NameLoc,
4746 SourceLocation LAngleLoc,
4747 SourceLocation RAngleLoc,
4748 const TemplateArgumentLoc *Args,
4749 unsigned NumArgs) {
4750 TemplateArgumentListInfo TransArgs(LAngleLoc, RAngleLoc);
4751 if (TransformTemplateArguments(Args, NumArgs, TransArgs))
4752 return ExprError();
4753
4754 CXXScopeSpec SS;
4755 DeclarationNameInfo NameInfo(ResolvedConcept->getDeclName(), NameLoc);
4756 return SemaRef.CheckConceptTemplateId(SS, SourceLocation(), NameInfo,
4757 ResolvedConcept, ResolvedConcept,
4758 &TransArgs, false);
4759 }
4760
4761 ExprResult TransformDependentTemplateIdExpr(DependentTemplateIdExpr *E) {
4762 if (!E->isConceptReference())
4763 return E;
4764
4766 unsigned Depth = TTP->getDepth();
4767 unsigned Pos = TTP->getPosition();
4768 if (!MLTAL.hasTemplateArgument(Depth, Pos))
4769 return E;
4770
4771 TemplateArgument Arg = MLTAL(Depth, Pos);
4774 UnsignedOrNone Index = PI->getSelectedIndex();
4775 if (Arg.getKind() != TemplateArgument::Pack || !Index ||
4776 *Index >= Arg.pack_size())
4777 return E;
4778 Arg = Arg.getPackAsArray()[*Index];
4779 }
4781 return E;
4782 ConceptDecl *ResolvedConcept = dyn_cast_if_present<ConceptDecl>(
4784 if (!ResolvedConcept)
4785 return E;
4786
4787 return RebuildConceptSpecialization(ResolvedConcept, E->getNameLoc(),
4788 E->getLAngleLoc(), E->getRAngleLoc(),
4789 E->template_arguments().data(),
4790 E->getNumTemplateArgs());
4791 }
4792 };
4793
4794 ConstraintExprTransformer Transformer(*this, MLTALForConstraint);
4795 ExprResult Res =
4796 Transformer.TransformExpr(const_cast<Expr *>(ConstraintExpr));
4797 return Res;
4798}
4799
4801 const MultiLevelTemplateArgumentList &TemplateArgs,
4802 bool CXXDirectInit) {
4803 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
4804 DeclarationName());
4805 return Instantiator.TransformInitializer(Init, CXXDirectInit);
4806}
4807
4808bool Sema::SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
4809 const MultiLevelTemplateArgumentList &TemplateArgs,
4810 SmallVectorImpl<Expr *> &Outputs) {
4811 if (Exprs.empty())
4812 return false;
4813
4814 TemplateInstantiator Instantiator(*this, TemplateArgs,
4816 DeclarationName());
4817 return Instantiator.TransformExprs(Exprs.data(), Exprs.size(),
4818 IsCall, Outputs);
4819}
4820
4823 const MultiLevelTemplateArgumentList &TemplateArgs) {
4824 if (!NNS)
4825 return NestedNameSpecifierLoc();
4826
4827 TemplateInstantiator Instantiator(*this, TemplateArgs, NNS.getBeginLoc(),
4828 DeclarationName());
4829 return Instantiator.TransformNestedNameSpecifierLoc(NNS);
4830}
4831
4834 const MultiLevelTemplateArgumentList &TemplateArgs) {
4835 TemplateInstantiator Instantiator(*this, TemplateArgs, NameInfo.getLoc(),
4836 NameInfo.getName());
4837 return Instantiator.TransformDeclarationNameInfo(NameInfo);
4838}
4839
4842 NestedNameSpecifierLoc &QualifierLoc, TemplateName Name,
4843 SourceLocation NameLoc,
4844 const MultiLevelTemplateArgumentList &TemplateArgs) {
4845 TemplateInstantiator Instantiator(*this, TemplateArgs, NameLoc,
4846 DeclarationName());
4847 return Instantiator.TransformTemplateName(QualifierLoc, TemplateKWLoc, Name,
4848 NameLoc);
4849}
4850
4851static const Decl *getCanonicalParmVarDecl(const Decl *D) {
4852 // When storing ParmVarDecls in the local instantiation scope, we always
4853 // want to use the ParmVarDecl from the canonical function declaration,
4854 // since the map is then valid for any redeclaration or definition of that
4855 // function.
4856 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(D)) {
4857 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
4858 unsigned i = PV->getFunctionScopeIndex();
4859 // This parameter might be from a freestanding function type within the
4860 // function and isn't necessarily referring to one of FD's parameters.
4861 if (i < FD->getNumParams() && FD->getParamDecl(i) == PV)
4862 return FD->getCanonicalDecl()->getParamDecl(i);
4863 }
4864 }
4865 return D;
4866}
4867
4868llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> *
4871 for (LocalInstantiationScope *Current = this; Current;
4872 Current = Current->Outer) {
4873
4874 // Check if we found something within this scope.
4875 const Decl *CheckD = D;
4876 do {
4877 LocalDeclsMap::iterator Found = Current->LocalDecls.find(CheckD);
4878 if (Found != Current->LocalDecls.end())
4879 return &Found->second;
4880
4881 // If this is a tag declaration, it's possible that we need to look for
4882 // a previous declaration.
4883 if (const TagDecl *Tag = dyn_cast<TagDecl>(CheckD))
4884 CheckD = Tag->getPreviousDecl();
4885 else
4886 CheckD = nullptr;
4887 } while (CheckD);
4888
4889 // If we aren't combined with our outer scope, we're done.
4890 if (!Current->CombineWithOuterScope)
4891 break;
4892 }
4893
4894 return nullptr;
4895}
4896
4897llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> *
4900 if (Result)
4901 return Result;
4902 // If we're performing a partial substitution during template argument
4903 // deduction, we may not have values for template parameters yet.
4906 return nullptr;
4907
4908 // Local types referenced prior to definition may require instantiation.
4909 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
4910 if (RD->isLocalClass())
4911 return nullptr;
4912
4913 // Enumeration types referenced prior to definition may appear as a result of
4914 // error recovery.
4915 if (isa<EnumDecl>(D))
4916 return nullptr;
4917
4918 // Materialized typedefs/type alias for implicit deduction guides may require
4919 // instantiation.
4920 if (isa<TypedefNameDecl>(D) &&
4922 return nullptr;
4923
4924 // If we didn't find the decl, then we either have a sema bug, or we have a
4925 // forward reference to a label declaration. Return null to indicate that
4926 // we have an uninstantiated label.
4927 assert(isa<LabelDecl>(D) && "declaration not instantiated in this scope");
4928 return nullptr;
4929}
4930
4933 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
4934 if (Stored.isNull()) {
4935#ifndef NDEBUG
4936 // It should not be present in any surrounding scope either.
4937 LocalInstantiationScope *Current = this;
4938 while (Current->CombineWithOuterScope && Current->Outer) {
4939 Current = Current->Outer;
4940 assert(!Current->LocalDecls.contains(D) &&
4941 "Instantiated local in inner and outer scopes");
4942 }
4943#endif
4944 Stored = Inst;
4945 } else if (DeclArgumentPack *Pack = dyn_cast<DeclArgumentPack *>(Stored)) {
4946 Pack->push_back(cast<ValueDecl>(Inst));
4947 } else {
4948 assert(cast<Decl *>(Stored) == Inst && "Already instantiated this local");
4949 }
4950}
4951
4953 VarDecl *Inst) {
4955 DeclArgumentPack *Pack = cast<DeclArgumentPack *>(LocalDecls[D]);
4956 Pack->push_back(Inst);
4957}
4958
4960#ifndef NDEBUG
4961 // This should be the first time we've been told about this decl.
4962 for (LocalInstantiationScope *Current = this;
4963 Current && Current->CombineWithOuterScope; Current = Current->Outer)
4964 assert(!Current->LocalDecls.contains(D) &&
4965 "Creating local pack after instantiation of local");
4966#endif
4967
4969 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
4971 Stored = Pack;
4972 ArgumentPacks.push_back(Pack);
4973}
4974
4976 for (DeclArgumentPack *Pack : ArgumentPacks)
4977 if (llvm::is_contained(*Pack, D))
4978 return true;
4979 return false;
4980}
4981
4983 const TemplateArgument *ExplicitArgs,
4984 unsigned NumExplicitArgs) {
4985 assert((!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack) &&
4986 "Already have a partially-substituted pack");
4987 assert((!PartiallySubstitutedPack
4988 || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) &&
4989 "Wrong number of arguments in partially-substituted pack");
4990 PartiallySubstitutedPack = Pack;
4991 ArgsInPartiallySubstitutedPack = ExplicitArgs;
4992 NumArgsInPartiallySubstitutedPack = NumExplicitArgs;
4993}
4994
4996 const TemplateArgument **ExplicitArgs,
4997 unsigned *NumExplicitArgs) const {
4998 if (ExplicitArgs)
4999 *ExplicitArgs = nullptr;
5000 if (NumExplicitArgs)
5001 *NumExplicitArgs = 0;
5002
5003 for (const LocalInstantiationScope *Current = this; Current;
5004 Current = Current->Outer) {
5005 if (Current->PartiallySubstitutedPack) {
5006 if (ExplicitArgs)
5007 *ExplicitArgs = Current->ArgsInPartiallySubstitutedPack;
5008 if (NumExplicitArgs)
5009 *NumExplicitArgs = Current->NumArgsInPartiallySubstitutedPack;
5010
5011 return Current->PartiallySubstitutedPack;
5012 }
5013
5014 if (!Current->CombineWithOuterScope)
5015 break;
5016 }
5017
5018 return nullptr;
5019}
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:5115
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:246
const clang::PrintingPolicy & getPrintingPolicy() const
Definition ASTContext.h:915
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
QualType getOriginalType() const
Definition TypeBase.h:3621
QualType getElementType() const
Definition TypeBase.h:3833
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:5145
Opcode getOpcode() const
Definition Expr.h:4152
QualType getPointeeType() const
Definition TypeBase.h:3666
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:2201
DeclContextLookupResult lookup_result
Definition DeclBase.h:2611
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.
bool isTranslationUnit() const
Definition DeclBase.h:2206
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:2407
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:4193
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this enumeration is an instantiation of a member enumeration of a class template specialization,...
Definition Decl.h:4465
EnumDecl * getInstantiatedFromMemberEnum() const
Returns the enumeration (declared within the template) from which this enumeration type was instantia...
Definition Decl.cpp:5265
EnumDecl * getDefinition() const
Definition Decl.h:4305
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:4830
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:4342
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition Decl.cpp:4391
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:5650
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5939
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:4872
QualType getReturnType() const
Definition TypeBase.h:5186
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
LocalInstantiationScope * cloneScopes(LocalInstantiationScope *Outermost)
Clone this scope, and all outer scopes, down to the given outermost scope.
Definition Template.h:477
llvm::PointerUnion< Decl *, DeclArgumentPack * > * findInstantiationOf(const Decl *D)
Find the instantiation of the declaration D within the current instantiation scope.
QualType getUnderlyingType() const
Definition TypeBase.h:6544
QualType getPointeeType() const
Definition TypeBase.h:3770
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:1851
virtual void printName(raw_ostream &OS, const PrintingPolicy &Policy) const
Pretty-print the unqualified name of this declaration.
Definition Decl.cpp:1677
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:2752
TypeLoc getPatternLoc() const
Definition TypeLoc.h:2768
A structure for storing a pack-index-template-name ([temp.names]).
QualType getInnerType() const
Definition TypeBase.h:3393
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:3055
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:3018
Expr * getUninstantiatedDefaultArg()
Definition Decl.cpp:3060
unsigned getFunctionScopeDepth() const
Definition Decl.h:1882
void setHasInheritedDefaultArg(bool I=true)
Definition Decl.h:1981
QualType getPointeeType() const
Definition TypeBase.h:3414
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:3848
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:3841
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:4507
bool isMemberSpecialization() const
Determines whether this template was a specialization of a member template.
QualType getPointeeTypeAsWritten() const
Definition TypeBase.h:3695
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:42
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:14011
RAII object used to temporarily allow the C++ 'this' expression to be used, with the given qualifiers...
Definition Sema.h:8718
A RAII object to temporarily push a declaration context.
Definition Sema.h:3683
A helper class for building up ExtParameterInfos.
Definition Sema.h:13380
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition Sema.h:12795
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:863
llvm::DenseSet< Module * > LookupModulesCache
Cache of additional modules that should be used for name lookup within the current template instantia...
Definition Sema.h:13974
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:13958
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition Sema.h:13409
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:2371
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:14355
void SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto, const MultiLevelTemplateArgumentList &Args)
SemaSYCL & SYCL()
Definition Sema.h:1603
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:1339
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:932
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.
TypeSourceInfo * SubstFunctionDeclType(TypeSourceInfo *T, const MultiLevelTemplateArgumentList &TemplateArgs, SourceLocation Loc, DeclarationName Entity, CXXRecordDecl *ThisContext, Qualifiers ThisTypeQuals, bool EvaluateConstraints=true, const FunctionDecl *Fn=nullptr, LateInstantiatedAttrVec *ParamAttrs=nullptr)
A form of SubstType intended specifically for instantiating the type of a FunctionDecl.
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:14041
ASTContext & getASTContext() const
Definition Sema.h:935
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:14123
void ActOnStartCXXInClassMemberInitializer()
Enter a new C++ default initializer scope.
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
Definition Sema.h:1243
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:277
void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs, const Decl *Pattern, Decl *Inst, LateInstantiatedAttrVec *LateAttrs=nullptr, LocalInstantiationScope *OuterMostScope=nullptr)
const LangOptions & getLangOpts() const
Definition Sema.h:928
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:12111
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:13421
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition Sema.h:1491
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:14404
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:13989
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)
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, const FunctionDecl *Fn=nullptr, LateInstantiatedAttrVec *ParamAttrs=nullptr)
Substitute the given template arguments into the given set of parameters, producing the set of parame...
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:14049
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:14005
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:1340
@ ConstantEvaluated
The current context is "potentially evaluated" in C++11 terms, but the expression is evaluated at com...
Definition Sema.h:6957
@ PotentiallyEvaluated
The current expression is potentially evaluated at run time, which means that code may be generated t...
Definition Sema.h:6967
unsigned LastEmittedCodeSynthesisContextDepth
The depth of the context stack at the point when the most recent error or warning was produced.
Definition Sema.h:13997
NestedNameSpecifierLoc SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS, const MultiLevelTemplateArgumentList &TemplateArgs)
bool RebuildingImmediateInvocation
Whether the AST is currently being rebuilt to correct immediate invocations.
Definition Sema.h:8437
SmallVector< ExpressionEvaluationContextRecord, 8 > ExprEvalContexts
A stack of expression evaluation contexts.
Definition Sema.h:8583
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:1341
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:1633
SmallVector< Module *, 16 > CodeSynthesisContextLookupModules
Extra modules inspected when performing a lookup during a template instantiation.
Definition Sema.h:13969
ExprResult ConvertParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg, SourceLocation EqualLoc)
llvm::BumpPtrAllocator BumpAlloc
Definition Sema.h:1284
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:648
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:674
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue)
Definition Sema.h:8931
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:3899
void setTagKind(TagKind TK)
Definition Decl.h:4103
void startDefinition()
Starts the definition of this tag declaration.
Definition Decl.cpp:5017
void setBraceRange(SourceRange R)
Definition Decl.h:3977
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.
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.
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:3730
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:8651
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:8662
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:9306
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:8941
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:2872
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:2882
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
Definition TypeBase.h:3003
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9537
bool isRecordType() const
Definition TypeBase.h:9044
QualType getUnderlyingType() const
Definition Decl.h:3799
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:5703
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:2370
VarDecl * getInstantiatedFromStaticDataMember() const
If this variable is an instantiated static data member of a class template specialization,...
Definition Decl.cpp:2766
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:2899
void deduceParmAddressSpace(const ASTContext &Ctxt)
Definition Decl.cpp:2955
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:2892
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.
QualType getElementType() const
Definition TypeBase.h:4413
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:879
CXXMethodDecl * CallOperator
The lambda's compiler-generated operator().
Definition ScopeInfo.h:882
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:62
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:243
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
@ Template
We are parsing a template declaration.
Definition Parser.h:82
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:374
@ Success
Template argument deduction was successful.
Definition Sema.h:376
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:845
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:6262
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:5707
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition TypeBase.h:5709
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:13460
SourceRange InstantiationRange
The source range that covers the construct that cause the instantiation, e.g., the template-id that c...
Definition Sema.h:13631
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:13604
SourceLocation PointOfInstantiation
The point of instantiation or synthesis within the source code.
Definition Sema.h:13591
SynthesisKind
The kind of template instantiation we are performing.
Definition Sema.h:13462
@ MarkingClassDllexported
We are marking a class as __dllexport.
Definition Sema.h:13551
@ DefaultTemplateArgumentInstantiation
We are instantiating a default argument for a template parameter.
Definition Sema.h:13472
@ ExplicitTemplateArgumentSubstitution
We are substituting explicit template arguments provided for a function template.
Definition Sema.h:13481
@ DefaultTemplateArgumentChecking
We are checking the validity of a default template argument that has been used when naming a template...
Definition Sema.h:13500
@ InitializingStructuredBinding
We are initializing a structured binding.
Definition Sema.h:13548
@ ExceptionSpecInstantiation
We are instantiating the exception specification for a function template which was deferred until it ...
Definition Sema.h:13508
@ NestedRequirementConstraintsCheck
We are checking the satisfaction of a nested requirement of a requires expression.
Definition Sema.h:13515
@ BuildingBuiltinDumpStructCall
We are building an implied call from __builtin_dump_struct.
Definition Sema.h:13555
@ DefiningSynthesizedFunction
We are defining a synthesized function (such as a defaulted special member).
Definition Sema.h:13526
@ Memoization
Added for Template instantiation observation.
Definition Sema.h:13561
@ LambdaExpressionSubstitution
We are substituting into a lambda expression.
Definition Sema.h:13491
@ TypeAliasTemplateInstantiation
We are instantiating a type alias template declaration.
Definition Sema.h:13567
@ BuildingDeductionGuides
We are building deduction guides for a class.
Definition Sema.h:13564
@ PartialOrderingTTP
We are performing partial ordering for template template parameters.
Definition Sema.h:13570
@ DeducedTemplateArgumentSubstitution
We are substituting template argument determined as part of template argument deduction for either a ...
Definition Sema.h:13488
@ PriorTemplateArgumentSubstitution
We are substituting prior template arguments into a new template parameter.
Definition Sema.h:13496
@ SYCLKernelLaunchOverloadResolution
We are performing overload resolution for a call to a function template or variable template named 's...
Definition Sema.h:13578
@ ExpansionStmtInstantiation
We are instantiating an expansion statement.
Definition Sema.h:13581
@ ExceptionSpecEvaluation
We are computing the exception specification for a defaulted special member function.
Definition Sema.h:13504
@ TemplateInstantiation
We are instantiating a template declaration.
Definition Sema.h:13465
@ DeclaringSpecialMember
We are declaring an implicit special member function.
Definition Sema.h:13518
@ DeclaringImplicitEqualityComparison
We are declaring an implicit 'operator==' for a defaulted 'operator<=>'.
Definition Sema.h:13522
@ DefaultFunctionArgumentInstantiation
We are instantiating a default argument for a function.
Definition Sema.h:13477
@ RewritingOperatorAsSpaceship
We are rewriting a comparison operator in terms of an operator<=>.
Definition Sema.h:13545
@ SYCLKernelLaunchLookup
We are performing name lookup for a function template or variable template named 'sycl_kernel_launch'...
Definition Sema.h:13574
@ RequirementInstantiation
We are instantiating a requirement of a requires expression.
Definition Sema.h:13511
Decl * Entity
The entity that is being synthesized.
Definition Sema.h:13594
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:13654
bool isInvalid() const
Determines whether we have exceeded the maximum recursive template instantiations.
Definition Sema.h:13807
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:14116
void set(DeclAccessPair Found, Decl *Spec, DeductionFailureInfo Info)
SourceLocation Ellipsis
UnsignedOrNone NumExpansions