Thanks to visit codestin.com
Credit goes to clang.llvm.org

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