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
621 Inst.Kind = Kind;
622 Inst.PointOfInstantiation = PointOfInstantiation;
623 Inst.Entity = Entity;
624 Inst.Template = Template;
625 Inst.TemplateArgs = TemplateArgs.data();
626 Inst.NumTemplateArgs = TemplateArgs.size();
627 Inst.DeductionInfo = DeductionInfo;
628 Inst.InstantiationRange = InstantiationRange;
629 Inst.InConstraintSubstitution =
631 Inst.InParameterMappingSubstitution =
633 if (!SemaRef.CodeSynthesisContexts.empty()) {
634 Inst.InConstraintSubstitution |=
635 SemaRef.CodeSynthesisContexts.back().InConstraintSubstitution;
636 Inst.InParameterMappingSubstitution |=
637 SemaRef.CodeSynthesisContexts.back().InParameterMappingSubstitution;
638 }
639
640 Invalid = SemaRef.pushCodeSynthesisContext(Inst);
641 if (!Invalid) {
642 AlreadyInstantiating =
643 !Inst.Entity
644 ? false
645 : !SemaRef.InstantiatingSpecializations
646 .insert({Inst.Entity->getCanonicalDecl(), Inst.Kind})
647 .second;
649 }
650}
651
653 Sema &SemaRef, SourceLocation PointOfInstantiation, Decl *Entity,
654 SourceRange InstantiationRange)
655 : InstantiatingTemplate(SemaRef,
656 CodeSynthesisContext::TemplateInstantiation,
657 PointOfInstantiation, InstantiationRange, Entity) {}
658
660 Sema &SemaRef, SourceLocation PointOfInstantiation, FunctionDecl *Entity,
661 ExceptionSpecification, SourceRange InstantiationRange)
663 SemaRef, CodeSynthesisContext::ExceptionSpecInstantiation,
664 PointOfInstantiation, InstantiationRange, Entity) {}
665
667 Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateParameter Param,
669 SourceRange InstantiationRange)
671 SemaRef,
672 CodeSynthesisContext::DefaultTemplateArgumentInstantiation,
673 PointOfInstantiation, InstantiationRange, getAsNamedDecl(Param),
674 Template, TemplateArgs) {}
675
677 Sema &SemaRef, SourceLocation PointOfInstantiation,
679 ArrayRef<TemplateArgument> TemplateArgs,
681 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
682 : InstantiatingTemplate(SemaRef, Kind, PointOfInstantiation,
683 InstantiationRange, FunctionTemplate, nullptr,
684 TemplateArgs, &DeductionInfo) {
688}
689
691 Sema &SemaRef, SourceLocation PointOfInstantiation,
693 ArrayRef<TemplateArgument> TemplateArgs,
694 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
696 SemaRef,
697 CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
698 PointOfInstantiation, InstantiationRange, Template, nullptr,
699 TemplateArgs, &DeductionInfo) {}
700
702 Sema &SemaRef, SourceLocation PointOfInstantiation,
704 ArrayRef<TemplateArgument> TemplateArgs,
705 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
707 SemaRef,
708 CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
709 PointOfInstantiation, InstantiationRange, PartialSpec, nullptr,
710 TemplateArgs, &DeductionInfo) {}
711
713 Sema &SemaRef, SourceLocation PointOfInstantiation,
715 ArrayRef<TemplateArgument> TemplateArgs,
716 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
718 SemaRef,
719 CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
720 PointOfInstantiation, InstantiationRange, PartialSpec, nullptr,
721 TemplateArgs, &DeductionInfo) {}
722
724 Sema &SemaRef, SourceLocation PointOfInstantiation, ParmVarDecl *Param,
725 ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange)
727 SemaRef,
728 CodeSynthesisContext::DefaultFunctionArgumentInstantiation,
729 PointOfInstantiation, InstantiationRange, Param, nullptr,
730 TemplateArgs) {}
731
733 Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template,
735 SourceRange InstantiationRange)
737 SemaRef,
738 CodeSynthesisContext::PriorTemplateArgumentSubstitution,
739 PointOfInstantiation, InstantiationRange, Param, Template,
740 TemplateArgs) {}
741
743 Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template,
745 SourceRange InstantiationRange)
747 SemaRef,
748 CodeSynthesisContext::PriorTemplateArgumentSubstitution,
749 PointOfInstantiation, InstantiationRange, Param, Template,
750 TemplateArgs) {}
751
753 Sema &SemaRef, SourceLocation PointOfInstantiation,
755 SourceRange InstantiationRange)
757 SemaRef, CodeSynthesisContext::TypeAliasTemplateInstantiation,
758 PointOfInstantiation, InstantiationRange, /*Entity=*/Entity,
759 /*Template=*/nullptr, TemplateArgs) {}
760
762 Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Template,
763 NamedDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
764 SourceRange InstantiationRange)
766 SemaRef, CodeSynthesisContext::DefaultTemplateArgumentChecking,
767 PointOfInstantiation, InstantiationRange, Param, Template,
768 TemplateArgs) {}
769
771 Sema &SemaRef, SourceLocation PointOfInstantiation,
773 SourceRange InstantiationRange)
775 SemaRef, CodeSynthesisContext::RequirementInstantiation,
776 PointOfInstantiation, InstantiationRange, /*Entity=*/nullptr,
777 /*Template=*/nullptr, /*TemplateArgs=*/{}, &DeductionInfo) {}
778
780 Sema &SemaRef, SourceLocation PointOfInstantiation,
782 SourceRange InstantiationRange)
784 SemaRef, CodeSynthesisContext::NestedRequirementConstraintsCheck,
785 PointOfInstantiation, InstantiationRange, /*Entity=*/nullptr,
786 /*Template=*/nullptr, /*TemplateArgs=*/{}) {}
787
789 Sema &SemaRef, SourceLocation PointOfInstantiation, const RequiresExpr *RE,
790 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
792 SemaRef, CodeSynthesisContext::RequirementParameterInstantiation,
793 PointOfInstantiation, InstantiationRange, /*Entity=*/nullptr,
794 /*Template=*/nullptr, /*TemplateArgs=*/{}, &DeductionInfo) {}
795
797 Sema &SemaRef, SourceLocation PointOfInstantiation,
799 ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange)
802 PointOfInstantiation, InstantiationRange, Template, nullptr,
803 TemplateArgs) {}
804
806 Sema &SemaRef, SourceLocation PointOfInstantiation,
808 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
811 PointOfInstantiation, InstantiationRange, Template, nullptr,
812 {}, &DeductionInfo) {}
813
815 Sema &SemaRef, SourceLocation PointOfInstantiation,
817 SourceRange InstantiationRange)
820 PointOfInstantiation, InstantiationRange, Template) {}
821
823 Sema &SemaRef, SourceLocation PointOfInstantiation,
825 SourceRange InstantiationRange)
828 PointOfInstantiation, InstantiationRange, Template) {}
829
831 Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Entity,
832 BuildingDeductionGuidesTag, SourceRange InstantiationRange)
834 SemaRef, CodeSynthesisContext::BuildingDeductionGuides,
835 PointOfInstantiation, InstantiationRange, Entity) {}
836
838 Sema &SemaRef, SourceLocation ArgLoc, PartialOrderingTTP,
839 TemplateDecl *PArg, SourceRange InstantiationRange)
841 ArgLoc, InstantiationRange, PArg) {}
842
846
847 if (!Ctx.isInstantiationRecord()) {
849 } else {
850 assert(SemaRef.NonInstantiationEntries <=
851 SemaRef.CodeSynthesisContexts.size());
852 if ((SemaRef.CodeSynthesisContexts.size() -
853 SemaRef.NonInstantiationEntries) >
854 SemaRef.getLangOpts().InstantiationDepth) {
856 diag::err_template_recursion_depth_exceeded)
857 << SemaRef.getLangOpts().InstantiationDepth << Ctx.InstantiationRange;
859 diag::note_template_recursion_depth)
860 << SemaRef.getLangOpts().InstantiationDepth;
861 return true;
862 }
863 }
864
865 CodeSynthesisContexts.push_back(Ctx);
866
867 // Check to see if we're low on stack space. We can't do anything about this
868 // from here, but we can at least warn the user.
869 StackHandler.warnOnStackNearlyExhausted(Ctx.PointOfInstantiation);
870 return false;
871}
872
874 auto &Active = CodeSynthesisContexts.back();
875 if (!Active.isInstantiationRecord()) {
876 assert(NonInstantiationEntries > 0);
878 }
879
880 InNonInstantiationSFINAEContext = Active.SavedInNonInstantiationSFINAEContext;
881
882 // Name lookup no longer looks in this template's defining module.
883 assert(CodeSynthesisContexts.size() >=
885 "forgot to remove a lookup module for a template instantiation");
886 if (CodeSynthesisContexts.size() ==
889 LookupModulesCache.erase(M);
891 }
892
893 // If we've left the code synthesis context for the current context stack,
894 // stop remembering that we've emitted that stack.
895 if (CodeSynthesisContexts.size() ==
898
899 CodeSynthesisContexts.pop_back();
900}
901
903 if (!Invalid) {
904 if (!AlreadyInstantiating) {
905 auto &Active = SemaRef.CodeSynthesisContexts.back();
906 if (Active.Entity)
907 SemaRef.InstantiatingSpecializations.erase(
908 {Active.Entity->getCanonicalDecl(), Active.Kind});
909 }
910
911 atTemplateEnd(SemaRef.TemplateInstCallbacks, SemaRef,
912 SemaRef.CodeSynthesisContexts.back());
913
914 SemaRef.popCodeSynthesisContext();
915 Invalid = true;
916 }
917}
918
919static std::string convertCallArgsToString(Sema &S,
921 std::string Result;
922 llvm::raw_string_ostream OS(Result);
923 llvm::ListSeparator Comma;
924 for (const Expr *Arg : Args) {
925 OS << Comma;
926 Arg->IgnoreParens()->printPretty(OS, nullptr,
928 }
929 return Result;
930}
931
933 // Determine which template instantiations to skip, if any.
934 unsigned SkipStart = CodeSynthesisContexts.size(), SkipEnd = SkipStart;
935 unsigned Limit = Diags.getTemplateBacktraceLimit();
936 if (Limit && Limit < CodeSynthesisContexts.size()) {
937 SkipStart = Limit / 2 + Limit % 2;
938 SkipEnd = CodeSynthesisContexts.size() - Limit / 2;
939 }
940
941 // FIXME: In all of these cases, we need to show the template arguments
942 unsigned InstantiationIdx = 0;
944 Active = CodeSynthesisContexts.rbegin(),
945 ActiveEnd = CodeSynthesisContexts.rend();
946 Active != ActiveEnd;
947 ++Active, ++InstantiationIdx) {
948 // Skip this instantiation?
949 if (InstantiationIdx >= SkipStart && InstantiationIdx < SkipEnd) {
950 if (InstantiationIdx == SkipStart) {
951 // Note that we're skipping instantiations.
952 DiagFunc(Active->PointOfInstantiation,
953 PDiag(diag::note_instantiation_contexts_suppressed)
954 << unsigned(CodeSynthesisContexts.size() - Limit));
955 }
956 continue;
957 }
958
959 switch (Active->Kind) {
961 Decl *D = Active->Entity;
962 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
963 unsigned DiagID = diag::note_template_member_class_here;
965 DiagID = diag::note_template_class_instantiation_here;
966 DiagFunc(Active->PointOfInstantiation,
967 PDiag(DiagID) << Record << Active->InstantiationRange);
968 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
969 unsigned DiagID;
970 if (Function->getPrimaryTemplate())
971 DiagID = diag::note_function_template_spec_here;
972 else
973 DiagID = diag::note_template_member_function_here;
974 DiagFunc(Active->PointOfInstantiation,
975 PDiag(DiagID) << Function << Active->InstantiationRange);
976 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
977 DiagFunc(Active->PointOfInstantiation,
978 PDiag(VD->isStaticDataMember()
979 ? diag::note_template_static_data_member_def_here
980 : diag::note_template_variable_def_here)
981 << VD << Active->InstantiationRange);
982 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
983 DiagFunc(Active->PointOfInstantiation,
984 PDiag(diag::note_template_enum_def_here)
985 << ED << Active->InstantiationRange);
986 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
987 DiagFunc(Active->PointOfInstantiation,
988 PDiag(diag::note_template_nsdmi_here)
989 << FD << Active->InstantiationRange);
990 } else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(D)) {
991 DiagFunc(Active->PointOfInstantiation,
992 PDiag(diag::note_template_class_instantiation_here)
993 << CTD << Active->InstantiationRange);
994 }
995 break;
996 }
997
999 TemplateDecl *Template = cast<TemplateDecl>(Active->Template);
1000 SmallString<128> TemplateArgsStr;
1001 llvm::raw_svector_ostream OS(TemplateArgsStr);
1002 Template->printName(OS, getPrintingPolicy());
1003 printTemplateArgumentList(OS, Active->template_arguments(),
1005 DiagFunc(Active->PointOfInstantiation,
1006 PDiag(diag::note_default_arg_instantiation_here)
1007 << OS.str() << Active->InstantiationRange);
1008 break;
1009 }
1010
1012 FunctionTemplateDecl *FnTmpl = cast<FunctionTemplateDecl>(Active->Entity);
1013 DiagFunc(Active->PointOfInstantiation,
1014 PDiag(diag::note_explicit_template_arg_substitution_here)
1015 << FnTmpl
1017 FnTmpl->getTemplateParameters(), Active->TemplateArgs,
1018 Active->NumTemplateArgs)
1019 << Active->InstantiationRange);
1020 break;
1021 }
1022
1024 if (FunctionTemplateDecl *FnTmpl =
1025 dyn_cast<FunctionTemplateDecl>(Active->Entity)) {
1026 DiagFunc(
1027 Active->PointOfInstantiation,
1028 PDiag(diag::note_function_template_deduction_instantiation_here)
1029 << FnTmpl
1031 FnTmpl->getTemplateParameters(), Active->TemplateArgs,
1032 Active->NumTemplateArgs)
1033 << Active->InstantiationRange);
1034 } else {
1035 bool IsVar = isa<VarTemplateDecl>(Active->Entity) ||
1036 isa<VarTemplateSpecializationDecl>(Active->Entity);
1037 bool IsTemplate = false;
1038 TemplateParameterList *Params;
1039 if (auto *D = dyn_cast<TemplateDecl>(Active->Entity)) {
1040 IsTemplate = true;
1041 Params = D->getTemplateParameters();
1042 } else if (auto *D = dyn_cast<ClassTemplatePartialSpecializationDecl>(
1043 Active->Entity)) {
1044 Params = D->getTemplateParameters();
1045 } else if (auto *D = dyn_cast<VarTemplatePartialSpecializationDecl>(
1046 Active->Entity)) {
1047 Params = D->getTemplateParameters();
1048 } else {
1049 llvm_unreachable("unexpected template kind");
1050 }
1051
1052 DiagFunc(Active->PointOfInstantiation,
1053 PDiag(diag::note_deduced_template_arg_substitution_here)
1054 << IsVar << IsTemplate << cast<NamedDecl>(Active->Entity)
1056 Active->TemplateArgs,
1057 Active->NumTemplateArgs)
1058 << Active->InstantiationRange);
1059 }
1060 break;
1061 }
1062
1064 ParmVarDecl *Param = cast<ParmVarDecl>(Active->Entity);
1065 FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());
1066
1067 SmallString<128> TemplateArgsStr;
1068 llvm::raw_svector_ostream OS(TemplateArgsStr);
1070 printTemplateArgumentList(OS, Active->template_arguments(),
1072 DiagFunc(Active->PointOfInstantiation,
1073 PDiag(diag::note_default_function_arg_instantiation_here)
1074 << OS.str() << Active->InstantiationRange);
1075 break;
1076 }
1077
1079 NamedDecl *Parm = cast<NamedDecl>(Active->Entity);
1080 std::string Name;
1081 if (!Parm->getName().empty())
1082 Name = std::string(" '") + Parm->getName().str() + "'";
1083
1084 TemplateParameterList *TemplateParams = nullptr;
1085 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
1086 TemplateParams = Template->getTemplateParameters();
1087 else
1088 TemplateParams =
1090 ->getTemplateParameters();
1091 DiagFunc(Active->PointOfInstantiation,
1092 PDiag(diag::note_prior_template_arg_substitution)
1093 << isa<TemplateTemplateParmDecl>(Parm) << Name
1094 << getTemplateArgumentBindingsText(TemplateParams,
1095 Active->TemplateArgs,
1096 Active->NumTemplateArgs)
1097 << Active->InstantiationRange);
1098 break;
1099 }
1100
1102 TemplateParameterList *TemplateParams = nullptr;
1103 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
1104 TemplateParams = Template->getTemplateParameters();
1105 else
1106 TemplateParams =
1108 ->getTemplateParameters();
1109
1110 DiagFunc(Active->PointOfInstantiation,
1111 PDiag(diag::note_template_default_arg_checking)
1112 << getTemplateArgumentBindingsText(TemplateParams,
1113 Active->TemplateArgs,
1114 Active->NumTemplateArgs)
1115 << Active->InstantiationRange);
1116 break;
1117 }
1118
1120 DiagFunc(Active->PointOfInstantiation,
1121 PDiag(diag::note_evaluating_exception_spec_here)
1122 << cast<FunctionDecl>(Active->Entity));
1123 break;
1124
1126 DiagFunc(Active->PointOfInstantiation,
1127 PDiag(diag::note_template_exception_spec_instantiation_here)
1128 << cast<FunctionDecl>(Active->Entity)
1129 << Active->InstantiationRange);
1130 break;
1131
1133 DiagFunc(Active->PointOfInstantiation,
1134 PDiag(diag::note_template_requirement_instantiation_here)
1135 << Active->InstantiationRange);
1136 break;
1138 DiagFunc(Active->PointOfInstantiation,
1139 PDiag(diag::note_template_requirement_params_instantiation_here)
1140 << Active->InstantiationRange);
1141 break;
1142
1144 DiagFunc(Active->PointOfInstantiation,
1145 PDiag(diag::note_nested_requirement_here)
1146 << Active->InstantiationRange);
1147 break;
1148
1150 DiagFunc(Active->PointOfInstantiation,
1151 PDiag(diag::note_in_declaration_of_implicit_special_member)
1152 << cast<CXXRecordDecl>(Active->Entity)
1153 << Active->SpecialMember);
1154 break;
1155
1157 DiagFunc(
1158 Active->Entity->getLocation(),
1159 PDiag(diag::note_in_declaration_of_implicit_equality_comparison));
1160 break;
1161
1163 // FIXME: For synthesized functions that are not defaulted,
1164 // produce a note.
1165 auto *FD = dyn_cast<FunctionDecl>(Active->Entity);
1166 // Note: if FD is nullptr currently setting DFK to DefaultedFunctionKind()
1167 // will ensure that DFK.isComparison() is false. This is important because
1168 // we will uncondtionally dereference FD in the else if.
1171 if (DFK.isSpecialMember()) {
1172 auto *MD = cast<CXXMethodDecl>(FD);
1173 DiagFunc(Active->PointOfInstantiation,
1174 PDiag(diag::note_member_synthesized_at)
1175 << MD->isExplicitlyDefaulted() << DFK.asSpecialMember()
1176 << Context.getCanonicalTagType(MD->getParent()));
1177 } else if (DFK.isComparison()) {
1178 QualType RecordType = FD->getParamDecl(0)
1179 ->getType()
1180 .getNonReferenceType()
1181 .getUnqualifiedType();
1182 DiagFunc(Active->PointOfInstantiation,
1183 PDiag(diag::note_comparison_synthesized_at)
1184 << (int)DFK.asComparison() << RecordType);
1185 }
1186 break;
1187 }
1188
1190 DiagFunc(Active->Entity->getLocation(),
1191 PDiag(diag::note_rewriting_operator_as_spaceship));
1192 break;
1193
1195 DiagFunc(Active->PointOfInstantiation,
1196 PDiag(diag::note_in_binding_decl_init)
1197 << cast<BindingDecl>(Active->Entity));
1198 break;
1199
1201 DiagFunc(Active->PointOfInstantiation,
1202 PDiag(diag::note_due_to_dllexported_class)
1203 << cast<CXXRecordDecl>(Active->Entity)
1204 << !getLangOpts().CPlusPlus11);
1205 break;
1206
1208 DiagFunc(Active->PointOfInstantiation,
1209 PDiag(diag::note_building_builtin_dump_struct_call)
1211 *this, llvm::ArrayRef(Active->CallArgs,
1212 Active->NumCallArgs)));
1213 break;
1214
1216 break;
1217
1219 DiagFunc(Active->PointOfInstantiation,
1220 PDiag(diag::note_lambda_substitution_here));
1221 break;
1223 unsigned DiagID = 0;
1224 if (!Active->Entity) {
1225 DiagFunc(Active->PointOfInstantiation,
1226 PDiag(diag::note_nested_requirement_here)
1227 << Active->InstantiationRange);
1228 break;
1229 }
1230 if (isa<ConceptDecl>(Active->Entity))
1231 DiagID = diag::note_concept_specialization_here;
1232 else if (isa<TemplateDecl>(Active->Entity))
1233 DiagID = diag::note_checking_constraints_for_template_id_here;
1234 else if (isa<VarTemplatePartialSpecializationDecl>(Active->Entity))
1235 DiagID = diag::note_checking_constraints_for_var_spec_id_here;
1236 else if (isa<ClassTemplatePartialSpecializationDecl>(Active->Entity))
1237 DiagID = diag::note_checking_constraints_for_class_spec_id_here;
1238 else {
1239 assert(isa<FunctionDecl>(Active->Entity));
1240 DiagID = diag::note_checking_constraints_for_function_here;
1241 }
1242 SmallString<128> TemplateArgsStr;
1243 llvm::raw_svector_ostream OS(TemplateArgsStr);
1244 cast<NamedDecl>(Active->Entity)->printName(OS, getPrintingPolicy());
1245 if (!isa<FunctionDecl>(Active->Entity)) {
1246 printTemplateArgumentList(OS, Active->template_arguments(),
1248 }
1249 DiagFunc(Active->PointOfInstantiation,
1250 PDiag(DiagID) << OS.str() << Active->InstantiationRange);
1251 break;
1252 }
1254 DiagFunc(Active->PointOfInstantiation,
1255 PDiag(diag::note_constraint_substitution_here)
1256 << Active->InstantiationRange);
1257 break;
1259 DiagFunc(Active->PointOfInstantiation,
1260 PDiag(diag::note_constraint_normalization_here)
1261 << cast<NamedDecl>(Active->Entity)
1262 << Active->InstantiationRange);
1263 break;
1265 DiagFunc(Active->PointOfInstantiation,
1266 PDiag(diag::note_parameter_mapping_substitution_here)
1267 << Active->InstantiationRange);
1268 break;
1270 DiagFunc(Active->PointOfInstantiation,
1271 PDiag(diag::note_building_deduction_guide_here));
1272 break;
1274 DiagFunc(Active->PointOfInstantiation,
1275 PDiag(diag::note_template_type_alias_instantiation_here)
1276 << cast<TypeAliasTemplateDecl>(Active->Entity)
1277 << Active->InstantiationRange);
1278 break;
1280 DiagFunc(Active->PointOfInstantiation,
1281 PDiag(diag::note_template_arg_template_params_mismatch));
1282 if (SourceLocation ParamLoc = Active->Entity->getLocation();
1283 ParamLoc.isValid())
1284 DiagFunc(ParamLoc, PDiag(diag::note_template_prev_declaration)
1285 << /*isTemplateTemplateParam=*/true
1286 << Active->InstantiationRange);
1287 break;
1288 }
1289 }
1290}
1291
1292std::optional<TemplateDeductionInfo *> Sema::isSFINAEContext() const {
1294 return std::optional<TemplateDeductionInfo *>(nullptr);
1295
1297 Active = CodeSynthesisContexts.rbegin(),
1298 ActiveEnd = CodeSynthesisContexts.rend();
1299 Active != ActiveEnd;
1300 ++Active)
1301 {
1302 switch (Active->Kind) {
1304 // An instantiation of an alias template may or may not be a SFINAE
1305 // context, depending on what else is on the stack.
1306 if (isa<TypeAliasTemplateDecl>(Active->Entity))
1307 break;
1308 [[fallthrough]];
1316 // This is a template instantiation, so there is no SFINAE.
1317 return std::nullopt;
1319 // [temp.deduct]p9
1320 // A lambda-expression appearing in a function type or a template
1321 // parameter is not considered part of the immediate context for the
1322 // purposes of template argument deduction.
1323 // CWG2672: A lambda-expression body is never in the immediate context.
1324 return std::nullopt;
1325
1331 // A default template argument instantiation and substitution into
1332 // template parameters with arguments for prior parameters may or may
1333 // not be a SFINAE context; look further up the stack.
1334 break;
1335
1338 // We're either substituting explicitly-specified template arguments,
1339 // deduced template arguments. SFINAE applies unless we are in a lambda
1340 // body, see [temp.deduct]p9.
1344 // SFINAE always applies in a constraint expression or a requirement
1345 // in a requires expression.
1346 assert(Active->DeductionInfo && "Missing deduction info pointer");
1347 return Active->DeductionInfo;
1348
1356 // This happens in a context unrelated to template instantiation, so
1357 // there is no SFINAE.
1358 return std::nullopt;
1359
1361 // FIXME: This should not be treated as a SFINAE context, because
1362 // we will cache an incorrect exception specification. However, clang
1363 // bootstrap relies this! See PR31692.
1364 break;
1365
1367 break;
1368 }
1369
1370 // The inner context was transparent for SFINAE. If it occurred within a
1371 // non-instantiation SFINAE context, then SFINAE applies.
1372 if (Active->SavedInNonInstantiationSFINAEContext)
1373 return std::optional<TemplateDeductionInfo *>(nullptr);
1374 }
1375
1376 return std::nullopt;
1377}
1378
1379//===----------------------------------------------------------------------===/
1380// Template Instantiation for Types
1381//===----------------------------------------------------------------------===/
1382namespace {
1383
1384 class TemplateInstantiator : public TreeTransform<TemplateInstantiator> {
1385 const MultiLevelTemplateArgumentList &TemplateArgs;
1386 SourceLocation Loc;
1387 DeclarationName Entity;
1388 // Whether to evaluate the C++20 constraints or simply substitute into them.
1389 bool EvaluateConstraints = true;
1390 // Whether Substitution was Incomplete, that is, we tried to substitute in
1391 // any user provided template arguments which were null.
1392 bool IsIncomplete = false;
1393 // Whether an incomplete substituion should be treated as an error.
1394 bool BailOutOnIncomplete;
1395
1396 // Whether to rebuild pack expansion types; We don't do that when
1397 // rebuilding the parameter mapping of a fold expression appearing
1398 // in a constraint expression.
1399 bool BuildPackExpansionTypes = true;
1400
1401 // CWG2770: Function parameters should be instantiated when they are
1402 // needed by a satisfaction check of an atomic constraint or
1403 // (recursively) by another function parameter.
1404 bool maybeInstantiateFunctionParameterToScope(ParmVarDecl *OldParm);
1405
1406 public:
1407 typedef TreeTransform<TemplateInstantiator> inherited;
1408
1409 TemplateInstantiator(Sema &SemaRef,
1410 const MultiLevelTemplateArgumentList &TemplateArgs,
1411 SourceLocation Loc, DeclarationName Entity,
1412 bool BailOutOnIncomplete = false)
1413 : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc),
1414 Entity(Entity), BailOutOnIncomplete(BailOutOnIncomplete) {}
1415
1416 void setEvaluateConstraints(bool B) {
1417 EvaluateConstraints = B;
1418 }
1419 bool getEvaluateConstraints() {
1420 return EvaluateConstraints;
1421 }
1422
1423 inline static struct ForParameterMappingSubstitution_t {
1424 } ForParameterMappingSubstitution;
1425
1426 TemplateInstantiator(ForParameterMappingSubstitution_t, Sema &SemaRef,
1427 SourceLocation Loc,
1428 const MultiLevelTemplateArgumentList &TemplateArgs,
1429 bool BuildPackExpansionTypes)
1430 : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc),
1431 BailOutOnIncomplete(false),
1432 BuildPackExpansionTypes(BuildPackExpansionTypes) {}
1433
1434 /// Determine whether the given type \p T has already been
1435 /// transformed.
1436 ///
1437 /// For the purposes of template instantiation, a type has already been
1438 /// transformed if it is NULL or if it is not dependent.
1439 bool AlreadyTransformed(QualType T);
1440
1441 /// Returns the location of the entity being instantiated, if known.
1442 SourceLocation getBaseLocation() { return Loc; }
1443
1444 /// Returns the name of the entity being instantiated, if any.
1445 DeclarationName getBaseEntity() { return Entity; }
1446
1447 /// Returns whether any substitution so far was incomplete.
1448 bool getIsIncomplete() const { return IsIncomplete; }
1449
1450 /// Sets the "base" location and entity when that
1451 /// information is known based on another transformation.
1452 void setBase(SourceLocation Loc, DeclarationName Entity) {
1453 this->Loc = Loc;
1454 this->Entity = Entity;
1455 }
1456
1457 unsigned TransformTemplateDepth(unsigned Depth) {
1458 return TemplateArgs.getNewDepth(Depth);
1459 }
1460
1461 bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
1462 SourceRange PatternRange,
1463 ArrayRef<UnexpandedParameterPack> Unexpanded,
1464 bool FailOnPackProducingTemplates,
1465 bool &ShouldExpand, bool &RetainExpansion,
1466 UnsignedOrNone &NumExpansions) {
1467 if (SemaRef.CurrentInstantiationScope &&
1468 (SemaRef.inConstraintSubstitution() ||
1469 SemaRef.inParameterMappingSubstitution())) {
1470 for (UnexpandedParameterPack ParmPack : Unexpanded) {
1471 NamedDecl *VD = ParmPack.first.dyn_cast<NamedDecl *>();
1472 if (auto *PVD = dyn_cast_if_present<ParmVarDecl>(VD);
1473 PVD && maybeInstantiateFunctionParameterToScope(PVD))
1474 return true;
1475 }
1476 }
1477
1478 return getSema().CheckParameterPacksForExpansion(
1479 EllipsisLoc, PatternRange, Unexpanded, TemplateArgs,
1480 FailOnPackProducingTemplates, ShouldExpand, RetainExpansion,
1481 NumExpansions);
1482 }
1483
1484 void ExpandingFunctionParameterPack(ParmVarDecl *Pack) {
1486 }
1487
1488 TemplateArgument ForgetPartiallySubstitutedPack() {
1489 TemplateArgument Result;
1490 if (NamedDecl *PartialPack = SemaRef.CurrentInstantiationScope
1492 MultiLevelTemplateArgumentList &TemplateArgs =
1493 const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
1494 unsigned Depth, Index;
1495 std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
1496 if (TemplateArgs.hasTemplateArgument(Depth, Index)) {
1497 Result = TemplateArgs(Depth, Index);
1498 TemplateArgs.setArgument(Depth, Index, TemplateArgument());
1499 } else {
1500 IsIncomplete = true;
1501 if (BailOutOnIncomplete)
1502 return TemplateArgument();
1503 }
1504 }
1505
1506 return Result;
1507 }
1508
1509 void RememberPartiallySubstitutedPack(TemplateArgument Arg) {
1510 if (Arg.isNull())
1511 return;
1512
1513 if (NamedDecl *PartialPack = SemaRef.CurrentInstantiationScope
1515 MultiLevelTemplateArgumentList &TemplateArgs =
1516 const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
1517 unsigned Depth, Index;
1518 std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
1519 TemplateArgs.setArgument(Depth, Index, Arg);
1520 }
1521 }
1522
1523 MultiLevelTemplateArgumentList ForgetSubstitution() {
1524 MultiLevelTemplateArgumentList New;
1525 New.addOuterRetainedLevels(this->TemplateArgs.getNumLevels());
1526
1527 MultiLevelTemplateArgumentList Old =
1528 const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
1529 const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs) =
1530 std::move(New);
1531 return Old;
1532 }
1533
1534 void RememberSubstitution(MultiLevelTemplateArgumentList Old) {
1535 const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs) = Old;
1536 }
1537
1538 TemplateArgument
1539 getTemplateArgumentPackPatternForRewrite(const TemplateArgument &TA) {
1540 if (TA.getKind() != TemplateArgument::Pack)
1541 return TA;
1542 if (SemaRef.ArgPackSubstIndex)
1543 return SemaRef.getPackSubstitutedTemplateArgument(TA);
1544 assert(TA.pack_size() == 1 && TA.pack_begin()->isPackExpansion() &&
1545 "unexpected pack arguments in template rewrite");
1546 TemplateArgument Arg = *TA.pack_begin();
1547 if (Arg.isPackExpansion())
1548 Arg = Arg.getPackExpansionPattern();
1549 return Arg;
1550 }
1551
1552 /// Transform the given declaration by instantiating a reference to
1553 /// this declaration.
1554 Decl *TransformDecl(SourceLocation Loc, Decl *D);
1555
1556 void transformAttrs(Decl *Old, Decl *New) {
1557 SemaRef.InstantiateAttrs(TemplateArgs, Old, New);
1558 }
1559
1560 void transformedLocalDecl(Decl *Old, ArrayRef<Decl *> NewDecls) {
1561 if (Old->isParameterPack() &&
1562 (NewDecls.size() != 1 || !NewDecls.front()->isParameterPack())) {
1564 for (auto *New : NewDecls)
1566 Old, cast<VarDecl>(New));
1567 return;
1568 }
1569
1570 assert(NewDecls.size() == 1 &&
1571 "should only have multiple expansions for a pack");
1572 Decl *New = NewDecls.front();
1573
1574 // If we've instantiated the call operator of a lambda or the call
1575 // operator template of a generic lambda, update the "instantiation of"
1576 // information.
1577 auto *NewMD = dyn_cast<CXXMethodDecl>(New);
1578 if (NewMD && isLambdaCallOperator(NewMD)) {
1579 auto *OldMD = dyn_cast<CXXMethodDecl>(Old);
1580 if (auto *NewTD = NewMD->getDescribedFunctionTemplate())
1581 NewTD->setInstantiatedFromMemberTemplate(
1582 OldMD->getDescribedFunctionTemplate());
1583 else
1584 NewMD->setInstantiationOfMemberFunction(OldMD,
1586 }
1587
1589
1590 // We recreated a local declaration, but not by instantiating it. There
1591 // may be pending dependent diagnostics to produce.
1592 if (auto *DC = dyn_cast<DeclContext>(Old);
1593 DC && DC->isDependentContext() && DC->isFunctionOrMethod())
1594 SemaRef.PerformDependentDiagnostics(DC, TemplateArgs);
1595 }
1596
1597 /// Transform the definition of the given declaration by
1598 /// instantiating it.
1599 Decl *TransformDefinition(SourceLocation Loc, Decl *D);
1600
1601 /// Transform the first qualifier within a scope by instantiating the
1602 /// declaration.
1603 NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc);
1604
1605 bool TransformExceptionSpec(SourceLocation Loc,
1606 FunctionProtoType::ExceptionSpecInfo &ESI,
1607 SmallVectorImpl<QualType> &Exceptions,
1608 bool &Changed);
1609
1610 /// Rebuild the exception declaration and register the declaration
1611 /// as an instantiated local.
1612 VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
1613 TypeSourceInfo *Declarator,
1614 SourceLocation StartLoc,
1615 SourceLocation NameLoc,
1616 IdentifierInfo *Name);
1617
1618 /// Rebuild the Objective-C exception declaration and register the
1619 /// declaration as an instantiated local.
1620 VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
1621 TypeSourceInfo *TSInfo, QualType T);
1622
1624 TransformTemplateName(NestedNameSpecifierLoc &QualifierLoc,
1625 SourceLocation TemplateKWLoc, TemplateName Name,
1626 SourceLocation NameLoc,
1627 QualType ObjectType = QualType(),
1628 NamedDecl *FirstQualifierInScope = nullptr,
1629 bool AllowInjectedClassName = false);
1630
1631 const AnnotateAttr *TransformAnnotateAttr(const AnnotateAttr *AA);
1632 const CXXAssumeAttr *TransformCXXAssumeAttr(const CXXAssumeAttr *AA);
1633 const LoopHintAttr *TransformLoopHintAttr(const LoopHintAttr *LH);
1634 const NoInlineAttr *TransformStmtNoInlineAttr(const Stmt *OrigS,
1635 const Stmt *InstS,
1636 const NoInlineAttr *A);
1637 const AlwaysInlineAttr *
1638 TransformStmtAlwaysInlineAttr(const Stmt *OrigS, const Stmt *InstS,
1639 const AlwaysInlineAttr *A);
1640 const CodeAlignAttr *TransformCodeAlignAttr(const CodeAlignAttr *CA);
1641 const OpenACCRoutineDeclAttr *
1642 TransformOpenACCRoutineDeclAttr(const OpenACCRoutineDeclAttr *A);
1643 ExprResult TransformPredefinedExpr(PredefinedExpr *E);
1644 ExprResult TransformDeclRefExpr(DeclRefExpr *E);
1645 ExprResult TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E);
1646
1647 ExprResult TransformTemplateParmRefExpr(DeclRefExpr *E,
1648 NonTypeTemplateParmDecl *D);
1649
1650 /// Rebuild a DeclRefExpr for a VarDecl reference.
1651 ExprResult RebuildVarDeclRefExpr(ValueDecl *PD, SourceLocation Loc);
1652
1653 /// Transform a reference to a function or init-capture parameter pack.
1654 ExprResult TransformFunctionParmPackRefExpr(DeclRefExpr *E, ValueDecl *PD);
1655
1656 /// Transform a FunctionParmPackExpr which was built when we couldn't
1657 /// expand a function parameter pack reference which refers to an expanded
1658 /// pack.
1659 ExprResult TransformFunctionParmPackExpr(FunctionParmPackExpr *E);
1660
1661 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
1662 FunctionProtoTypeLoc TL) {
1663 // Call the base version; it will forward to our overridden version below.
1664 return inherited::TransformFunctionProtoType(TLB, TL);
1665 }
1666
1667 QualType TransformTagType(TypeLocBuilder &TLB, TagTypeLoc TL) {
1668 auto Type = inherited::TransformTagType(TLB, TL);
1669 if (!Type.isNull())
1670 return Type;
1671 // Special case for transforming a deduction guide, we return a
1672 // transformed TemplateSpecializationType.
1673 // FIXME: Why is this hack necessary?
1674 if (const auto *ICNT = dyn_cast<InjectedClassNameType>(TL.getTypePtr());
1675 ICNT && SemaRef.CodeSynthesisContexts.back().Kind ==
1677 Type = inherited::TransformType(
1678 ICNT->getOriginalDecl()->getCanonicalTemplateSpecializationType(
1679 SemaRef.Context));
1680 TLB.pushTrivial(SemaRef.Context, Type, TL.getNameLoc());
1681 }
1682 return Type;
1683 }
1684 // Override the default version to handle a rewrite-template-arg-pack case
1685 // for building a deduction guide.
1686 bool TransformTemplateArgument(const TemplateArgumentLoc &Input,
1687 TemplateArgumentLoc &Output,
1688 bool Uneval = false) {
1689 const TemplateArgument &Arg = Input.getArgument();
1690 std::vector<TemplateArgument> TArgs;
1691 switch (Arg.getKind()) {
1693 assert(SemaRef.CodeSynthesisContexts.empty() ||
1694 SemaRef.CodeSynthesisContexts.back().Kind ==
1696 // Literally rewrite the template argument pack, instead of unpacking
1697 // it.
1698 for (auto &pack : Arg.getPackAsArray()) {
1699 TemplateArgumentLoc Input = SemaRef.getTrivialTemplateArgumentLoc(
1700 pack, QualType(), SourceLocation{});
1701 TemplateArgumentLoc Output;
1702 if (TransformTemplateArgument(Input, Output, Uneval))
1703 return true; // fails
1704 TArgs.push_back(Output.getArgument());
1705 }
1706 Output = SemaRef.getTrivialTemplateArgumentLoc(
1707 TemplateArgument(llvm::ArrayRef(TArgs).copy(SemaRef.Context)),
1708 QualType(), SourceLocation{});
1709 return false;
1710 default:
1711 break;
1712 }
1713 return inherited::TransformTemplateArgument(Input, Output, Uneval);
1714 }
1715
1716 // This has to be here to allow its overload.
1717 ExprResult RebuildPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
1718 UnsignedOrNone NumExpansions) {
1719 return inherited::RebuildPackExpansion(Pattern, EllipsisLoc,
1720 NumExpansions);
1721 }
1722
1723 TemplateArgumentLoc RebuildPackExpansion(TemplateArgumentLoc Pattern,
1724 SourceLocation EllipsisLoc,
1725 UnsignedOrNone NumExpansions) {
1726 // We don't rewrite a PackExpansion type when we want to normalize a
1727 // CXXFoldExpr constraint. We'll expand it when evaluating the constraint.
1728 if (BuildPackExpansionTypes)
1729 return inherited::RebuildPackExpansion(Pattern, EllipsisLoc,
1730 NumExpansions);
1731 return Pattern;
1732 }
1733
1735 QualType
1736 TransformTemplateSpecializationType(TypeLocBuilder &TLB,
1737 TemplateSpecializationTypeLoc TL) {
1738 auto *T = TL.getTypePtr();
1739 if (!getSema().ArgPackSubstIndex || !T->isSugared() ||
1740 !isPackProducingBuiltinTemplateName(T->getTemplateName()))
1742 // Look through sugar to get to the SubstBuiltinTemplatePackType that we
1743 // need to substitute into.
1744
1745 // `TransformType` code below will handle picking the element from a pack
1746 // with the index `ArgPackSubstIndex`.
1747 // FIXME: add ability to represent sugarred type for N-th element of a
1748 // builtin pack and produce the sugar here.
1749 QualType R = TransformType(T->desugar());
1750 TLB.pushTrivial(getSema().getASTContext(), R, TL.getBeginLoc());
1751 return R;
1752 }
1753
1754 UnsignedOrNone ComputeSizeOfPackExprWithoutSubstitution(
1755 ArrayRef<TemplateArgument> PackArgs) {
1756 // Don't do this when rewriting template parameters for CTAD:
1757 // 1) The heuristic needs the unpacked Subst* nodes to figure out the
1758 // expanded size, but this never applies since Subst* nodes are not
1759 // created in rewrite scenarios.
1760 //
1761 // 2) The heuristic substitutes into the pattern with pack expansion
1762 // suppressed, which does not meet the requirements for argument
1763 // rewriting when template arguments include a non-pack matching against
1764 // a pack, particularly when rewriting an alias CTAD.
1765 if (TemplateArgs.isRewrite())
1766 return std::nullopt;
1767
1768 return inherited::ComputeSizeOfPackExprWithoutSubstitution(PackArgs);
1769 }
1770
1771 template<typename Fn>
1772 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
1773 FunctionProtoTypeLoc TL,
1774 CXXRecordDecl *ThisContext,
1775 Qualifiers ThisTypeQuals,
1776 Fn TransformExceptionSpec);
1777
1778 ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm,
1779 int indexAdjustment,
1780 UnsignedOrNone NumExpansions,
1781 bool ExpectParameterPack);
1782
1783 using inherited::TransformTemplateTypeParmType;
1784 /// Transforms a template type parameter type by performing
1785 /// substitution of the corresponding template type argument.
1786 QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
1787 TemplateTypeParmTypeLoc TL,
1788 bool SuppressObjCLifetime);
1789
1790 QualType BuildSubstTemplateTypeParmType(
1791 TypeLocBuilder &TLB, bool SuppressObjCLifetime, bool Final,
1792 Decl *AssociatedDecl, unsigned Index, UnsignedOrNone PackIndex,
1793 TemplateArgument Arg, SourceLocation NameLoc);
1794
1795 /// Transforms an already-substituted template type parameter pack
1796 /// into either itself (if we aren't substituting into its pack expansion)
1797 /// or the appropriate substituted argument.
1798 using inherited::TransformSubstTemplateTypeParmPackType;
1799 QualType
1800 TransformSubstTemplateTypeParmPackType(TypeLocBuilder &TLB,
1801 SubstTemplateTypeParmPackTypeLoc TL,
1802 bool SuppressObjCLifetime);
1803 QualType
1804 TransformSubstBuiltinTemplatePackType(TypeLocBuilder &TLB,
1805 SubstBuiltinTemplatePackTypeLoc TL);
1806
1808 ComputeLambdaDependency(LambdaScopeInfo *LSI) {
1809 if (auto TypeAlias =
1810 TemplateInstArgsHelpers::getEnclosingTypeAliasTemplateDecl(
1811 getSema());
1812 TypeAlias && TemplateInstArgsHelpers::isLambdaEnclosedByTypeAliasDecl(
1813 LSI->CallOperator, TypeAlias.PrimaryTypeAliasDecl)) {
1814 unsigned TypeAliasDeclDepth = TypeAlias.Template->getTemplateDepth();
1815 if (TypeAliasDeclDepth >= TemplateArgs.getNumSubstitutedLevels())
1816 return CXXRecordDecl::LambdaDependencyKind::LDK_AlwaysDependent;
1817 for (const TemplateArgument &TA : TypeAlias.AssociatedTemplateArguments)
1818 if (TA.isDependent())
1819 return CXXRecordDecl::LambdaDependencyKind::LDK_AlwaysDependent;
1820 }
1821 return inherited::ComputeLambdaDependency(LSI);
1822 }
1823
1824 ExprResult TransformLambdaExpr(LambdaExpr *E) {
1825 // Do not rebuild lambdas to avoid creating a new type.
1826 // Lambdas have already been processed inside their eval contexts.
1828 return E;
1829 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true,
1830 /*InstantiatingLambdaOrBlock=*/true);
1831 Sema::ConstraintEvalRAII<TemplateInstantiator> RAII(*this);
1832
1833 return inherited::TransformLambdaExpr(E);
1834 }
1835
1836 ExprResult TransformBlockExpr(BlockExpr *E) {
1837 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true,
1838 /*InstantiatingLambdaOrBlock=*/true);
1839 return inherited::TransformBlockExpr(E);
1840 }
1841
1842 ExprResult RebuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc,
1843 LambdaScopeInfo *LSI) {
1844 CXXMethodDecl *MD = LSI->CallOperator;
1845 for (ParmVarDecl *PVD : MD->parameters()) {
1846 assert(PVD && "null in a parameter list");
1847 if (!PVD->hasDefaultArg())
1848 continue;
1849 Expr *UninstExpr = PVD->getUninstantiatedDefaultArg();
1850 // FIXME: Obtain the source location for the '=' token.
1851 SourceLocation EqualLoc = UninstExpr->getBeginLoc();
1852 if (SemaRef.SubstDefaultArgument(EqualLoc, PVD, TemplateArgs)) {
1853 // If substitution fails, the default argument is set to a
1854 // RecoveryExpr that wraps the uninstantiated default argument so
1855 // that downstream diagnostics are omitted.
1856 ExprResult ErrorResult = SemaRef.CreateRecoveryExpr(
1857 UninstExpr->getBeginLoc(), UninstExpr->getEndLoc(), {UninstExpr},
1858 UninstExpr->getType());
1859 if (ErrorResult.isUsable())
1860 PVD->setDefaultArg(ErrorResult.get());
1861 }
1862 }
1863 return inherited::RebuildLambdaExpr(StartLoc, EndLoc, LSI);
1864 }
1865
1866 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
1867 // Currently, we instantiate the body when instantiating the lambda
1868 // expression. However, `EvaluateConstraints` is disabled during the
1869 // instantiation of the lambda expression, causing the instantiation
1870 // failure of the return type requirement in the body. If p0588r1 is fully
1871 // implemented, the body will be lazily instantiated, and this problem
1872 // will not occur. Here, `EvaluateConstraints` is temporarily set to
1873 // `true` to temporarily fix this issue.
1874 // FIXME: This temporary fix can be removed after fully implementing
1875 // p0588r1.
1876 llvm::SaveAndRestore _(EvaluateConstraints, true);
1877 return inherited::TransformLambdaBody(E, Body);
1878 }
1879
1880 ExprResult TransformRequiresExpr(RequiresExpr *E) {
1881 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
1882 ExprResult TransReq = inherited::TransformRequiresExpr(E);
1883 if (TransReq.isInvalid())
1884 return TransReq;
1885 assert(TransReq.get() != E &&
1886 "Do not change value of isSatisfied for the existing expression. "
1887 "Create a new expression instead.");
1888 if (E->getBody()->isDependentContext()) {
1889 Sema::SFINAETrap Trap(SemaRef);
1890 // We recreate the RequiresExpr body, but not by instantiating it.
1891 // Produce pending diagnostics for dependent access check.
1892 SemaRef.PerformDependentDiagnostics(E->getBody(), TemplateArgs);
1893 // FIXME: Store SFINAE diagnostics in RequiresExpr for diagnosis.
1894 if (Trap.hasErrorOccurred())
1895 TransReq.getAs<RequiresExpr>()->setSatisfied(false);
1896 }
1897 return TransReq;
1898 }
1899
1900 bool TransformRequiresExprRequirements(
1901 ArrayRef<concepts::Requirement *> Reqs,
1902 SmallVectorImpl<concepts::Requirement *> &Transformed) {
1903 bool SatisfactionDetermined = false;
1904 for (concepts::Requirement *Req : Reqs) {
1905 concepts::Requirement *TransReq = nullptr;
1906 if (!SatisfactionDetermined) {
1907 if (auto *TypeReq = dyn_cast<concepts::TypeRequirement>(Req))
1908 TransReq = TransformTypeRequirement(TypeReq);
1909 else if (auto *ExprReq = dyn_cast<concepts::ExprRequirement>(Req))
1910 TransReq = TransformExprRequirement(ExprReq);
1911 else
1912 TransReq = TransformNestedRequirement(
1914 if (!TransReq)
1915 return true;
1916 if (!TransReq->isDependent() && !TransReq->isSatisfied())
1917 // [expr.prim.req]p6
1918 // [...] The substitution and semantic constraint checking
1919 // proceeds in lexical order and stops when a condition that
1920 // determines the result of the requires-expression is
1921 // encountered. [..]
1922 SatisfactionDetermined = true;
1923 } else
1924 TransReq = Req;
1925 Transformed.push_back(TransReq);
1926 }
1927 return false;
1928 }
1929
1930 TemplateParameterList *TransformTemplateParameterList(
1931 TemplateParameterList *OrigTPL) {
1932 if (!OrigTPL || !OrigTPL->size()) return OrigTPL;
1933
1934 DeclContext *Owner = OrigTPL->getParam(0)->getDeclContext();
1935 TemplateDeclInstantiator DeclInstantiator(getSema(),
1936 /* DeclContext *Owner */ Owner, TemplateArgs);
1937 DeclInstantiator.setEvaluateConstraints(EvaluateConstraints);
1938 return DeclInstantiator.SubstTemplateParams(OrigTPL);
1939 }
1940
1941 concepts::TypeRequirement *
1942 TransformTypeRequirement(concepts::TypeRequirement *Req);
1943 concepts::ExprRequirement *
1944 TransformExprRequirement(concepts::ExprRequirement *Req);
1945 concepts::NestedRequirement *
1946 TransformNestedRequirement(concepts::NestedRequirement *Req);
1947 ExprResult TransformRequiresTypeParams(
1948 SourceLocation KWLoc, SourceLocation RBraceLoc, const RequiresExpr *RE,
1949 RequiresExprBodyDecl *Body, ArrayRef<ParmVarDecl *> Params,
1950 SmallVectorImpl<QualType> &PTypes,
1951 SmallVectorImpl<ParmVarDecl *> &TransParams,
1952 Sema::ExtParameterInfoBuilder &PInfos);
1953 };
1954}
1955
1956bool TemplateInstantiator::AlreadyTransformed(QualType T) {
1957 if (T.isNull())
1958 return true;
1959
1962 return false;
1963
1964 getSema().MarkDeclarationsReferencedInType(Loc, T);
1965 return true;
1966}
1967
1968Decl *TemplateInstantiator::TransformDecl(SourceLocation Loc, Decl *D) {
1969 if (!D)
1970 return nullptr;
1971
1972 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(D)) {
1973 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1974 // If the corresponding template argument is NULL or non-existent, it's
1975 // because we are performing instantiation from explicitly-specified
1976 // template arguments in a function template, but there were some
1977 // arguments left unspecified.
1978 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
1979 TTP->getPosition())) {
1980 IsIncomplete = true;
1981 return BailOutOnIncomplete ? nullptr : D;
1982 }
1983
1984 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
1985
1986 if (TTP->isParameterPack()) {
1987 assert(Arg.getKind() == TemplateArgument::Pack &&
1988 "Missing argument pack");
1989 Arg = SemaRef.getPackSubstitutedTemplateArgument(Arg);
1990 }
1991
1993 assert(!Template.isNull() && Template.getAsTemplateDecl() &&
1994 "Wrong kind of template template argument");
1995 return Template.getAsTemplateDecl();
1996 }
1997
1998 // Fall through to find the instantiated declaration for this template
1999 // template parameter.
2000 }
2001
2002 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(D);
2003 PVD && SemaRef.CurrentInstantiationScope &&
2004 (SemaRef.inConstraintSubstitution() ||
2005 SemaRef.inParameterMappingSubstitution()) &&
2006 maybeInstantiateFunctionParameterToScope(PVD))
2007 return nullptr;
2008
2009 return SemaRef.FindInstantiatedDecl(Loc, cast<NamedDecl>(D), TemplateArgs);
2010}
2011
2012bool TemplateInstantiator::maybeInstantiateFunctionParameterToScope(
2013 ParmVarDecl *OldParm) {
2014 if (SemaRef.CurrentInstantiationScope->getInstantiationOfIfExists(OldParm))
2015 return false;
2016
2017 if (!OldParm->isParameterPack())
2018 return !TransformFunctionTypeParam(OldParm, /*indexAdjustment=*/0,
2019 /*NumExpansions=*/std::nullopt,
2020 /*ExpectParameterPack=*/false);
2021
2022 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2023
2024 // Find the parameter packs that could be expanded.
2025 TypeLoc TL = OldParm->getTypeSourceInfo()->getTypeLoc();
2026 PackExpansionTypeLoc ExpansionTL = TL.castAs<PackExpansionTypeLoc>();
2027 TypeLoc Pattern = ExpansionTL.getPatternLoc();
2028 SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
2029 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
2030
2031 bool ShouldExpand = false;
2032 bool RetainExpansion = false;
2033 UnsignedOrNone OrigNumExpansions =
2034 ExpansionTL.getTypePtr()->getNumExpansions();
2035 UnsignedOrNone NumExpansions = OrigNumExpansions;
2036 if (TryExpandParameterPacks(ExpansionTL.getEllipsisLoc(),
2037 Pattern.getSourceRange(), Unexpanded,
2038 /*FailOnPackProducingTemplates=*/true,
2039 ShouldExpand, RetainExpansion, NumExpansions))
2040 return true;
2041
2042 assert(ShouldExpand && !RetainExpansion &&
2043 "Shouldn't preserve pack expansion when evaluating constraints");
2044 ExpandingFunctionParameterPack(OldParm);
2045 for (unsigned I = 0; I != *NumExpansions; ++I) {
2046 Sema::ArgPackSubstIndexRAII SubstIndex(getSema(), I);
2047 if (!TransformFunctionTypeParam(OldParm, /*indexAdjustment=*/0,
2048 /*NumExpansions=*/OrigNumExpansions,
2049 /*ExpectParameterPack=*/false))
2050 return true;
2051 }
2052 return false;
2053}
2054
2055Decl *TemplateInstantiator::TransformDefinition(SourceLocation Loc, Decl *D) {
2056 Decl *Inst = getSema().SubstDecl(D, getSema().CurContext, TemplateArgs);
2057 if (!Inst)
2058 return nullptr;
2059
2060 getSema().CurrentInstantiationScope->InstantiatedLocal(D, Inst);
2061 return Inst;
2062}
2063
2064bool TemplateInstantiator::TransformExceptionSpec(
2065 SourceLocation Loc, FunctionProtoType::ExceptionSpecInfo &ESI,
2066 SmallVectorImpl<QualType> &Exceptions, bool &Changed) {
2067 if (ESI.Type == EST_Uninstantiated) {
2068 ESI.instantiate();
2069 Changed = true;
2070 }
2071 return inherited::TransformExceptionSpec(Loc, ESI, Exceptions, Changed);
2072}
2073
2074NamedDecl *
2075TemplateInstantiator::TransformFirstQualifierInScope(NamedDecl *D,
2076 SourceLocation Loc) {
2077 // If the first part of the nested-name-specifier was a template type
2078 // parameter, instantiate that type parameter down to a tag type.
2079 if (TemplateTypeParmDecl *TTPD = dyn_cast_or_null<TemplateTypeParmDecl>(D)) {
2080 const TemplateTypeParmType *TTP
2081 = cast<TemplateTypeParmType>(getSema().Context.getTypeDeclType(TTPD));
2082
2083 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
2084 // FIXME: This needs testing w/ member access expressions.
2085 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getIndex());
2086
2087 if (TTP->isParameterPack()) {
2088 assert(Arg.getKind() == TemplateArgument::Pack &&
2089 "Missing argument pack");
2090
2091 if (!getSema().ArgPackSubstIndex)
2092 return nullptr;
2093
2094 Arg = SemaRef.getPackSubstitutedTemplateArgument(Arg);
2095 }
2096
2097 QualType T = Arg.getAsType();
2098 if (T.isNull())
2099 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
2100
2101 if (const TagType *Tag = T->getAs<TagType>())
2102 return Tag->getOriginalDecl();
2103
2104 // The resulting type is not a tag; complain.
2105 getSema().Diag(Loc, diag::err_nested_name_spec_non_tag) << T;
2106 return nullptr;
2107 }
2108 }
2109
2110 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
2111}
2112
2113VarDecl *
2114TemplateInstantiator::RebuildExceptionDecl(VarDecl *ExceptionDecl,
2115 TypeSourceInfo *Declarator,
2116 SourceLocation StartLoc,
2117 SourceLocation NameLoc,
2118 IdentifierInfo *Name) {
2119 VarDecl *Var = inherited::RebuildExceptionDecl(ExceptionDecl, Declarator,
2120 StartLoc, NameLoc, Name);
2121 if (Var)
2122 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
2123 return Var;
2124}
2125
2126VarDecl *TemplateInstantiator::RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
2127 TypeSourceInfo *TSInfo,
2128 QualType T) {
2129 VarDecl *Var = inherited::RebuildObjCExceptionDecl(ExceptionDecl, TSInfo, T);
2130 if (Var)
2131 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
2132 return Var;
2133}
2134
2135TemplateName TemplateInstantiator::TransformTemplateName(
2136 NestedNameSpecifierLoc &QualifierLoc, SourceLocation TemplateKWLoc,
2137 TemplateName Name, SourceLocation NameLoc, QualType ObjectType,
2138 NamedDecl *FirstQualifierInScope, bool AllowInjectedClassName) {
2139 if (Name.getKind() == TemplateName::Template) {
2140 assert(!QualifierLoc && "Unexpected qualifier");
2141 if (auto *TTP =
2142 dyn_cast<TemplateTemplateParmDecl>(Name.getAsTemplateDecl());
2143 TTP && TTP->getDepth() < TemplateArgs.getNumLevels()) {
2144 // If the corresponding template argument is NULL or non-existent, it's
2145 // because we are performing instantiation from explicitly-specified
2146 // template arguments in a function template, but there were some
2147 // arguments left unspecified.
2148 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
2149 TTP->getPosition())) {
2150 IsIncomplete = true;
2151 return BailOutOnIncomplete ? TemplateName() : Name;
2152 }
2153
2154 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
2155
2156 if (TemplateArgs.isRewrite()) {
2157 // We're rewriting the template parameter as a reference to another
2158 // template parameter.
2159 Arg = getTemplateArgumentPackPatternForRewrite(Arg);
2160 assert(Arg.getKind() == TemplateArgument::Template &&
2161 "unexpected nontype template argument kind in template rewrite");
2162 return Arg.getAsTemplate();
2163 }
2164
2165 auto [AssociatedDecl, Final] =
2166 TemplateArgs.getAssociatedDecl(TTP->getDepth());
2167 UnsignedOrNone PackIndex = std::nullopt;
2168 if (TTP->isParameterPack()) {
2169 assert(Arg.getKind() == TemplateArgument::Pack &&
2170 "Missing argument pack");
2171
2172 if (!getSema().ArgPackSubstIndex) {
2173 // We have the template argument pack to substitute, but we're not
2174 // actually expanding the enclosing pack expansion yet. So, just
2175 // keep the entire argument pack.
2176 return getSema().Context.getSubstTemplateTemplateParmPack(
2177 Arg, AssociatedDecl, TTP->getIndex(), Final);
2178 }
2179
2180 PackIndex = SemaRef.getPackIndex(Arg);
2181 Arg = SemaRef.getPackSubstitutedTemplateArgument(Arg);
2182 }
2183
2185 assert(!Template.isNull() && "Null template template argument");
2186 return getSema().Context.getSubstTemplateTemplateParm(
2187 Template, AssociatedDecl, TTP->getIndex(), PackIndex, Final);
2188 }
2189 }
2190
2191 if (SubstTemplateTemplateParmPackStorage *SubstPack
2193 if (!getSema().ArgPackSubstIndex)
2194 return Name;
2195
2196 TemplateArgument Pack = SubstPack->getArgumentPack();
2198 SemaRef.getPackSubstitutedTemplateArgument(Pack).getAsTemplate();
2199 return getSema().Context.getSubstTemplateTemplateParm(
2200 Template, SubstPack->getAssociatedDecl(), SubstPack->getIndex(),
2201 SemaRef.getPackIndex(Pack), SubstPack->getFinal());
2202 }
2203
2204 return inherited::TransformTemplateName(
2205 QualifierLoc, TemplateKWLoc, Name, NameLoc, ObjectType,
2206 FirstQualifierInScope, AllowInjectedClassName);
2207}
2208
2210TemplateInstantiator::TransformPredefinedExpr(PredefinedExpr *E) {
2211 if (!E->isTypeDependent())
2212 return E;
2213
2214 return getSema().BuildPredefinedExpr(E->getLocation(), E->getIdentKind());
2215}
2216
2218TemplateInstantiator::TransformTemplateParmRefExpr(DeclRefExpr *E,
2219 NonTypeTemplateParmDecl *NTTP) {
2220 // If the corresponding template argument is NULL or non-existent, it's
2221 // because we are performing instantiation from explicitly-specified
2222 // template arguments in a function template, but there were some
2223 // arguments left unspecified.
2224 if (!TemplateArgs.hasTemplateArgument(NTTP->getDepth(),
2225 NTTP->getPosition())) {
2226 IsIncomplete = true;
2227 return BailOutOnIncomplete ? ExprError() : E;
2228 }
2229
2230 TemplateArgument Arg = TemplateArgs(NTTP->getDepth(), NTTP->getPosition());
2231
2232 if (TemplateArgs.isRewrite()) {
2233 // We're rewriting the template parameter as a reference to another
2234 // template parameter.
2235 Arg = getTemplateArgumentPackPatternForRewrite(Arg);
2236 assert(Arg.getKind() == TemplateArgument::Expression &&
2237 "unexpected nontype template argument kind in template rewrite");
2238 // FIXME: This can lead to the same subexpression appearing multiple times
2239 // in a complete expression.
2240 return Arg.getAsExpr();
2241 }
2242
2243 auto [AssociatedDecl, Final] =
2244 TemplateArgs.getAssociatedDecl(NTTP->getDepth());
2245 UnsignedOrNone PackIndex = std::nullopt;
2246 if (NTTP->isParameterPack()) {
2247 assert(Arg.getKind() == TemplateArgument::Pack &&
2248 "Missing argument pack");
2249
2250 if (!getSema().ArgPackSubstIndex) {
2251 // We have an argument pack, but we can't select a particular argument
2252 // out of it yet. Therefore, we'll build an expression to hold on to that
2253 // argument pack.
2254 QualType TargetType = SemaRef.SubstType(NTTP->getType(), TemplateArgs,
2255 E->getLocation(),
2256 NTTP->getDeclName());
2257 if (TargetType.isNull())
2258 return ExprError();
2259
2260 QualType ExprType = TargetType.getNonLValueExprType(SemaRef.Context);
2261 if (TargetType->isRecordType())
2262 ExprType.addConst();
2263 return new (SemaRef.Context) SubstNonTypeTemplateParmPackExpr(
2264 ExprType, TargetType->isReferenceType() ? VK_LValue : VK_PRValue,
2265 E->getLocation(), Arg, AssociatedDecl, NTTP->getPosition(), Final);
2266 }
2267 PackIndex = SemaRef.getPackIndex(Arg);
2268 Arg = SemaRef.getPackSubstitutedTemplateArgument(Arg);
2269 }
2270 return SemaRef.BuildSubstNonTypeTemplateParmExpr(
2271 AssociatedDecl, NTTP, E->getLocation(), Arg, PackIndex, Final);
2272}
2273
2274const AnnotateAttr *
2275TemplateInstantiator::TransformAnnotateAttr(const AnnotateAttr *AA) {
2276 SmallVector<Expr *> Args;
2277 for (Expr *Arg : AA->args()) {
2278 ExprResult Res = getDerived().TransformExpr(Arg);
2279 if (Res.isUsable())
2280 Args.push_back(Res.get());
2281 }
2282 return AnnotateAttr::CreateImplicit(getSema().Context, AA->getAnnotation(),
2283 Args.data(), Args.size(), AA->getRange());
2284}
2285
2286const CXXAssumeAttr *
2287TemplateInstantiator::TransformCXXAssumeAttr(const CXXAssumeAttr *AA) {
2288 ExprResult Res = getDerived().TransformExpr(AA->getAssumption());
2289 if (!Res.isUsable())
2290 return AA;
2291
2292 if (!(Res.get()->getDependence() & ExprDependence::TypeValueInstantiation)) {
2293 Res = getSema().BuildCXXAssumeExpr(Res.get(), AA->getAttrName(),
2294 AA->getRange());
2295 if (!Res.isUsable())
2296 return AA;
2297 }
2298
2299 return CXXAssumeAttr::CreateImplicit(getSema().Context, Res.get(),
2300 AA->getRange());
2301}
2302
2303const LoopHintAttr *
2304TemplateInstantiator::TransformLoopHintAttr(const LoopHintAttr *LH) {
2305 Expr *TransformedExpr = getDerived().TransformExpr(LH->getValue()).get();
2306
2307 if (TransformedExpr == LH->getValue())
2308 return LH;
2309
2310 // Generate error if there is a problem with the value.
2311 if (getSema().CheckLoopHintExpr(TransformedExpr, LH->getLocation(),
2312 LH->getSemanticSpelling() ==
2313 LoopHintAttr::Pragma_unroll))
2314 return LH;
2315
2316 LoopHintAttr::OptionType Option = LH->getOption();
2317 LoopHintAttr::LoopHintState State = LH->getState();
2318
2319 llvm::APSInt ValueAPS =
2320 TransformedExpr->EvaluateKnownConstInt(getSema().getASTContext());
2321 // The values of 0 and 1 block any unrolling of the loop.
2322 if (ValueAPS.isZero() || ValueAPS.isOne()) {
2323 Option = LoopHintAttr::Unroll;
2324 State = LoopHintAttr::Disable;
2325 }
2326
2327 // Create new LoopHintValueAttr with integral expression in place of the
2328 // non-type template parameter.
2329 return LoopHintAttr::CreateImplicit(getSema().Context, Option, State,
2330 TransformedExpr, *LH);
2331}
2332const NoInlineAttr *TemplateInstantiator::TransformStmtNoInlineAttr(
2333 const Stmt *OrigS, const Stmt *InstS, const NoInlineAttr *A) {
2334 if (!A || getSema().CheckNoInlineAttr(OrigS, InstS, *A))
2335 return nullptr;
2336
2337 return A;
2338}
2339const AlwaysInlineAttr *TemplateInstantiator::TransformStmtAlwaysInlineAttr(
2340 const Stmt *OrigS, const Stmt *InstS, const AlwaysInlineAttr *A) {
2341 if (!A || getSema().CheckAlwaysInlineAttr(OrigS, InstS, *A))
2342 return nullptr;
2343
2344 return A;
2345}
2346
2347const CodeAlignAttr *
2348TemplateInstantiator::TransformCodeAlignAttr(const CodeAlignAttr *CA) {
2349 Expr *TransformedExpr = getDerived().TransformExpr(CA->getAlignment()).get();
2350 return getSema().BuildCodeAlignAttr(*CA, TransformedExpr);
2351}
2352const OpenACCRoutineDeclAttr *
2353TemplateInstantiator::TransformOpenACCRoutineDeclAttr(
2354 const OpenACCRoutineDeclAttr *A) {
2355 llvm_unreachable("RoutineDecl should only be a declaration attribute, as it "
2356 "applies to a Function Decl (and a few places for VarDecl)");
2357}
2358
2359ExprResult TemplateInstantiator::RebuildVarDeclRefExpr(ValueDecl *PD,
2360 SourceLocation Loc) {
2361 DeclarationNameInfo NameInfo(PD->getDeclName(), Loc);
2362 return getSema().BuildDeclarationNameExpr(CXXScopeSpec(), NameInfo, PD);
2363}
2364
2366TemplateInstantiator::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {
2367 if (getSema().ArgPackSubstIndex) {
2368 // We can expand this parameter pack now.
2369 ValueDecl *D = E->getExpansion(*getSema().ArgPackSubstIndex);
2370 ValueDecl *VD = cast_or_null<ValueDecl>(TransformDecl(E->getExprLoc(), D));
2371 if (!VD)
2372 return ExprError();
2373 return RebuildVarDeclRefExpr(VD, E->getExprLoc());
2374 }
2375
2376 QualType T = TransformType(E->getType());
2377 if (T.isNull())
2378 return ExprError();
2379
2380 // Transform each of the parameter expansions into the corresponding
2381 // parameters in the instantiation of the function decl.
2382 SmallVector<ValueDecl *, 8> Vars;
2383 Vars.reserve(E->getNumExpansions());
2384 for (FunctionParmPackExpr::iterator I = E->begin(), End = E->end();
2385 I != End; ++I) {
2386 ValueDecl *D = cast_or_null<ValueDecl>(TransformDecl(E->getExprLoc(), *I));
2387 if (!D)
2388 return ExprError();
2389 Vars.push_back(D);
2390 }
2391
2392 auto *PackExpr =
2394 E->getParameterPackLocation(), Vars);
2395 getSema().MarkFunctionParmPackReferenced(PackExpr);
2396 return PackExpr;
2397}
2398
2400TemplateInstantiator::TransformFunctionParmPackRefExpr(DeclRefExpr *E,
2401 ValueDecl *PD) {
2402 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
2403 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
2404 = getSema().CurrentInstantiationScope->findInstantiationOf(PD);
2405 assert(Found && "no instantiation for parameter pack");
2406
2407 Decl *TransformedDecl;
2408 if (DeclArgumentPack *Pack = dyn_cast<DeclArgumentPack *>(*Found)) {
2409 // If this is a reference to a function parameter pack which we can
2410 // substitute but can't yet expand, build a FunctionParmPackExpr for it.
2411 if (!getSema().ArgPackSubstIndex) {
2412 QualType T = TransformType(E->getType());
2413 if (T.isNull())
2414 return ExprError();
2415 auto *PackExpr = FunctionParmPackExpr::Create(getSema().Context, T, PD,
2416 E->getExprLoc(), *Pack);
2417 getSema().MarkFunctionParmPackReferenced(PackExpr);
2418 return PackExpr;
2419 }
2420
2421 TransformedDecl = (*Pack)[*getSema().ArgPackSubstIndex];
2422 } else {
2423 TransformedDecl = cast<Decl *>(*Found);
2424 }
2425
2426 // We have either an unexpanded pack or a specific expansion.
2427 return RebuildVarDeclRefExpr(cast<ValueDecl>(TransformedDecl),
2428 E->getExprLoc());
2429}
2430
2432TemplateInstantiator::TransformDeclRefExpr(DeclRefExpr *E) {
2433 NamedDecl *D = E->getDecl();
2434
2435 // Handle references to non-type template parameters and non-type template
2436 // parameter packs.
2437 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) {
2438 if (NTTP->getDepth() < TemplateArgs.getNumLevels())
2439 return TransformTemplateParmRefExpr(E, NTTP);
2440
2441 // We have a non-type template parameter that isn't fully substituted;
2442 // FindInstantiatedDecl will find it in the local instantiation scope.
2443 }
2444
2445 // Handle references to function parameter packs.
2446 if (VarDecl *PD = dyn_cast<VarDecl>(D))
2447 if (PD->isParameterPack())
2448 return TransformFunctionParmPackRefExpr(E, PD);
2449
2450 return inherited::TransformDeclRefExpr(E);
2451}
2452
2453ExprResult TemplateInstantiator::TransformCXXDefaultArgExpr(
2454 CXXDefaultArgExpr *E) {
2455 assert(!cast<FunctionDecl>(E->getParam()->getDeclContext())->
2456 getDescribedFunctionTemplate() &&
2457 "Default arg expressions are never formed in dependent cases.");
2458 return SemaRef.BuildCXXDefaultArgExpr(
2460 E->getParam());
2461}
2462
2463template<typename Fn>
2464QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB,
2465 FunctionProtoTypeLoc TL,
2466 CXXRecordDecl *ThisContext,
2467 Qualifiers ThisTypeQuals,
2468 Fn TransformExceptionSpec) {
2469 // If this is a lambda or block, the transformation MUST be done in the
2470 // CurrentInstantiationScope since it introduces a mapping of
2471 // the original to the newly created transformed parameters.
2472 //
2473 // In that case, TemplateInstantiator::TransformLambdaExpr will
2474 // have already pushed a scope for this prototype, so don't create
2475 // a second one.
2476 LocalInstantiationScope *Current = getSema().CurrentInstantiationScope;
2477 std::optional<LocalInstantiationScope> Scope;
2478 if (!Current || !Current->isLambdaOrBlock())
2479 Scope.emplace(SemaRef, /*CombineWithOuterScope=*/true);
2480
2481 return inherited::TransformFunctionProtoType(
2482 TLB, TL, ThisContext, ThisTypeQuals, TransformExceptionSpec);
2483}
2484
2485ParmVarDecl *TemplateInstantiator::TransformFunctionTypeParam(
2486 ParmVarDecl *OldParm, int indexAdjustment, UnsignedOrNone NumExpansions,
2487 bool ExpectParameterPack) {
2488 auto NewParm = SemaRef.SubstParmVarDecl(
2489 OldParm, TemplateArgs, indexAdjustment, NumExpansions,
2490 ExpectParameterPack, EvaluateConstraints);
2491 if (NewParm && SemaRef.getLangOpts().OpenCL)
2492 SemaRef.deduceOpenCLAddressSpace(NewParm);
2493 return NewParm;
2494}
2495
2496QualType TemplateInstantiator::BuildSubstTemplateTypeParmType(
2497 TypeLocBuilder &TLB, bool SuppressObjCLifetime, bool Final,
2498 Decl *AssociatedDecl, unsigned Index, UnsignedOrNone PackIndex,
2499 TemplateArgument Arg, SourceLocation NameLoc) {
2500 QualType Replacement = Arg.getAsType();
2501
2502 // If the template parameter had ObjC lifetime qualifiers,
2503 // then any such qualifiers on the replacement type are ignored.
2504 if (SuppressObjCLifetime) {
2505 Qualifiers RQs;
2506 RQs = Replacement.getQualifiers();
2507 RQs.removeObjCLifetime();
2508 Replacement =
2509 SemaRef.Context.getQualifiedType(Replacement.getUnqualifiedType(), RQs);
2510 }
2511
2512 // TODO: only do this uniquing once, at the start of instantiation.
2513 QualType Result = getSema().Context.getSubstTemplateTypeParmType(
2514 Replacement, AssociatedDecl, Index, PackIndex, Final);
2515 SubstTemplateTypeParmTypeLoc NewTL =
2516 TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
2517 NewTL.setNameLoc(NameLoc);
2518 return Result;
2519}
2520
2521QualType
2522TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB,
2523 TemplateTypeParmTypeLoc TL,
2524 bool SuppressObjCLifetime) {
2525 const TemplateTypeParmType *T = TL.getTypePtr();
2526 if (T->getDepth() < TemplateArgs.getNumLevels()) {
2527 // Replace the template type parameter with its corresponding
2528 // template argument.
2529
2530 // If the corresponding template argument is NULL or doesn't exist, it's
2531 // because we are performing instantiation from explicitly-specified
2532 // template arguments in a function template class, but there were some
2533 // arguments left unspecified.
2534 if (!TemplateArgs.hasTemplateArgument(T->getDepth(), T->getIndex())) {
2535 IsIncomplete = true;
2536 if (BailOutOnIncomplete)
2537 return QualType();
2538
2539 TemplateTypeParmTypeLoc NewTL
2540 = TLB.push<TemplateTypeParmTypeLoc>(TL.getType());
2541 NewTL.setNameLoc(TL.getNameLoc());
2542 return TL.getType();
2543 }
2544
2545 TemplateArgument Arg = TemplateArgs(T->getDepth(), T->getIndex());
2546
2547 if (TemplateArgs.isRewrite()) {
2548 // We're rewriting the template parameter as a reference to another
2549 // template parameter.
2550 Arg = getTemplateArgumentPackPatternForRewrite(Arg);
2551 assert(Arg.getKind() == TemplateArgument::Type &&
2552 "unexpected nontype template argument kind in template rewrite");
2553 QualType NewT = Arg.getAsType();
2554 TLB.pushTrivial(SemaRef.Context, NewT, TL.getNameLoc());
2555 return NewT;
2556 }
2557
2558 auto [AssociatedDecl, Final] =
2559 TemplateArgs.getAssociatedDecl(T->getDepth());
2560 UnsignedOrNone PackIndex = std::nullopt;
2561 if (T->isParameterPack()) {
2562 assert(Arg.getKind() == TemplateArgument::Pack &&
2563 "Missing argument pack");
2564
2565 if (!getSema().ArgPackSubstIndex) {
2566 // We have the template argument pack, but we're not expanding the
2567 // enclosing pack expansion yet. Just save the template argument
2568 // pack for later substitution.
2569 QualType Result = getSema().Context.getSubstTemplateTypeParmPackType(
2570 AssociatedDecl, T->getIndex(), Final, Arg);
2571 SubstTemplateTypeParmPackTypeLoc NewTL
2572 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(Result);
2573 NewTL.setNameLoc(TL.getNameLoc());
2574 return Result;
2575 }
2576
2577 // PackIndex starts from last element.
2578 PackIndex = SemaRef.getPackIndex(Arg);
2579 Arg = SemaRef.getPackSubstitutedTemplateArgument(Arg);
2580 }
2581
2582 assert(Arg.getKind() == TemplateArgument::Type &&
2583 "Template argument kind mismatch");
2584
2585 return BuildSubstTemplateTypeParmType(TLB, SuppressObjCLifetime, Final,
2586 AssociatedDecl, T->getIndex(),
2587 PackIndex, Arg, TL.getNameLoc());
2588 }
2589
2590 // The template type parameter comes from an inner template (e.g.,
2591 // the template parameter list of a member template inside the
2592 // template we are instantiating). Create a new template type
2593 // parameter with the template "level" reduced by one.
2594 TemplateTypeParmDecl *NewTTPDecl = nullptr;
2595 if (TemplateTypeParmDecl *OldTTPDecl = T->getDecl())
2596 NewTTPDecl = cast_or_null<TemplateTypeParmDecl>(
2597 TransformDecl(TL.getNameLoc(), OldTTPDecl));
2598 QualType Result = getSema().Context.getTemplateTypeParmType(
2599 T->getDepth() - TemplateArgs.getNumSubstitutedLevels(), T->getIndex(),
2600 T->isParameterPack(), NewTTPDecl);
2601 TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result);
2602 NewTL.setNameLoc(TL.getNameLoc());
2603 return Result;
2604}
2605
2606QualType TemplateInstantiator::TransformSubstTemplateTypeParmPackType(
2607 TypeLocBuilder &TLB, SubstTemplateTypeParmPackTypeLoc TL,
2608 bool SuppressObjCLifetime) {
2609 const SubstTemplateTypeParmPackType *T = TL.getTypePtr();
2610
2611 Decl *NewReplaced = TransformDecl(TL.getNameLoc(), T->getAssociatedDecl());
2612
2613 if (!getSema().ArgPackSubstIndex) {
2614 // We aren't expanding the parameter pack, so just return ourselves.
2615 QualType Result = TL.getType();
2616 if (NewReplaced != T->getAssociatedDecl())
2617 Result = getSema().Context.getSubstTemplateTypeParmPackType(
2618 NewReplaced, T->getIndex(), T->getFinal(), T->getArgumentPack());
2619 SubstTemplateTypeParmPackTypeLoc NewTL =
2620 TLB.push<SubstTemplateTypeParmPackTypeLoc>(Result);
2621 NewTL.setNameLoc(TL.getNameLoc());
2622 return Result;
2623 }
2624
2625 TemplateArgument Pack = T->getArgumentPack();
2626 TemplateArgument Arg = SemaRef.getPackSubstitutedTemplateArgument(Pack);
2627 return BuildSubstTemplateTypeParmType(
2628 TLB, SuppressObjCLifetime, T->getFinal(), NewReplaced, T->getIndex(),
2629 SemaRef.getPackIndex(Pack), Arg, TL.getNameLoc());
2630}
2631
2632QualType TemplateInstantiator::TransformSubstBuiltinTemplatePackType(
2633 TypeLocBuilder &TLB, SubstBuiltinTemplatePackTypeLoc TL) {
2634 if (!getSema().ArgPackSubstIndex)
2635 return TreeTransform::TransformSubstBuiltinTemplatePackType(TLB, TL);
2636 TemplateArgument Result = SemaRef.getPackSubstitutedTemplateArgument(
2637 TL.getTypePtr()->getArgumentPack());
2638 TLB.pushTrivial(SemaRef.getASTContext(), Result.getAsType(),
2639 TL.getBeginLoc());
2640 return Result.getAsType();
2641}
2642
2643static concepts::Requirement::SubstitutionDiagnostic *
2645 Sema::EntityPrinter Printer) {
2646 SmallString<128> Message;
2647 SourceLocation ErrorLoc;
2648 if (Info.hasSFINAEDiagnostic()) {
2651 Info.takeSFINAEDiagnostic(PDA);
2652 PDA.second.EmitToString(S.getDiagnostics(), Message);
2653 ErrorLoc = PDA.first;
2654 } else {
2655 ErrorLoc = Info.getLocation();
2656 }
2657 SmallString<128> Entity;
2658 llvm::raw_svector_ostream OS(Entity);
2659 Printer(OS);
2660 const ASTContext &C = S.Context;
2662 C.backupStr(Entity), ErrorLoc, C.backupStr(Message)};
2663}
2664
2665concepts::Requirement::SubstitutionDiagnostic *
2667 SmallString<128> Entity;
2668 llvm::raw_svector_ostream OS(Entity);
2669 Printer(OS);
2670 const ASTContext &C = Context;
2672 /*SubstitutedEntity=*/C.backupStr(Entity),
2673 /*DiagLoc=*/Location, /*DiagMessage=*/StringRef()};
2674}
2675
2676ExprResult TemplateInstantiator::TransformRequiresTypeParams(
2677 SourceLocation KWLoc, SourceLocation RBraceLoc, const RequiresExpr *RE,
2680 SmallVectorImpl<ParmVarDecl *> &TransParams,
2682
2683 TemplateDeductionInfo Info(KWLoc);
2684 Sema::InstantiatingTemplate TypeInst(SemaRef, KWLoc,
2685 RE, Info,
2686 SourceRange{KWLoc, RBraceLoc});
2688
2689 unsigned ErrorIdx;
2690 if (getDerived().TransformFunctionTypeParams(
2691 KWLoc, Params, /*ParamTypes=*/nullptr, /*ParamInfos=*/nullptr, PTypes,
2692 &TransParams, PInfos, &ErrorIdx) ||
2693 Trap.hasErrorOccurred()) {
2695 ParmVarDecl *FailedDecl = Params[ErrorIdx];
2696 // Add a 'failed' Requirement to contain the error that caused the failure
2697 // here.
2698 TransReqs.push_back(RebuildTypeRequirement(createSubstDiag(
2699 SemaRef, Info, [&](llvm::raw_ostream &OS) { OS << *FailedDecl; })));
2700 return getDerived().RebuildRequiresExpr(KWLoc, Body, RE->getLParenLoc(),
2701 TransParams, RE->getRParenLoc(),
2702 TransReqs, RBraceLoc);
2703 }
2704
2705 return ExprResult{};
2706}
2707
2708concepts::TypeRequirement *
2709TemplateInstantiator::TransformTypeRequirement(concepts::TypeRequirement *Req) {
2710 if (!Req->isDependent() && !AlwaysRebuild())
2711 return Req;
2712 if (Req->isSubstitutionFailure()) {
2713 if (AlwaysRebuild())
2714 return RebuildTypeRequirement(
2716 return Req;
2717 }
2718
2719 Sema::SFINAETrap Trap(SemaRef);
2720 TemplateDeductionInfo Info(Req->getType()->getTypeLoc().getBeginLoc());
2721 Sema::InstantiatingTemplate TypeInst(SemaRef,
2722 Req->getType()->getTypeLoc().getBeginLoc(), Req, Info,
2723 Req->getType()->getTypeLoc().getSourceRange());
2724 if (TypeInst.isInvalid())
2725 return nullptr;
2726 TypeSourceInfo *TransType = TransformType(Req->getType());
2727 if (!TransType || Trap.hasErrorOccurred())
2728 return RebuildTypeRequirement(createSubstDiag(SemaRef, Info,
2729 [&] (llvm::raw_ostream& OS) {
2730 Req->getType()->getType().print(OS, SemaRef.getPrintingPolicy());
2731 }));
2732 return RebuildTypeRequirement(TransType);
2733}
2734
2735concepts::ExprRequirement *
2736TemplateInstantiator::TransformExprRequirement(concepts::ExprRequirement *Req) {
2737 if (!Req->isDependent() && !AlwaysRebuild())
2738 return Req;
2739
2740 Sema::SFINAETrap Trap(SemaRef);
2741
2742 llvm::PointerUnion<Expr *, concepts::Requirement::SubstitutionDiagnostic *>
2743 TransExpr;
2744 if (Req->isExprSubstitutionFailure())
2745 TransExpr = Req->getExprSubstitutionDiagnostic();
2746 else {
2747 Expr *E = Req->getExpr();
2748 TemplateDeductionInfo Info(E->getBeginLoc());
2749 Sema::InstantiatingTemplate ExprInst(SemaRef, E->getBeginLoc(), Req, Info,
2750 E->getSourceRange());
2751 if (ExprInst.isInvalid())
2752 return nullptr;
2753 ExprResult TransExprRes = TransformExpr(E);
2754 if (!TransExprRes.isInvalid() && !Trap.hasErrorOccurred() &&
2755 TransExprRes.get()->hasPlaceholderType())
2756 TransExprRes = SemaRef.CheckPlaceholderExpr(TransExprRes.get());
2757 if (TransExprRes.isInvalid() || Trap.hasErrorOccurred())
2758 TransExpr = createSubstDiag(SemaRef, Info, [&](llvm::raw_ostream &OS) {
2759 E->printPretty(OS, nullptr, SemaRef.getPrintingPolicy());
2760 });
2761 else
2762 TransExpr = TransExprRes.get();
2763 }
2764
2765 std::optional<concepts::ExprRequirement::ReturnTypeRequirement> TransRetReq;
2766 const auto &RetReq = Req->getReturnTypeRequirement();
2767 if (RetReq.isEmpty())
2768 TransRetReq.emplace();
2769 else if (RetReq.isSubstitutionFailure())
2770 TransRetReq.emplace(RetReq.getSubstitutionDiagnostic());
2771 else if (RetReq.isTypeConstraint()) {
2772 TemplateParameterList *OrigTPL =
2773 RetReq.getTypeConstraintTemplateParameterList();
2774 TemplateDeductionInfo Info(OrigTPL->getTemplateLoc());
2775 Sema::InstantiatingTemplate TPLInst(SemaRef, OrigTPL->getTemplateLoc(),
2776 Req, Info, OrigTPL->getSourceRange());
2777 if (TPLInst.isInvalid())
2778 return nullptr;
2779 TemplateParameterList *TPL = TransformTemplateParameterList(OrigTPL);
2780 if (!TPL || Trap.hasErrorOccurred())
2781 TransRetReq.emplace(createSubstDiag(SemaRef, Info,
2782 [&] (llvm::raw_ostream& OS) {
2783 RetReq.getTypeConstraint()->getImmediatelyDeclaredConstraint()
2784 ->printPretty(OS, nullptr, SemaRef.getPrintingPolicy());
2785 }));
2786 else {
2787 TPLInst.Clear();
2788 TransRetReq.emplace(TPL);
2789 }
2790 }
2791 assert(TransRetReq && "All code paths leading here must set TransRetReq");
2792 if (Expr *E = TransExpr.dyn_cast<Expr *>())
2793 return RebuildExprRequirement(E, Req->isSimple(), Req->getNoexceptLoc(),
2794 std::move(*TransRetReq));
2795 return RebuildExprRequirement(
2797 Req->isSimple(), Req->getNoexceptLoc(), std::move(*TransRetReq));
2798}
2799
2800concepts::NestedRequirement *
2801TemplateInstantiator::TransformNestedRequirement(
2802 concepts::NestedRequirement *Req) {
2803
2804 ASTContext &C = SemaRef.Context;
2805
2806 Expr *Constraint = Req->getConstraintExpr();
2807 ConstraintSatisfaction Satisfaction;
2808
2809 auto NestedReqWithDiag = [&C, this](Expr *E,
2810 ConstraintSatisfaction Satisfaction) {
2811 Satisfaction.IsSatisfied = false;
2812 SmallString<128> Entity;
2813 llvm::raw_svector_ostream OS(Entity);
2814 E->printPretty(OS, nullptr, SemaRef.getPrintingPolicy());
2815 return new (C) concepts::NestedRequirement(
2816 SemaRef.Context, C.backupStr(Entity), std::move(Satisfaction));
2817 };
2818
2819 if (Req->hasInvalidConstraint()) {
2820 if (AlwaysRebuild())
2821 return RebuildNestedRequirement(Req->getInvalidConstraintEntity(),
2823 return Req;
2824 }
2825
2826 if (!getEvaluateConstraints()) {
2827 ExprResult TransConstraint = TransformExpr(Req->getConstraintExpr());
2828 if (TransConstraint.isInvalid() || !TransConstraint.get())
2829 return nullptr;
2830 if (TransConstraint.get()->isInstantiationDependent())
2831 return new (SemaRef.Context)
2832 concepts::NestedRequirement(TransConstraint.get());
2833 ConstraintSatisfaction Satisfaction;
2834 return new (SemaRef.Context) concepts::NestedRequirement(
2835 SemaRef.Context, TransConstraint.get(), Satisfaction);
2836 }
2837
2838 bool Success;
2839 Expr *NewConstraint;
2840 TemplateDeductionInfo Info(Constraint->getBeginLoc());
2841 {
2842 EnterExpressionEvaluationContext ContextRAII(
2844
2845 Sema::InstantiatingTemplate ConstrInst(
2846 SemaRef, Constraint->getBeginLoc(), Req,
2847 Sema::InstantiatingTemplate::ConstraintsCheck(),
2848 Constraint->getSourceRange());
2849
2850 if (ConstrInst.isInvalid())
2851 return nullptr;
2852
2853 Sema::SFINAETrap Trap(SemaRef);
2854
2855 Success = !SemaRef.CheckConstraintSatisfaction(
2856 Req, AssociatedConstraint(Constraint, SemaRef.ArgPackSubstIndex),
2857 TemplateArgs, Constraint->getSourceRange(), Satisfaction,
2858 /*TopLevelConceptId=*/nullptr, &NewConstraint);
2859
2860 assert(!Success || !Trap.hasErrorOccurred() &&
2861 "Substitution failures must be handled "
2862 "by CheckConstraintSatisfaction.");
2863 }
2864
2865 if (!Success || Satisfaction.HasSubstitutionFailure())
2866 return NestedReqWithDiag(Constraint, Satisfaction);
2867
2868 // FIXME: const correctness
2869 // MLTAL might be dependent.
2870 if (!NewConstraint) {
2871 if (!Satisfaction.IsSatisfied)
2872 return NestedReqWithDiag(Constraint, Satisfaction);
2873
2874 NewConstraint = Constraint;
2875 }
2876 return new (C) concepts::NestedRequirement(C, NewConstraint, Satisfaction);
2877}
2878
2881 SourceLocation Loc,
2882 DeclarationName Entity,
2883 bool AllowDeducedTST) {
2884 assert(!CodeSynthesisContexts.empty() &&
2885 "Cannot perform an instantiation without some context on the "
2886 "instantiation stack");
2887
2888 if (!T->getType()->isInstantiationDependentType() &&
2889 !T->getType()->isVariablyModifiedType())
2890 return T;
2891
2892 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
2893 return AllowDeducedTST ? Instantiator.TransformTypeWithDeducedTST(T)
2894 : Instantiator.TransformType(T);
2895}
2896
2899 SourceLocation Loc,
2900 DeclarationName Entity) {
2901 assert(!CodeSynthesisContexts.empty() &&
2902 "Cannot perform an instantiation without some context on the "
2903 "instantiation stack");
2904
2905 if (TL.getType().isNull())
2906 return nullptr;
2907
2910 // FIXME: Make a copy of the TypeLoc data here, so that we can
2911 // return a new TypeSourceInfo. Inefficient!
2912 TypeLocBuilder TLB;
2913 TLB.pushFullCopy(TL);
2914 return TLB.getTypeSourceInfo(Context, TL.getType());
2915 }
2916
2917 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
2918 TypeLocBuilder TLB;
2919 TLB.reserve(TL.getFullDataSize());
2920 QualType Result = Instantiator.TransformType(TLB, TL);
2921 if (Result.isNull())
2922 return nullptr;
2923
2924 return TLB.getTypeSourceInfo(Context, Result);
2925}
2926
2927/// Deprecated form of the above.
2929 const MultiLevelTemplateArgumentList &TemplateArgs,
2930 SourceLocation Loc, DeclarationName Entity,
2931 bool *IsIncompleteSubstitution) {
2932 assert(!CodeSynthesisContexts.empty() &&
2933 "Cannot perform an instantiation without some context on the "
2934 "instantiation stack");
2935
2936 // If T is not a dependent type or a variably-modified type, there
2937 // is nothing to do.
2938 if (!T->isInstantiationDependentType() && !T->isVariablyModifiedType())
2939 return T;
2940
2941 TemplateInstantiator Instantiator(
2942 *this, TemplateArgs, Loc, Entity,
2943 /*BailOutOnIncomplete=*/IsIncompleteSubstitution != nullptr);
2944 QualType QT = Instantiator.TransformType(T);
2945 if (IsIncompleteSubstitution && Instantiator.getIsIncomplete())
2946 *IsIncompleteSubstitution = true;
2947 return QT;
2948}
2949
2951 if (T->getType()->isInstantiationDependentType() ||
2952 T->getType()->isVariablyModifiedType())
2953 return true;
2954
2955 TypeLoc TL = T->getTypeLoc().IgnoreParens();
2956 if (!TL.getAs<FunctionProtoTypeLoc>())
2957 return false;
2958
2960 for (ParmVarDecl *P : FP.getParams()) {
2961 // This must be synthesized from a typedef.
2962 if (!P) continue;
2963
2964 // If there are any parameters, a new TypeSourceInfo that refers to the
2965 // instantiated parameters must be built.
2966 return true;
2967 }
2968
2969 return false;
2970}
2971
2974 SourceLocation Loc,
2975 DeclarationName Entity,
2976 CXXRecordDecl *ThisContext,
2977 Qualifiers ThisTypeQuals,
2978 bool EvaluateConstraints) {
2979 assert(!CodeSynthesisContexts.empty() &&
2980 "Cannot perform an instantiation without some context on the "
2981 "instantiation stack");
2982
2984 return T;
2985
2986 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
2987 Instantiator.setEvaluateConstraints(EvaluateConstraints);
2988
2989 TypeLocBuilder TLB;
2990
2991 TypeLoc TL = T->getTypeLoc();
2992 TLB.reserve(TL.getFullDataSize());
2993
2995
2996 if (FunctionProtoTypeLoc Proto =
2998 // Instantiate the type, other than its exception specification. The
2999 // exception specification is instantiated in InitFunctionInstantiation
3000 // once we've built the FunctionDecl.
3001 // FIXME: Set the exception specification to EST_Uninstantiated here,
3002 // instead of rebuilding the function type again later.
3003 Result = Instantiator.TransformFunctionProtoType(
3004 TLB, Proto, ThisContext, ThisTypeQuals,
3006 bool &Changed) { return false; });
3007 } else {
3008 Result = Instantiator.TransformType(TLB, TL);
3009 }
3010 // When there are errors resolving types, clang may use IntTy as a fallback,
3011 // breaking our assumption that function declarations have function types.
3012 if (Result.isNull() || !Result->isFunctionType())
3013 return nullptr;
3014
3015 return TLB.getTypeSourceInfo(Context, Result);
3016}
3017
3020 SmallVectorImpl<QualType> &ExceptionStorage,
3021 const MultiLevelTemplateArgumentList &Args) {
3022 bool Changed = false;
3023 TemplateInstantiator Instantiator(*this, Args, Loc, DeclarationName());
3024 return Instantiator.TransformExceptionSpec(Loc, ESI, ExceptionStorage,
3025 Changed);
3026}
3027
3029 const MultiLevelTemplateArgumentList &Args) {
3032
3033 SmallVector<QualType, 4> ExceptionStorage;
3034 if (SubstExceptionSpec(New->getTypeSourceInfo()->getTypeLoc().getEndLoc(),
3035 ESI, ExceptionStorage, Args))
3036 // On error, recover by dropping the exception specification.
3037 ESI.Type = EST_None;
3038
3040}
3041
3042namespace {
3043
3044 struct GetContainedInventedTypeParmVisitor :
3045 public TypeVisitor<GetContainedInventedTypeParmVisitor,
3046 TemplateTypeParmDecl *> {
3047 using TypeVisitor<GetContainedInventedTypeParmVisitor,
3048 TemplateTypeParmDecl *>::Visit;
3049
3051 if (T.isNull())
3052 return nullptr;
3053 return Visit(T.getTypePtr());
3054 }
3055 // The deduced type itself.
3056 TemplateTypeParmDecl *VisitTemplateTypeParmType(
3057 const TemplateTypeParmType *T) {
3058 if (!T->getDecl() || !T->getDecl()->isImplicit())
3059 return nullptr;
3060 return T->getDecl();
3061 }
3062
3063 // Only these types can contain 'auto' types, and subsequently be replaced
3064 // by references to invented parameters.
3065
3066 TemplateTypeParmDecl *VisitPointerType(const PointerType *T) {
3067 return Visit(T->getPointeeType());
3068 }
3069
3070 TemplateTypeParmDecl *VisitBlockPointerType(const BlockPointerType *T) {
3071 return Visit(T->getPointeeType());
3072 }
3073
3074 TemplateTypeParmDecl *VisitReferenceType(const ReferenceType *T) {
3075 return Visit(T->getPointeeTypeAsWritten());
3076 }
3077
3078 TemplateTypeParmDecl *VisitMemberPointerType(const MemberPointerType *T) {
3079 return Visit(T->getPointeeType());
3080 }
3081
3082 TemplateTypeParmDecl *VisitArrayType(const ArrayType *T) {
3083 return Visit(T->getElementType());
3084 }
3085
3086 TemplateTypeParmDecl *VisitDependentSizedExtVectorType(
3087 const DependentSizedExtVectorType *T) {
3088 return Visit(T->getElementType());
3089 }
3090
3091 TemplateTypeParmDecl *VisitVectorType(const VectorType *T) {
3092 return Visit(T->getElementType());
3093 }
3094
3095 TemplateTypeParmDecl *VisitFunctionProtoType(const FunctionProtoType *T) {
3096 return VisitFunctionType(T);
3097 }
3098
3099 TemplateTypeParmDecl *VisitFunctionType(const FunctionType *T) {
3100 return Visit(T->getReturnType());
3101 }
3102
3103 TemplateTypeParmDecl *VisitParenType(const ParenType *T) {
3104 return Visit(T->getInnerType());
3105 }
3106
3107 TemplateTypeParmDecl *VisitAttributedType(const AttributedType *T) {
3108 return Visit(T->getModifiedType());
3109 }
3110
3111 TemplateTypeParmDecl *VisitMacroQualifiedType(const MacroQualifiedType *T) {
3112 return Visit(T->getUnderlyingType());
3113 }
3114
3115 TemplateTypeParmDecl *VisitAdjustedType(const AdjustedType *T) {
3116 return Visit(T->getOriginalType());
3117 }
3118
3119 TemplateTypeParmDecl *VisitPackExpansionType(const PackExpansionType *T) {
3120 return Visit(T->getPattern());
3121 }
3122 };
3123
3124} // namespace
3125
3127 TemplateTypeParmDecl *Inst, const TypeConstraint *TC,
3128 const MultiLevelTemplateArgumentList &TemplateArgs,
3129 bool EvaluateConstraints) {
3130 const ASTTemplateArgumentListInfo *TemplArgInfo =
3132
3133 if (!EvaluateConstraints && !inParameterMappingSubstitution()) {
3135 if (!Index)
3136 Index = SemaRef.ArgPackSubstIndex;
3139 return false;
3140 }
3141
3142 TemplateArgumentListInfo InstArgs;
3143
3144 if (TemplArgInfo) {
3145 InstArgs.setLAngleLoc(TemplArgInfo->LAngleLoc);
3146 InstArgs.setRAngleLoc(TemplArgInfo->RAngleLoc);
3147 if (SubstTemplateArguments(TemplArgInfo->arguments(), TemplateArgs,
3148 InstArgs))
3149 return true;
3150 }
3151 return AttachTypeConstraint(
3153 TC->getNamedConcept(),
3154 /*FoundDecl=*/TC->getConceptReference()->getFoundDecl(), &InstArgs, Inst,
3155 Inst->isParameterPack()
3157 ->getEllipsisLoc()
3158 : SourceLocation());
3159}
3160
3163 const MultiLevelTemplateArgumentList &TemplateArgs,
3164 int indexAdjustment, UnsignedOrNone NumExpansions,
3165 bool ExpectParameterPack, bool EvaluateConstraint) {
3166 TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
3167 TypeSourceInfo *NewDI = nullptr;
3168
3169 TypeLoc OldTL = OldDI->getTypeLoc();
3170 if (PackExpansionTypeLoc ExpansionTL = OldTL.getAs<PackExpansionTypeLoc>()) {
3171
3172 // We have a function parameter pack. Substitute into the pattern of the
3173 // expansion.
3174 NewDI = SubstType(ExpansionTL.getPatternLoc(), TemplateArgs,
3175 OldParm->getLocation(), OldParm->getDeclName());
3176 if (!NewDI)
3177 return nullptr;
3178
3179 if (NewDI->getType()->containsUnexpandedParameterPack()) {
3180 // We still have unexpanded parameter packs, which means that
3181 // our function parameter is still a function parameter pack.
3182 // Therefore, make its type a pack expansion type.
3183 NewDI = CheckPackExpansion(NewDI, ExpansionTL.getEllipsisLoc(),
3184 NumExpansions);
3185 } else if (ExpectParameterPack) {
3186 // We expected to get a parameter pack but didn't (because the type
3187 // itself is not a pack expansion type), so complain. This can occur when
3188 // the substitution goes through an alias template that "loses" the
3189 // pack expansion.
3190 Diag(OldParm->getLocation(),
3191 diag::err_function_parameter_pack_without_parameter_packs)
3192 << NewDI->getType();
3193 return nullptr;
3194 }
3195 } else {
3196 NewDI = SubstType(OldDI, TemplateArgs, OldParm->getLocation(),
3197 OldParm->getDeclName());
3198 }
3199
3200 if (!NewDI)
3201 return nullptr;
3202
3203 if (NewDI->getType()->isVoidType()) {
3204 Diag(OldParm->getLocation(), diag::err_param_with_void_type);
3205 return nullptr;
3206 }
3207
3208 // In abbreviated templates, TemplateTypeParmDecls with possible
3209 // TypeConstraints are created when the parameter list is originally parsed.
3210 // The TypeConstraints can therefore reference other functions parameters in
3211 // the abbreviated function template, which is why we must instantiate them
3212 // here, when the instantiated versions of those referenced parameters are in
3213 // scope.
3214 if (TemplateTypeParmDecl *TTP =
3215 GetContainedInventedTypeParmVisitor().Visit(OldDI->getType())) {
3216 if (const TypeConstraint *TC = TTP->getTypeConstraint()) {
3217 auto *Inst = cast_or_null<TemplateTypeParmDecl>(
3218 FindInstantiatedDecl(TTP->getLocation(), TTP, TemplateArgs));
3219 // We will first get here when instantiating the abbreviated function
3220 // template's described function, but we might also get here later.
3221 // Make sure we do not instantiate the TypeConstraint more than once.
3222 if (Inst && !Inst->getTypeConstraint()) {
3223 if (SubstTypeConstraint(Inst, TC, TemplateArgs, EvaluateConstraint))
3224 return nullptr;
3225 }
3226 }
3227 }
3228
3229 ParmVarDecl *NewParm = CheckParameter(Context.getTranslationUnitDecl(),
3230 OldParm->getInnerLocStart(),
3231 OldParm->getLocation(),
3232 OldParm->getIdentifier(),
3233 NewDI->getType(), NewDI,
3234 OldParm->getStorageClass());
3235 if (!NewParm)
3236 return nullptr;
3237
3238 // Mark the (new) default argument as uninstantiated (if any).
3239 if (OldParm->hasUninstantiatedDefaultArg()) {
3240 Expr *Arg = OldParm->getUninstantiatedDefaultArg();
3241 NewParm->setUninstantiatedDefaultArg(Arg);
3242 } else if (OldParm->hasUnparsedDefaultArg()) {
3243 NewParm->setUnparsedDefaultArg();
3244 UnparsedDefaultArgInstantiations[OldParm].push_back(NewParm);
3245 } else if (Expr *Arg = OldParm->getDefaultArg()) {
3246 // Default arguments cannot be substituted until the declaration context
3247 // for the associated function or lambda capture class is available.
3248 // This is necessary for cases like the following where construction of
3249 // the lambda capture class for the outer lambda is dependent on the
3250 // parameter types but where the default argument is dependent on the
3251 // outer lambda's declaration context.
3252 // template <typename T>
3253 // auto f() {
3254 // return [](T = []{ return T{}; }()) { return 0; };
3255 // }
3256 NewParm->setUninstantiatedDefaultArg(Arg);
3257 }
3258
3262
3263 if (OldParm->isParameterPack() && !NewParm->isParameterPack()) {
3264 // Add the new parameter to the instantiated parameter pack.
3265 CurrentInstantiationScope->InstantiatedLocalPackArg(OldParm, NewParm);
3266 } else {
3267 // Introduce an Old -> New mapping
3268 CurrentInstantiationScope->InstantiatedLocal(OldParm, NewParm);
3269 }
3270
3271 // FIXME: OldParm may come from a FunctionProtoType, in which case CurContext
3272 // can be anything, is this right ?
3273 NewParm->setDeclContext(CurContext);
3274
3275 NewParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
3276 OldParm->getFunctionScopeIndex() + indexAdjustment);
3277
3278 InstantiateAttrs(TemplateArgs, OldParm, NewParm);
3279
3280 return NewParm;
3281}
3282
3285 const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
3286 const MultiLevelTemplateArgumentList &TemplateArgs,
3287 SmallVectorImpl<QualType> &ParamTypes,
3289 ExtParameterInfoBuilder &ParamInfos) {
3290 assert(!CodeSynthesisContexts.empty() &&
3291 "Cannot perform an instantiation without some context on the "
3292 "instantiation stack");
3293
3294 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
3295 DeclarationName());
3296 return Instantiator.TransformFunctionTypeParams(
3297 Loc, Params, nullptr, ExtParamInfos, ParamTypes, OutParams, ParamInfos);
3298}
3299
3301 SourceLocation Loc,
3302 ParmVarDecl *Param,
3303 const MultiLevelTemplateArgumentList &TemplateArgs,
3304 bool ForCallExpr) {
3305 FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());
3306 Expr *PatternExpr = Param->getUninstantiatedDefaultArg();
3307
3310
3311 InstantiatingTemplate Inst(*this, Loc, Param, TemplateArgs.getInnermost());
3312 if (Inst.isInvalid())
3313 return true;
3314 if (Inst.isAlreadyInstantiating()) {
3315 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
3316 Param->setInvalidDecl();
3317 return true;
3318 }
3319
3321 // C++ [dcl.fct.default]p5:
3322 // The names in the [default argument] expression are bound, and
3323 // the semantic constraints are checked, at the point where the
3324 // default argument expression appears.
3325 ContextRAII SavedContext(*this, FD);
3326 {
3327 std::optional<LocalInstantiationScope> LIS;
3328
3329 if (ForCallExpr) {
3330 // When instantiating a default argument due to use in a call expression,
3331 // an instantiation scope that includes the parameters of the callee is
3332 // required to satisfy references from the default argument. For example:
3333 // template<typename T> void f(T a, int = decltype(a)());
3334 // void g() { f(0); }
3335 LIS.emplace(*this);
3337 /*ForDefinition*/ false);
3338 if (addInstantiatedParametersToScope(FD, PatternFD, *LIS, TemplateArgs))
3339 return true;
3340 }
3341
3343 Result = SubstInitializer(PatternExpr, TemplateArgs,
3344 /*DirectInit*/ false);
3345 });
3346 }
3347 if (Result.isInvalid())
3348 return true;
3349
3350 if (ForCallExpr) {
3351 // Check the expression as an initializer for the parameter.
3352 InitializedEntity Entity
3355 Param->getLocation(),
3356 /*FIXME:EqualLoc*/ PatternExpr->getBeginLoc());
3357 Expr *ResultE = Result.getAs<Expr>();
3358
3359 InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
3360 Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
3361 if (Result.isInvalid())
3362 return true;
3363
3364 Result =
3365 ActOnFinishFullExpr(Result.getAs<Expr>(), Param->getOuterLocStart(),
3366 /*DiscardedValue*/ false);
3367 } else {
3368 // FIXME: Obtain the source location for the '=' token.
3369 SourceLocation EqualLoc = PatternExpr->getBeginLoc();
3370 Result = ConvertParamDefaultArgument(Param, Result.getAs<Expr>(), EqualLoc);
3371 }
3372 if (Result.isInvalid())
3373 return true;
3374
3375 // Remember the instantiated default argument.
3376 Param->setDefaultArg(Result.getAs<Expr>());
3377
3378 return false;
3379}
3380
3381// See TreeTransform::PreparePackForExpansion for the relevant comment.
3382// This function implements the same concept for base specifiers.
3383static bool
3385 const MultiLevelTemplateArgumentList &TemplateArgs,
3386 TypeSourceInfo *&Out, UnexpandedInfo &Info) {
3387 SourceRange BaseSourceRange = Base.getSourceRange();
3388 SourceLocation BaseEllipsisLoc = Base.getEllipsisLoc();
3389 Info.Ellipsis = Base.getEllipsisLoc();
3390 auto ComputeInfo = [&S, &TemplateArgs, BaseSourceRange, BaseEllipsisLoc](
3391 TypeSourceInfo *BaseTypeInfo,
3392 bool IsLateExpansionAttempt, UnexpandedInfo &Info) {
3393 // This is a pack expansion. See whether we should expand it now, or
3394 // wait until later.
3396 S.collectUnexpandedParameterPacks(BaseTypeInfo->getTypeLoc(), Unexpanded);
3397 if (IsLateExpansionAttempt) {
3398 // Request expansion only when there is an opportunity to expand a pack
3399 // that required a substituion first.
3400 bool SawPackTypes =
3401 llvm::any_of(Unexpanded, [](UnexpandedParameterPack P) {
3402 return P.first.dyn_cast<const SubstBuiltinTemplatePackType *>();
3403 });
3404 if (!SawPackTypes) {
3405 Info.Expand = false;
3406 return false;
3407 }
3408 }
3409
3410 // Determine whether the set of unexpanded parameter packs can and should be
3411 // expanded.
3412 Info.Expand = false;
3413 Info.RetainExpansion = false;
3414 Info.NumExpansions = std::nullopt;
3416 BaseEllipsisLoc, BaseSourceRange, Unexpanded, TemplateArgs,
3417 /*FailOnPackProducingTemplates=*/false, Info.Expand,
3418 Info.RetainExpansion, Info.NumExpansions);
3419 };
3420
3421 if (ComputeInfo(Base.getTypeSourceInfo(), false, Info))
3422 return true;
3423
3424 if (Info.Expand) {
3425 Out = Base.getTypeSourceInfo();
3426 return false;
3427 }
3428
3429 // The resulting base specifier will (still) be a pack expansion.
3430 {
3431 Sema::ArgPackSubstIndexRAII SubstIndex(S, std::nullopt);
3432 Out = S.SubstType(Base.getTypeSourceInfo(), TemplateArgs,
3433 BaseSourceRange.getBegin(), DeclarationName());
3434 }
3435 if (!Out->getType()->containsUnexpandedParameterPack())
3436 return false;
3437
3438 // Some packs will learn their length after substitution.
3439 // We may need to request their expansion.
3440 if (ComputeInfo(Out, /*IsLateExpansionAttempt=*/true, Info))
3441 return true;
3442 if (Info.Expand)
3443 Info.ExpandUnderForgetSubstitions = true;
3444 return false;
3445}
3446
3447bool
3449 CXXRecordDecl *Pattern,
3450 const MultiLevelTemplateArgumentList &TemplateArgs) {
3451 bool Invalid = false;
3452 SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases;
3453 for (const auto &Base : Pattern->bases()) {
3454 if (!Base.getType()->isDependentType()) {
3455 if (const CXXRecordDecl *RD = Base.getType()->getAsCXXRecordDecl()) {
3456 if (RD->isInvalidDecl())
3457 Instantiation->setInvalidDecl();
3458 }
3459 InstantiatedBases.push_back(new (Context) CXXBaseSpecifier(Base));
3460 continue;
3461 }
3462
3463 SourceLocation EllipsisLoc;
3464 TypeSourceInfo *BaseTypeLoc = nullptr;
3465 if (Base.isPackExpansion()) {
3466 UnexpandedInfo Info;
3467 if (PreparePackForExpansion(*this, Base, TemplateArgs, BaseTypeLoc,
3468 Info)) {
3469 Invalid = true;
3470 continue;
3471 }
3472
3473 // If we should expand this pack expansion now, do so.
3475 const MultiLevelTemplateArgumentList *ArgsForSubst = &TemplateArgs;
3477 ArgsForSubst = &EmptyList;
3478
3479 if (Info.Expand) {
3480 for (unsigned I = 0; I != *Info.NumExpansions; ++I) {
3481 Sema::ArgPackSubstIndexRAII SubstIndex(*this, I);
3482
3483 TypeSourceInfo *Expanded =
3484 SubstType(BaseTypeLoc, *ArgsForSubst,
3485 Base.getSourceRange().getBegin(), DeclarationName());
3486 if (!Expanded) {
3487 Invalid = true;
3488 continue;
3489 }
3490
3491 if (CXXBaseSpecifier *InstantiatedBase = CheckBaseSpecifier(
3492 Instantiation, Base.getSourceRange(), Base.isVirtual(),
3493 Base.getAccessSpecifierAsWritten(), Expanded,
3494 SourceLocation()))
3495 InstantiatedBases.push_back(InstantiatedBase);
3496 else
3497 Invalid = true;
3498 }
3499
3500 continue;
3501 }
3502
3503 // The resulting base specifier will (still) be a pack expansion.
3504 EllipsisLoc = Base.getEllipsisLoc();
3505 Sema::ArgPackSubstIndexRAII SubstIndex(*this, std::nullopt);
3506 BaseTypeLoc =
3507 SubstType(BaseTypeLoc, *ArgsForSubst,
3508 Base.getSourceRange().getBegin(), DeclarationName());
3509 } else {
3510 BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
3511 TemplateArgs,
3512 Base.getSourceRange().getBegin(),
3513 DeclarationName());
3514 }
3515
3516 if (!BaseTypeLoc) {
3517 Invalid = true;
3518 continue;
3519 }
3520
3521 if (CXXBaseSpecifier *InstantiatedBase
3522 = CheckBaseSpecifier(Instantiation,
3523 Base.getSourceRange(),
3524 Base.isVirtual(),
3525 Base.getAccessSpecifierAsWritten(),
3526 BaseTypeLoc,
3527 EllipsisLoc))
3528 InstantiatedBases.push_back(InstantiatedBase);
3529 else
3530 Invalid = true;
3531 }
3532
3533 if (!Invalid && AttachBaseSpecifiers(Instantiation, InstantiatedBases))
3534 Invalid = true;
3535
3536 return Invalid;
3537}
3538
3539// Defined via #include from SemaTemplateInstantiateDecl.cpp
3540namespace clang {
3541 namespace sema {
3543 const MultiLevelTemplateArgumentList &TemplateArgs);
3545 const Attr *At, ASTContext &C, Sema &S,
3546 const MultiLevelTemplateArgumentList &TemplateArgs);
3547 }
3548}
3549
3550bool
3552 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
3553 const MultiLevelTemplateArgumentList &TemplateArgs,
3555 bool Complain) {
3556 CXXRecordDecl *PatternDef
3557 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
3558 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
3559 Instantiation->getInstantiatedFromMemberClass(),
3560 Pattern, PatternDef, TSK, Complain))
3561 return true;
3562
3563 llvm::TimeTraceScope TimeScope("InstantiateClass", [&]() {
3564 llvm::TimeTraceMetadata M;
3565 llvm::raw_string_ostream OS(M.Detail);
3566 Instantiation->getNameForDiagnostic(OS, getPrintingPolicy(),
3567 /*Qualified=*/true);
3568 if (llvm::isTimeTraceVerbose()) {
3569 auto Loc = SourceMgr.getExpansionLoc(Instantiation->getLocation());
3570 M.File = SourceMgr.getFilename(Loc);
3571 M.Line = SourceMgr.getExpansionLineNumber(Loc);
3572 }
3573 return M;
3574 });
3575
3576 Pattern = PatternDef;
3577
3578 // Record the point of instantiation.
3579 if (MemberSpecializationInfo *MSInfo
3580 = Instantiation->getMemberSpecializationInfo()) {
3581 MSInfo->setTemplateSpecializationKind(TSK);
3582 MSInfo->setPointOfInstantiation(PointOfInstantiation);
3583 } else if (ClassTemplateSpecializationDecl *Spec
3584 = dyn_cast<ClassTemplateSpecializationDecl>(Instantiation)) {
3585 Spec->setTemplateSpecializationKind(TSK);
3586 Spec->setPointOfInstantiation(PointOfInstantiation);
3587 }
3588
3589 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
3590 if (Inst.isInvalid())
3591 return true;
3592 assert(!Inst.isAlreadyInstantiating() && "should have been caught by caller");
3593 PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
3594 "instantiating class definition");
3595
3596 // Enter the scope of this instantiation. We don't use
3597 // PushDeclContext because we don't have a scope.
3598 ContextRAII SavedContext(*this, Instantiation);
3601
3602 // If this is an instantiation of a local class, merge this local
3603 // instantiation scope with the enclosing scope. Otherwise, every
3604 // instantiation of a class has its own local instantiation scope.
3605 bool MergeWithParentScope = !Instantiation->isDefinedOutsideFunctionOrMethod();
3606 LocalInstantiationScope Scope(*this, MergeWithParentScope);
3607
3608 // Some class state isn't processed immediately but delayed till class
3609 // instantiation completes. We may not be ready to handle any delayed state
3610 // already on the stack as it might correspond to a different class, so save
3611 // it now and put it back later.
3612 SavePendingParsedClassStateRAII SavedPendingParsedClassState(*this);
3613
3614 // Pull attributes from the pattern onto the instantiation.
3615 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
3616
3617 // Start the definition of this instantiation.
3618 Instantiation->startDefinition();
3619
3620 // The instantiation is visible here, even if it was first declared in an
3621 // unimported module.
3622 Instantiation->setVisibleDespiteOwningModule();
3623
3624 // FIXME: This loses the as-written tag kind for an explicit instantiation.
3625 Instantiation->setTagKind(Pattern->getTagKind());
3626
3627 // Do substitution on the base class specifiers.
3628 if (SubstBaseSpecifiers(Instantiation, Pattern, TemplateArgs))
3629 Instantiation->setInvalidDecl();
3630
3631 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
3632 Instantiator.setEvaluateConstraints(false);
3633 SmallVector<Decl*, 4> Fields;
3634 // Delay instantiation of late parsed attributes.
3635 LateInstantiatedAttrVec LateAttrs;
3636 Instantiator.enableLateAttributeInstantiation(&LateAttrs);
3637
3638 bool MightHaveConstexprVirtualFunctions = false;
3639 for (auto *Member : Pattern->decls()) {
3640 // Don't instantiate members not belonging in this semantic context.
3641 // e.g. for:
3642 // @code
3643 // template <int i> class A {
3644 // class B *g;
3645 // };
3646 // @endcode
3647 // 'class B' has the template as lexical context but semantically it is
3648 // introduced in namespace scope.
3649 if (Member->getDeclContext() != Pattern)
3650 continue;
3651
3652 // BlockDecls can appear in a default-member-initializer. They must be the
3653 // child of a BlockExpr, so we only know how to instantiate them from there.
3654 // Similarly, lambda closure types are recreated when instantiating the
3655 // corresponding LambdaExpr.
3656 if (isa<BlockDecl>(Member) ||
3658 continue;
3659
3660 if (Member->isInvalidDecl()) {
3661 Instantiation->setInvalidDecl();
3662 continue;
3663 }
3664
3665 Decl *NewMember = Instantiator.Visit(Member);
3666 if (NewMember) {
3667 if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember)) {
3668 Fields.push_back(Field);
3669 } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(NewMember)) {
3670 // C++11 [temp.inst]p1: The implicit instantiation of a class template
3671 // specialization causes the implicit instantiation of the definitions
3672 // of unscoped member enumerations.
3673 // Record a point of instantiation for this implicit instantiation.
3674 if (TSK == TSK_ImplicitInstantiation && !Enum->isScoped() &&
3675 Enum->isCompleteDefinition()) {
3676 MemberSpecializationInfo *MSInfo =Enum->getMemberSpecializationInfo();
3677 assert(MSInfo && "no spec info for member enum specialization");
3679 MSInfo->setPointOfInstantiation(PointOfInstantiation);
3680 }
3681 } else if (StaticAssertDecl *SA = dyn_cast<StaticAssertDecl>(NewMember)) {
3682 if (SA->isFailed()) {
3683 // A static_assert failed. Bail out; instantiating this
3684 // class is probably not meaningful.
3685 Instantiation->setInvalidDecl();
3686 break;
3687 }
3688 } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewMember)) {
3689 if (MD->isConstexpr() && !MD->getFriendObjectKind() &&
3690 (MD->isVirtualAsWritten() || Instantiation->getNumBases()))
3691 MightHaveConstexprVirtualFunctions = true;
3692 }
3693
3694 if (NewMember->isInvalidDecl())
3695 Instantiation->setInvalidDecl();
3696 } else {
3697 // FIXME: Eventually, a NULL return will mean that one of the
3698 // instantiations was a semantic disaster, and we'll want to mark the
3699 // declaration invalid.
3700 // For now, we expect to skip some members that we can't yet handle.
3701 }
3702 }
3703
3704 // Finish checking fields.
3705 ActOnFields(nullptr, Instantiation->getLocation(), Instantiation, Fields,
3707 CheckCompletedCXXClass(nullptr, Instantiation);
3708
3709 // Default arguments are parsed, if not instantiated. We can go instantiate
3710 // default arg exprs for default constructors if necessary now. Unless we're
3711 // parsing a class, in which case wait until that's finished.
3712 if (ParsingClassDepth == 0)
3714
3715 // Instantiate late parsed attributes, and attach them to their decls.
3716 // See Sema::InstantiateAttrs
3717 for (LateInstantiatedAttrVec::iterator I = LateAttrs.begin(),
3718 E = LateAttrs.end(); I != E; ++I) {
3719 assert(CurrentInstantiationScope == Instantiator.getStartingScope());
3720 CurrentInstantiationScope = I->Scope;
3721
3722 // Allow 'this' within late-parsed attributes.
3723 auto *ND = cast<NamedDecl>(I->NewDecl);
3724 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
3725 CXXThisScopeRAII ThisScope(*this, ThisContext, Qualifiers(),
3726 ND->isCXXInstanceMember());
3727
3728 Attr *NewAttr =
3729 instantiateTemplateAttribute(I->TmplAttr, Context, *this, TemplateArgs);
3730 if (NewAttr)
3731 I->NewDecl->addAttr(NewAttr);
3733 Instantiator.getStartingScope());
3734 }
3735 Instantiator.disableLateAttributeInstantiation();
3736 LateAttrs.clear();
3737
3739
3740 // FIXME: We should do something similar for explicit instantiations so they
3741 // end up in the right module.
3742 if (TSK == TSK_ImplicitInstantiation) {
3743 Instantiation->setLocation(Pattern->getLocation());
3744 Instantiation->setLocStart(Pattern->getInnerLocStart());
3745 Instantiation->setBraceRange(Pattern->getBraceRange());
3746 }
3747
3748 if (!Instantiation->isInvalidDecl()) {
3749 // Perform any dependent diagnostics from the pattern.
3750 if (Pattern->isDependentContext())
3751 PerformDependentDiagnostics(Pattern, TemplateArgs);
3752
3753 // Instantiate any out-of-line class template partial
3754 // specializations now.
3756 P = Instantiator.delayed_partial_spec_begin(),
3757 PEnd = Instantiator.delayed_partial_spec_end();
3758 P != PEnd; ++P) {
3760 P->first, P->second)) {
3761 Instantiation->setInvalidDecl();
3762 break;
3763 }
3764 }
3765
3766 // Instantiate any out-of-line variable template partial
3767 // specializations now.
3769 P = Instantiator.delayed_var_partial_spec_begin(),
3770 PEnd = Instantiator.delayed_var_partial_spec_end();
3771 P != PEnd; ++P) {
3773 P->first, P->second)) {
3774 Instantiation->setInvalidDecl();
3775 break;
3776 }
3777 }
3778 }
3779
3780 // Exit the scope of this instantiation.
3781 SavedContext.pop();
3782
3783 if (!Instantiation->isInvalidDecl()) {
3784 // Always emit the vtable for an explicit instantiation definition
3785 // of a polymorphic class template specialization. Otherwise, eagerly
3786 // instantiate only constexpr virtual functions in preparation for their use
3787 // in constant evaluation.
3789 MarkVTableUsed(PointOfInstantiation, Instantiation, true);
3790 else if (MightHaveConstexprVirtualFunctions)
3791 MarkVirtualMembersReferenced(PointOfInstantiation, Instantiation,
3792 /*ConstexprOnly*/ true);
3793 }
3794
3795 Consumer.HandleTagDeclDefinition(Instantiation);
3796
3797 return Instantiation->isInvalidDecl();
3798}
3799
3800bool Sema::InstantiateEnum(SourceLocation PointOfInstantiation,
3801 EnumDecl *Instantiation, EnumDecl *Pattern,
3802 const MultiLevelTemplateArgumentList &TemplateArgs,
3804 EnumDecl *PatternDef = Pattern->getDefinition();
3805 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
3806 Instantiation->getInstantiatedFromMemberEnum(),
3807 Pattern, PatternDef, TSK,/*Complain*/true))
3808 return true;
3809 Pattern = PatternDef;
3810
3811 // Record the point of instantiation.
3812 if (MemberSpecializationInfo *MSInfo
3813 = Instantiation->getMemberSpecializationInfo()) {
3814 MSInfo->setTemplateSpecializationKind(TSK);
3815 MSInfo->setPointOfInstantiation(PointOfInstantiation);
3816 }
3817
3818 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
3819 if (Inst.isInvalid())
3820 return true;
3821 if (Inst.isAlreadyInstantiating())
3822 return false;
3823 PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
3824 "instantiating enum definition");
3825
3826 // The instantiation is visible here, even if it was first declared in an
3827 // unimported module.
3828 Instantiation->setVisibleDespiteOwningModule();
3829
3830 // Enter the scope of this instantiation. We don't use
3831 // PushDeclContext because we don't have a scope.
3832 ContextRAII SavedContext(*this, Instantiation);
3835
3836 LocalInstantiationScope Scope(*this, /*MergeWithParentScope*/true);
3837
3838 // Pull attributes from the pattern onto the instantiation.
3839 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
3840
3841 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
3842 Instantiator.InstantiateEnumDefinition(Instantiation, Pattern);
3843
3844 // Exit the scope of this instantiation.
3845 SavedContext.pop();
3846
3847 return Instantiation->isInvalidDecl();
3848}
3849
3851 SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
3852 FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs) {
3853 // If there is no initializer, we don't need to do anything.
3854 if (!Pattern->hasInClassInitializer())
3855 return false;
3856
3857 assert(Instantiation->getInClassInitStyle() ==
3858 Pattern->getInClassInitStyle() &&
3859 "pattern and instantiation disagree about init style");
3860
3861 // Error out if we haven't parsed the initializer of the pattern yet because
3862 // we are waiting for the closing brace of the outer class.
3863 Expr *OldInit = Pattern->getInClassInitializer();
3864 if (!OldInit) {
3865 RecordDecl *PatternRD = Pattern->getParent();
3866 RecordDecl *OutermostClass = PatternRD->getOuterLexicalRecordContext();
3867 Diag(PointOfInstantiation,
3868 diag::err_default_member_initializer_not_yet_parsed)
3869 << OutermostClass << Pattern;
3870 Diag(Pattern->getEndLoc(),
3871 diag::note_default_member_initializer_not_yet_parsed);
3872 Instantiation->setInvalidDecl();
3873 return true;
3874 }
3875
3876 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
3877 if (Inst.isInvalid())
3878 return true;
3879 if (Inst.isAlreadyInstantiating()) {
3880 // Error out if we hit an instantiation cycle for this initializer.
3881 Diag(PointOfInstantiation, diag::err_default_member_initializer_cycle)
3882 << Instantiation;
3883 return true;
3884 }
3885 PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
3886 "instantiating default member init");
3887
3888 // Enter the scope of this instantiation. We don't use PushDeclContext because
3889 // we don't have a scope.
3890 ContextRAII SavedContext(*this, Instantiation->getParent());
3893 ExprEvalContexts.back().DelayedDefaultInitializationContext = {
3894 PointOfInstantiation, Instantiation, CurContext};
3895
3896 LocalInstantiationScope Scope(*this, true);
3897
3898 // Instantiate the initializer.
3900 CXXThisScopeRAII ThisScope(*this, Instantiation->getParent(), Qualifiers());
3901
3902 ExprResult NewInit = SubstInitializer(OldInit, TemplateArgs,
3903 /*CXXDirectInit=*/false);
3904 Expr *Init = NewInit.get();
3905 assert((!Init || !isa<ParenListExpr>(Init)) && "call-style init in class");
3907 Instantiation, Init ? Init->getBeginLoc() : SourceLocation(), Init);
3908
3909 if (auto *L = getASTMutationListener())
3910 L->DefaultMemberInitializerInstantiated(Instantiation);
3911
3912 // Return true if the in-class initializer is still missing.
3913 return !Instantiation->getInClassInitializer();
3914}
3915
3916namespace {
3917 /// A partial specialization whose template arguments have matched
3918 /// a given template-id.
3919 struct PartialSpecMatchResult {
3922 };
3923}
3924
3926 SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec) {
3927 if (ClassTemplateSpec->getTemplateSpecializationKind() ==
3929 return true;
3930
3932 ClassTemplateDecl *CTD = ClassTemplateSpec->getSpecializedTemplate();
3933 CTD->getPartialSpecializations(PartialSpecs);
3934 for (ClassTemplatePartialSpecializationDecl *CTPSD : PartialSpecs) {
3935 // C++ [temp.spec.partial.member]p2:
3936 // If the primary member template is explicitly specialized for a given
3937 // (implicit) specialization of the enclosing class template, the partial
3938 // specializations of the member template are ignored for this
3939 // specialization of the enclosing class template. If a partial
3940 // specialization of the member template is explicitly specialized for a
3941 // given (implicit) specialization of the enclosing class template, the
3942 // primary member template and its other partial specializations are still
3943 // considered for this specialization of the enclosing class template.
3945 !CTPSD->getMostRecentDecl()->isMemberSpecialization())
3946 continue;
3947
3948 TemplateDeductionInfo Info(Loc);
3949 if (DeduceTemplateArguments(CTPSD,
3950 ClassTemplateSpec->getTemplateArgs().asArray(),
3952 return true;
3953 }
3954
3955 return false;
3956}
3957
3958/// Get the instantiation pattern to use to instantiate the definition of a
3959/// given ClassTemplateSpecializationDecl (either the pattern of the primary
3960/// template or of a partial specialization).
3962 Sema &S, SourceLocation PointOfInstantiation,
3963 ClassTemplateSpecializationDecl *ClassTemplateSpec,
3964 TemplateSpecializationKind TSK, bool PrimaryStrictPackMatch) {
3965 Sema::InstantiatingTemplate Inst(S, PointOfInstantiation, ClassTemplateSpec);
3966 if (Inst.isInvalid())
3967 return {/*Invalid=*/true};
3968 if (Inst.isAlreadyInstantiating())
3969 return {/*Invalid=*/false};
3970
3971 llvm::PointerUnion<ClassTemplateDecl *,
3973 Specialized = ClassTemplateSpec->getSpecializedTemplateOrPartial();
3975 // Find best matching specialization.
3976 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
3977
3978 // C++ [temp.class.spec.match]p1:
3979 // When a class template is used in a context that requires an
3980 // instantiation of the class, it is necessary to determine
3981 // whether the instantiation is to be generated using the primary
3982 // template or one of the partial specializations. This is done by
3983 // matching the template arguments of the class template
3984 // specialization with the template argument lists of the partial
3985 // specializations.
3986 typedef PartialSpecMatchResult MatchResult;
3987 SmallVector<MatchResult, 4> Matched, ExtraMatched;
3989 Template->getPartialSpecializations(PartialSpecs);
3990 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation);
3991 for (ClassTemplatePartialSpecializationDecl *Partial : PartialSpecs) {
3992 // C++ [temp.spec.partial.member]p2:
3993 // If the primary member template is explicitly specialized for a given
3994 // (implicit) specialization of the enclosing class template, the
3995 // partial specializations of the member template are ignored for this
3996 // specialization of the enclosing class template. If a partial
3997 // specialization of the member template is explicitly specialized for a
3998 // given (implicit) specialization of the enclosing class template, the
3999 // primary member template and its other partial specializations are
4000 // still considered for this specialization of the enclosing class
4001 // template.
4002 if (Template->getMostRecentDecl()->isMemberSpecialization() &&
4003 !Partial->getMostRecentDecl()->isMemberSpecialization())
4004 continue;
4005
4006 TemplateDeductionInfo Info(FailedCandidates.getLocation());
4008 Partial, ClassTemplateSpec->getTemplateArgs().asArray(), Info);
4010 // Store the failed-deduction information for use in diagnostics, later.
4011 // TODO: Actually use the failed-deduction info?
4012 FailedCandidates.addCandidate().set(
4014 MakeDeductionFailureInfo(S.Context, Result, Info));
4015 (void)Result;
4016 } else {
4017 auto &List = Info.hasStrictPackMatch() ? ExtraMatched : Matched;
4018 List.push_back(MatchResult{Partial, Info.takeCanonical()});
4019 }
4020 }
4021 if (Matched.empty() && PrimaryStrictPackMatch)
4022 Matched = std::move(ExtraMatched);
4023
4024 // If we're dealing with a member template where the template parameters
4025 // have been instantiated, this provides the original template parameters
4026 // from which the member template's parameters were instantiated.
4027
4028 if (Matched.size() >= 1) {
4029 SmallVectorImpl<MatchResult>::iterator Best = Matched.begin();
4030 if (Matched.size() == 1) {
4031 // -- If exactly one matching specialization is found, the
4032 // instantiation is generated from that specialization.
4033 // We don't need to do anything for this.
4034 } else {
4035 // -- If more than one matching specialization is found, the
4036 // partial order rules (14.5.4.2) are used to determine
4037 // whether one of the specializations is more specialized
4038 // than the others. If none of the specializations is more
4039 // specialized than all of the other matching
4040 // specializations, then the use of the class template is
4041 // ambiguous and the program is ill-formed.
4043 PEnd = Matched.end();
4044 P != PEnd; ++P) {
4046 P->Partial, Best->Partial, PointOfInstantiation) ==
4047 P->Partial)
4048 Best = P;
4049 }
4050
4051 // Determine if the best partial specialization is more specialized than
4052 // the others.
4053 bool Ambiguous = false;
4054 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
4055 PEnd = Matched.end();
4056 P != PEnd; ++P) {
4057 if (P != Best && S.getMoreSpecializedPartialSpecialization(
4058 P->Partial, Best->Partial,
4059 PointOfInstantiation) != Best->Partial) {
4060 Ambiguous = true;
4061 break;
4062 }
4063 }
4064
4065 if (Ambiguous) {
4066 // Partial ordering did not produce a clear winner. Complain.
4067 Inst.Clear();
4068 S.Diag(PointOfInstantiation,
4069 diag::err_partial_spec_ordering_ambiguous)
4070 << ClassTemplateSpec;
4071
4072 // Print the matching partial specializations.
4073 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
4074 PEnd = Matched.end();
4075 P != PEnd; ++P)
4076 S.Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
4078 P->Partial->getTemplateParameters(), *P->Args);
4079
4080 return {/*Invalid=*/true};
4081 }
4082 }
4083
4084 ClassTemplateSpec->setInstantiationOf(Best->Partial, Best->Args);
4085 } else {
4086 // -- If no matches are found, the instantiation is generated
4087 // from the primary template.
4088 }
4089 }
4090
4091 CXXRecordDecl *Pattern = nullptr;
4092 Specialized = ClassTemplateSpec->getSpecializedTemplateOrPartial();
4093 if (auto *PartialSpec =
4094 Specialized.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
4095 // Instantiate using the best class template partial specialization.
4096 while (PartialSpec->getInstantiatedFromMember()) {
4097 // If we've found an explicit specialization of this class template,
4098 // stop here and use that as the pattern.
4099 if (PartialSpec->isMemberSpecialization())
4100 break;
4101
4102 PartialSpec = PartialSpec->getInstantiatedFromMember();
4103 }
4104 Pattern = PartialSpec;
4105 } else {
4106 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
4107 while (Template->getInstantiatedFromMemberTemplate()) {
4108 // If we've found an explicit specialization of this class template,
4109 // stop here and use that as the pattern.
4110 if (Template->isMemberSpecialization())
4111 break;
4112
4113 Template = Template->getInstantiatedFromMemberTemplate();
4114 }
4115 Pattern = Template->getTemplatedDecl();
4116 }
4117
4118 return Pattern;
4119}
4120
4122 SourceLocation PointOfInstantiation,
4123 ClassTemplateSpecializationDecl *ClassTemplateSpec,
4124 TemplateSpecializationKind TSK, bool Complain,
4125 bool PrimaryStrictPackMatch) {
4126 // Perform the actual instantiation on the canonical declaration.
4127 ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>(
4128 ClassTemplateSpec->getCanonicalDecl());
4129 if (ClassTemplateSpec->isInvalidDecl())
4130 return true;
4131
4132 bool HadAvaibilityWarning =
4133 ShouldDiagnoseAvailabilityOfDecl(ClassTemplateSpec, nullptr, nullptr)
4134 .first != AR_Available;
4135
4137 getPatternForClassTemplateSpecialization(*this, PointOfInstantiation,
4138 ClassTemplateSpec, TSK,
4139 PrimaryStrictPackMatch);
4140
4141 if (!Pattern.isUsable())
4142 return Pattern.isInvalid();
4143
4144 bool Err = InstantiateClass(
4145 PointOfInstantiation, ClassTemplateSpec, Pattern.get(),
4146 getTemplateInstantiationArgs(ClassTemplateSpec), TSK, Complain);
4147
4148 // If we haven't already warn on avaibility, consider the avaibility
4149 // attributes of the partial specialization.
4150 // Note that - because we need to have deduced the partial specialization -
4151 // We can only emit these warnings when the specialization is instantiated.
4152 if (!Err && !HadAvaibilityWarning) {
4153 assert(ClassTemplateSpec->getTemplateSpecializationKind() !=
4155 DiagnoseAvailabilityOfDecl(ClassTemplateSpec, PointOfInstantiation);
4156 }
4157 return Err;
4158}
4159
4160void
4162 CXXRecordDecl *Instantiation,
4163 const MultiLevelTemplateArgumentList &TemplateArgs,
4165 // FIXME: We need to notify the ASTMutationListener that we did all of these
4166 // things, in case we have an explicit instantiation definition in a PCM, a
4167 // module, or preamble, and the declaration is in an imported AST.
4168 assert(
4171 (TSK == TSK_ImplicitInstantiation && Instantiation->isLocalClass())) &&
4172 "Unexpected template specialization kind!");
4173 for (auto *D : Instantiation->decls()) {
4174 bool SuppressNew = false;
4175 if (auto *Function = dyn_cast<FunctionDecl>(D)) {
4176 if (FunctionDecl *Pattern =
4177 Function->getInstantiatedFromMemberFunction()) {
4178
4179 if (Function->getTrailingRequiresClause()) {
4180 ConstraintSatisfaction Satisfaction;
4181 if (CheckFunctionConstraints(Function, Satisfaction) ||
4182 !Satisfaction.IsSatisfied) {
4183 continue;
4184 }
4185 }
4186
4187 if (Function->hasAttr<ExcludeFromExplicitInstantiationAttr>())
4188 continue;
4189
4191 Function->getTemplateSpecializationKind();
4192 if (PrevTSK == TSK_ExplicitSpecialization)
4193 continue;
4194
4196 PointOfInstantiation, TSK, Function, PrevTSK,
4197 Function->getPointOfInstantiation(), SuppressNew) ||
4198 SuppressNew)
4199 continue;
4200
4201 // C++11 [temp.explicit]p8:
4202 // An explicit instantiation definition that names a class template
4203 // specialization explicitly instantiates the class template
4204 // specialization and is only an explicit instantiation definition
4205 // of members whose definition is visible at the point of
4206 // instantiation.
4207 if (TSK == TSK_ExplicitInstantiationDefinition && !Pattern->isDefined())
4208 continue;
4209
4210 Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
4211
4212 if (Function->isDefined()) {
4213 // Let the ASTConsumer know that this function has been explicitly
4214 // instantiated now, and its linkage might have changed.
4215 Consumer.HandleTopLevelDecl(DeclGroupRef(Function));
4216 } else if (TSK == TSK_ExplicitInstantiationDefinition) {
4217 InstantiateFunctionDefinition(PointOfInstantiation, Function);
4218 } else if (TSK == TSK_ImplicitInstantiation) {
4220 std::make_pair(Function, PointOfInstantiation));
4221 }
4222 }
4223 } else if (auto *Var = dyn_cast<VarDecl>(D)) {
4225 continue;
4226
4227 if (Var->isStaticDataMember()) {
4228 if (Var->hasAttr<ExcludeFromExplicitInstantiationAttr>())
4229 continue;
4230
4232 assert(MSInfo && "No member specialization information?");
4233 if (MSInfo->getTemplateSpecializationKind()
4235 continue;
4236
4237 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
4238 Var,
4240 MSInfo->getPointOfInstantiation(),
4241 SuppressNew) ||
4242 SuppressNew)
4243 continue;
4244
4246 // C++0x [temp.explicit]p8:
4247 // An explicit instantiation definition that names a class template
4248 // specialization explicitly instantiates the class template
4249 // specialization and is only an explicit instantiation definition
4250 // of members whose definition is visible at the point of
4251 // instantiation.
4253 continue;
4254
4255 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
4256 InstantiateVariableDefinition(PointOfInstantiation, Var);
4257 } else {
4258 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
4259 }
4260 }
4261 } else if (auto *Record = dyn_cast<CXXRecordDecl>(D)) {
4262 if (Record->hasAttr<ExcludeFromExplicitInstantiationAttr>())
4263 continue;
4264
4265 // Always skip the injected-class-name, along with any
4266 // redeclarations of nested classes, since both would cause us
4267 // to try to instantiate the members of a class twice.
4268 // Skip closure types; they'll get instantiated when we instantiate
4269 // the corresponding lambda-expression.
4270 if (Record->isInjectedClassName() || Record->getPreviousDecl() ||
4271 Record->isLambda())
4272 continue;
4273
4274 MemberSpecializationInfo *MSInfo = Record->getMemberSpecializationInfo();
4275 assert(MSInfo && "No member specialization information?");
4276
4277 if (MSInfo->getTemplateSpecializationKind()
4279 continue;
4280
4281 if (Context.getTargetInfo().getTriple().isOSWindows() &&
4283 // On Windows, explicit instantiation decl of the outer class doesn't
4284 // affect the inner class. Typically extern template declarations are
4285 // used in combination with dll import/export annotations, but those
4286 // are not propagated from the outer class templates to inner classes.
4287 // Therefore, do not instantiate inner classes on this platform, so
4288 // that users don't end up with undefined symbols during linking.
4289 continue;
4290 }
4291
4292 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
4293 Record,
4295 MSInfo->getPointOfInstantiation(),
4296 SuppressNew) ||
4297 SuppressNew)
4298 continue;
4299
4300 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
4301 assert(Pattern && "Missing instantiated-from-template information");
4302
4303 if (!Record->getDefinition()) {
4304 if (!Pattern->getDefinition()) {
4305 // C++0x [temp.explicit]p8:
4306 // An explicit instantiation definition that names a class template
4307 // specialization explicitly instantiates the class template
4308 // specialization and is only an explicit instantiation definition
4309 // of members whose definition is visible at the point of
4310 // instantiation.
4312 MSInfo->setTemplateSpecializationKind(TSK);
4313 MSInfo->setPointOfInstantiation(PointOfInstantiation);
4314 }
4315
4316 continue;
4317 }
4318
4319 InstantiateClass(PointOfInstantiation, Record, Pattern,
4320 TemplateArgs,
4321 TSK);
4322 } else {
4324 Record->getTemplateSpecializationKind() ==
4326 Record->setTemplateSpecializationKind(TSK);
4327 MarkVTableUsed(PointOfInstantiation, Record, true);
4328 }
4329 }
4330
4331 Pattern = cast_or_null<CXXRecordDecl>(Record->getDefinition());
4332 if (Pattern)
4333 InstantiateClassMembers(PointOfInstantiation, Pattern, TemplateArgs,
4334 TSK);
4335 } else if (auto *Enum = dyn_cast<EnumDecl>(D)) {
4336 MemberSpecializationInfo *MSInfo = Enum->getMemberSpecializationInfo();
4337 assert(MSInfo && "No member specialization information?");
4338
4339 if (MSInfo->getTemplateSpecializationKind()
4341 continue;
4342
4344 PointOfInstantiation, TSK, Enum,
4346 MSInfo->getPointOfInstantiation(), SuppressNew) ||
4347 SuppressNew)
4348 continue;
4349
4350 if (Enum->getDefinition())
4351 continue;
4352
4353 EnumDecl *Pattern = Enum->getTemplateInstantiationPattern();
4354 assert(Pattern && "Missing instantiated-from-template information");
4355
4357 if (!Pattern->getDefinition())
4358 continue;
4359
4360 InstantiateEnum(PointOfInstantiation, Enum, Pattern, TemplateArgs, TSK);
4361 } else {
4362 MSInfo->setTemplateSpecializationKind(TSK);
4363 MSInfo->setPointOfInstantiation(PointOfInstantiation);
4364 }
4365 } else if (auto *Field = dyn_cast<FieldDecl>(D)) {
4366 // No need to instantiate in-class initializers during explicit
4367 // instantiation.
4368 if (Field->hasInClassInitializer() && TSK == TSK_ImplicitInstantiation) {
4369 // Handle local classes which could have substituted template params.
4370 CXXRecordDecl *ClassPattern =
4371 Instantiation->isLocalClass()
4372 ? Instantiation->getInstantiatedFromMemberClass()
4373 : Instantiation->getTemplateInstantiationPattern();
4374
4376 ClassPattern->lookup(Field->getDeclName());
4377 FieldDecl *Pattern = Lookup.find_first<FieldDecl>();
4378 assert(Pattern);
4379 InstantiateInClassInitializer(PointOfInstantiation, Field, Pattern,
4380 TemplateArgs);
4381 }
4382 }
4383 }
4384}
4385
4386void
4388 SourceLocation PointOfInstantiation,
4389 ClassTemplateSpecializationDecl *ClassTemplateSpec,
4391 // C++0x [temp.explicit]p7:
4392 // An explicit instantiation that names a class template
4393 // specialization is an explicit instantion of the same kind
4394 // (declaration or definition) of each of its members (not
4395 // including members inherited from base classes) that has not
4396 // been previously explicitly specialized in the translation unit
4397 // containing the explicit instantiation, except as described
4398 // below.
4399 InstantiateClassMembers(PointOfInstantiation, ClassTemplateSpec,
4400 getTemplateInstantiationArgs(ClassTemplateSpec),
4401 TSK);
4402}
4403
4406 if (!S)
4407 return S;
4408
4409 TemplateInstantiator Instantiator(*this, TemplateArgs,
4411 DeclarationName());
4412 return Instantiator.TransformStmt(S);
4413}
4414
4416 const TemplateArgumentLoc &Input,
4417 const MultiLevelTemplateArgumentList &TemplateArgs,
4419 const DeclarationName &Entity) {
4420 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity);
4421 return Instantiator.TransformTemplateArgument(Input, Output);
4422}
4423
4426 const MultiLevelTemplateArgumentList &TemplateArgs,
4428 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
4429 DeclarationName());
4430 return Instantiator.TransformTemplateArguments(Args.begin(), Args.end(), Out);
4431}
4432
4435 const MultiLevelTemplateArgumentList &TemplateArgs,
4436 TemplateArgumentListInfo &Out, bool BuildPackExpansionTypes) {
4437 TemplateInstantiator Instantiator(
4438 TemplateInstantiator::ForParameterMappingSubstitution, *this, BaseLoc,
4439 TemplateArgs, BuildPackExpansionTypes);
4440 return Instantiator.TransformTemplateArguments(Args.begin(), Args.end(), Out);
4441}
4442
4445 if (!E)
4446 return E;
4447
4448 TemplateInstantiator Instantiator(*this, TemplateArgs,
4450 DeclarationName());
4451 return Instantiator.TransformExpr(E);
4452}
4453
4456 const MultiLevelTemplateArgumentList &TemplateArgs) {
4457 if (!E)
4458 return E;
4459
4460 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
4461 DeclarationName());
4462 return Instantiator.TransformAddressOfOperand(E);
4463}
4464
4467 const MultiLevelTemplateArgumentList &TemplateArgs) {
4468 // FIXME: should call SubstExpr directly if this function is equivalent or
4469 // should it be different?
4470 return SubstExpr(E, TemplateArgs);
4471}
4472
4474 Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs) {
4475 if (!E)
4476 return E;
4477
4478 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
4479 DeclarationName());
4480 Instantiator.setEvaluateConstraints(false);
4481 return Instantiator.TransformExpr(E);
4482}
4483
4485 const MultiLevelTemplateArgumentList &TemplateArgs,
4486 bool CXXDirectInit) {
4487 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
4488 DeclarationName());
4489 return Instantiator.TransformInitializer(Init, CXXDirectInit);
4490}
4491
4492bool Sema::SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
4493 const MultiLevelTemplateArgumentList &TemplateArgs,
4494 SmallVectorImpl<Expr *> &Outputs) {
4495 if (Exprs.empty())
4496 return false;
4497
4498 TemplateInstantiator Instantiator(*this, TemplateArgs,
4500 DeclarationName());
4501 return Instantiator.TransformExprs(Exprs.data(), Exprs.size(),
4502 IsCall, Outputs);
4503}
4504
4507 const MultiLevelTemplateArgumentList &TemplateArgs) {
4508 if (!NNS)
4509 return NestedNameSpecifierLoc();
4510
4511 TemplateInstantiator Instantiator(*this, TemplateArgs, NNS.getBeginLoc(),
4512 DeclarationName());
4513 return Instantiator.TransformNestedNameSpecifierLoc(NNS);
4514}
4515
4518 const MultiLevelTemplateArgumentList &TemplateArgs) {
4519 TemplateInstantiator Instantiator(*this, TemplateArgs, NameInfo.getLoc(),
4520 NameInfo.getName());
4521 return Instantiator.TransformDeclarationNameInfo(NameInfo);
4522}
4523
4526 NestedNameSpecifierLoc &QualifierLoc, TemplateName Name,
4527 SourceLocation NameLoc,
4528 const MultiLevelTemplateArgumentList &TemplateArgs) {
4529 TemplateInstantiator Instantiator(*this, TemplateArgs, NameLoc,
4530 DeclarationName());
4531 return Instantiator.TransformTemplateName(QualifierLoc, TemplateKWLoc, Name,
4532 NameLoc);
4533}
4534
4535static const Decl *getCanonicalParmVarDecl(const Decl *D) {
4536 // When storing ParmVarDecls in the local instantiation scope, we always
4537 // want to use the ParmVarDecl from the canonical function declaration,
4538 // since the map is then valid for any redeclaration or definition of that
4539 // function.
4540 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(D)) {
4541 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
4542 unsigned i = PV->getFunctionScopeIndex();
4543 // This parameter might be from a freestanding function type within the
4544 // function and isn't necessarily referring to one of FD's parameters.
4545 if (i < FD->getNumParams() && FD->getParamDecl(i) == PV)
4546 return FD->getCanonicalDecl()->getParamDecl(i);
4547 }
4548 }
4549 return D;
4550}
4551
4552llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> *
4555 for (LocalInstantiationScope *Current = this; Current;
4556 Current = Current->Outer) {
4557
4558 // Check if we found something within this scope.
4559 const Decl *CheckD = D;
4560 do {
4561 LocalDeclsMap::iterator Found = Current->LocalDecls.find(CheckD);
4562 if (Found != Current->LocalDecls.end())
4563 return &Found->second;
4564
4565 // If this is a tag declaration, it's possible that we need to look for
4566 // a previous declaration.
4567 if (const TagDecl *Tag = dyn_cast<TagDecl>(CheckD))
4568 CheckD = Tag->getPreviousDecl();
4569 else
4570 CheckD = nullptr;
4571 } while (CheckD);
4572
4573 // If we aren't combined with our outer scope, we're done.
4574 if (!Current->CombineWithOuterScope)
4575 break;
4576 }
4577
4578 return nullptr;
4579}
4580
4581llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> *
4584 if (Result)
4585 return Result;
4586 // If we're performing a partial substitution during template argument
4587 // deduction, we may not have values for template parameters yet.
4590 return nullptr;
4591
4592 // Local types referenced prior to definition may require instantiation.
4593 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
4594 if (RD->isLocalClass())
4595 return nullptr;
4596
4597 // Enumeration types referenced prior to definition may appear as a result of
4598 // error recovery.
4599 if (isa<EnumDecl>(D))
4600 return nullptr;
4601
4602 // Materialized typedefs/type alias for implicit deduction guides may require
4603 // instantiation.
4604 if (isa<TypedefNameDecl>(D) &&
4606 return nullptr;
4607
4608 // If we didn't find the decl, then we either have a sema bug, or we have a
4609 // forward reference to a label declaration. Return null to indicate that
4610 // we have an uninstantiated label.
4611 assert(isa<LabelDecl>(D) && "declaration not instantiated in this scope");
4612 return nullptr;
4613}
4614
4617 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
4618 if (Stored.isNull()) {
4619#ifndef NDEBUG
4620 // It should not be present in any surrounding scope either.
4621 LocalInstantiationScope *Current = this;
4622 while (Current->CombineWithOuterScope && Current->Outer) {
4623 Current = Current->Outer;
4624 assert(!Current->LocalDecls.contains(D) &&
4625 "Instantiated local in inner and outer scopes");
4626 }
4627#endif
4628 Stored = Inst;
4629 } else if (DeclArgumentPack *Pack = dyn_cast<DeclArgumentPack *>(Stored)) {
4630 Pack->push_back(cast<ValueDecl>(Inst));
4631 } else {
4632 assert(cast<Decl *>(Stored) == Inst && "Already instantiated this local");
4633 }
4634}
4635
4637 VarDecl *Inst) {
4639 DeclArgumentPack *Pack = cast<DeclArgumentPack *>(LocalDecls[D]);
4640 Pack->push_back(Inst);
4641}
4642
4644#ifndef NDEBUG
4645 // This should be the first time we've been told about this decl.
4646 for (LocalInstantiationScope *Current = this;
4647 Current && Current->CombineWithOuterScope; Current = Current->Outer)
4648 assert(!Current->LocalDecls.contains(D) &&
4649 "Creating local pack after instantiation of local");
4650#endif
4651
4653 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
4655 Stored = Pack;
4656 ArgumentPacks.push_back(Pack);
4657}
4658
4660 for (DeclArgumentPack *Pack : ArgumentPacks)
4661 if (llvm::is_contained(*Pack, D))
4662 return true;
4663 return false;
4664}
4665
4667 const TemplateArgument *ExplicitArgs,
4668 unsigned NumExplicitArgs) {
4669 assert((!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack) &&
4670 "Already have a partially-substituted pack");
4671 assert((!PartiallySubstitutedPack
4672 || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) &&
4673 "Wrong number of arguments in partially-substituted pack");
4674 PartiallySubstitutedPack = Pack;
4675 ArgsInPartiallySubstitutedPack = ExplicitArgs;
4676 NumArgsInPartiallySubstitutedPack = NumExplicitArgs;
4677}
4678
4680 const TemplateArgument **ExplicitArgs,
4681 unsigned *NumExplicitArgs) const {
4682 if (ExplicitArgs)
4683 *ExplicitArgs = nullptr;
4684 if (NumExplicitArgs)
4685 *NumExplicitArgs = 0;
4686
4687 for (const LocalInstantiationScope *Current = this; Current;
4688 Current = Current->Outer) {
4689 if (Current->PartiallySubstitutedPack) {
4690 if (ExplicitArgs)
4691 *ExplicitArgs = Current->ArgsInPartiallySubstitutedPack;
4692 if (NumExplicitArgs)
4693 *NumExplicitArgs = Current->NumArgsInPartiallySubstitutedPack;
4694
4695 return Current->PartiallySubstitutedPack;
4696 }
4697
4698 if (!Current->CombineWithOuterScope)
4699 break;
4700 }
4701
4702 return nullptr;
4703}
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:197
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:47
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h: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
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:822
NestedNameSpecifier getQualifier() const
Retrieve the nested-name-specifier that qualifies the name of this declaration, if it was present in ...
Definition Decl.h:837
TypeSourceInfo * getTypeSourceInfo() const
Definition Decl.h:809
RAII object that enters a new expression evaluation context.
Represents an enum.
Definition Decl.h:4007
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this enumeration is an instantiation of a member enumeration of a class template specialization,...
Definition Decl.h:4270
EnumDecl * getInstantiatedFromMemberEnum() const
Returns the enumeration (declared within the template) from which this enumeration type was instantia...
Definition Decl.cpp:5080
EnumDecl * getDefinition() const
Definition Decl.h:4110
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:3160
Expr * getInClassInitializer() const
Get the C++11 default member initializer for this member, or null if one has not been set.
Definition Decl.cpp:4713
bool hasInClassInitializer() const
Determine whether this member has a C++11 default member initializer.
Definition Decl.h:3340
InClassInitStyle getInClassInitStyle() const
Get the kind of (C++11) default member initializer that this field has.
Definition Decl.h:3334
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3396
Represents a function declaration or definition.
Definition Decl.h:2000
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2774
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:4252
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition Decl.cpp:4301
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition Decl.h:2470
bool isVirtualAsWritten() const
Whether this function is marked as virtual explicitly.
Definition Decl.h:2344
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:4884
ValueDecl *const * iterator
Iterators over the parameters which the parameter pack expanded into.
Definition ExprCXX.h:4876
ValueDecl * getParameterPack() const
Get the parameter pack which this expression refers to.
Definition ExprCXX.h:4869
iterator end() const
Definition ExprCXX.h:4878
unsigned getNumExpansions() const
Get the number of parameters in this parameter pack.
Definition ExprCXX.h:4881
SourceLocation getParameterPackLocation() const
Get the location of the parameter pack.
Definition ExprCXX.h:4872
iterator begin() const
Definition ExprCXX.h:4877
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:369
LocalInstantiationScope(Sema &SemaRef, bool CombineWithOuterScope=false, bool InstantiatingLambdaOrBlock=false)
Definition Template.h:437
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:372
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:509
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:575
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:269
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:274
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:295
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:301
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:340
virtual void getNameForDiagnostic(raw_ostream &OS, const PrintingPolicy &Policy, bool Qualified) const
Appends a human-readable name for this declaration into the given stream.
Definition Decl.cpp: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:1790
unsigned getFunctionScopeIndex() const
Returns the index of this parameter in its prototype or method scope.
Definition Decl.h:1850
SourceLocation getExplicitObjectParamThisLoc() const
Definition Decl.h:1886
void setUnparsedDefaultArg()
Specify that this parameter has an unparsed default argument.
Definition Decl.h:1931
bool hasUnparsedDefaultArg() const
Determines whether this parameter has a default argument that has not yet been parsed.
Definition Decl.h:1919
void setUninstantiatedDefaultArg(Expr *arg)
Definition Decl.cpp:3039
void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex)
Definition Decl.h:1823
bool hasUninstantiatedDefaultArg() const
Definition Decl.h:1923
bool hasInheritedDefaultArg() const
Definition Decl.h:1935
void setExplicitObjectParameterLoc(SourceLocation Loc)
Definition Decl.h:1882
Expr * getDefaultArg()
Definition Decl.cpp:3002
Expr * getUninstantiatedDefaultArg()
Definition Decl.cpp:3044
unsigned getFunctionScopeDepth() const
Definition Decl.h:1840
void setHasInheritedDefaultArg(bool I=true)
Definition Decl.h:1939
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:4312
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:13552
RAII object used to temporarily allow the C++ 'this' expression to be used, with the given qualifiers...
Definition Sema.h:8401
A RAII object to temporarily push a declaration context.
Definition Sema.h:3476
For a defaulted function, the kind of defaulted function that it is.
Definition Sema.h:6321
DefaultedComparisonKind asComparison() const
Definition Sema.h:6353
CXXSpecialMemberKind asSpecialMember() const
Definition Sema.h:6350
A helper class for building up ExtParameterInfos.
Definition Sema.h:12955
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition Sema.h:12392
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:854
llvm::DenseSet< Module * > LookupModulesCache
Cache of additional modules that should be used for name lookup within the current template instantia...
Definition Sema.h:13502
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:13486
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition Sema.h:12984
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:2285
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:13863
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:1283
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:13513
ExprResult SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs)
DiagnosticsEngine & getDiagnostics() const
Definition Sema.h:922
ExprResult SubstConstraintExprWithoutSatisfaction(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs)
void PrintInstantiationStack()
Definition Sema.h:13580
ASTContext & getASTContext() const
Definition Sema.h:925
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:14025
void ActOnStartCXXInClassMemberInitializer()
Enter a new C++ default initializer scope.
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
Definition Sema.h:1191
bool pushCodeSynthesisContext(CodeSynthesisContext Ctx)
bool SubstTemplateArguments(ArrayRef< TemplateArgumentLoc > Args, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateArgumentListInfo &Outputs)
Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, TranslationUnitKind TUKind=TU_Complete, CodeCompleteConsumer *CompletionConsumer=nullptr)
Definition Sema.cpp:272
void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs, const Decl *Pattern, Decl *Inst, LateInstantiatedAttrVec *LateAttrs=nullptr, LocalInstantiationScope *OuterMostScope=nullptr)
const LangOptions & getLangOpts() const
Definition Sema.h:918
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:13538
TemplateArgument getPackSubstitutedTemplateArgument(TemplateArgument Arg) const
Definition Sema.h:11724
bool usesPartialOrExplicitSpecialization(SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec)
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:12996
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:1418
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:13912
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:13522
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:13852
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:13546
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:1284
@ ConstantEvaluated
The current context is "potentially evaluated" in C++11 terms, but the expression is evaluated at com...
Definition Sema.h:6696
@ PotentiallyEvaluated
The current expression is potentially evaluated at run time, which means that code may be generated t...
Definition Sema.h:6706
unsigned LastEmittedCodeSynthesisContextDepth
The depth of the context stack at the point when the most recent error or warning was produced.
Definition Sema.h:13530
bool inParameterMappingSubstitution() const
Definition Sema.h:13857
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:8120
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:8270
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:1286
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:1285
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:1560
SmallVector< Module *, 16 > CodeSynthesisContextLookupModules
Extra modules inspected when performing a lookup during a template instantiation.
Definition Sema.h:13497
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
bool SubstTemplateArgumentsInParameterMapping(ArrayRef< TemplateArgumentLoc > Args, SourceLocation BaseLoc, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateArgumentListInfo &Out, bool BuildPackExpansionTypes)
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:8609
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:3717
void setTagKind(TagKind TK)
Definition Decl.h:3915
SourceRange getBraceRange() const
Definition Decl.h:3788
SourceLocation getInnerLocStart() const
Return SourceLocation representing start of source range ignoring outer template declarations.
Definition Decl.h:3793
void startDefinition()
Starts the definition of this tag declaration.
Definition Decl.cpp:4894
TagKind getTagKind() const
Definition Decl.h:3911
void setBraceRange(SourceRange R)
Definition Decl.h:3789
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:671
SmallVectorImpl< std::pair< ClassTemplateDecl *, ClassTemplatePartialSpecializationDecl * > >::iterator delayed_partial_spec_iterator
Definition Template.h:684
delayed_var_partial_spec_iterator delayed_var_partial_spec_end()
Definition Template.h:710
delayed_partial_spec_iterator delayed_partial_spec_begin()
Return an iterator to the beginning of the set of "delayed" partial specializations,...
Definition Template.h:694
void setEvaluateConstraints(bool B)
Definition Template.h:612
LocalInstantiationScope * getStartingScope() const
Definition Template.h:682
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:687
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:706
delayed_var_partial_spec_iterator delayed_var_partial_spec_begin()
Definition Template.h:698
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:227
const ASTTemplateArgumentListInfo * getTemplateArgsAsWritten() const
Definition ASTConcept.h:266
UnsignedOrNone getArgPackSubstIndex() const
Definition ASTConcept.h:250
Expr * getImmediatelyDeclaredConstraint() const
Get the immediately-declared constraint expression introduced by this type-constraint,...
Definition ASTConcept.h:244
const NestedNameSpecifierLoc & getNestedNameSpecifierLoc() const
Definition ASTConcept.h:276
TemplateDecl * getNamedConcept() const
Definition ASTConcept.h:254
const DeclarationNameInfo & getConceptNameInfo() const
Definition ASTConcept.h:280
ConceptReference * getConceptReference() const
Definition ASTConcept.h:248
void setLocStart(SourceLocation L)
Definition Decl.h:3548
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:8265
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:8276
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:8887
bool isReferenceType() const
Definition TypeBase.h:8555
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:9107
bool isRecordType() const
Definition TypeBase.h:8658
QualType getUnderlyingType() const
Definition Decl.h:3617
QualType getType() const
Definition Decl.h:723
bool isParameterPack() const
Determine whether this value is actually a function parameter pack, init-capture pack,...
Definition Decl.cpp:5512
Represents a variable declaration or definition.
Definition Decl.h:926
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition Decl.h:1283
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:1168
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)
if(T->getSizeExpr()) TRY_TO(TraverseStmt(const_cast< Expr * >(T -> getSizeExpr())))
@ Specialization
We are substituting template parameters for template arguments in order to form a template specializa...
Definition Template.h:50
@ Ambiguous
Name lookup results in an ambiguity; use getAmbiguityKind to figure out what kind of ambiguity we hav...
Definition Lookup.h:64
@ TemplateName
The identifier is a template name. FIXME: Add an annotation for that.
Definition Parser.h:61
NamedDecl * getAsNamedDecl(TemplateParameter P)
std::pair< llvm::PointerUnion< const TemplateTypeParmType *, NamedDecl *, const TemplateSpecializationType *, const SubstBuiltinTemplatePackType * >, SourceLocation > UnexpandedParameterPack
Definition Sema.h:236
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:562
@ 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:367
@ Success
Template argument deduction was successful.
Definition Sema.h:369
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:13001
SourceRange InstantiationRange
The source range that covers the construct that cause the instantiation, e.g., the template-id that c...
Definition Sema.h:13171
enum clang::Sema::CodeSynthesisContext::SynthesisKind Kind
bool SavedInNonInstantiationSFINAEContext
Was the enclosing context a non-instantiation SFINAE context?
Definition Sema.h:13118
const TemplateArgument * TemplateArgs
The list of template arguments we are substituting, if they are not part of the entity.
Definition Sema.h:13140
sema::TemplateDeductionInfo * DeductionInfo
The template deduction info object associated with the substitution or checking of explicit or deduce...
Definition Sema.h:13166
SourceLocation PointOfInstantiation
The point of instantiation or synthesis within the source code.
Definition Sema.h:13127
SynthesisKind
The kind of template instantiation we are performing.
Definition Sema.h:13003
@ MarkingClassDllexported
We are marking a class as __dllexport.
Definition Sema.h:13095
@ DefaultTemplateArgumentInstantiation
We are instantiating a default argument for a template parameter.
Definition Sema.h:13013
@ ExplicitTemplateArgumentSubstitution
We are substituting explicit template arguments provided for a function template.
Definition Sema.h:13022
@ DefaultTemplateArgumentChecking
We are checking the validity of a default template argument that has been used when naming a template...
Definition Sema.h:13041
@ InitializingStructuredBinding
We are initializing a structured binding.
Definition Sema.h:13092
@ ExceptionSpecInstantiation
We are instantiating the exception specification for a function template which was deferred until it ...
Definition Sema.h:13049
@ NestedRequirementConstraintsCheck
We are checking the satisfaction of a nested requirement of a requires expression.
Definition Sema.h:13056
@ BuildingBuiltinDumpStructCall
We are building an implied call from __builtin_dump_struct.
Definition Sema.h:13099
@ DefiningSynthesizedFunction
We are defining a synthesized function (such as a defaulted special member).
Definition Sema.h:13067
@ Memoization
Added for Template instantiation observation.
Definition Sema.h:13105
@ LambdaExpressionSubstitution
We are substituting into a lambda expression.
Definition Sema.h:13032
@ TypeAliasTemplateInstantiation
We are instantiating a type alias template declaration.
Definition Sema.h:13111
@ BuildingDeductionGuides
We are building deduction guides for a class.
Definition Sema.h:13108
@ PartialOrderingTTP
We are performing partial ordering for template template parameters.
Definition Sema.h:13114
@ DeducedTemplateArgumentSubstitution
We are substituting template argument determined as part of template argument deduction for either a ...
Definition Sema.h:13029
@ PriorTemplateArgumentSubstitution
We are substituting prior template arguments into a new template parameter.
Definition Sema.h:13037
@ ExceptionSpecEvaluation
We are computing the exception specification for a defaulted special member function.
Definition Sema.h:13045
@ TemplateInstantiation
We are instantiating a template declaration.
Definition Sema.h:13006
@ DeclaringSpecialMember
We are declaring an implicit special member function.
Definition Sema.h:13059
@ DeclaringImplicitEqualityComparison
We are declaring an implicit 'operator==' for a defaulted 'operator<=>'.
Definition Sema.h:13063
@ DefaultFunctionArgumentInstantiation
We are instantiating a default argument for a function.
Definition Sema.h:13018
@ RewritingOperatorAsSpaceship
We are rewriting a comparison operator in terms of an operator<=>.
Definition Sema.h:13089
@ RequirementInstantiation
We are instantiating a requirement of a requires expression.
Definition Sema.h:13052
Decl * Entity
The entity that is being synthesized.
Definition Sema.h:13130
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:13197
bool isInvalid() const
Determines whether we have exceeded the maximum recursive template instantiations.
Definition Sema.h:13357
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:13361
void set(DeclAccessPair Found, Decl *Spec, DeductionFailureInfo Info)
SourceLocation Ellipsis
UnsignedOrNone NumExpansions