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